]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_driver/src/lib.rs
53ae913f94f124f9dd1166c5eb723e177d21253b
[rust.git] / compiler / rustc_driver / src / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(let_else)]
9 #![feature(once_cell)]
10 #![recursion_limit = "256"]
11 #![allow(rustc::potential_query_instability)]
12
13 #[macro_use]
14 extern crate tracing;
15
16 pub extern crate rustc_plugin_impl as plugin;
17
18 use rustc_ast as ast;
19 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
20 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
21 use rustc_data_structures::sync::SeqCst;
22 use rustc_errors::registry::{InvalidErrorCode, Registry};
23 use rustc_errors::{ErrorGuaranteed, PResult};
24 use rustc_feature::find_gated_cfg;
25 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
26 use rustc_interface::{interface, Queries};
27 use rustc_lint::LintStore;
28 use rustc_log::stdout_isatty;
29 use rustc_metadata::locator;
30 use rustc_save_analysis as save;
31 use rustc_save_analysis::DumpHandler;
32 use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS};
33 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
34 use rustc_session::cstore::MetadataLoader;
35 use rustc_session::getopts;
36 use rustc_session::lint::{Lint, LintId};
37 use rustc_session::{config, DiagnosticOutput, Session};
38 use rustc_session::{early_error, early_error_no_abort, early_warn};
39 use rustc_span::source_map::{FileLoader, FileName};
40 use rustc_span::symbol::sym;
41 use rustc_target::json::ToJson;
42
43 use std::borrow::Cow;
44 use std::cmp::max;
45 use std::default::Default;
46 use std::env;
47 use std::ffi::OsString;
48 use std::fs;
49 use std::io::{self, Read, Write};
50 use std::panic::{self, catch_unwind};
51 use std::path::PathBuf;
52 use std::process::{self, Command, Stdio};
53 use std::str;
54 use std::sync::LazyLock;
55 use std::time::Instant;
56
57 pub mod args;
58 pub mod pretty;
59
60 /// Exit status code used for successful compilation and help output.
61 pub const EXIT_SUCCESS: i32 = 0;
62
63 /// Exit status code used for compilation failures and invalid flags.
64 pub const EXIT_FAILURE: i32 = 1;
65
66 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
67     ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
68
69 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
70
71 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
72
73 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
74
75 pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
76     match result {
77         Err(..) => {
78             sess.abort_if_errors();
79             panic!("error reported but abort_if_errors didn't abort???");
80         }
81         Ok(x) => x,
82     }
83 }
84
85 pub trait Callbacks {
86     /// Called before creating the compiler instance
87     fn config(&mut self, _config: &mut interface::Config) {}
88     /// Called after parsing. Return value instructs the compiler whether to
89     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
90     fn after_parsing<'tcx>(
91         &mut self,
92         _compiler: &interface::Compiler,
93         _queries: &'tcx Queries<'tcx>,
94     ) -> Compilation {
95         Compilation::Continue
96     }
97     /// Called after expansion. Return value instructs the compiler whether to
98     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
99     fn after_expansion<'tcx>(
100         &mut self,
101         _compiler: &interface::Compiler,
102         _queries: &'tcx Queries<'tcx>,
103     ) -> Compilation {
104         Compilation::Continue
105     }
106     /// Called after analysis. Return value instructs the compiler whether to
107     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
108     fn after_analysis<'tcx>(
109         &mut self,
110         _compiler: &interface::Compiler,
111         _queries: &'tcx Queries<'tcx>,
112     ) -> Compilation {
113         Compilation::Continue
114     }
115 }
116
117 #[derive(Default)]
118 pub struct TimePassesCallbacks {
119     time_passes: bool,
120 }
121
122 impl Callbacks for TimePassesCallbacks {
123     fn config(&mut self, config: &mut interface::Config) {
124         // If a --prints=... option has been given, we don't print the "total"
125         // time because it will mess up the --prints output. See #64339.
126         self.time_passes = config.opts.prints.is_empty() && config.opts.time_passes();
127         config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
128     }
129 }
130
131 pub fn diagnostics_registry() -> Registry {
132     Registry::new(rustc_error_codes::DIAGNOSTICS)
133 }
134
135 /// This is the primary entry point for rustc.
136 pub struct RunCompiler<'a, 'b> {
137     at_args: &'a [String],
138     callbacks: &'b mut (dyn Callbacks + Send),
139     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
140     emitter: Option<Box<dyn Write + Send>>,
141     make_codegen_backend:
142         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
143 }
144
145 impl<'a, 'b> RunCompiler<'a, 'b> {
146     pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
147         Self { at_args, callbacks, file_loader: None, emitter: None, make_codegen_backend: None }
148     }
149
150     /// Set a custom codegen backend.
151     ///
152     /// Used by cg_clif.
153     pub fn set_make_codegen_backend(
154         &mut self,
155         make_codegen_backend: Option<
156             Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
157         >,
158     ) -> &mut Self {
159         self.make_codegen_backend = make_codegen_backend;
160         self
161     }
162
163     /// Emit diagnostics to the specified location.
164     ///
165     /// Used by RLS.
166     pub fn set_emitter(&mut self, emitter: Option<Box<dyn Write + Send>>) -> &mut Self {
167         self.emitter = emitter;
168         self
169     }
170
171     /// Load files from sources other than the file system.
172     ///
173     /// Used by RLS.
174     pub fn set_file_loader(
175         &mut self,
176         file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
177     ) -> &mut Self {
178         self.file_loader = file_loader;
179         self
180     }
181
182     /// Parse args and run the compiler.
183     pub fn run(self) -> interface::Result<()> {
184         run_compiler(
185             self.at_args,
186             self.callbacks,
187             self.file_loader,
188             self.emitter,
189             self.make_codegen_backend,
190         )
191     }
192 }
193 fn run_compiler(
194     at_args: &[String],
195     callbacks: &mut (dyn Callbacks + Send),
196     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
197     emitter: Option<Box<dyn Write + Send>>,
198     make_codegen_backend: Option<
199         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
200     >,
201 ) -> interface::Result<()> {
202     let args = args::arg_expand_all(at_args);
203
204     let diagnostic_output = emitter.map_or(DiagnosticOutput::Default, DiagnosticOutput::Raw);
205     let Some(matches) = handle_options(&args) else { return Ok(()) };
206
207     let sopts = config::build_session_options(&matches);
208
209     if let Some(ref code) = matches.opt_str("explain") {
210         handle_explain(diagnostics_registry(), code, sopts.error_format);
211         return Ok(());
212     }
213
214     let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
215     let check_cfg = interface::parse_check_cfg(matches.opt_strs("check-cfg"));
216     let (odir, ofile) = make_output(&matches);
217     let mut config = interface::Config {
218         opts: sopts,
219         crate_cfg: cfg,
220         crate_check_cfg: check_cfg,
221         input: Input::File(PathBuf::new()),
222         input_path: None,
223         output_file: ofile,
224         output_dir: odir,
225         file_loader,
226         diagnostic_output,
227         lint_caps: Default::default(),
228         parse_sess_created: None,
229         register_lints: None,
230         override_queries: None,
231         make_codegen_backend,
232         registry: diagnostics_registry(),
233     };
234
235     match make_input(config.opts.error_format, &matches.free) {
236         Err(reported) => return Err(reported),
237         Ok(Some((input, input_file_path))) => {
238             config.input = input;
239             config.input_path = input_file_path;
240
241             callbacks.config(&mut config);
242         }
243         Ok(None) => match matches.free.len() {
244             0 => {
245                 callbacks.config(&mut config);
246                 interface::run_compiler(config, |compiler| {
247                     let sopts = &compiler.session().opts;
248                     if sopts.describe_lints {
249                         let mut lint_store = rustc_lint::new_lint_store(
250                             sopts.unstable_opts.no_interleave_lints,
251                             compiler.session().enable_internal_lints(),
252                         );
253                         let registered_lints =
254                             if let Some(register_lints) = compiler.register_lints() {
255                                 register_lints(compiler.session(), &mut lint_store);
256                                 true
257                             } else {
258                                 false
259                             };
260                         describe_lints(compiler.session(), &lint_store, registered_lints);
261                         return;
262                     }
263                     let should_stop = print_crate_info(
264                         &***compiler.codegen_backend(),
265                         compiler.session(),
266                         None,
267                         compiler.output_dir(),
268                         compiler.output_file(),
269                         compiler.temps_dir(),
270                     );
271
272                     if should_stop == Compilation::Stop {
273                         return;
274                     }
275                     early_error(sopts.error_format, "no input filename given")
276                 });
277                 return Ok(());
278             }
279             1 => panic!("make_input should have provided valid inputs"),
280             _ => early_error(
281                 config.opts.error_format,
282                 &format!(
283                     "multiple input filenames provided (first two filenames are `{}` and `{}`)",
284                     matches.free[0], matches.free[1],
285                 ),
286             ),
287         },
288     };
289
290     interface::run_compiler(config, |compiler| {
291         let sess = compiler.session();
292         let should_stop = print_crate_info(
293             &***compiler.codegen_backend(),
294             sess,
295             Some(compiler.input()),
296             compiler.output_dir(),
297             compiler.output_file(),
298             compiler.temps_dir(),
299         )
300         .and_then(|| {
301             list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input())
302         })
303         .and_then(|| try_process_rlink(sess, compiler));
304
305         if should_stop == Compilation::Stop {
306             return sess.compile_status();
307         }
308
309         let linker = compiler.enter(|queries| {
310             let early_exit = || sess.compile_status().map(|_| None);
311             queries.parse()?;
312
313             if let Some(ppm) = &sess.opts.pretty {
314                 if ppm.needs_ast_map() {
315                     let expanded_crate = queries.expansion()?.peek().0.clone();
316                     queries.global_ctxt()?.peek_mut().enter(|tcx| {
317                         pretty::print_after_hir_lowering(
318                             tcx,
319                             compiler.input(),
320                             &*expanded_crate,
321                             *ppm,
322                             compiler.output_file().as_ref().map(|p| &**p),
323                         );
324                         Ok(())
325                     })?;
326                 } else {
327                     let krate = queries.parse()?.take();
328                     pretty::print_after_parsing(
329                         sess,
330                         compiler.input(),
331                         &krate,
332                         *ppm,
333                         compiler.output_file().as_ref().map(|p| &**p),
334                     );
335                 }
336                 trace!("finished pretty-printing");
337                 return early_exit();
338             }
339
340             if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
341                 return early_exit();
342             }
343
344             if sess.opts.unstable_opts.parse_only || sess.opts.unstable_opts.show_span.is_some() {
345                 return early_exit();
346             }
347
348             {
349                 let (_, lint_store) = &*queries.register_plugins()?.peek();
350
351                 // Lint plugins are registered; now we can process command line flags.
352                 if sess.opts.describe_lints {
353                     describe_lints(sess, lint_store, true);
354                     return early_exit();
355                 }
356             }
357
358             queries.expansion()?;
359             if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
360                 return early_exit();
361             }
362
363             queries.prepare_outputs()?;
364
365             if sess.opts.output_types.contains_key(&OutputType::DepInfo)
366                 && sess.opts.output_types.len() == 1
367             {
368                 return early_exit();
369             }
370
371             queries.global_ctxt()?;
372
373             if sess.opts.unstable_opts.no_analysis {
374                 return early_exit();
375             }
376
377             queries.global_ctxt()?.peek_mut().enter(|tcx| {
378                 let result = tcx.analysis(());
379                 if sess.opts.unstable_opts.save_analysis {
380                     let crate_name = queries.crate_name()?.peek().clone();
381                     sess.time("save_analysis", || {
382                         save::process_crate(
383                             tcx,
384                             &crate_name,
385                             compiler.input(),
386                             None,
387                             DumpHandler::new(
388                                 compiler.output_dir().as_ref().map(|p| &**p),
389                                 &crate_name,
390                             ),
391                         )
392                     });
393                 }
394                 result
395             })?;
396
397             if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
398                 return early_exit();
399             }
400
401             queries.ongoing_codegen()?;
402
403             if sess.opts.unstable_opts.print_type_sizes {
404                 sess.code_stats.print_type_sizes();
405             }
406
407             let linker = queries.linker()?;
408             Ok(Some(linker))
409         })?;
410
411         if let Some(linker) = linker {
412             let _timer = sess.timer("link");
413             linker.link()?
414         }
415
416         if sess.opts.unstable_opts.perf_stats {
417             sess.print_perf_stats();
418         }
419
420         if sess.opts.unstable_opts.print_fuel.is_some() {
421             eprintln!(
422                 "Fuel used by {}: {}",
423                 sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
424                 sess.print_fuel.load(SeqCst)
425             );
426         }
427
428         Ok(())
429     })
430 }
431
432 #[cfg(unix)]
433 pub fn set_sigpipe_handler() {
434     unsafe {
435         // Set the SIGPIPE signal handler, so that an EPIPE
436         // will cause rustc to terminate, as expected.
437         assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
438     }
439 }
440
441 #[cfg(windows)]
442 pub fn set_sigpipe_handler() {}
443
444 // Extract output directory and file from matches.
445 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
446     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
447     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
448     (odir, ofile)
449 }
450
451 // Extract input (string or file and optional path) from matches.
452 fn make_input(
453     error_format: ErrorOutputType,
454     free_matches: &[String],
455 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorGuaranteed> {
456     if free_matches.len() == 1 {
457         let ifile = &free_matches[0];
458         if ifile == "-" {
459             let mut src = String::new();
460             if io::stdin().read_to_string(&mut src).is_err() {
461                 // Immediately stop compilation if there was an issue reading
462                 // the input (for example if the input stream is not UTF-8).
463                 let reported = early_error_no_abort(
464                     error_format,
465                     "couldn't read from stdin, as it did not contain valid UTF-8",
466                 );
467                 return Err(reported);
468             }
469             if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
470                 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
471                     "when UNSTABLE_RUSTDOC_TEST_PATH is set \
472                                     UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
473                 );
474                 let line = isize::from_str_radix(&line, 10)
475                     .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
476                 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
477                 Ok(Some((Input::Str { name: file_name, input: src }, None)))
478             } else {
479                 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
480             }
481         } else {
482             Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
483         }
484     } else {
485         Ok(None)
486     }
487 }
488
489 /// Whether to stop or continue compilation.
490 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
491 pub enum Compilation {
492     Stop,
493     Continue,
494 }
495
496 impl Compilation {
497     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
498         match self {
499             Compilation::Stop => Compilation::Stop,
500             Compilation::Continue => next(),
501         }
502     }
503 }
504
505 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
506     let upper_cased_code = code.to_ascii_uppercase();
507     let normalised = if upper_cased_code.starts_with('E') {
508         upper_cased_code
509     } else {
510         format!("E{0:0>4}", code)
511     };
512     match registry.try_find_description(&normalised) {
513         Ok(Some(description)) => {
514             let mut is_in_code_block = false;
515             let mut text = String::new();
516             // Slice off the leading newline and print.
517             for line in description.lines() {
518                 let indent_level =
519                     line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
520                 let dedented_line = &line[indent_level..];
521                 if dedented_line.starts_with("```") {
522                     is_in_code_block = !is_in_code_block;
523                     text.push_str(&line[..(indent_level + 3)]);
524                 } else if is_in_code_block && dedented_line.starts_with("# ") {
525                     continue;
526                 } else {
527                     text.push_str(line);
528                 }
529                 text.push('\n');
530             }
531             if stdout_isatty() {
532                 show_content_with_pager(&text);
533             } else {
534                 print!("{}", text);
535             }
536         }
537         Ok(None) => {
538             early_error(output, &format!("no extended information for {}", code));
539         }
540         Err(InvalidErrorCode) => {
541             early_error(output, &format!("{} is not a valid error code", code));
542         }
543     }
544 }
545
546 fn show_content_with_pager(content: &str) {
547     let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
548         if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
549     });
550
551     let mut fallback_to_println = false;
552
553     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
554         Ok(mut pager) => {
555             if let Some(pipe) = pager.stdin.as_mut() {
556                 if pipe.write_all(content.as_bytes()).is_err() {
557                     fallback_to_println = true;
558                 }
559             }
560
561             if pager.wait().is_err() {
562                 fallback_to_println = true;
563             }
564         }
565         Err(_) => {
566             fallback_to_println = true;
567         }
568     }
569
570     // If pager fails for whatever reason, we should still print the content
571     // to standard output
572     if fallback_to_println {
573         print!("{}", content);
574     }
575 }
576
577 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
578     if sess.opts.unstable_opts.link_only {
579         if let Input::File(file) = compiler.input() {
580             // FIXME: #![crate_type] and #![crate_name] support not implemented yet
581             sess.init_crate_types(collect_crate_types(sess, &[]));
582             let outputs = compiler.build_output_filenames(sess, &[]);
583             let rlink_data = fs::read(file).unwrap_or_else(|err| {
584                 sess.fatal(&format!("failed to read rlink file: {}", err));
585             });
586             let codegen_results = match CodegenResults::deserialize_rlink(rlink_data) {
587                 Ok(codegen) => codegen,
588                 Err(error) => {
589                     sess.fatal(&format!("Could not deserialize .rlink file: {error}"));
590                 }
591             };
592             let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
593             abort_on_err(result, sess);
594         } else {
595             sess.fatal("rlink must be a file")
596         }
597         Compilation::Stop
598     } else {
599         Compilation::Continue
600     }
601 }
602
603 pub fn list_metadata(
604     sess: &Session,
605     metadata_loader: &dyn MetadataLoader,
606     input: &Input,
607 ) -> Compilation {
608     if sess.opts.unstable_opts.ls {
609         match *input {
610             Input::File(ref ifile) => {
611                 let path = &(*ifile);
612                 let mut v = Vec::new();
613                 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
614                 println!("{}", String::from_utf8(v).unwrap());
615             }
616             Input::Str { .. } => {
617                 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
618             }
619         }
620         return Compilation::Stop;
621     }
622
623     Compilation::Continue
624 }
625
626 fn print_crate_info(
627     codegen_backend: &dyn CodegenBackend,
628     sess: &Session,
629     input: Option<&Input>,
630     odir: &Option<PathBuf>,
631     ofile: &Option<PathBuf>,
632     temps_dir: &Option<PathBuf>,
633 ) -> Compilation {
634     use rustc_session::config::PrintRequest::*;
635     // NativeStaticLibs and LinkArgs are special - printed during linking
636     // (empty iterator returns true)
637     if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
638         return Compilation::Continue;
639     }
640
641     let attrs = match input {
642         None => None,
643         Some(input) => {
644             let result = parse_crate_attrs(sess, input);
645             match result {
646                 Ok(attrs) => Some(attrs),
647                 Err(mut parse_error) => {
648                     parse_error.emit();
649                     return Compilation::Stop;
650                 }
651             }
652         }
653     };
654     for req in &sess.opts.prints {
655         match *req {
656             TargetList => {
657                 let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
658                 targets.sort_unstable();
659                 println!("{}", targets.join("\n"));
660             }
661             Sysroot => println!("{}", sess.sysroot.display()),
662             TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
663             TargetSpec => {
664                 println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
665             }
666             FileNames | CrateName => {
667                 let input = input.unwrap_or_else(|| {
668                     early_error(ErrorOutputType::default(), "no input file provided")
669                 });
670                 let attrs = attrs.as_ref().unwrap();
671                 let t_outputs = rustc_interface::util::build_output_filenames(
672                     input, odir, ofile, temps_dir, attrs, sess,
673                 );
674                 let id = rustc_session::output::find_crate_name(sess, attrs, input);
675                 if *req == PrintRequest::CrateName {
676                     println!("{}", id);
677                     continue;
678                 }
679                 let crate_types = collect_crate_types(sess, attrs);
680                 for &style in &crate_types {
681                     let fname =
682                         rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
683                     println!("{}", fname.file_name().unwrap().to_string_lossy());
684                 }
685             }
686             Cfg => {
687                 let mut cfgs = sess
688                     .parse_sess
689                     .config
690                     .iter()
691                     .filter_map(|&(name, value)| {
692                         // Note that crt-static is a specially recognized cfg
693                         // directive that's printed out here as part of
694                         // rust-lang/rust#37406, but in general the
695                         // `target_feature` cfg is gated under
696                         // rust-lang/rust#29717. For now this is just
697                         // specifically allowing the crt-static cfg and that's
698                         // it, this is intended to get into Cargo and then go
699                         // through to build scripts.
700                         if (name != sym::target_feature || value != Some(sym::crt_dash_static))
701                             && !sess.is_nightly_build()
702                             && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
703                         {
704                             return None;
705                         }
706
707                         if let Some(value) = value {
708                             Some(format!("{}=\"{}\"", name, value))
709                         } else {
710                             Some(name.to_string())
711                         }
712                     })
713                     .collect::<Vec<String>>();
714
715                 cfgs.sort();
716                 for cfg in cfgs {
717                     println!("{}", cfg);
718                 }
719             }
720             RelocationModels
721             | CodeModels
722             | TlsModels
723             | TargetCPUs
724             | StackProtectorStrategies
725             | TargetFeatures => {
726                 codegen_backend.print(*req, sess);
727             }
728             // Any output here interferes with Cargo's parsing of other printed output
729             NativeStaticLibs => {}
730             LinkArgs => {}
731         }
732     }
733     Compilation::Stop
734 }
735
736 /// Prints version information
737 pub fn version(binary: &str, matches: &getopts::Matches) {
738     let verbose = matches.opt_present("verbose");
739
740     println!("{} {}", binary, util::version_str().unwrap_or("unknown version"));
741
742     if verbose {
743         fn unw(x: Option<&str>) -> &str {
744             x.unwrap_or("unknown")
745         }
746         println!("binary: {}", binary);
747         println!("commit-hash: {}", unw(util::commit_hash_str()));
748         println!("commit-date: {}", unw(util::commit_date_str()));
749         println!("host: {}", config::host_triple());
750         println!("release: {}", unw(util::release_str()));
751
752         let debug_flags = matches.opt_strs("Z");
753         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
754         get_codegen_backend(&None, backend_name).print_version();
755     }
756 }
757
758 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
759     let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
760     let mut options = getopts::Options::new();
761     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
762         (option.apply)(&mut options);
763     }
764     let message = "Usage: rustc [OPTIONS] INPUT";
765     let nightly_help = if nightly_build {
766         "\n    -Z help             Print unstable compiler options"
767     } else {
768         ""
769     };
770     let verbose_help = if verbose {
771         ""
772     } else {
773         "\n    --help -v           Print the full set of options rustc accepts"
774     };
775     let at_path = if verbose {
776         "    @path               Read newline separated options from `path`\n"
777     } else {
778         ""
779     };
780     println!(
781         "{options}{at_path}\nAdditional help:
782     -C help             Print codegen options
783     -W help             \
784               Print 'lint' options and default settings{nightly}{verbose}\n",
785         options = options.usage(message),
786         at_path = at_path,
787         nightly = nightly_help,
788         verbose = verbose_help
789     );
790 }
791
792 fn print_wall_help() {
793     println!(
794         "
795 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
796 default. Use `rustc -W help` to see all available lints. It's more common to put
797 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
798 the command line flag directly.
799 "
800     );
801 }
802
803 /// Write to stdout lint command options, together with a list of all available lints
804 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
805     println!(
806         "
807 Available lint options:
808     -W <foo>           Warn about <foo>
809     -A <foo>           \
810               Allow <foo>
811     -D <foo>           Deny <foo>
812     -F <foo>           Forbid <foo> \
813               (deny <foo> and all attempts to override)
814
815 "
816     );
817
818     fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
819         // The sort doesn't case-fold but it's doubtful we care.
820         lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
821         lints
822     }
823
824     fn sort_lint_groups(
825         lints: Vec<(&'static str, Vec<LintId>, bool)>,
826     ) -> Vec<(&'static str, Vec<LintId>)> {
827         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
828         lints.sort_by_key(|l| l.0);
829         lints
830     }
831
832     let (plugin, builtin): (Vec<_>, _) =
833         lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
834     let plugin = sort_lints(sess, plugin);
835     let builtin = sort_lints(sess, builtin);
836
837     let (plugin_groups, builtin_groups): (Vec<_>, _) =
838         lint_store.get_lint_groups().partition(|&(.., p)| p);
839     let plugin_groups = sort_lint_groups(plugin_groups);
840     let builtin_groups = sort_lint_groups(builtin_groups);
841
842     let max_name_len =
843         plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
844     let padded = |x: &str| {
845         let mut s = " ".repeat(max_name_len - x.chars().count());
846         s.push_str(x);
847         s
848     };
849
850     println!("Lint checks provided by rustc:\n");
851
852     let print_lints = |lints: Vec<&Lint>| {
853         println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
854         println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
855         for lint in lints {
856             let name = lint.name_lower().replace('_', "-");
857             println!(
858                 "    {}  {:7.7}  {}",
859                 padded(&name),
860                 lint.default_level(sess.edition()).as_str(),
861                 lint.desc
862             );
863         }
864         println!("\n");
865     };
866
867     print_lints(builtin);
868
869     let max_name_len = max(
870         "warnings".len(),
871         plugin_groups
872             .iter()
873             .chain(&builtin_groups)
874             .map(|&(s, _)| s.chars().count())
875             .max()
876             .unwrap_or(0),
877     );
878
879     let padded = |x: &str| {
880         let mut s = " ".repeat(max_name_len - x.chars().count());
881         s.push_str(x);
882         s
883     };
884
885     println!("Lint groups provided by rustc:\n");
886
887     let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
888         println!("    {}  sub-lints", padded("name"));
889         println!("    {}  ---------", padded("----"));
890
891         if all_warnings {
892             println!("    {}  all lints that are set to issue warnings", padded("warnings"));
893         }
894
895         for (name, to) in lints {
896             let name = name.to_lowercase().replace('_', "-");
897             let desc = to
898                 .into_iter()
899                 .map(|x| x.to_string().replace('_', "-"))
900                 .collect::<Vec<String>>()
901                 .join(", ");
902             println!("    {}  {}", padded(&name), desc);
903         }
904         println!("\n");
905     };
906
907     print_lint_groups(builtin_groups, true);
908
909     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
910         (false, 0, _) | (false, _, 0) => {
911             println!("Lint tools like Clippy can provide additional lints and lint groups.");
912         }
913         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
914         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
915         (true, l, g) => {
916             if l > 0 {
917                 println!("Lint checks provided by plugins loaded by this crate:\n");
918                 print_lints(plugin);
919             }
920             if g > 0 {
921                 println!("Lint groups provided by plugins loaded by this crate:\n");
922                 print_lint_groups(plugin_groups, false);
923             }
924         }
925     }
926 }
927
928 fn describe_debug_flags() {
929     println!("\nAvailable options:\n");
930     print_flag_list("-Z", config::Z_OPTIONS);
931 }
932
933 fn describe_codegen_flags() {
934     println!("\nAvailable codegen options:\n");
935     print_flag_list("-C", config::CG_OPTIONS);
936 }
937
938 pub fn print_flag_list<T>(
939     cmdline_opt: &str,
940     flag_list: &[(&'static str, T, &'static str, &'static str)],
941 ) {
942     let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
943
944     for &(name, _, _, desc) in flag_list {
945         println!(
946             "    {} {:>width$}=val -- {}",
947             cmdline_opt,
948             name.replace('_', "-"),
949             desc,
950             width = max_len
951         );
952     }
953 }
954
955 /// Process command line options. Emits messages as appropriate. If compilation
956 /// should continue, returns a getopts::Matches object parsed from args,
957 /// otherwise returns `None`.
958 ///
959 /// The compiler's handling of options is a little complicated as it ties into
960 /// our stability story. The current intention of each compiler option is to
961 /// have one of two modes:
962 ///
963 /// 1. An option is stable and can be used everywhere.
964 /// 2. An option is unstable, and can only be used on nightly.
965 ///
966 /// Like unstable library and language features, however, unstable options have
967 /// always required a form of "opt in" to indicate that you're using them. This
968 /// provides the easy ability to scan a code base to check to see if anything
969 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
970 ///
971 /// All options behind `-Z` are considered unstable by default. Other top-level
972 /// options can also be considered unstable, and they were unlocked through the
973 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
974 /// instability in both cases, though.
975 ///
976 /// So with all that in mind, the comments below have some more detail about the
977 /// contortions done here to get things to work out correctly.
978 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
979     // Throw away the first argument, the name of the binary
980     let args = &args[1..];
981
982     if args.is_empty() {
983         // user did not write `-v` nor `-Z unstable-options`, so do not
984         // include that extra information.
985         let nightly_build =
986             rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
987         usage(false, false, nightly_build);
988         return None;
989     }
990
991     // Parse with *all* options defined in the compiler, we don't worry about
992     // option stability here we just want to parse as much as possible.
993     let mut options = getopts::Options::new();
994     for option in config::rustc_optgroups() {
995         (option.apply)(&mut options);
996     }
997     let matches = options.parse(args).unwrap_or_else(|e| {
998         let msg = match e {
999             getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1000                 .iter()
1001                 .map(|&(name, ..)| ('C', name))
1002                 .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1003                 .find(|&(_, name)| *opt == name.replace('_', "-"))
1004                 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
1005             _ => None,
1006         };
1007         early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1008     });
1009
1010     // For all options we just parsed, we check a few aspects:
1011     //
1012     // * If the option is stable, we're all good
1013     // * If the option wasn't passed, we're all good
1014     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1015     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1016     //   this option that was passed.
1017     // * If we're a nightly compiler, then unstable options are now unlocked, so
1018     //   we're good to go.
1019     // * Otherwise, if we're an unstable option then we generate an error
1020     //   (unstable option being used on stable)
1021     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1022
1023     if matches.opt_present("h") || matches.opt_present("help") {
1024         // Only show unstable options in --help if we accept unstable options.
1025         let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1026         let nightly_build = nightly_options::match_is_nightly_build(&matches);
1027         usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1028         return None;
1029     }
1030
1031     // Handle the special case of -Wall.
1032     let wall = matches.opt_strs("W");
1033     if wall.iter().any(|x| *x == "all") {
1034         print_wall_help();
1035         rustc_errors::FatalError.raise();
1036     }
1037
1038     // Don't handle -W help here, because we might first load plugins.
1039     let debug_flags = matches.opt_strs("Z");
1040     if debug_flags.iter().any(|x| *x == "help") {
1041         describe_debug_flags();
1042         return None;
1043     }
1044
1045     let cg_flags = matches.opt_strs("C");
1046
1047     if cg_flags.iter().any(|x| *x == "help") {
1048         describe_codegen_flags();
1049         return None;
1050     }
1051
1052     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1053         early_warn(
1054             ErrorOutputType::default(),
1055             "the --no-stack-check flag is deprecated and does nothing",
1056         );
1057     }
1058
1059     if cg_flags.iter().any(|x| *x == "passes=list") {
1060         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1061         get_codegen_backend(&None, backend_name).print_passes();
1062         return None;
1063     }
1064
1065     if matches.opt_present("version") {
1066         version("rustc", &matches);
1067         return None;
1068     }
1069
1070     Some(matches)
1071 }
1072
1073 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1074     match input {
1075         Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1076         Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1077             name.clone(),
1078             input.clone(),
1079             &sess.parse_sess,
1080         ),
1081     }
1082 }
1083
1084 /// Gets a list of extra command-line flags provided by the user, as strings.
1085 ///
1086 /// This function is used during ICEs to show more information useful for
1087 /// debugging, since some ICEs only happens with non-default compiler flags
1088 /// (and the users don't always report them).
1089 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1090     let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
1091
1092     let mut result = Vec::new();
1093     let mut excluded_cargo_defaults = false;
1094     while let Some(arg) = args.next() {
1095         if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
1096             let content = if arg.len() == a.len() {
1097                 match args.next() {
1098                     Some(arg) => arg.to_string(),
1099                     None => continue,
1100                 }
1101             } else if arg.get(a.len()..a.len() + 1) == Some("=") {
1102                 arg[a.len() + 1..].to_string()
1103             } else {
1104                 arg[a.len()..].to_string()
1105             };
1106             if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| content.starts_with(exc)) {
1107                 excluded_cargo_defaults = true;
1108             } else {
1109                 result.push(a.to_string());
1110                 match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| content.starts_with(*s))
1111                 {
1112                     Some(s) => result.push(s.to_string()),
1113                     None => result.push(content),
1114                 }
1115             }
1116         }
1117     }
1118
1119     if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1120 }
1121
1122 /// Runs a closure and catches unwinds triggered by fatal errors.
1123 ///
1124 /// The compiler currently unwinds with a special sentinel value to abort
1125 /// compilation on fatal errors. This function catches that sentinel and turns
1126 /// the panic into a `Result` instead.
1127 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed> {
1128     catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1129         if value.is::<rustc_errors::FatalErrorMarker>() {
1130             ErrorGuaranteed::unchecked_claim_error_was_emitted()
1131         } else {
1132             panic::resume_unwind(value);
1133         }
1134     })
1135 }
1136
1137 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1138 /// that also computes the exit code.
1139 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1140     let result = catch_fatal_errors(f).and_then(|result| result);
1141     match result {
1142         Ok(()) => EXIT_SUCCESS,
1143         Err(_) => EXIT_FAILURE,
1144     }
1145 }
1146
1147 static DEFAULT_HOOK: LazyLock<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1148     LazyLock::new(|| {
1149         let hook = panic::take_hook();
1150         panic::set_hook(Box::new(|info| {
1151             // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1152             (*DEFAULT_HOOK)(info);
1153
1154             // Separate the output with an empty line
1155             eprintln!();
1156
1157             // Print the ICE message
1158             report_ice(info, BUG_REPORT_URL);
1159         }));
1160         hook
1161     });
1162
1163 /// Prints the ICE message, including query stack, but without backtrace.
1164 ///
1165 /// The message will point the user at `bug_report_url` to report the ICE.
1166 ///
1167 /// When `install_ice_hook` is called, this function will be called as the panic
1168 /// hook.
1169 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1170     let fallback_bundle =
1171         rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1172     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1173         rustc_errors::ColorConfig::Auto,
1174         None,
1175         None,
1176         fallback_bundle,
1177         false,
1178         false,
1179         None,
1180         false,
1181     ));
1182     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1183
1184     // a .span_bug or .bug call has already printed what
1185     // it wants to print.
1186     if !info.payload().is::<rustc_errors::ExplicitBug>() {
1187         let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1188         handler.emit_diagnostic(&mut d);
1189     }
1190
1191     let mut xs: Vec<Cow<'static, str>> = vec![
1192         "the compiler unexpectedly panicked. this is a bug.".into(),
1193         format!("we would appreciate a bug report: {}", bug_report_url).into(),
1194         format!(
1195             "rustc {} running on {}",
1196             util::version_str().unwrap_or("unknown_version"),
1197             config::host_triple()
1198         )
1199         .into(),
1200     ];
1201
1202     if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1203         xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1204
1205         if excluded_cargo_defaults {
1206             xs.push("some of the compiler flags provided by cargo are hidden".into());
1207         }
1208     }
1209
1210     for note in &xs {
1211         handler.note_without_error(note.as_ref());
1212     }
1213
1214     // If backtraces are enabled, also print the query stack
1215     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1216
1217     let num_frames = if backtrace { None } else { Some(2) };
1218
1219     interface::try_print_query_stack(&handler, num_frames);
1220
1221     #[cfg(windows)]
1222     unsafe {
1223         if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1224             // Trigger a debugger if we crashed during bootstrap
1225             winapi::um::debugapi::DebugBreak();
1226         }
1227     }
1228 }
1229
1230 /// Installs a panic hook that will print the ICE message on unexpected panics.
1231 ///
1232 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1233 pub fn install_ice_hook() {
1234     // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1235     // full backtraces. When a compiler ICE happens, we want to gather
1236     // as much information as possible to present in the issue opened
1237     // by the user. Compiler developers and other rustc users can
1238     // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1239     // (e.g. `RUST_BACKTRACE=1`)
1240     if std::env::var("RUST_BACKTRACE").is_err() {
1241         std::env::set_var("RUST_BACKTRACE", "full");
1242     }
1243     LazyLock::force(&DEFAULT_HOOK);
1244 }
1245
1246 /// This allows tools to enable rust logging without having to magically match rustc's
1247 /// tracing crate version.
1248 pub fn init_rustc_env_logger() {
1249     if let Err(error) = rustc_log::init_rustc_env_logger() {
1250         early_error(ErrorOutputType::default(), &error.to_string());
1251     }
1252 }
1253
1254 /// This allows tools to enable rust logging without having to magically match rustc's
1255 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1256 /// other than `RUSTC_LOG`.
1257 pub fn init_env_logger(env: &str) {
1258     if let Err(error) = rustc_log::init_env_logger(env) {
1259         early_error(ErrorOutputType::default(), &error.to_string());
1260     }
1261 }
1262
1263 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1264 mod signal_handler {
1265     extern "C" {
1266         fn backtrace_symbols_fd(
1267             buffer: *const *mut libc::c_void,
1268             size: libc::c_int,
1269             fd: libc::c_int,
1270         );
1271     }
1272
1273     extern "C" fn print_stack_trace(_: libc::c_int) {
1274         const MAX_FRAMES: usize = 256;
1275         static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1276             [std::ptr::null_mut(); MAX_FRAMES];
1277         unsafe {
1278             let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1279             if depth == 0 {
1280                 return;
1281             }
1282             backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1283         }
1284     }
1285
1286     // When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1287     // process, print a stack trace and then exit.
1288     pub(super) fn install() {
1289         unsafe {
1290             const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1291             let mut alt_stack: libc::stack_t = std::mem::zeroed();
1292             alt_stack.ss_sp =
1293                 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1294                     as *mut libc::c_void;
1295             alt_stack.ss_size = ALT_STACK_SIZE;
1296             libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1297
1298             let mut sa: libc::sigaction = std::mem::zeroed();
1299             sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1300             sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1301             libc::sigemptyset(&mut sa.sa_mask);
1302             libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1303         }
1304     }
1305 }
1306
1307 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1308 mod signal_handler {
1309     pub(super) fn install() {}
1310 }
1311
1312 pub fn main() -> ! {
1313     let start_time = Instant::now();
1314     let start_rss = get_resident_set_size();
1315     init_rustc_env_logger();
1316     signal_handler::install();
1317     let mut callbacks = TimePassesCallbacks::default();
1318     install_ice_hook();
1319     let exit_code = catch_with_exit_code(|| {
1320         let args = env::args_os()
1321             .enumerate()
1322             .map(|(i, arg)| {
1323                 arg.into_string().unwrap_or_else(|arg| {
1324                     early_error(
1325                         ErrorOutputType::default(),
1326                         &format!("argument {} is not valid Unicode: {:?}", i, arg),
1327                     )
1328                 })
1329             })
1330             .collect::<Vec<_>>();
1331         RunCompiler::new(&args, &mut callbacks).run()
1332     });
1333
1334     if callbacks.time_passes {
1335         let end_rss = get_resident_set_size();
1336         print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1337     }
1338
1339     process::exit(exit_code)
1340 }