1use crate::CharonFailure;
3use crate::toolchain::CHARON_SYSROOT_VAR;
4use crate::translate::translate_crate;
5use charon_lib::errors::ErrorCtx;
6use charon_lib::options::{self, CliOpts, MirLevel, selected_crate_var};
7use charon_lib::transform::TransformCtx;
8use charon_lib::utils::arg_value;
9use itertools::Itertools;
10use rustc_driver::{Callbacks, Compilation};
11use rustc_interface::Config;
12use rustc_interface::interface::Compiler;
13use rustc_middle::ty::{InstanceKind, TyCtxt};
14use rustc_middle::util::Providers;
15use rustc_session::config::JobsMode;
16use rustc_session::output::{OutputType, OutputTypes};
17use rustc_span::{ErrorGuaranteed, Symbol};
18use rustc_structures::CrateType;
19use std::num::NonZero;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::{env, fmt};
22
23fn run_compiler_with_callbacks(
25 args: Vec<String>,
26 callbacks: &mut (dyn Callbacks + Send),
27) -> Result<(), CharonFailure> {
28 rustc_driver::catch_fatal_errors(|| rustc_driver::compiler_entrypoint(&args, callbacks))
29 .map_err(|_| CharonFailure::RustcError)
30}
31
32fn set_mir_options(config: &mut Config) {
34 config.opts.unstable_opts.always_encode_mir = true;
35 config.opts.unstable_opts.mir_opt_level = Some(0);
36 config.opts.unstable_opts.mir_preserve_ub = true;
37 let disabled_mir_passes = ["CheckAlignment", "CheckNull"];
38 for pass in disabled_mir_passes {
39 config
40 .opts
41 .unstable_opts
42 .mir_enable_passes
43 .push((pass.to_owned(), false));
44 }
45}
46
47fn set_parallel_frontend(config: &mut Config) {
49 if config.opts.unstable_opts.threads.is_none() {
50 const RUSTC_MAX_THREADS_CAP: usize = u8::MAX as usize;
52 let threads = std::thread::available_parallelism()
53 .map_or(1, |n| n.get())
54 .min(RUSTC_MAX_THREADS_CAP);
55 if let Some(threads) = NonZero::new(threads).filter(|n| n.get() > 1) {
56 config.opts.jobs.frontend = JobsMode::Parallel(threads);
57 }
58 }
59}
60
61static SKIP_BORROWCK: AtomicBool = AtomicBool::new(false);
63fn set_skip_borrowck() {
64 SKIP_BORROWCK.store(true, Ordering::SeqCst);
65}
66fn skip_borrowck_if_set(providers: &mut Providers) {
67 if SKIP_BORROWCK.load(Ordering::SeqCst) {
68 providers.queries.mir_borrowck = |tcx, _def_id| {
69 Ok(tcx.arena.alloc(Default::default()))
71 }
72 }
73}
74
75fn setup_compiler(
76 config: &mut Config,
77 options: &CliOpts,
78 is_target_crate: bool,
79 do_translate: bool,
80 emit_artifacts: bool,
81 codegen: bool,
82) {
83 if is_target_crate && let Some(crate_name) = &config.opts.crate_name {
84 let var = selected_crate_var(crate_name);
87 config.track_state = Some(Box::new(move |sess| {
88 let value = env::var(&var).ok().map(|value| Symbol::intern(&value));
89 let var = Symbol::intern(&var);
90 sess.env_depinfo.borrow_mut().insert((var, value));
91 }));
92 }
93
94 if do_translate {
95 if options.skip_borrowck {
96 set_skip_borrowck();
98 }
99
100 config.override_queries = Some(|_sess, providers| {
101 skip_borrowck_if_set(providers);
102
103 });
111
112 config.opts.unstable_opts.no_codegen = !codegen;
113 if !emit_artifacts {
114 config.opts.output_types = OutputTypes::new(&[(OutputType::Object, None)]);
115 }
116 set_parallel_frontend(config);
117 }
118 if is_target_crate
119 && !codegen
120 && config.opts.prints.is_empty()
121 && config.opts.crate_types.contains(&CrateType::Rlib)
122 {
123 config
126 .opts
127 .crate_types
128 .retain(|t| !matches!(t, CrateType::Cdylib | CrateType::StaticLib));
129 }
130 set_mir_options(config);
131}
132
133fn precheck_rustc_errors(tcx: TyCtxt<'_>) -> bool {
137 type QueryResult = Result<(), ErrorGuaranteed>;
138
139 tcx.par_hir_for_each_module(|module| {
140 tcx.ensure_ok().check_mod_attrs(module);
141 tcx.ensure_ok().check_mod_unstable_api_usage(module);
142 });
143
144 let _: QueryResult = tcx.ensure_result().check_type_wf(());
145 for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
146 let _: QueryResult = tcx.ensure_result().coherent_trait(trait_def_id);
147 }
148 let _: QueryResult = tcx.ensure_result().crate_inherent_impls_validity_check(());
149 let _: QueryResult = tcx.ensure_result().crate_inherent_impls_overlap_check(());
150
151 tcx.par_hir_body_owners(|def_id| {
152 let def_kind = tcx.def_kind(def_id);
153 if !matches!(def_kind, rustc_hir::def::DefKind::AnonConst)
154 && !tcx.is_typeck_child(def_id.to_def_id())
155 {
156 tcx.ensure_ok().typeck(def_id);
157 }
158 });
159
160 tcx.dcx().has_errors().is_some()
161}
162
163fn prefetch_local_mir(tcx: TyCtxt<'_>, level: MirLevel) {
166 tcx.par_hir_body_owners(|def_id| {
167 if tcx.is_intrinsic_that_must_be_overridden(def_id) {
168 return;
169 }
170 match level {
171 MirLevel::Built => tcx.ensure_done().mir_built(def_id),
172 MirLevel::Promoted => tcx.ensure_done().mir_promoted(def_id),
173 MirLevel::Elaborated => tcx
174 .ensure_done()
175 .mir_drops_elaborated_and_const_checked(def_id),
176 MirLevel::Optimized => {}
177 }
178 });
179}
180
181fn check_late_rustc_errors(tcx: TyCtxt<'_>) {
184 tcx.par_hir_body_owners(|def_id| {
185 if !tcx.is_intrinsic_that_must_be_overridden(def_id) {
187 let _ = tcx.instance_mir(InstanceKind::Item(def_id.to_def_id()));
188 }
189 });
190
191 if tcx.dcx().err_count() == 0 {
192 let _ = tcx.collect_and_partition_mono_items(());
193 }
194}
195
196pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailure> {
200 let mut compiler_args: Vec<String> = env::args().skip(1).collect();
203 trace!(
204 "charon-driver called with args: {}",
205 compiler_args.iter().format(" ")
206 );
207
208 let is_workspace_dependency =
213 env::var("CHARON_USING_CARGO").is_ok() && env::var("CARGO_PRIMARY_PACKAGE").is_err();
214 let emit_artifacts =
217 env::var("CHARON_USING_CARGO").is_ok() || env::var("CHARON_EMIT_ARTIFACTS").is_ok();
218 let mut codegen = emit_artifacts;
220 let is_target_crate = arg_value(&compiler_args, "--target").is_some();
228 let is_selected_crate = !is_workspace_dependency && is_target_crate;
230
231 let mut error_ctx = ErrorCtx::new();
232
233 let options = match env::var(options::CHARON_ARGS)
237 .ok()
238 .map(|opts| serde_json::from_str::<options::CliOpts>(&opts).unwrap())
239 {
240 Some(options) => options,
241 None if !is_selected_crate => Default::default(),
242 None => {
243 register_error!(
244 error_ctx,
245 no_crate,
246 "environment variable `CHARON_ARGS` not set; \
247 don't call `charon-driver` directly, call `charon rustc` instead"
248 );
249 return Err(CharonFailure::CharonError(1));
250 }
251 };
252
253 if options.sysroot.as_deref() == Some("default") {
254 } else if let Some(sysroot) = options.sysroot.as_ref()
256 && sysroot != "miri"
257 {
258 compiler_args.push(format!("--sysroot={sysroot}"));
259 } else if is_target_crate && let Ok(sysroot) = env::var(CHARON_SYSROOT_VAR) {
260 compiler_args.push(format!("--sysroot={sysroot}"));
262 codegen = false;
264 }
265
266 let output = if !is_selected_crate {
267 trace!("Skipping charon; running compiler normally instead.");
268 let mut callback = RunCompilerNormallyCallbacks {
270 is_target_crate,
271 codegen,
272 };
273 run_compiler_with_callbacks(compiler_args, &mut callback)?;
274 None
275 } else {
276 error_ctx.continue_on_failure = !options.abort_on_error;
277 error_ctx.error_on_warnings = options.error_on_warnings;
278
279 for extra_flag in options.rustc_args.iter().cloned() {
280 compiler_args.push(extra_flag);
281 }
282
283 let mut callback = CharonCallbacks {
285 options: &options,
286 emit_artifacts,
287 codegen,
288 error_ctx: Some(error_ctx),
289 transform_ctx: None,
290 };
291 charon_lib::timing::time("rustc-driver", || {
292 run_compiler_with_callbacks(compiler_args, &mut callback)
293 })?;
294 let ctx = callback.transform_ctx.ok_or(CharonFailure::RustcError)?;
296 Some((ctx, options))
297 };
298 Ok(output)
299}
300
301pub struct CharonCallbacks<'a> {
303 options: &'a CliOpts,
304 emit_artifacts: bool,
307 codegen: bool,
309 error_ctx: Option<ErrorCtx>,
311 transform_ctx: Option<TransformCtx>,
314}
315impl<'a> Callbacks for CharonCallbacks<'a> {
316 fn config(&mut self, config: &mut Config) {
317 setup_compiler(
318 config,
319 self.options,
320 true,
321 true,
322 self.emit_artifacts,
323 self.codegen,
324 );
325 }
326
327 fn after_expansion<'tcx>(&mut self, compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
332 rustc_hir::def_id::DEF_ID_DEBUG
334 .swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
335
336 if charon_lib::timing::time("rustc-precheck-errors", || precheck_rustc_errors(tcx)) {
337 return Compilation::Continue;
338 }
339 charon_lib::timing::time("rustc-prefetch-mir", || {
340 prefetch_local_mir(tcx, self.options.mir_level())
341 });
342
343 self.transform_ctx = charon_lib::timing::time("translate-crate", || {
344 translate_crate::translate(
345 tcx,
346 self.options,
347 self.error_ctx.take().unwrap(),
348 compiler.sess.opts.sysroot.path().to_owned(),
349 )
350 })
351 .ok();
352
353 Compilation::Continue
354 }
355 fn after_analysis<'tcx>(&mut self, _compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
356 if !self.emit_artifacts {
357 charon_lib::timing::time("rustc-late-checks", || check_late_rustc_errors(tcx));
358 }
359 Compilation::Continue
360 }
361}
362
363pub struct RunCompilerNormallyCallbacks {
365 is_target_crate: bool,
366 codegen: bool,
367}
368
369impl Callbacks for RunCompilerNormallyCallbacks {
370 fn config(&mut self, config: &mut Config) {
371 setup_compiler(
372 config,
373 &Default::default(),
374 self.is_target_crate,
375 false,
376 true,
377 self.codegen,
378 );
379 }
380}
381
382fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 rustc_middle::ty::tls::with_opt(|opt_tcx| {
385 if let Some(tcx) = opt_tcx {
386 let crate_name = if def_id.is_local() {
387 tcx.crate_name(rustc_hir::def_id::LOCAL_CRATE)
388 } else {
389 tcx.cstore_untracked().crate_name(def_id.krate)
390 };
391 write!(
392 f,
393 "{}{}",
394 crate_name,
395 tcx.def_path(def_id).to_string_no_crate_verbose()
396 )?;
397 } else {
398 write!(f, "<can't access `tcx` to print `DefId` path>")?;
399 }
400 Ok(())
401 })
402}