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