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