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(rustc_diagnostic_macros)]
13 #![feature(set_stdio)]
15 #![feature(integer_atomics)]
17 #![recursion_limit="256"]
19 #![deny(rust_2018_idioms)]
21 pub extern crate getopts;
27 use pretty::{PpMode, UserIdentifiedItem};
29 //use rustc_resolve as resolve;
30 use rustc_save_analysis as save;
31 use rustc_save_analysis::DumpHandler;
32 use rustc::session::{config, Session, DiagnosticOutput};
33 use rustc::session::config::{Input, PrintRequest, ErrorOutputType, OutputType};
34 use rustc::session::config::nightly_options;
35 use rustc::session::{early_error, early_warn};
36 use rustc::lint::Lint;
38 use rustc::hir::def_id::LOCAL_CRATE;
39 use rustc::util::common::{time, ErrorReported, install_panic_hook};
40 use rustc_metadata::locator;
41 use rustc_metadata::cstore::CStore;
42 use rustc_codegen_utils::codegen_backend::CodegenBackend;
43 use rustc_interface::interface;
44 use rustc_interface::util::get_codegen_sysroot;
45 use rustc_data_structures::sync::SeqCst;
47 use serialize::json::ToJson;
51 use std::default::Default;
53 use std::ffi::OsString;
54 use std::io::{self, Read, Write};
55 use std::panic::{self, catch_unwind};
56 use std::path::PathBuf;
57 use std::process::{self, Command, Stdio};
62 use syntax::source_map::FileLoader;
63 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
64 use syntax::parse::{self, PResult};
65 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
69 /// Exit status code used for successful compilation and help output.
70 pub const EXIT_SUCCESS: i32 = 0;
72 /// Exit status code used for compilation failures and invalid flags.
73 pub const EXIT_FAILURE: i32 = 1;
75 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
78 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
80 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
82 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
84 pub fn source_name(input: &Input) -> FileName {
86 Input::File(ref ifile) => ifile.clone().into(),
87 Input::Str { ref name, .. } => name.clone(),
91 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
94 sess.abort_if_errors();
95 panic!("error reported but abort_if_errors didn't abort???");
101 pub trait Callbacks {
102 /// Called before creating the compiler instance
103 fn config(&mut self, _config: &mut interface::Config) {}
104 /// Called after parsing and returns true to continue execution
105 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> bool {
108 /// Called after analysis and returns true to continue execution
109 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> bool {
114 pub struct DefaultCallbacks;
116 impl Callbacks for DefaultCallbacks {}
118 // Parse args and run the compiler. This is the primary entry point for rustc.
119 // See comments on CompilerCalls below for details about the callbacks argument.
120 // The FileLoader provides a way to load files from sources other than the file system.
123 callbacks: &mut (dyn Callbacks + Send),
124 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
125 emitter: Option<Box<dyn Write + Send>>
126 ) -> interface::Result<()> {
127 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
128 .unwrap_or(DiagnosticOutput::Default);
129 let matches = match handle_options(args) {
130 Some(matches) => matches,
131 None => return Ok(()),
134 install_panic_hook();
136 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
138 let mut dummy_config = |sopts, cfg, diagnostic_output| {
139 let mut config = interface::Config {
142 input: Input::File(PathBuf::new()),
150 lint_caps: Default::default(),
152 callbacks.config(&mut config);
156 if let Some(ref code) = matches.opt_str("explain") {
157 handle_explain(code, sopts.error_format);
161 let (odir, ofile) = make_output(&matches);
162 let (input, input_file_path, input_err) = match make_input(&matches.free) {
165 match matches.free.len() {
167 let config = dummy_config(sopts, cfg, diagnostic_output);
168 interface::run_compiler(config, |compiler| {
169 let sopts = &compiler.session().opts;
170 if sopts.describe_lints {
173 &*compiler.session().lint_store.borrow(),
178 let should_stop = RustcDefaultCalls::print_crate_info(
179 &***compiler.codegen_backend(),
186 if should_stop == Compilation::Stop {
189 early_error(sopts.error_format, "no input filename given")
193 1 => panic!("make_input should have provided valid inputs"),
194 _ => early_error(sopts.error_format, &format!(
195 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
203 if let Some(err) = input_err {
204 // Immediately stop compilation if there was an issue reading
205 // the input (for example if the input stream is not UTF-8).
206 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
207 compiler.session().err(&err.to_string());
209 return Err(ErrorReported);
212 let mut config = interface::Config {
216 input_path: input_file_path,
223 lint_caps: Default::default(),
226 callbacks.config(&mut config);
228 interface::run_compiler(config, |compiler| {
229 let sess = compiler.session();
230 let should_stop = RustcDefaultCalls::print_crate_info(
231 &***compiler.codegen_backend(),
233 Some(compiler.input()),
234 compiler.output_dir(),
235 compiler.output_file(),
236 ).and_then(|| RustcDefaultCalls::list_metadata(
243 if should_stop == Compilation::Stop {
244 return sess.compile_status();
247 let pretty_info = parse_pretty(sess, &matches);
251 if let Some((ppm, opt_uii)) = pretty_info {
252 if ppm.needs_ast_map(&opt_uii) {
253 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
254 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
255 let expanded_crate = compiler.expansion()?.take().0;
256 pretty::print_after_hir_lowering(
262 compiler.output_file().as_ref().map(|p| &**p),
266 return sess.compile_status();
268 let mut krate = compiler.parse()?.take();
269 pretty::visit_crate(sess, &mut krate, ppm);
270 pretty::print_after_parsing(
275 compiler.output_file().as_ref().map(|p| &**p),
277 return sess.compile_status();
281 if !callbacks.after_parsing(compiler) {
282 return sess.compile_status();
285 if sess.opts.debugging_opts.parse_only ||
286 sess.opts.debugging_opts.show_span.is_some() ||
287 sess.opts.debugging_opts.ast_json_noexpand {
288 return sess.compile_status();
291 compiler.register_plugins()?;
293 // Lint plugins are registered; now we can process command line flags.
294 if sess.opts.describe_lints {
295 describe_lints(&sess, &sess.lint_store.borrow(), true);
296 return sess.compile_status();
299 compiler.prepare_outputs()?;
301 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
302 && sess.opts.output_types.len() == 1
304 return sess.compile_status();
307 compiler.global_ctxt()?;
309 if sess.opts.debugging_opts.no_analysis ||
310 sess.opts.debugging_opts.ast_json {
311 return sess.compile_status();
314 if sess.opts.debugging_opts.save_analysis {
315 let expanded_crate = &compiler.expansion()?.peek().0;
316 let crate_name = compiler.crate_name()?.peek().clone();
317 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
318 let result = tcx.analysis(LOCAL_CRATE);
320 time(sess, "save analysis", || {
327 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
332 // AST will be dropped *after* the `after_analysis` callback
333 // (needed by the RLS)
336 // Drop AST after creating GlobalCtxt to free memory
337 mem::drop(compiler.expansion()?.take());
340 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
342 if !callbacks.after_analysis(compiler) {
343 return sess.compile_status();
346 if sess.opts.debugging_opts.save_analysis {
347 mem::drop(compiler.expansion()?.take());
350 compiler.ongoing_codegen()?;
352 // Drop GlobalCtxt after starting codegen to free memory
353 mem::drop(compiler.global_ctxt()?.take());
355 if sess.opts.debugging_opts.print_type_sizes {
356 sess.code_stats.borrow().print_type_sizes();
361 if sess.opts.debugging_opts.perf_stats {
362 sess.print_perf_stats();
365 if sess.print_fuel_crate.is_some() {
366 eprintln!("Fuel used by {}: {}",
367 sess.print_fuel_crate.as_ref().unwrap(),
368 sess.print_fuel.load(SeqCst));
376 pub fn set_sigpipe_handler() {
378 // Set the SIGPIPE signal handler, so that an EPIPE
379 // will cause rustc to terminate, as expected.
380 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
385 pub fn set_sigpipe_handler() {}
387 // Extract output directory and file from matches.
388 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
389 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
390 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
394 // Extract input (string or file and optional path) from matches.
395 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
396 if free_matches.len() == 1 {
397 let ifile = &free_matches[0];
399 let mut src = String::new();
400 let err = if io::stdin().read_to_string(&mut src).is_err() {
401 Some(io::Error::new(io::ErrorKind::InvalidData,
402 "couldn't read from stdin, as it did not contain valid UTF-8"))
406 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
409 Some((Input::File(PathBuf::from(ifile)),
410 Some(PathBuf::from(ifile)), None))
417 fn parse_pretty(sess: &Session,
418 matches: &getopts::Matches)
419 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
420 let pretty = if sess.opts.debugging_opts.unstable_options {
421 matches.opt_default("pretty", "normal").map(|a| {
422 // stable pretty-print variants only
423 pretty::parse_pretty(sess, &a, false)
429 if pretty.is_none() {
430 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
431 // extended with unstable pretty-print variants
432 pretty::parse_pretty(sess, &a, true)
439 // Whether to stop or continue compilation.
440 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
441 pub enum Compilation {
447 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
449 Compilation::Stop => Compilation::Stop,
450 Compilation::Continue => next(),
455 /// CompilerCalls instance for a regular rustc build.
456 #[derive(Copy, Clone)]
457 pub struct RustcDefaultCalls;
459 // FIXME remove these and use winapi 0.3 instead
460 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
462 fn stdout_isatty() -> bool {
463 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
467 fn stdout_isatty() -> bool {
470 type HANDLE = *mut u8;
471 type LPDWORD = *mut u32;
472 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
474 fn GetStdHandle(which: DWORD) -> HANDLE;
475 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
478 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
480 GetConsoleMode(handle, &mut out) != 0
484 fn handle_explain(code: &str,
485 output: ErrorOutputType) {
486 let descriptions = rustc_interface::util::diagnostics_registry();
487 let normalised = if code.starts_with("E") {
490 format!("E{0:0>4}", code)
492 match descriptions.find_description(&normalised) {
493 Some(ref description) => {
494 let mut is_in_code_block = false;
495 let mut text = String::new();
497 // Slice off the leading newline and print.
498 for line in description[1..].lines() {
499 let indent_level = line.find(|c: char| !c.is_whitespace())
500 .unwrap_or_else(|| line.len());
501 let dedented_line = &line[indent_level..];
502 if dedented_line.starts_with("```") {
503 is_in_code_block = !is_in_code_block;
504 text.push_str(&line[..(indent_level+3)]);
505 } else if is_in_code_block && dedented_line.starts_with("# ") {
514 show_content_with_pager(&text);
520 early_error(output, &format!("no extended information for {}", code));
525 fn show_content_with_pager(content: &String) {
526 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
527 OsString::from("more.com")
529 OsString::from("less")
532 let mut fallback_to_println = false;
534 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
536 if let Some(pipe) = pager.stdin.as_mut() {
537 if pipe.write_all(content.as_bytes()).is_err() {
538 fallback_to_println = true;
542 if pager.wait().is_err() {
543 fallback_to_println = true;
547 fallback_to_println = true;
551 // If pager fails for whatever reason, we should still print the content
552 // to standard output
553 if fallback_to_println {
554 print!("{}", content);
558 impl RustcDefaultCalls {
559 pub fn list_metadata(sess: &Session,
561 matches: &getopts::Matches,
564 let r = matches.opt_strs("Z");
565 if r.iter().any(|s| *s == "ls") {
567 &Input::File(ref ifile) => {
568 let path = &(*ifile);
569 let mut v = Vec::new();
570 locator::list_file_metadata(&sess.target.target,
572 &*cstore.metadata_loader,
575 println!("{}", String::from_utf8(v).unwrap());
577 &Input::Str { .. } => {
578 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
581 return Compilation::Stop;
584 Compilation::Continue
588 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
590 input: Option<&Input>,
591 odir: &Option<PathBuf>,
592 ofile: &Option<PathBuf>)
594 use rustc::session::config::PrintRequest::*;
595 // PrintRequest::NativeStaticLibs is special - printed during linking
596 // (empty iterator returns true)
597 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
598 return Compilation::Continue;
601 let attrs = match input {
604 let result = parse_crate_attrs(sess, input);
606 Ok(attrs) => Some(attrs),
607 Err(mut parse_error) => {
609 return Compilation::Stop;
614 for req in &sess.opts.prints {
617 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
619 println!("{}", targets.join("\n"));
621 Sysroot => println!("{}", sess.sysroot.display()),
622 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
623 FileNames | CrateName => {
624 let input = input.unwrap_or_else(||
625 early_error(ErrorOutputType::default(), "no input file provided"));
626 let attrs = attrs.as_ref().unwrap();
627 let t_outputs = rustc_interface::util::build_output_filenames(
634 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
635 if *req == PrintRequest::CrateName {
639 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
640 for &style in &crate_types {
641 let fname = rustc_codegen_utils::link::filename_for_input(
647 println!("{}", fname.file_name().unwrap().to_string_lossy());
651 let allow_unstable_cfg = UnstableFeatures::from_environment()
654 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
655 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
656 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
657 node: ast::MetaItemKind::Word,
661 // Note that crt-static is a specially recognized cfg
662 // directive that's printed out here as part of
663 // rust-lang/rust#37406, but in general the
664 // `target_feature` cfg is gated under
665 // rust-lang/rust#29717. For now this is just
666 // specifically allowing the crt-static cfg and that's
667 // it, this is intended to get into Cargo and then go
668 // through to build scripts.
669 let value = value.as_ref().map(|s| s.as_str());
670 let value = value.as_ref().map(|s| s.as_ref());
671 if name != "target_feature" || value != Some("crt-static") {
672 if !allow_unstable_cfg && gated_cfg.is_some() {
677 if let Some(value) = value {
678 Some(format!("{}=\"{}\"", name, value))
680 Some(name.to_string())
682 }).collect::<Vec<String>>();
689 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
690 codegen_backend.print(*req, sess);
692 // Any output here interferes with Cargo's parsing of other printed output
693 PrintRequest::NativeStaticLibs => {}
696 return Compilation::Stop;
700 /// Returns a version string such as "0.12.0-dev".
701 fn release_str() -> Option<&'static str> {
702 option_env!("CFG_RELEASE")
705 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
706 fn commit_hash_str() -> Option<&'static str> {
707 option_env!("CFG_VER_HASH")
710 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
711 fn commit_date_str() -> Option<&'static str> {
712 option_env!("CFG_VER_DATE")
715 /// Prints version information
716 pub fn version(binary: &str, matches: &getopts::Matches) {
717 let verbose = matches.opt_present("verbose");
719 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
722 fn unw(x: Option<&str>) -> &str {
723 x.unwrap_or("unknown")
725 println!("binary: {}", binary);
726 println!("commit-hash: {}", unw(commit_hash_str()));
727 println!("commit-date: {}", unw(commit_date_str()));
728 println!("host: {}", config::host_triple());
729 println!("release: {}", unw(release_str()));
730 get_codegen_sysroot("llvm")().print_version();
734 fn usage(verbose: bool, include_unstable_options: bool) {
735 let groups = if verbose {
736 config::rustc_optgroups()
738 config::rustc_short_optgroups()
740 let mut options = getopts::Options::new();
741 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
742 (option.apply)(&mut options);
744 let message = "Usage: rustc [OPTIONS] INPUT";
745 let nightly_help = if nightly_options::is_nightly_build() {
746 "\n -Z help Print internal options for debugging rustc"
750 let verbose_help = if verbose {
753 "\n --help -v Print the full set of options rustc accepts"
755 println!("{}\nAdditional help:
756 -C help Print codegen options
758 Print 'lint' options and default settings{}{}\n",
759 options.usage(message),
764 fn print_wall_help() {
766 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
767 default. Use `rustc -W help` to see all available lints. It's more common to put
768 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
769 the command line flag directly.
773 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
775 Available lint options:
776 -W <foo> Warn about <foo>
780 -F <foo> Forbid <foo> \
781 (deny <foo> and all attempts to override)
785 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
786 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
787 // The sort doesn't case-fold but it's doubtful we care.
788 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
792 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
793 -> Vec<(&'static str, Vec<lint::LintId>)> {
794 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
795 lints.sort_by_key(|l| l.0);
799 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
802 .partition(|&(_, p)| p);
803 let plugin = sort_lints(sess, plugin);
804 let builtin = sort_lints(sess, builtin);
806 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
809 .partition(|&(.., p)| p);
810 let plugin_groups = sort_lint_groups(plugin_groups);
811 let builtin_groups = sort_lint_groups(builtin_groups);
813 let max_name_len = plugin.iter()
815 .map(|&s| s.name.chars().count())
818 let padded = |x: &str| {
819 let mut s = " ".repeat(max_name_len - x.chars().count());
824 println!("Lint checks provided by rustc:\n");
825 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
826 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
828 let print_lints = |lints: Vec<&Lint>| {
830 let name = lint.name_lower().replace("_", "-");
831 println!(" {} {:7.7} {}",
833 lint.default_level.as_str(),
839 print_lints(builtin);
841 let max_name_len = max("warnings".len(),
843 .chain(&builtin_groups)
844 .map(|&(s, _)| s.chars().count())
848 let padded = |x: &str| {
849 let mut s = " ".repeat(max_name_len - x.chars().count());
854 println!("Lint groups provided by rustc:\n");
855 println!(" {} {}", padded("name"), "sub-lints");
856 println!(" {} {}", padded("----"), "---------");
857 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
859 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
860 for (name, to) in lints {
861 let name = name.to_lowercase().replace("_", "-");
862 let desc = to.into_iter()
863 .map(|x| x.to_string().replace("_", "-"))
864 .collect::<Vec<String>>()
866 println!(" {} {}", padded(&name), desc);
871 print_lint_groups(builtin_groups);
873 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
874 (false, 0, _) | (false, _, 0) => {
875 println!("Compiler plugins can provide additional lints and lint groups. To see a \
876 listing of these, re-run `rustc -W help` with a crate filename.");
878 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
879 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
882 println!("Lint checks provided by plugins loaded by this crate:\n");
886 println!("Lint groups provided by plugins loaded by this crate:\n");
887 print_lint_groups(plugin_groups);
893 fn describe_debug_flags() {
894 println!("\nAvailable debug options:\n");
895 print_flag_list("-Z", config::DB_OPTIONS);
898 fn describe_codegen_flags() {
899 println!("\nAvailable codegen options:\n");
900 print_flag_list("-C", config::CG_OPTIONS);
903 fn print_flag_list<T>(cmdline_opt: &str,
904 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
905 let max_len = flag_list.iter()
906 .map(|&(name, _, opt_type_desc, _)| {
907 let extra_len = match opt_type_desc {
911 name.chars().count() + extra_len
916 for &(name, _, opt_type_desc, desc) in flag_list {
917 let (width, extra) = match opt_type_desc {
918 Some(..) => (max_len - 4, "=val"),
919 None => (max_len, ""),
921 println!(" {} {:>width$}{} -- {}",
923 name.replace("_", "-"),
930 /// Process command line options. Emits messages as appropriate. If compilation
931 /// should continue, returns a getopts::Matches object parsed from args,
932 /// otherwise returns `None`.
934 /// The compiler's handling of options is a little complicated as it ties into
935 /// our stability story, and it's even *more* complicated by historical
936 /// accidents. The current intention of each compiler option is to have one of
939 /// 1. An option is stable and can be used everywhere.
940 /// 2. An option is unstable, but was historically allowed on the stable
942 /// 3. An option is unstable, and can only be used on nightly.
944 /// Like unstable library and language features, however, unstable options have
945 /// always required a form of "opt in" to indicate that you're using them. This
946 /// provides the easy ability to scan a code base to check to see if anything
947 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
949 /// All options behind `-Z` are considered unstable by default. Other top-level
950 /// options can also be considered unstable, and they were unlocked through the
951 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
952 /// instability in both cases, though.
954 /// So with all that in mind, the comments below have some more detail about the
955 /// contortions done here to get things to work out correctly.
956 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
957 // Throw away the first argument, the name of the binary
958 let args = &args[1..];
961 // user did not write `-v` nor `-Z unstable-options`, so do not
962 // include that extra information.
967 // Parse with *all* options defined in the compiler, we don't worry about
968 // option stability here we just want to parse as much as possible.
969 let mut options = getopts::Options::new();
970 for option in config::rustc_optgroups() {
971 (option.apply)(&mut options);
973 let matches = options.parse(args).unwrap_or_else(|f|
974 early_error(ErrorOutputType::default(), &f.to_string()));
976 // For all options we just parsed, we check a few aspects:
978 // * If the option is stable, we're all good
979 // * If the option wasn't passed, we're all good
980 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
981 // ourselves), then we require the `-Z unstable-options` flag to unlock
982 // this option that was passed.
983 // * If we're a nightly compiler, then unstable options are now unlocked, so
985 // * Otherwise, if we're a truly unstable option then we generate an error
986 // (unstable option being used on stable)
987 // * If we're a historically stable-but-should-be-unstable option then we
988 // emit a warning that we're going to turn this into an error soon.
989 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
991 if matches.opt_present("h") || matches.opt_present("help") {
992 // Only show unstable options in --help if we *really* accept unstable
993 // options, which catches the case where we got `-Z unstable-options` on
994 // the stable channel of Rust which was accidentally allowed
996 usage(matches.opt_present("verbose"),
997 nightly_options::is_unstable_enabled(&matches));
1001 // Handle the special case of -Wall.
1002 let wall = matches.opt_strs("W");
1003 if wall.iter().any(|x| *x == "all") {
1008 // Don't handle -W help here, because we might first load plugins.
1009 let r = matches.opt_strs("Z");
1010 if r.iter().any(|x| *x == "help") {
1011 describe_debug_flags();
1015 let cg_flags = matches.opt_strs("C");
1017 if cg_flags.iter().any(|x| *x == "help") {
1018 describe_codegen_flags();
1022 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1023 early_warn(ErrorOutputType::default(),
1024 "the --no-stack-check flag is deprecated and does nothing");
1027 if cg_flags.iter().any(|x| *x == "passes=list") {
1028 get_codegen_sysroot("llvm")().print_passes();
1032 if matches.opt_present("version") {
1033 version("rustc", &matches);
1040 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1042 Input::File(ref ifile) => {
1043 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1045 Input::Str { ref name, ref input } => {
1046 parse::parse_crate_attrs_from_source_str(name.clone(),
1053 /// Gets a list of extra command-line flags provided by the user, as strings.
1055 /// This function is used during ICEs to show more information useful for
1056 /// debugging, since some ICEs only happens with non-default compiler flags
1057 /// (and the users don't always report them).
1058 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1059 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1061 // Avoid printing help because of empty args. This can suggest the compiler
1062 // itself is not the program root (consider RLS).
1067 let matches = if let Some(matches) = handle_options(&args) {
1073 let mut result = Vec::new();
1074 let mut excluded_cargo_defaults = false;
1075 for flag in ICE_REPORT_COMPILER_FLAGS {
1076 let prefix = if flag.len() == 1 { "-" } else { "--" };
1078 for content in &matches.opt_strs(flag) {
1079 // Split always returns the first element
1080 let name = if let Some(first) = content.split('=').next() {
1086 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1092 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1093 result.push(format!("{}{} {}", prefix, flag, content));
1095 excluded_cargo_defaults = true;
1100 if !result.is_empty() {
1101 Some((result, excluded_cargo_defaults))
1107 /// Runs a procedure which will detect panics in the compiler and print nicer
1108 /// error messages rather than just failing the test.
1110 /// The diagnostic emitter yielded to the procedure should be used for reporting
1111 /// errors of the compiler.
1112 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1113 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1114 if value.is::<errors::FatalErrorMarker>() {
1117 // Thread panicked without emitting a fatal diagnostic
1121 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1125 let handler = errors::Handler::with_emitter(true, None, emitter);
1127 // a .span_bug or .bug call has already printed what
1128 // it wants to print.
1129 if !value.is::<errors::ExplicitBug>() {
1130 handler.emit(&MultiSpan::new(),
1132 errors::Level::Bug);
1135 let mut xs: Vec<Cow<'static, str>> = vec![
1136 "the compiler unexpectedly panicked. this is a bug.".into(),
1137 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1138 format!("rustc {} running on {}",
1139 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1140 config::host_triple()).into(),
1143 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1144 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1146 if excluded_cargo_defaults {
1147 xs.push("some of the compiler flags provided by cargo are hidden".into());
1152 handler.emit(&MultiSpan::new(),
1154 errors::Level::Note);
1157 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1162 /// This allows tools to enable rust logging without having to magically match rustc's
1163 /// log crate version
1164 pub fn init_rustc_env_logger() {
1169 init_rustc_env_logger();
1170 let result = report_ices_to_stderr_if_any(|| {
1171 let args = env::args_os().enumerate()
1172 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1173 early_error(ErrorOutputType::default(),
1174 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1176 .collect::<Vec<_>>();
1177 run_compiler(&args, &mut DefaultCallbacks, None, None)
1178 }).and_then(|result| result);
1179 process::exit(match result {
1180 Ok(_) => EXIT_SUCCESS,
1181 Err(_) => EXIT_FAILURE,