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