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