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