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