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