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