5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![feature(box_syntax)]
10 #![cfg_attr(unix, feature(libc))]
12 #![feature(set_stdio)]
14 #![feature(integer_atomics)]
16 #![recursion_limit="256"]
18 pub extern crate getopts;
24 extern crate lazy_static;
26 pub extern crate rustc_plugin_impl as plugin;
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;
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;
48 use rustc_serialize::json::ToJson;
52 use std::default::Default;
54 use std::ffi::OsString;
55 use std::io::{self, Read, Write};
57 use std::panic::{self, catch_unwind};
58 use std::path::PathBuf;
59 use std::process::{self, Command, Stdio};
61 use std::time::Instant;
64 use syntax::source_map::FileLoader;
65 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
66 use syntax::symbol::sym;
67 use syntax_pos::{DUMMY_SP, FileName};
72 /// Exit status code used for successful compilation and help output.
73 pub const EXIT_SUCCESS: i32 = 0;
75 /// Exit status code used for compilation failures and invalid flags.
76 pub const EXIT_FAILURE: i32 = 1;
78 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
81 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
83 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
85 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
87 pub fn source_name(input: &Input) -> FileName {
89 Input::File(ref ifile) => ifile.clone().into(),
90 Input::Str { ref name, .. } => name.clone(),
94 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
97 sess.abort_if_errors();
98 panic!("error reported but abort_if_errors didn't abort???");
104 pub trait Callbacks {
105 /// Called before creating the compiler instance
106 fn config(&mut self, _config: &mut interface::Config) {}
107 /// Called after parsing. Return value instructs the compiler whether to
108 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
109 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
110 Compilation::Continue
112 /// Called after expansion. Return value instructs the compiler whether to
113 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
114 fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
115 Compilation::Continue
117 /// Called after analysis. Return value instructs the compiler whether to
118 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
119 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
120 Compilation::Continue
124 pub struct DefaultCallbacks;
126 impl Callbacks for DefaultCallbacks {}
129 pub struct TimePassesCallbacks {
133 impl Callbacks for TimePassesCallbacks {
134 fn config(&mut self, config: &mut interface::Config) {
135 // If a --prints=... option has been given, we don't print the "total"
136 // time because it will mess up the --prints output. See #64339.
138 config.opts.prints.is_empty() &&
139 (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
143 pub fn diagnostics_registry() -> Registry {
144 Registry::new(&rustc_error_codes::DIAGNOSTICS)
147 // Parse args and run the compiler. This is the primary entry point for rustc.
148 // See comments on CompilerCalls below for details about the callbacks argument.
149 // The FileLoader provides a way to load files from sources other than the file system.
152 callbacks: &mut (dyn Callbacks + Send),
153 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
154 emitter: Option<Box<dyn Write + Send>>
155 ) -> interface::Result<()> {
156 let mut args = Vec::new();
158 match args::arg_expand(arg.clone()) {
159 Ok(arg) => args.extend(arg),
160 Err(err) => early_error(ErrorOutputType::default(),
161 &format!("Failed to load argument file: {}", err)),
164 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
165 .unwrap_or(DiagnosticOutput::Default);
166 let matches = match handle_options(&args) {
167 Some(matches) => matches,
168 None => return Ok(()),
171 let sopts = config::build_session_options(&matches);
172 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
174 let mut dummy_config = |sopts, cfg, diagnostic_output| {
175 let mut config = interface::Config {
178 input: Input::File(PathBuf::new()),
186 lint_caps: Default::default(),
187 register_lints: None,
188 override_queries: None,
189 registry: diagnostics_registry(),
191 callbacks.config(&mut config);
195 if let Some(ref code) = matches.opt_str("explain") {
196 handle_explain(diagnostics_registry(), code, sopts.error_format);
200 let (odir, ofile) = make_output(&matches);
201 let (input, input_file_path, input_err) = match make_input(&matches.free) {
204 match matches.free.len() {
206 let config = dummy_config(sopts, cfg, diagnostic_output);
207 interface::run_compiler(config, |compiler| {
208 let sopts = &compiler.session().opts;
209 if sopts.describe_lints {
210 let lint_store = rustc_lint::new_lint_store(
211 sopts.debugging_opts.no_interleave_lints,
212 compiler.session().unstable_options(),
221 let should_stop = RustcDefaultCalls::print_crate_info(
222 &***compiler.codegen_backend(),
229 if should_stop == Compilation::Stop {
232 early_error(sopts.error_format, "no input filename given")
236 1 => panic!("make_input should have provided valid inputs"),
237 _ => early_error(sopts.error_format, &format!(
238 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
246 if let Some(err) = input_err {
247 // Immediately stop compilation if there was an issue reading
248 // the input (for example if the input stream is not UTF-8).
249 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
250 compiler.session().err(&err.to_string());
252 return Err(ErrorReported);
255 let mut config = interface::Config {
259 input_path: input_file_path,
266 lint_caps: Default::default(),
267 register_lints: None,
268 override_queries: None,
269 registry: diagnostics_registry(),
272 callbacks.config(&mut config);
274 interface::run_compiler(config, |compiler| {
275 let sess = compiler.session();
276 let should_stop = RustcDefaultCalls::print_crate_info(
277 &***compiler.codegen_backend(),
279 Some(compiler.input()),
280 compiler.output_dir(),
281 compiler.output_file(),
282 ).and_then(|| RustcDefaultCalls::list_metadata(
284 &*compiler.codegen_backend().metadata_loader(),
289 if should_stop == Compilation::Stop {
290 return sess.compile_status();
295 if let Some((ppm, opt_uii)) = &sess.opts.pretty {
296 if ppm.needs_ast_map(&opt_uii) {
297 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
298 let expanded_crate = compiler.expansion()?.take().0;
299 pretty::print_after_hir_lowering(
305 compiler.output_file().as_ref().map(|p| &**p),
310 let krate = compiler.parse()?.take();
311 pretty::print_after_parsing(
316 compiler.output_file().as_ref().map(|p| &**p),
319 return sess.compile_status();
322 if callbacks.after_parsing(compiler) == Compilation::Stop {
323 return sess.compile_status();
326 if sess.opts.debugging_opts.parse_only ||
327 sess.opts.debugging_opts.show_span.is_some() ||
328 sess.opts.debugging_opts.ast_json_noexpand {
329 return sess.compile_status();
333 let (_, _, lint_store) = &*compiler.register_plugins()?.peek();
335 // Lint plugins are registered; now we can process command line flags.
336 if sess.opts.describe_lints {
337 describe_lints(&sess, &lint_store, true);
338 return sess.compile_status();
342 compiler.expansion()?;
343 if callbacks.after_expansion(compiler) == Compilation::Stop {
344 return sess.compile_status();
347 compiler.prepare_outputs()?;
349 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
350 && sess.opts.output_types.len() == 1
352 return sess.compile_status();
355 compiler.global_ctxt()?;
357 if sess.opts.debugging_opts.no_analysis ||
358 sess.opts.debugging_opts.ast_json {
359 return sess.compile_status();
362 if sess.opts.debugging_opts.save_analysis {
363 let expanded_crate = &compiler.expansion()?.peek().0;
364 let crate_name = compiler.crate_name()?.peek().clone();
365 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
366 let result = tcx.analysis(LOCAL_CRATE);
368 time(sess, "save analysis", || {
375 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
380 // AST will be dropped *after* the `after_analysis` callback
381 // (needed by the RLS)
384 // Drop AST after creating GlobalCtxt to free memory
385 mem::drop(compiler.expansion()?.take());
388 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
390 if callbacks.after_analysis(compiler) == Compilation::Stop {
391 return sess.compile_status();
394 if sess.opts.debugging_opts.save_analysis {
395 mem::drop(compiler.expansion()?.take());
398 compiler.ongoing_codegen()?;
400 // Drop GlobalCtxt after starting codegen to free memory
401 mem::drop(compiler.global_ctxt()?.take());
403 if sess.opts.debugging_opts.print_type_sizes {
404 sess.code_stats.print_type_sizes();
409 if sess.opts.debugging_opts.perf_stats {
410 sess.print_perf_stats();
413 if sess.print_fuel_crate.is_some() {
414 eprintln!("Fuel used by {}: {}",
415 sess.print_fuel_crate.as_ref().unwrap(),
416 sess.print_fuel.load(SeqCst));
424 pub fn set_sigpipe_handler() {
426 // Set the SIGPIPE signal handler, so that an EPIPE
427 // will cause rustc to terminate, as expected.
428 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
433 pub fn set_sigpipe_handler() {}
435 // Extract output directory and file from matches.
436 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
437 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
438 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
442 // Extract input (string or file and optional path) from matches.
443 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
444 if free_matches.len() == 1 {
445 let ifile = &free_matches[0];
447 let mut src = String::new();
448 let err = if io::stdin().read_to_string(&mut src).is_err() {
449 Some(io::Error::new(io::ErrorKind::InvalidData,
450 "couldn't read from stdin, as it did not contain valid UTF-8"))
454 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
455 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").
456 expect("when UNSTABLE_RUSTDOC_TEST_PATH is set \
457 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set");
458 let line = isize::from_str_radix(&line, 10).
459 expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
460 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
461 return Some((Input::Str { name: file_name, input: src }, None, err));
463 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
466 Some((Input::File(PathBuf::from(ifile)),
467 Some(PathBuf::from(ifile)), None))
474 // Whether to stop or continue compilation.
475 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
476 pub enum Compilation {
482 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
484 Compilation::Stop => Compilation::Stop,
485 Compilation::Continue => next(),
490 /// CompilerCalls instance for a regular rustc build.
491 #[derive(Copy, Clone)]
492 pub struct RustcDefaultCalls;
494 // FIXME remove these and use winapi 0.3 instead
495 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
497 fn stdout_isatty() -> bool {
498 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
502 fn stdout_isatty() -> bool {
505 type HANDLE = *mut u8;
506 type LPDWORD = *mut u32;
507 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
509 fn GetStdHandle(which: DWORD) -> HANDLE;
510 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
513 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
515 GetConsoleMode(handle, &mut out) != 0
519 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
520 let normalised = if code.starts_with("E") {
523 format!("E{0:0>4}", code)
525 match registry.find_description(&normalised) {
526 Some(ref description) => {
527 let mut is_in_code_block = false;
528 let mut text = String::new();
530 // Slice off the leading newline and print.
531 for line in description.lines() {
532 let indent_level = line.find(|c: char| !c.is_whitespace())
533 .unwrap_or_else(|| line.len());
534 let dedented_line = &line[indent_level..];
535 if dedented_line.starts_with("```") {
536 is_in_code_block = !is_in_code_block;
537 text.push_str(&line[..(indent_level + 3)]);
538 } else if is_in_code_block && dedented_line.starts_with("# ") {
547 show_content_with_pager(&text);
553 early_error(output, &format!("no extended information for {}", code));
558 fn show_content_with_pager(content: &String) {
559 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
560 OsString::from("more.com")
562 OsString::from("less")
565 let mut fallback_to_println = false;
567 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
569 if let Some(pipe) = pager.stdin.as_mut() {
570 if pipe.write_all(content.as_bytes()).is_err() {
571 fallback_to_println = true;
575 if pager.wait().is_err() {
576 fallback_to_println = true;
580 fallback_to_println = true;
584 // If pager fails for whatever reason, we should still print the content
585 // to standard output
586 if fallback_to_println {
587 print!("{}", content);
591 impl RustcDefaultCalls {
592 pub fn list_metadata(sess: &Session,
593 metadata_loader: &dyn MetadataLoader,
594 matches: &getopts::Matches,
597 let r = matches.opt_strs("Z");
598 if r.iter().any(|s| *s == "ls") {
600 &Input::File(ref ifile) => {
601 let path = &(*ifile);
602 let mut v = Vec::new();
603 locator::list_file_metadata(&sess.target.target,
608 println!("{}", String::from_utf8(v).unwrap());
610 &Input::Str { .. } => {
611 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
614 return Compilation::Stop;
617 Compilation::Continue
621 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
623 input: Option<&Input>,
624 odir: &Option<PathBuf>,
625 ofile: &Option<PathBuf>)
627 use rustc::session::config::PrintRequest::*;
628 // PrintRequest::NativeStaticLibs is special - printed during linking
629 // (empty iterator returns true)
630 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
631 return Compilation::Continue;
634 let attrs = match input {
637 let result = parse_crate_attrs(sess, input);
639 Ok(attrs) => Some(attrs),
640 Err(mut parse_error) => {
642 return Compilation::Stop;
647 for req in &sess.opts.prints {
650 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
652 println!("{}", targets.join("\n"));
654 Sysroot => println!("{}", sess.sysroot.display()),
655 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
656 FileNames | CrateName => {
657 let input = input.unwrap_or_else(||
658 early_error(ErrorOutputType::default(), "no input file provided"));
659 let attrs = attrs.as_ref().unwrap();
660 let t_outputs = rustc_interface::util::build_output_filenames(
667 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
668 if *req == PrintRequest::CrateName {
672 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
673 for &style in &crate_types {
674 let fname = rustc_codegen_utils::link::filename_for_input(
680 println!("{}", fname.file_name().unwrap().to_string_lossy());
684 let allow_unstable_cfg = UnstableFeatures::from_environment()
687 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
688 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
689 path: ast::Path::from_ident(ast::Ident::with_dummy_span(name)),
690 kind: ast::MetaItemKind::Word,
694 // Note that crt-static is a specially recognized cfg
695 // directive that's printed out here as part of
696 // rust-lang/rust#37406, but in general the
697 // `target_feature` cfg is gated under
698 // rust-lang/rust#29717. For now this is just
699 // specifically allowing the crt-static cfg and that's
700 // it, this is intended to get into Cargo and then go
701 // through to build scripts.
702 let value = value.as_ref().map(|s| s.as_str());
703 let value = value.as_ref().map(|s| s.as_ref());
704 if name != sym::target_feature || value != Some("crt-static") {
705 if !allow_unstable_cfg && gated_cfg.is_some() {
710 if let Some(value) = value {
711 Some(format!("{}=\"{}\"", name, value))
713 Some(name.to_string())
715 }).collect::<Vec<String>>();
722 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
723 codegen_backend.print(*req, sess);
725 // Any output here interferes with Cargo's parsing of other printed output
726 PrintRequest::NativeStaticLibs => {}
729 return Compilation::Stop;
733 /// Returns a version string such as "0.12.0-dev".
734 fn release_str() -> Option<&'static str> {
735 option_env!("CFG_RELEASE")
738 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
739 fn commit_hash_str() -> Option<&'static str> {
740 option_env!("CFG_VER_HASH")
743 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
744 fn commit_date_str() -> Option<&'static str> {
745 option_env!("CFG_VER_DATE")
748 /// Prints version information
749 pub fn version(binary: &str, matches: &getopts::Matches) {
750 let verbose = matches.opt_present("verbose");
752 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
755 fn unw(x: Option<&str>) -> &str {
756 x.unwrap_or("unknown")
758 println!("binary: {}", binary);
759 println!("commit-hash: {}", unw(commit_hash_str()));
760 println!("commit-date: {}", unw(commit_date_str()));
761 println!("host: {}", config::host_triple());
762 println!("release: {}", unw(release_str()));
763 get_codegen_sysroot("llvm")().print_version();
767 fn usage(verbose: bool, include_unstable_options: bool) {
768 let groups = if verbose {
769 config::rustc_optgroups()
771 config::rustc_short_optgroups()
773 let mut options = getopts::Options::new();
774 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
775 (option.apply)(&mut options);
777 let message = "Usage: rustc [OPTIONS] INPUT";
778 let nightly_help = if nightly_options::is_nightly_build() {
779 "\n -Z help Print unstable compiler options"
783 let verbose_help = if verbose {
786 "\n --help -v Print the full set of options rustc accepts"
788 let at_path = if verbose && nightly_options::is_nightly_build() {
789 " @path Read newline separated options from `path`\n"
793 println!("{options}{at_path}\nAdditional help:
794 -C help Print codegen options
796 Print 'lint' options and default settings{nightly}{verbose}\n",
797 options = options.usage(message),
799 nightly = nightly_help,
800 verbose = verbose_help);
803 fn print_wall_help() {
805 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
806 default. Use `rustc -W help` to see all available lints. It's more common to put
807 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
808 the command line flag directly.
812 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
814 Available lint options:
815 -W <foo> Warn about <foo>
819 -F <foo> Forbid <foo> \
820 (deny <foo> and all attempts to override)
824 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
825 // The sort doesn't case-fold but it's doubtful we care.
826 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
830 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
831 -> Vec<(&'static str, Vec<lint::LintId>)> {
832 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
833 lints.sort_by_key(|l| l.0);
837 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
840 .partition(|&lint| lint.is_plugin);
841 let plugin = sort_lints(sess, plugin);
842 let builtin = sort_lints(sess, builtin);
844 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
847 .partition(|&(.., p)| p);
848 let plugin_groups = sort_lint_groups(plugin_groups);
849 let builtin_groups = sort_lint_groups(builtin_groups);
851 let max_name_len = plugin.iter()
853 .map(|&s| s.name.chars().count())
856 let padded = |x: &str| {
857 let mut s = " ".repeat(max_name_len - x.chars().count());
862 println!("Lint checks provided by rustc:\n");
863 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
864 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
866 let print_lints = |lints: Vec<&Lint>| {
868 let name = lint.name_lower().replace("_", "-");
869 println!(" {} {:7.7} {}",
871 lint.default_level.as_str(),
877 print_lints(builtin);
879 let max_name_len = max("warnings".len(),
881 .chain(&builtin_groups)
882 .map(|&(s, _)| s.chars().count())
886 let padded = |x: &str| {
887 let mut s = " ".repeat(max_name_len - x.chars().count());
892 println!("Lint groups provided by rustc:\n");
893 println!(" {} {}", padded("name"), "sub-lints");
894 println!(" {} {}", padded("----"), "---------");
895 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
897 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
898 for (name, to) in lints {
899 let name = name.to_lowercase().replace("_", "-");
900 let desc = to.into_iter()
901 .map(|x| x.to_string().replace("_", "-"))
902 .collect::<Vec<String>>()
904 println!(" {} {}", padded(&name), desc);
909 print_lint_groups(builtin_groups);
911 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
912 (false, 0, _) | (false, _, 0) => {
913 println!("Compiler plugins can provide additional lints and lint groups. To see a \
914 listing of these, re-run `rustc -W help` with a crate filename.");
916 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
917 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
920 println!("Lint checks provided by plugins loaded by this crate:\n");
924 println!("Lint groups provided by plugins loaded by this crate:\n");
925 print_lint_groups(plugin_groups);
931 fn describe_debug_flags() {
932 println!("\nAvailable options:\n");
933 print_flag_list("-Z", config::DB_OPTIONS);
936 fn describe_codegen_flags() {
937 println!("\nAvailable codegen options:\n");
938 print_flag_list("-C", config::CG_OPTIONS);
941 fn print_flag_list<T>(cmdline_opt: &str,
942 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
943 let max_len = flag_list.iter()
944 .map(|&(name, _, opt_type_desc, _)| {
945 let extra_len = match opt_type_desc {
949 name.chars().count() + extra_len
954 for &(name, _, opt_type_desc, desc) in flag_list {
955 let (width, extra) = match opt_type_desc {
956 Some(..) => (max_len - 4, "=val"),
957 None => (max_len, ""),
959 println!(" {} {:>width$}{} -- {}",
961 name.replace("_", "-"),
968 /// Process command line options. Emits messages as appropriate. If compilation
969 /// should continue, returns a getopts::Matches object parsed from args,
970 /// otherwise returns `None`.
972 /// The compiler's handling of options is a little complicated as it ties into
973 /// our stability story. The current intention of each compiler option is to
974 /// have one of two modes:
976 /// 1. An option is stable and can be used everywhere.
977 /// 2. An option is unstable, and can only be used on nightly.
979 /// Like unstable library and language features, however, unstable options have
980 /// always required a form of "opt in" to indicate that you're using them. This
981 /// provides the easy ability to scan a code base to check to see if anything
982 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
984 /// All options behind `-Z` are considered unstable by default. Other top-level
985 /// options can also be considered unstable, and they were unlocked through the
986 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
987 /// instability in both cases, though.
989 /// So with all that in mind, the comments below have some more detail about the
990 /// contortions done here to get things to work out correctly.
991 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
992 // Throw away the first argument, the name of the binary
993 let args = &args[1..];
996 // user did not write `-v` nor `-Z unstable-options`, so do not
997 // include that extra information.
1002 // Parse with *all* options defined in the compiler, we don't worry about
1003 // option stability here we just want to parse as much as possible.
1004 let mut options = getopts::Options::new();
1005 for option in config::rustc_optgroups() {
1006 (option.apply)(&mut options);
1008 let matches = options.parse(args).unwrap_or_else(|f|
1009 early_error(ErrorOutputType::default(), &f.to_string()));
1011 // For all options we just parsed, we check a few aspects:
1013 // * If the option is stable, we're all good
1014 // * If the option wasn't passed, we're all good
1015 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1016 // ourselves), then we require the `-Z unstable-options` flag to unlock
1017 // this option that was passed.
1018 // * If we're a nightly compiler, then unstable options are now unlocked, so
1019 // we're good to go.
1020 // * Otherwise, if we're an unstable option then we generate an error
1021 // (unstable option being used on stable)
1022 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1024 if matches.opt_present("h") || matches.opt_present("help") {
1025 // Only show unstable options in --help if we accept unstable options.
1026 usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
1030 // Handle the special case of -Wall.
1031 let wall = matches.opt_strs("W");
1032 if wall.iter().any(|x| *x == "all") {
1037 // Don't handle -W help here, because we might first load plugins.
1038 let r = matches.opt_strs("Z");
1039 if r.iter().any(|x| *x == "help") {
1040 describe_debug_flags();
1044 let cg_flags = matches.opt_strs("C");
1046 if cg_flags.iter().any(|x| *x == "help") {
1047 describe_codegen_flags();
1051 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1052 early_warn(ErrorOutputType::default(),
1053 "the --no-stack-check flag is deprecated and does nothing");
1056 if cg_flags.iter().any(|x| *x == "passes=list") {
1057 get_codegen_sysroot("llvm")().print_passes();
1061 if matches.opt_present("version") {
1062 version("rustc", &matches);
1069 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1071 Input::File(ifile) => {
1072 rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1074 Input::Str { name, input } => {
1075 rustc_parse::parse_crate_attrs_from_source_str(
1084 /// Gets a list of extra command-line flags provided by the user, as strings.
1086 /// This function is used during ICEs to show more information useful for
1087 /// debugging, since some ICEs only happens with non-default compiler flags
1088 /// (and the users don't always report them).
1089 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1090 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1092 // Avoid printing help because of empty args. This can suggest the compiler
1093 // itself is not the program root (consider RLS).
1098 let matches = if let Some(matches) = handle_options(&args) {
1104 let mut result = Vec::new();
1105 let mut excluded_cargo_defaults = false;
1106 for flag in ICE_REPORT_COMPILER_FLAGS {
1107 let prefix = if flag.len() == 1 { "-" } else { "--" };
1109 for content in &matches.opt_strs(flag) {
1110 // Split always returns the first element
1111 let name = if let Some(first) = content.split('=').next() {
1117 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1123 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1124 result.push(format!("{}{} {}", prefix, flag, content));
1126 excluded_cargo_defaults = true;
1131 if !result.is_empty() {
1132 Some((result, excluded_cargo_defaults))
1138 /// Runs a closure and catches unwinds triggered by fatal errors.
1140 /// The compiler currently unwinds with a special sentinel value to abort
1141 /// compilation on fatal errors. This function catches that sentinel and turns
1142 /// the panic into a `Result` instead.
1143 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1144 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1145 if value.is::<errors::FatalErrorMarker>() {
1148 panic::resume_unwind(value);
1154 static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
1155 let hook = panic::take_hook();
1156 panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
1161 /// Prints the ICE message, including backtrace and query stack.
1163 /// The message will point the user at `bug_report_url` to report the ICE.
1165 /// When `install_ice_hook` is called, this function will be called as the panic
1167 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1168 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1169 (*DEFAULT_HOOK)(info);
1171 // Separate the output with an empty line
1174 let emitter = Box::new(errors::emitter::EmitterWriter::stderr(
1175 errors::ColorConfig::Auto,
1182 let handler = errors::Handler::with_emitter(true, None, emitter);
1184 // a .span_bug or .bug call has already printed what
1185 // it wants to print.
1186 if !info.payload().is::<errors::ExplicitBug>() {
1187 let d = errors::Diagnostic::new(errors::Level::Bug, "unexpected panic");
1188 handler.emit_diagnostic(&d);
1189 handler.abort_if_errors_and_should_abort();
1192 let mut xs: Vec<Cow<'static, str>> = vec![
1193 "the compiler unexpectedly panicked. this is a bug.".into(),
1194 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1195 format!("rustc {} running on {}",
1196 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1197 config::host_triple()).into(),
1200 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1201 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1203 if excluded_cargo_defaults {
1204 xs.push("some of the compiler flags provided by cargo are hidden".into());
1209 handler.note_without_error(¬e);
1212 // If backtraces are enabled, also print the query stack
1213 let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
1216 TyCtxt::try_print_query_stack(&handler);
1221 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1225 // Trigger a debugger if we crashed during bootstrap
1231 /// Installs a panic hook that will print the ICE message on unexpected panics.
1233 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1234 pub fn install_ice_hook() {
1235 lazy_static::initialize(&DEFAULT_HOOK);
1238 /// This allows tools to enable rust logging without having to magically match rustc's
1239 /// log crate version
1240 pub fn init_rustc_env_logger() {
1241 env_logger::init_from_env("RUSTC_LOG");
1245 let start = Instant::now();
1246 init_rustc_env_logger();
1247 let mut callbacks = TimePassesCallbacks::default();
1249 let result = catch_fatal_errors(|| {
1250 let args = env::args_os().enumerate()
1251 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1252 early_error(ErrorOutputType::default(),
1253 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1255 .collect::<Vec<_>>();
1256 run_compiler(&args, &mut callbacks, None, None)
1257 }).and_then(|result| result);
1258 let exit_code = match result {
1259 Ok(_) => EXIT_SUCCESS,
1260 Err(_) => EXIT_FAILURE,
1262 // The extra `\t` is necessary to align this label with the others.
1264 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1265 process::exit(exit_code);