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