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