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