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