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