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