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