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;
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 // Parse args and run the compiler. This is the primary entry point for rustc.
144 // See comments on CompilerCalls below for details about the callbacks argument.
145 // The FileLoader provides a way to load files from sources other than the file system.
148 callbacks: &mut (dyn Callbacks + Send),
149 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
150 emitter: Option<Box<dyn Write + Send>>
151 ) -> interface::Result<()> {
152 let mut args = Vec::new();
154 match args::arg_expand(arg.clone()) {
155 Ok(arg) => args.extend(arg),
156 Err(err) => early_error(ErrorOutputType::default(),
157 &format!("Failed to load argument file: {}", err)),
160 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
161 .unwrap_or(DiagnosticOutput::Default);
162 let matches = match handle_options(&args) {
163 Some(matches) => matches,
164 None => return Ok(()),
167 let sopts = config::build_session_options(&matches);
168 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
170 let mut dummy_config = |sopts, cfg, diagnostic_output| {
171 let mut config = interface::Config {
174 input: Input::File(PathBuf::new()),
182 lint_caps: Default::default(),
183 register_lints: None,
185 callbacks.config(&mut config);
189 if let Some(ref code) = matches.opt_str("explain") {
190 handle_explain(code, sopts.error_format);
194 let (odir, ofile) = make_output(&matches);
195 let (input, input_file_path, input_err) = match make_input(&matches.free) {
198 match matches.free.len() {
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(),
215 let should_stop = RustcDefaultCalls::print_crate_info(
216 &***compiler.codegen_backend(),
223 if should_stop == Compilation::Stop {
226 early_error(sopts.error_format, "no input filename given")
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 `{}`)",
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());
246 return Err(ErrorReported);
249 let mut config = interface::Config {
253 input_path: input_file_path,
260 lint_caps: Default::default(),
261 register_lints: None,
264 callbacks.config(&mut config);
266 interface::run_compiler(config, |compiler| {
267 let sess = compiler.session();
268 let should_stop = RustcDefaultCalls::print_crate_info(
269 &***compiler.codegen_backend(),
271 Some(compiler.input()),
272 compiler.output_dir(),
273 compiler.output_file(),
274 ).and_then(|| RustcDefaultCalls::list_metadata(
276 &*compiler.codegen_backend().metadata_loader(),
281 if should_stop == Compilation::Stop {
282 return sess.compile_status();
287 if let Some((ppm, opt_uii)) = &sess.opts.pretty {
288 if ppm.needs_ast_map(&opt_uii) {
289 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
290 let expanded_crate = compiler.expansion()?.take().0;
291 pretty::print_after_hir_lowering(
297 compiler.output_file().as_ref().map(|p| &**p),
302 let krate = compiler.parse()?.take();
303 pretty::print_after_parsing(
308 compiler.output_file().as_ref().map(|p| &**p),
311 return sess.compile_status();
314 if callbacks.after_parsing(compiler) == Compilation::Stop {
315 return sess.compile_status();
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();
325 let (_, _, lint_store) = &*compiler.register_plugins()?.peek();
327 // Lint plugins are registered; now we can process command line flags.
328 if sess.opts.describe_lints {
329 describe_lints(&sess, &lint_store, true);
330 return sess.compile_status();
334 compiler.expansion()?;
335 if callbacks.after_expansion(compiler) == Compilation::Stop {
336 return sess.compile_status();
339 compiler.prepare_outputs()?;
341 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
342 && sess.opts.output_types.len() == 1
344 return sess.compile_status();
347 compiler.global_ctxt()?;
349 if sess.opts.debugging_opts.no_analysis ||
350 sess.opts.debugging_opts.ast_json {
351 return sess.compile_status();
354 if sess.opts.debugging_opts.save_analysis {
355 let expanded_crate = &compiler.expansion()?.peek().0;
356 let crate_name = compiler.crate_name()?.peek().clone();
357 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
358 let result = tcx.analysis(LOCAL_CRATE);
360 time(sess, "save analysis", || {
367 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
372 // AST will be dropped *after* the `after_analysis` callback
373 // (needed by the RLS)
376 // Drop AST after creating GlobalCtxt to free memory
377 mem::drop(compiler.expansion()?.take());
380 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
382 if callbacks.after_analysis(compiler) == Compilation::Stop {
383 return sess.compile_status();
386 if sess.opts.debugging_opts.save_analysis {
387 mem::drop(compiler.expansion()?.take());
390 compiler.ongoing_codegen()?;
392 // Drop GlobalCtxt after starting codegen to free memory
393 mem::drop(compiler.global_ctxt()?.take());
395 if sess.opts.debugging_opts.print_type_sizes {
396 sess.code_stats.print_type_sizes();
401 if sess.opts.debugging_opts.perf_stats {
402 sess.print_perf_stats();
405 if sess.print_fuel_crate.is_some() {
406 eprintln!("Fuel used by {}: {}",
407 sess.print_fuel_crate.as_ref().unwrap(),
408 sess.print_fuel.load(SeqCst));
416 pub fn set_sigpipe_handler() {
418 // Set the SIGPIPE signal handler, so that an EPIPE
419 // will cause rustc to terminate, as expected.
420 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
425 pub fn set_sigpipe_handler() {}
427 // Extract output directory and file from matches.
428 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
429 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
430 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
434 // Extract input (string or file and optional path) from matches.
435 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
436 if free_matches.len() == 1 {
437 let ifile = &free_matches[0];
439 let mut src = String::new();
440 let err = if io::stdin().read_to_string(&mut src).is_err() {
441 Some(io::Error::new(io::ErrorKind::InvalidData,
442 "couldn't read from stdin, as it did not contain valid UTF-8"))
446 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
447 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").
448 expect("when UNSTABLE_RUSTDOC_TEST_PATH is set \
449 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set");
450 let line = isize::from_str_radix(&line, 10).
451 expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
452 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
453 return Some((Input::Str { name: file_name, input: src }, None, err));
455 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
458 Some((Input::File(PathBuf::from(ifile)),
459 Some(PathBuf::from(ifile)), None))
466 // Whether to stop or continue compilation.
467 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
468 pub enum Compilation {
474 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
476 Compilation::Stop => Compilation::Stop,
477 Compilation::Continue => next(),
482 /// CompilerCalls instance for a regular rustc build.
483 #[derive(Copy, Clone)]
484 pub struct RustcDefaultCalls;
486 // FIXME remove these and use winapi 0.3 instead
487 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
489 fn stdout_isatty() -> bool {
490 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
494 fn stdout_isatty() -> bool {
497 type HANDLE = *mut u8;
498 type LPDWORD = *mut u32;
499 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
501 fn GetStdHandle(which: DWORD) -> HANDLE;
502 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
505 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
507 GetConsoleMode(handle, &mut out) != 0
511 fn handle_explain(code: &str,
512 output: ErrorOutputType) {
513 let descriptions = rustc_interface::util::diagnostics_registry();
514 let normalised = if code.starts_with("E") {
517 format!("E{0:0>4}", code)
519 match descriptions.find_description(&normalised) {
520 Some(ref description) => {
521 let mut is_in_code_block = false;
522 let mut text = String::new();
524 // Slice off the leading newline and print.
525 for line in description[1..].lines() {
526 let indent_level = line.find(|c: char| !c.is_whitespace())
527 .unwrap_or_else(|| line.len());
528 let dedented_line = &line[indent_level..];
529 if dedented_line.starts_with("```") {
530 is_in_code_block = !is_in_code_block;
531 text.push_str(&line[..(indent_level+3)]);
532 } else if is_in_code_block && dedented_line.starts_with("# ") {
541 show_content_with_pager(&text);
547 early_error(output, &format!("no extended information for {}", code));
552 fn show_content_with_pager(content: &String) {
553 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
554 OsString::from("more.com")
556 OsString::from("less")
559 let mut fallback_to_println = false;
561 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
563 if let Some(pipe) = pager.stdin.as_mut() {
564 if pipe.write_all(content.as_bytes()).is_err() {
565 fallback_to_println = true;
569 if pager.wait().is_err() {
570 fallback_to_println = true;
574 fallback_to_println = true;
578 // If pager fails for whatever reason, we should still print the content
579 // to standard output
580 if fallback_to_println {
581 print!("{}", content);
585 impl RustcDefaultCalls {
586 pub fn list_metadata(sess: &Session,
587 metadata_loader: &dyn MetadataLoader,
588 matches: &getopts::Matches,
591 let r = matches.opt_strs("Z");
592 if r.iter().any(|s| *s == "ls") {
594 &Input::File(ref ifile) => {
595 let path = &(*ifile);
596 let mut v = Vec::new();
597 locator::list_file_metadata(&sess.target.target,
602 println!("{}", String::from_utf8(v).unwrap());
604 &Input::Str { .. } => {
605 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
608 return Compilation::Stop;
611 Compilation::Continue
615 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
617 input: Option<&Input>,
618 odir: &Option<PathBuf>,
619 ofile: &Option<PathBuf>)
621 use rustc::session::config::PrintRequest::*;
622 // PrintRequest::NativeStaticLibs is special - printed during linking
623 // (empty iterator returns true)
624 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
625 return Compilation::Continue;
628 let attrs = match input {
631 let result = parse_crate_attrs(sess, input);
633 Ok(attrs) => Some(attrs),
634 Err(mut parse_error) => {
636 return Compilation::Stop;
641 for req in &sess.opts.prints {
644 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
646 println!("{}", targets.join("\n"));
648 Sysroot => println!("{}", sess.sysroot.display()),
649 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
650 FileNames | CrateName => {
651 let input = input.unwrap_or_else(||
652 early_error(ErrorOutputType::default(), "no input file provided"));
653 let attrs = attrs.as_ref().unwrap();
654 let t_outputs = rustc_interface::util::build_output_filenames(
661 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
662 if *req == PrintRequest::CrateName {
666 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
667 for &style in &crate_types {
668 let fname = rustc_codegen_utils::link::filename_for_input(
674 println!("{}", fname.file_name().unwrap().to_string_lossy());
678 let allow_unstable_cfg = UnstableFeatures::from_environment()
681 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
682 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
683 path: ast::Path::from_ident(ast::Ident::with_dummy_span(name)),
684 kind: ast::MetaItemKind::Word,
688 // Note that crt-static is a specially recognized cfg
689 // directive that's printed out here as part of
690 // rust-lang/rust#37406, but in general the
691 // `target_feature` cfg is gated under
692 // rust-lang/rust#29717. For now this is just
693 // specifically allowing the crt-static cfg and that's
694 // it, this is intended to get into Cargo and then go
695 // through to build scripts.
696 let value = value.as_ref().map(|s| s.as_str());
697 let value = value.as_ref().map(|s| s.as_ref());
698 if name != sym::target_feature || value != Some("crt-static") {
699 if !allow_unstable_cfg && gated_cfg.is_some() {
704 if let Some(value) = value {
705 Some(format!("{}=\"{}\"", name, value))
707 Some(name.to_string())
709 }).collect::<Vec<String>>();
716 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
717 codegen_backend.print(*req, sess);
719 // Any output here interferes with Cargo's parsing of other printed output
720 PrintRequest::NativeStaticLibs => {}
723 return Compilation::Stop;
727 /// Returns a version string such as "0.12.0-dev".
728 fn release_str() -> Option<&'static str> {
729 option_env!("CFG_RELEASE")
732 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
733 fn commit_hash_str() -> Option<&'static str> {
734 option_env!("CFG_VER_HASH")
737 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
738 fn commit_date_str() -> Option<&'static str> {
739 option_env!("CFG_VER_DATE")
742 /// Prints version information
743 pub fn version(binary: &str, matches: &getopts::Matches) {
744 let verbose = matches.opt_present("verbose");
746 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
749 fn unw(x: Option<&str>) -> &str {
750 x.unwrap_or("unknown")
752 println!("binary: {}", binary);
753 println!("commit-hash: {}", unw(commit_hash_str()));
754 println!("commit-date: {}", unw(commit_date_str()));
755 println!("host: {}", config::host_triple());
756 println!("release: {}", unw(release_str()));
757 get_codegen_sysroot("llvm")().print_version();
761 fn usage(verbose: bool, include_unstable_options: bool) {
762 let groups = if verbose {
763 config::rustc_optgroups()
765 config::rustc_short_optgroups()
767 let mut options = getopts::Options::new();
768 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
769 (option.apply)(&mut options);
771 let message = "Usage: rustc [OPTIONS] INPUT";
772 let nightly_help = if nightly_options::is_nightly_build() {
773 "\n -Z help Print unstable compiler options"
777 let verbose_help = if verbose {
780 "\n --help -v Print the full set of options rustc accepts"
782 let at_path = if verbose && nightly_options::is_nightly_build() {
783 " @path Read newline separated options from `path`\n"
787 println!("{options}{at_path}\nAdditional help:
788 -C help Print codegen options
790 Print 'lint' options and default settings{nightly}{verbose}\n",
791 options = options.usage(message),
793 nightly = nightly_help,
794 verbose = verbose_help);
797 fn print_wall_help() {
799 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
800 default. Use `rustc -W help` to see all available lints. It's more common to put
801 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
802 the command line flag directly.
806 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
808 Available lint options:
809 -W <foo> Warn about <foo>
813 -F <foo> Forbid <foo> \
814 (deny <foo> and all attempts to override)
818 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
819 // The sort doesn't case-fold but it's doubtful we care.
820 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
824 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
825 -> Vec<(&'static str, Vec<lint::LintId>)> {
826 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
827 lints.sort_by_key(|l| l.0);
831 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
834 .partition(|&lint| lint.is_plugin);
835 let plugin = sort_lints(sess, plugin);
836 let builtin = sort_lints(sess, builtin);
838 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
841 .partition(|&(.., p)| p);
842 let plugin_groups = sort_lint_groups(plugin_groups);
843 let builtin_groups = sort_lint_groups(builtin_groups);
845 let max_name_len = plugin.iter()
847 .map(|&s| s.name.chars().count())
850 let padded = |x: &str| {
851 let mut s = " ".repeat(max_name_len - x.chars().count());
856 println!("Lint checks provided by rustc:\n");
857 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
858 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
860 let print_lints = |lints: Vec<&Lint>| {
862 let name = lint.name_lower().replace("_", "-");
863 println!(" {} {:7.7} {}",
865 lint.default_level.as_str(),
871 print_lints(builtin);
873 let max_name_len = max("warnings".len(),
875 .chain(&builtin_groups)
876 .map(|&(s, _)| s.chars().count())
880 let padded = |x: &str| {
881 let mut s = " ".repeat(max_name_len - x.chars().count());
886 println!("Lint groups provided by rustc:\n");
887 println!(" {} {}", padded("name"), "sub-lints");
888 println!(" {} {}", padded("----"), "---------");
889 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
891 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
892 for (name, to) in lints {
893 let name = name.to_lowercase().replace("_", "-");
894 let desc = to.into_iter()
895 .map(|x| x.to_string().replace("_", "-"))
896 .collect::<Vec<String>>()
898 println!(" {} {}", padded(&name), desc);
903 print_lint_groups(builtin_groups);
905 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
906 (false, 0, _) | (false, _, 0) => {
907 println!("Compiler plugins can provide additional lints and lint groups. To see a \
908 listing of these, re-run `rustc -W help` with a crate filename.");
910 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
911 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
914 println!("Lint checks provided by plugins loaded by this crate:\n");
918 println!("Lint groups provided by plugins loaded by this crate:\n");
919 print_lint_groups(plugin_groups);
925 fn describe_debug_flags() {
926 println!("\nAvailable options:\n");
927 print_flag_list("-Z", config::DB_OPTIONS);
930 fn describe_codegen_flags() {
931 println!("\nAvailable codegen options:\n");
932 print_flag_list("-C", config::CG_OPTIONS);
935 fn print_flag_list<T>(cmdline_opt: &str,
936 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
937 let max_len = flag_list.iter()
938 .map(|&(name, _, opt_type_desc, _)| {
939 let extra_len = match opt_type_desc {
943 name.chars().count() + extra_len
948 for &(name, _, opt_type_desc, desc) in flag_list {
949 let (width, extra) = match opt_type_desc {
950 Some(..) => (max_len - 4, "=val"),
951 None => (max_len, ""),
953 println!(" {} {:>width$}{} -- {}",
955 name.replace("_", "-"),
962 /// Process command line options. Emits messages as appropriate. If compilation
963 /// should continue, returns a getopts::Matches object parsed from args,
964 /// otherwise returns `None`.
966 /// The compiler's handling of options is a little complicated as it ties into
967 /// our stability story. The current intention of each compiler option is to
968 /// have one of two modes:
970 /// 1. An option is stable and can be used everywhere.
971 /// 2. An option is unstable, and can only be used on nightly.
973 /// Like unstable library and language features, however, unstable options have
974 /// always required a form of "opt in" to indicate that you're using them. This
975 /// provides the easy ability to scan a code base to check to see if anything
976 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
978 /// All options behind `-Z` are considered unstable by default. Other top-level
979 /// options can also be considered unstable, and they were unlocked through the
980 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
981 /// instability in both cases, though.
983 /// So with all that in mind, the comments below have some more detail about the
984 /// contortions done here to get things to work out correctly.
985 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
986 // Throw away the first argument, the name of the binary
987 let args = &args[1..];
990 // user did not write `-v` nor `-Z unstable-options`, so do not
991 // include that extra information.
996 // Parse with *all* options defined in the compiler, we don't worry about
997 // option stability here we just want to parse as much as possible.
998 let mut options = getopts::Options::new();
999 for option in config::rustc_optgroups() {
1000 (option.apply)(&mut options);
1002 let matches = options.parse(args).unwrap_or_else(|f|
1003 early_error(ErrorOutputType::default(), &f.to_string()));
1005 // For all options we just parsed, we check a few aspects:
1007 // * If the option is stable, we're all good
1008 // * If the option wasn't passed, we're all good
1009 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1010 // ourselves), then we require the `-Z unstable-options` flag to unlock
1011 // this option that was passed.
1012 // * If we're a nightly compiler, then unstable options are now unlocked, so
1013 // we're good to go.
1014 // * Otherwise, if we're an unstable option then we generate an error
1015 // (unstable option being used on stable)
1016 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1018 if matches.opt_present("h") || matches.opt_present("help") {
1019 // Only show unstable options in --help if we accept unstable options.
1020 usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
1024 // Handle the special case of -Wall.
1025 let wall = matches.opt_strs("W");
1026 if wall.iter().any(|x| *x == "all") {
1031 // Don't handle -W help here, because we might first load plugins.
1032 let r = matches.opt_strs("Z");
1033 if r.iter().any(|x| *x == "help") {
1034 describe_debug_flags();
1038 let cg_flags = matches.opt_strs("C");
1040 if cg_flags.iter().any(|x| *x == "help") {
1041 describe_codegen_flags();
1045 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1046 early_warn(ErrorOutputType::default(),
1047 "the --no-stack-check flag is deprecated and does nothing");
1050 if cg_flags.iter().any(|x| *x == "passes=list") {
1051 get_codegen_sysroot("llvm")().print_passes();
1055 if matches.opt_present("version") {
1056 version("rustc", &matches);
1063 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1065 Input::File(ifile) => {
1066 rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1068 Input::Str { name, input } => {
1069 rustc_parse::parse_crate_attrs_from_source_str(
1078 /// Gets a list of extra command-line flags provided by the user, as strings.
1080 /// This function is used during ICEs to show more information useful for
1081 /// debugging, since some ICEs only happens with non-default compiler flags
1082 /// (and the users don't always report them).
1083 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1084 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1086 // Avoid printing help because of empty args. This can suggest the compiler
1087 // itself is not the program root (consider RLS).
1092 let matches = if let Some(matches) = handle_options(&args) {
1098 let mut result = Vec::new();
1099 let mut excluded_cargo_defaults = false;
1100 for flag in ICE_REPORT_COMPILER_FLAGS {
1101 let prefix = if flag.len() == 1 { "-" } else { "--" };
1103 for content in &matches.opt_strs(flag) {
1104 // Split always returns the first element
1105 let name = if let Some(first) = content.split('=').next() {
1111 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1117 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1118 result.push(format!("{}{} {}", prefix, flag, content));
1120 excluded_cargo_defaults = true;
1125 if !result.is_empty() {
1126 Some((result, excluded_cargo_defaults))
1132 /// Runs a closure and catches unwinds triggered by fatal errors.
1134 /// The compiler currently unwinds with a special sentinel value to abort
1135 /// compilation on fatal errors. This function catches that sentinel and turns
1136 /// the panic into a `Result` instead.
1137 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1138 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1139 if value.is::<errors::FatalErrorMarker>() {
1142 panic::resume_unwind(value);
1148 static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
1149 let hook = panic::take_hook();
1150 panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
1155 /// Prints the ICE message, including backtrace and query stack.
1157 /// The message will point the user at `bug_report_url` to report the ICE.
1159 /// When `install_ice_hook` is called, this function will be called as the panic
1161 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1162 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1163 (*DEFAULT_HOOK)(info);
1165 // Separate the output with an empty line
1168 let emitter = Box::new(errors::emitter::EmitterWriter::stderr(
1169 errors::ColorConfig::Auto,
1176 let handler = errors::Handler::with_emitter(true, None, emitter);
1178 // a .span_bug or .bug call has already printed what
1179 // it wants to print.
1180 if !info.payload().is::<errors::ExplicitBug>() {
1181 let d = errors::Diagnostic::new(errors::Level::Bug, "unexpected panic");
1182 handler.emit_diagnostic(&d);
1183 handler.abort_if_errors_and_should_abort();
1186 let mut xs: Vec<Cow<'static, str>> = vec![
1187 "the compiler unexpectedly panicked. this is a bug.".into(),
1188 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1189 format!("rustc {} running on {}",
1190 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1191 config::host_triple()).into(),
1194 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1195 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1197 if excluded_cargo_defaults {
1198 xs.push("some of the compiler flags provided by cargo are hidden".into());
1203 handler.note_without_error(¬e);
1206 // If backtraces are enabled, also print the query stack
1207 let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
1210 TyCtxt::try_print_query_stack(&handler);
1215 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1219 // Trigger a debugger if we crashed during bootstrap
1225 /// Installs a panic hook that will print the ICE message on unexpected panics.
1227 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1228 pub fn install_ice_hook() {
1229 lazy_static::initialize(&DEFAULT_HOOK);
1232 /// This allows tools to enable rust logging without having to magically match rustc's
1233 /// log crate version
1234 pub fn init_rustc_env_logger() {
1235 env_logger::init_from_env("RUSTC_LOG");
1239 let start = Instant::now();
1240 init_rustc_env_logger();
1241 let mut callbacks = TimePassesCallbacks::default();
1243 let result = catch_fatal_errors(|| {
1244 let args = env::args_os().enumerate()
1245 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1246 early_error(ErrorOutputType::default(),
1247 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1249 .collect::<Vec<_>>();
1250 run_compiler(&args, &mut callbacks, None, None)
1251 }).and_then(|result| result);
1252 let exit_code = match result {
1253 Ok(_) => EXIT_SUCCESS,
1254 Err(_) => EXIT_FAILURE,
1256 // The extra `\t` is necessary to align this label with the others.
1258 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1259 process::exit(exit_code);