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)]
22 pub extern crate getopts;
28 use pretty::{PpMode, UserIdentifiedItem};
30 //use rustc_resolve as resolve;
31 use rustc_save_analysis as save;
32 use rustc_save_analysis::DumpHandler;
33 use rustc::session::{config, Session, DiagnosticOutput};
34 use rustc::session::config::{Input, PrintRequest, ErrorOutputType, OutputType};
35 use rustc::session::config::nightly_options;
36 use rustc::session::{early_error, early_warn};
37 use rustc::lint::Lint;
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::util::common::{time, ErrorReported, install_panic_hook};
41 use rustc_metadata::locator;
42 use rustc_metadata::cstore::CStore;
43 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 serialize::json::ToJson;
52 use std::default::Default;
54 use std::ffi::OsString;
55 use std::io::{self, Read, Write};
56 use std::panic::{self, catch_unwind};
57 use std::path::PathBuf;
58 use std::process::{self, Command, Stdio};
63 use syntax::source_map::FileLoader;
64 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
65 use syntax::parse::{self, PResult};
66 use syntax::symbol::sym;
67 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
71 /// Exit status code used for successful compilation and help output.
72 pub const EXIT_SUCCESS: i32 = 0;
74 /// Exit status code used for compilation failures and invalid flags.
75 pub const EXIT_FAILURE: i32 = 1;
77 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
80 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
82 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
84 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
86 pub fn source_name(input: &Input) -> FileName {
88 Input::File(ref ifile) => ifile.clone().into(),
89 Input::Str { ref name, .. } => name.clone(),
93 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
96 sess.abort_if_errors();
97 panic!("error reported but abort_if_errors didn't abort???");
103 pub trait Callbacks {
104 /// Called before creating the compiler instance
105 fn config(&mut self, _config: &mut interface::Config) {}
106 /// Called after parsing and returns true to continue execution
107 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> bool {
110 /// Called after analysis and returns true to continue execution
111 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> bool {
116 pub struct DefaultCallbacks;
118 impl Callbacks for DefaultCallbacks {}
120 // Parse args and run the compiler. This is the primary entry point for rustc.
121 // See comments on CompilerCalls below for details about the callbacks argument.
122 // The FileLoader provides a way to load files from sources other than the file system.
125 callbacks: &mut (dyn Callbacks + Send),
126 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
127 emitter: Option<Box<dyn Write + Send>>
128 ) -> interface::Result<()> {
129 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
130 .unwrap_or(DiagnosticOutput::Default);
131 let matches = match handle_options(args) {
132 Some(matches) => matches,
133 None => return Ok(()),
136 install_panic_hook();
138 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
140 let mut dummy_config = |sopts, cfg, diagnostic_output| {
141 let mut config = interface::Config {
144 input: Input::File(PathBuf::new()),
152 lint_caps: Default::default(),
154 callbacks.config(&mut config);
158 if let Some(ref code) = matches.opt_str("explain") {
159 handle_explain(code, sopts.error_format);
163 let (odir, ofile) = make_output(&matches);
164 let (input, input_file_path, input_err) = match make_input(&matches.free) {
167 match matches.free.len() {
169 let config = dummy_config(sopts, cfg, diagnostic_output);
170 interface::run_compiler(config, |compiler| {
171 let sopts = &compiler.session().opts;
172 if sopts.describe_lints {
175 &*compiler.session().lint_store.borrow(),
180 let should_stop = RustcDefaultCalls::print_crate_info(
181 &***compiler.codegen_backend(),
188 if should_stop == Compilation::Stop {
191 early_error(sopts.error_format, "no input filename given")
195 1 => panic!("make_input should have provided valid inputs"),
196 _ => early_error(sopts.error_format, &format!(
197 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
205 if let Some(err) = input_err {
206 // Immediately stop compilation if there was an issue reading
207 // the input (for example if the input stream is not UTF-8).
208 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
209 compiler.session().err(&err.to_string());
211 return Err(ErrorReported);
214 let mut config = interface::Config {
218 input_path: input_file_path,
225 lint_caps: Default::default(),
228 callbacks.config(&mut config);
230 interface::run_compiler(config, |compiler| {
231 let sess = compiler.session();
232 let should_stop = RustcDefaultCalls::print_crate_info(
233 &***compiler.codegen_backend(),
235 Some(compiler.input()),
236 compiler.output_dir(),
237 compiler.output_file(),
238 ).and_then(|| RustcDefaultCalls::list_metadata(
245 if should_stop == Compilation::Stop {
246 return sess.compile_status();
249 let pretty_info = parse_pretty(sess, &matches);
253 if let Some((ppm, opt_uii)) = pretty_info {
254 if ppm.needs_ast_map(&opt_uii) {
255 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
256 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
257 let expanded_crate = compiler.expansion()?.take().0;
258 pretty::print_after_hir_lowering(
264 compiler.output_file().as_ref().map(|p| &**p),
268 return sess.compile_status();
270 let mut krate = compiler.parse()?.take();
271 pretty::visit_crate(sess, &mut krate, ppm);
272 pretty::print_after_parsing(
277 compiler.output_file().as_ref().map(|p| &**p),
279 return sess.compile_status();
283 if !callbacks.after_parsing(compiler) {
284 return sess.compile_status();
287 if sess.opts.debugging_opts.parse_only ||
288 sess.opts.debugging_opts.show_span.is_some() ||
289 sess.opts.debugging_opts.ast_json_noexpand {
290 return sess.compile_status();
293 compiler.register_plugins()?;
295 // Lint plugins are registered; now we can process command line flags.
296 if sess.opts.describe_lints {
297 describe_lints(&sess, &sess.lint_store.borrow(), true);
298 return sess.compile_status();
301 compiler.prepare_outputs()?;
303 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
304 && sess.opts.output_types.len() == 1
306 return sess.compile_status();
309 compiler.global_ctxt()?;
311 if sess.opts.debugging_opts.no_analysis ||
312 sess.opts.debugging_opts.ast_json {
313 return sess.compile_status();
316 if sess.opts.debugging_opts.save_analysis {
317 let expanded_crate = &compiler.expansion()?.peek().0;
318 let crate_name = compiler.crate_name()?.peek().clone();
319 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
320 let result = tcx.analysis(LOCAL_CRATE);
322 time(sess, "save analysis", || {
329 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
334 // AST will be dropped *after* the `after_analysis` callback
335 // (needed by the RLS)
338 // Drop AST after creating GlobalCtxt to free memory
339 mem::drop(compiler.expansion()?.take());
342 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
344 if !callbacks.after_analysis(compiler) {
345 return sess.compile_status();
348 if sess.opts.debugging_opts.save_analysis {
349 mem::drop(compiler.expansion()?.take());
352 compiler.ongoing_codegen()?;
354 // Drop GlobalCtxt after starting codegen to free memory
355 mem::drop(compiler.global_ctxt()?.take());
357 if sess.opts.debugging_opts.print_type_sizes {
358 sess.code_stats.borrow().print_type_sizes();
363 if sess.opts.debugging_opts.perf_stats {
364 sess.print_perf_stats();
367 if sess.print_fuel_crate.is_some() {
368 eprintln!("Fuel used by {}: {}",
369 sess.print_fuel_crate.as_ref().unwrap(),
370 sess.print_fuel.load(SeqCst));
378 pub fn set_sigpipe_handler() {
380 // Set the SIGPIPE signal handler, so that an EPIPE
381 // will cause rustc to terminate, as expected.
382 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
387 pub fn set_sigpipe_handler() {}
389 // Extract output directory and file from matches.
390 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
391 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
392 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
396 // Extract input (string or file and optional path) from matches.
397 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
398 if free_matches.len() == 1 {
399 let ifile = &free_matches[0];
401 let mut src = String::new();
402 let err = if io::stdin().read_to_string(&mut src).is_err() {
403 Some(io::Error::new(io::ErrorKind::InvalidData,
404 "couldn't read from stdin, as it did not contain valid UTF-8"))
408 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
411 Some((Input::File(PathBuf::from(ifile)),
412 Some(PathBuf::from(ifile)), None))
419 fn parse_pretty(sess: &Session,
420 matches: &getopts::Matches)
421 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
422 let pretty = if sess.opts.debugging_opts.unstable_options {
423 matches.opt_default("pretty", "normal").map(|a| {
424 // stable pretty-print variants only
425 pretty::parse_pretty(sess, &a, false)
431 if pretty.is_none() {
432 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
433 // extended with unstable pretty-print variants
434 pretty::parse_pretty(sess, &a, true)
441 // Whether to stop or continue compilation.
442 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
443 pub enum Compilation {
449 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
451 Compilation::Stop => Compilation::Stop,
452 Compilation::Continue => next(),
457 /// CompilerCalls instance for a regular rustc build.
458 #[derive(Copy, Clone)]
459 pub struct RustcDefaultCalls;
461 // FIXME remove these and use winapi 0.3 instead
462 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
464 fn stdout_isatty() -> bool {
465 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
469 fn stdout_isatty() -> bool {
472 type HANDLE = *mut u8;
473 type LPDWORD = *mut u32;
474 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
476 fn GetStdHandle(which: DWORD) -> HANDLE;
477 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
480 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
482 GetConsoleMode(handle, &mut out) != 0
486 fn handle_explain(code: &str,
487 output: ErrorOutputType) {
488 let descriptions = rustc_interface::util::diagnostics_registry();
489 let normalised = if code.starts_with("E") {
492 format!("E{0:0>4}", code)
494 match descriptions.find_description(&normalised) {
495 Some(ref description) => {
496 let mut is_in_code_block = false;
497 let mut text = String::new();
499 // Slice off the leading newline and print.
500 for line in description[1..].lines() {
501 let indent_level = line.find(|c: char| !c.is_whitespace())
502 .unwrap_or_else(|| line.len());
503 let dedented_line = &line[indent_level..];
504 if dedented_line.starts_with("```") {
505 is_in_code_block = !is_in_code_block;
506 text.push_str(&line[..(indent_level+3)]);
507 } else if is_in_code_block && dedented_line.starts_with("# ") {
516 show_content_with_pager(&text);
522 early_error(output, &format!("no extended information for {}", code));
527 fn show_content_with_pager(content: &String) {
528 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
529 OsString::from("more.com")
531 OsString::from("less")
534 let mut fallback_to_println = false;
536 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
538 if let Some(pipe) = pager.stdin.as_mut() {
539 if pipe.write_all(content.as_bytes()).is_err() {
540 fallback_to_println = true;
544 if pager.wait().is_err() {
545 fallback_to_println = true;
549 fallback_to_println = true;
553 // If pager fails for whatever reason, we should still print the content
554 // to standard output
555 if fallback_to_println {
556 print!("{}", content);
560 impl RustcDefaultCalls {
561 pub fn list_metadata(sess: &Session,
563 matches: &getopts::Matches,
566 let r = matches.opt_strs("Z");
567 if r.iter().any(|s| *s == "ls") {
569 &Input::File(ref ifile) => {
570 let path = &(*ifile);
571 let mut v = Vec::new();
572 locator::list_file_metadata(&sess.target.target,
574 &*cstore.metadata_loader,
577 println!("{}", String::from_utf8(v).unwrap());
579 &Input::Str { .. } => {
580 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
583 return Compilation::Stop;
586 Compilation::Continue
590 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
592 input: Option<&Input>,
593 odir: &Option<PathBuf>,
594 ofile: &Option<PathBuf>)
596 use rustc::session::config::PrintRequest::*;
597 // PrintRequest::NativeStaticLibs is special - printed during linking
598 // (empty iterator returns true)
599 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
600 return Compilation::Continue;
603 let attrs = match input {
606 let result = parse_crate_attrs(sess, input);
608 Ok(attrs) => Some(attrs),
609 Err(mut parse_error) => {
611 return Compilation::Stop;
616 for req in &sess.opts.prints {
619 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
621 println!("{}", targets.join("\n"));
623 Sysroot => println!("{}", sess.sysroot.display()),
624 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
625 FileNames | CrateName => {
626 let input = input.unwrap_or_else(||
627 early_error(ErrorOutputType::default(), "no input file provided"));
628 let attrs = attrs.as_ref().unwrap();
629 let t_outputs = rustc_interface::util::build_output_filenames(
636 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
637 if *req == PrintRequest::CrateName {
641 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
642 for &style in &crate_types {
643 let fname = rustc_codegen_utils::link::filename_for_input(
649 println!("{}", fname.file_name().unwrap().to_string_lossy());
653 let allow_unstable_cfg = UnstableFeatures::from_environment()
656 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
657 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
658 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
659 node: ast::MetaItemKind::Word,
663 // Note that crt-static is a specially recognized cfg
664 // directive that's printed out here as part of
665 // rust-lang/rust#37406, but in general the
666 // `target_feature` cfg is gated under
667 // rust-lang/rust#29717. For now this is just
668 // specifically allowing the crt-static cfg and that's
669 // it, this is intended to get into Cargo and then go
670 // through to build scripts.
671 let value = value.as_ref().map(|s| s.as_str());
672 let value = value.as_ref().map(|s| s.as_ref());
673 if name != sym::target_feature || value != Some("crt-static") {
674 if !allow_unstable_cfg && gated_cfg.is_some() {
679 if let Some(value) = value {
680 Some(format!("{}=\"{}\"", name, value))
682 Some(name.to_string())
684 }).collect::<Vec<String>>();
691 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
692 codegen_backend.print(*req, sess);
694 // Any output here interferes with Cargo's parsing of other printed output
695 PrintRequest::NativeStaticLibs => {}
698 return Compilation::Stop;
702 /// Returns a version string such as "0.12.0-dev".
703 fn release_str() -> Option<&'static str> {
704 option_env!("CFG_RELEASE")
707 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
708 fn commit_hash_str() -> Option<&'static str> {
709 option_env!("CFG_VER_HASH")
712 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
713 fn commit_date_str() -> Option<&'static str> {
714 option_env!("CFG_VER_DATE")
717 /// Prints version information
718 pub fn version(binary: &str, matches: &getopts::Matches) {
719 let verbose = matches.opt_present("verbose");
721 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
724 fn unw(x: Option<&str>) -> &str {
725 x.unwrap_or("unknown")
727 println!("binary: {}", binary);
728 println!("commit-hash: {}", unw(commit_hash_str()));
729 println!("commit-date: {}", unw(commit_date_str()));
730 println!("host: {}", config::host_triple());
731 println!("release: {}", unw(release_str()));
732 get_codegen_sysroot("llvm")().print_version();
736 fn usage(verbose: bool, include_unstable_options: bool) {
737 let groups = if verbose {
738 config::rustc_optgroups()
740 config::rustc_short_optgroups()
742 let mut options = getopts::Options::new();
743 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
744 (option.apply)(&mut options);
746 let message = "Usage: rustc [OPTIONS] INPUT";
747 let nightly_help = if nightly_options::is_nightly_build() {
748 "\n -Z help Print unstable compiler options"
752 let verbose_help = if verbose {
755 "\n --help -v Print the full set of options rustc accepts"
757 println!("{}\nAdditional help:
758 -C help Print codegen options
760 Print 'lint' options and default settings{}{}\n",
761 options.usage(message),
766 fn print_wall_help() {
768 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
769 default. Use `rustc -W help` to see all available lints. It's more common to put
770 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
771 the command line flag directly.
775 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
777 Available lint options:
778 -W <foo> Warn about <foo>
782 -F <foo> Forbid <foo> \
783 (deny <foo> and all attempts to override)
787 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
788 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
789 // The sort doesn't case-fold but it's doubtful we care.
790 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
794 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
795 -> Vec<(&'static str, Vec<lint::LintId>)> {
796 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
797 lints.sort_by_key(|l| l.0);
801 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
804 .partition(|&(_, p)| p);
805 let plugin = sort_lints(sess, plugin);
806 let builtin = sort_lints(sess, builtin);
808 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
811 .partition(|&(.., p)| p);
812 let plugin_groups = sort_lint_groups(plugin_groups);
813 let builtin_groups = sort_lint_groups(builtin_groups);
815 let max_name_len = plugin.iter()
817 .map(|&s| s.name.chars().count())
820 let padded = |x: &str| {
821 let mut s = " ".repeat(max_name_len - x.chars().count());
826 println!("Lint checks provided by rustc:\n");
827 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
828 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
830 let print_lints = |lints: Vec<&Lint>| {
832 let name = lint.name_lower().replace("_", "-");
833 println!(" {} {:7.7} {}",
835 lint.default_level.as_str(),
841 print_lints(builtin);
843 let max_name_len = max("warnings".len(),
845 .chain(&builtin_groups)
846 .map(|&(s, _)| s.chars().count())
850 let padded = |x: &str| {
851 let mut s = " ".repeat(max_name_len - x.chars().count());
856 println!("Lint groups provided by rustc:\n");
857 println!(" {} {}", padded("name"), "sub-lints");
858 println!(" {} {}", padded("----"), "---------");
859 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
861 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
862 for (name, to) in lints {
863 let name = name.to_lowercase().replace("_", "-");
864 let desc = to.into_iter()
865 .map(|x| x.to_string().replace("_", "-"))
866 .collect::<Vec<String>>()
868 println!(" {} {}", padded(&name), desc);
873 print_lint_groups(builtin_groups);
875 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
876 (false, 0, _) | (false, _, 0) => {
877 println!("Compiler plugins can provide additional lints and lint groups. To see a \
878 listing of these, re-run `rustc -W help` with a crate filename.");
880 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
881 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
884 println!("Lint checks provided by plugins loaded by this crate:\n");
888 println!("Lint groups provided by plugins loaded by this crate:\n");
889 print_lint_groups(plugin_groups);
895 fn describe_debug_flags() {
896 println!("\nAvailable options:\n");
897 print_flag_list("-Z", config::DB_OPTIONS);
900 fn describe_codegen_flags() {
901 println!("\nAvailable codegen options:\n");
902 print_flag_list("-C", config::CG_OPTIONS);
905 fn print_flag_list<T>(cmdline_opt: &str,
906 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
907 let max_len = flag_list.iter()
908 .map(|&(name, _, opt_type_desc, _)| {
909 let extra_len = match opt_type_desc {
913 name.chars().count() + extra_len
918 for &(name, _, opt_type_desc, desc) in flag_list {
919 let (width, extra) = match opt_type_desc {
920 Some(..) => (max_len - 4, "=val"),
921 None => (max_len, ""),
923 println!(" {} {:>width$}{} -- {}",
925 name.replace("_", "-"),
932 /// Process command line options. Emits messages as appropriate. If compilation
933 /// should continue, returns a getopts::Matches object parsed from args,
934 /// otherwise returns `None`.
936 /// The compiler's handling of options is a little complicated as it ties into
937 /// our stability story, and it's even *more* complicated by historical
938 /// accidents. The current intention of each compiler option is to have one of
941 /// 1. An option is stable and can be used everywhere.
942 /// 2. An option is unstable, but was historically allowed on the stable
944 /// 3. An option is unstable, and can only be used on nightly.
946 /// Like unstable library and language features, however, unstable options have
947 /// always required a form of "opt in" to indicate that you're using them. This
948 /// provides the easy ability to scan a code base to check to see if anything
949 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
951 /// All options behind `-Z` are considered unstable by default. Other top-level
952 /// options can also be considered unstable, and they were unlocked through the
953 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
954 /// instability in both cases, though.
956 /// So with all that in mind, the comments below have some more detail about the
957 /// contortions done here to get things to work out correctly.
958 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
959 // Throw away the first argument, the name of the binary
960 let args = &args[1..];
963 // user did not write `-v` nor `-Z unstable-options`, so do not
964 // include that extra information.
969 // Parse with *all* options defined in the compiler, we don't worry about
970 // option stability here we just want to parse as much as possible.
971 let mut options = getopts::Options::new();
972 for option in config::rustc_optgroups() {
973 (option.apply)(&mut options);
975 let matches = options.parse(args).unwrap_or_else(|f|
976 early_error(ErrorOutputType::default(), &f.to_string()));
978 // For all options we just parsed, we check a few aspects:
980 // * If the option is stable, we're all good
981 // * If the option wasn't passed, we're all good
982 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
983 // ourselves), then we require the `-Z unstable-options` flag to unlock
984 // this option that was passed.
985 // * If we're a nightly compiler, then unstable options are now unlocked, so
987 // * Otherwise, if we're a truly unstable option then we generate an error
988 // (unstable option being used on stable)
989 // * If we're a historically stable-but-should-be-unstable option then we
990 // emit a warning that we're going to turn this into an error soon.
991 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
993 if matches.opt_present("h") || matches.opt_present("help") {
994 // Only show unstable options in --help if we *really* accept unstable
995 // options, which catches the case where we got `-Z unstable-options` on
996 // the stable channel of Rust which was accidentally allowed
998 usage(matches.opt_present("verbose"),
999 nightly_options::is_unstable_enabled(&matches));
1003 // Handle the special case of -Wall.
1004 let wall = matches.opt_strs("W");
1005 if wall.iter().any(|x| *x == "all") {
1010 // Don't handle -W help here, because we might first load plugins.
1011 let r = matches.opt_strs("Z");
1012 if r.iter().any(|x| *x == "help") {
1013 describe_debug_flags();
1017 let cg_flags = matches.opt_strs("C");
1019 if cg_flags.iter().any(|x| *x == "help") {
1020 describe_codegen_flags();
1024 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1025 early_warn(ErrorOutputType::default(),
1026 "the --no-stack-check flag is deprecated and does nothing");
1029 if cg_flags.iter().any(|x| *x == "passes=list") {
1030 get_codegen_sysroot("llvm")().print_passes();
1034 if matches.opt_present("version") {
1035 version("rustc", &matches);
1042 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1044 Input::File(ref ifile) => {
1045 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1047 Input::Str { ref name, ref input } => {
1048 parse::parse_crate_attrs_from_source_str(name.clone(),
1055 /// Gets a list of extra command-line flags provided by the user, as strings.
1057 /// This function is used during ICEs to show more information useful for
1058 /// debugging, since some ICEs only happens with non-default compiler flags
1059 /// (and the users don't always report them).
1060 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1061 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1063 // Avoid printing help because of empty args. This can suggest the compiler
1064 // itself is not the program root (consider RLS).
1069 let matches = if let Some(matches) = handle_options(&args) {
1075 let mut result = Vec::new();
1076 let mut excluded_cargo_defaults = false;
1077 for flag in ICE_REPORT_COMPILER_FLAGS {
1078 let prefix = if flag.len() == 1 { "-" } else { "--" };
1080 for content in &matches.opt_strs(flag) {
1081 // Split always returns the first element
1082 let name = if let Some(first) = content.split('=').next() {
1088 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1094 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1095 result.push(format!("{}{} {}", prefix, flag, content));
1097 excluded_cargo_defaults = true;
1102 if !result.is_empty() {
1103 Some((result, excluded_cargo_defaults))
1109 /// Runs a procedure which will detect panics in the compiler and print nicer
1110 /// error messages rather than just failing the test.
1112 /// The diagnostic emitter yielded to the procedure should be used for reporting
1113 /// errors of the compiler.
1114 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1115 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1116 if value.is::<errors::FatalErrorMarker>() {
1119 // Thread panicked without emitting a fatal diagnostic
1123 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1127 let handler = errors::Handler::with_emitter(true, None, emitter);
1129 // a .span_bug or .bug call has already printed what
1130 // it wants to print.
1131 if !value.is::<errors::ExplicitBug>() {
1132 handler.emit(&MultiSpan::new(),
1134 errors::Level::Bug);
1137 let mut xs: Vec<Cow<'static, str>> = vec![
1138 "the compiler unexpectedly panicked. this is a bug.".into(),
1139 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1140 format!("rustc {} running on {}",
1141 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1142 config::host_triple()).into(),
1145 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1146 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1148 if excluded_cargo_defaults {
1149 xs.push("some of the compiler flags provided by cargo are hidden".into());
1154 handler.emit(&MultiSpan::new(),
1156 errors::Level::Note);
1159 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1164 /// This allows tools to enable rust logging without having to magically match rustc's
1165 /// log crate version
1166 pub fn init_rustc_env_logger() {
1167 env_logger::init_from_env("RUSTC_LOG");
1171 init_rustc_env_logger();
1172 let result = report_ices_to_stderr_if_any(|| {
1173 let args = env::args_os().enumerate()
1174 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1175 early_error(ErrorOutputType::default(),
1176 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1178 .collect::<Vec<_>>();
1179 run_compiler(&args, &mut DefaultCallbacks, None, None)
1180 }).and_then(|result| result);
1181 process::exit(match result {
1182 Ok(_) => EXIT_SUCCESS,
1183 Err(_) => EXIT_FAILURE,