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