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