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