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