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