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