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