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_pos::{DUMMY_SP, MultiSpan, FileName};
70 /// Exit status code used for successful compilation and help output.
71 pub const EXIT_SUCCESS: i32 = 0;
73 /// Exit status code used for compilation failures and invalid flags.
74 pub const EXIT_FAILURE: i32 = 1;
76 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
79 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
81 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
83 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
85 pub fn source_name(input: &Input) -> FileName {
87 Input::File(ref ifile) => ifile.clone().into(),
88 Input::Str { ref name, .. } => name.clone(),
92 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
95 sess.abort_if_errors();
96 panic!("error reported but abort_if_errors didn't abort???");
102 pub trait Callbacks {
103 /// Called before creating the compiler instance
104 fn config(&mut self, _config: &mut interface::Config) {}
105 /// Called after parsing and returns true to continue execution
106 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> bool {
109 /// Called after analysis and returns true to continue execution
110 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> bool {
115 pub struct DefaultCallbacks;
117 impl Callbacks for DefaultCallbacks {}
119 // Parse args and run the compiler. This is the primary entry point for rustc.
120 // See comments on CompilerCalls below for details about the callbacks argument.
121 // The FileLoader provides a way to load files from sources other than the file system.
124 callbacks: &mut (dyn Callbacks + Send),
125 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
126 emitter: Option<Box<dyn Write + Send>>
127 ) -> interface::Result<()> {
128 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
129 .unwrap_or(DiagnosticOutput::Default);
130 let matches = match handle_options(args) {
131 Some(matches) => matches,
132 None => return Ok(()),
135 install_panic_hook();
137 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
139 let mut dummy_config = |sopts, cfg, diagnostic_output| {
140 let mut config = interface::Config {
143 input: Input::File(PathBuf::new()),
151 lint_caps: Default::default(),
153 callbacks.config(&mut config);
157 if let Some(ref code) = matches.opt_str("explain") {
158 handle_explain(code, sopts.error_format);
162 let (odir, ofile) = make_output(&matches);
163 let (input, input_file_path, input_err) = match make_input(&matches.free) {
166 match matches.free.len() {
168 let config = dummy_config(sopts, cfg, diagnostic_output);
169 interface::run_compiler(config, |compiler| {
170 let sopts = &compiler.session().opts;
171 if sopts.describe_lints {
174 &*compiler.session().lint_store.borrow(),
179 let should_stop = RustcDefaultCalls::print_crate_info(
180 &***compiler.codegen_backend(),
187 if should_stop == Compilation::Stop {
190 early_error(sopts.error_format, "no input filename given")
194 1 => panic!("make_input should have provided valid inputs"),
195 _ => early_error(sopts.error_format, &format!(
196 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
204 if let Some(err) = input_err {
205 // Immediately stop compilation if there was an issue reading
206 // the input (for example if the input stream is not UTF-8).
207 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
208 compiler.session().err(&err.to_string());
210 return Err(ErrorReported);
213 let mut config = interface::Config {
217 input_path: input_file_path,
224 lint_caps: Default::default(),
227 callbacks.config(&mut config);
229 interface::run_compiler(config, |compiler| {
230 let sess = compiler.session();
231 let should_stop = RustcDefaultCalls::print_crate_info(
232 &***compiler.codegen_backend(),
234 Some(compiler.input()),
235 compiler.output_dir(),
236 compiler.output_file(),
237 ).and_then(|| RustcDefaultCalls::list_metadata(
244 if should_stop == Compilation::Stop {
245 return sess.compile_status();
248 let pretty_info = parse_pretty(sess, &matches);
252 if let Some((ppm, opt_uii)) = pretty_info {
253 if ppm.needs_ast_map(&opt_uii) {
254 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
255 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
256 let expanded_crate = compiler.expansion()?.take().0;
257 pretty::print_after_hir_lowering(
263 compiler.output_file().as_ref().map(|p| &**p),
267 return sess.compile_status();
269 let mut krate = compiler.parse()?.take();
270 pretty::visit_crate(sess, &mut krate, ppm);
271 pretty::print_after_parsing(
276 compiler.output_file().as_ref().map(|p| &**p),
278 return sess.compile_status();
282 if !callbacks.after_parsing(compiler) {
283 return sess.compile_status();
286 if sess.opts.debugging_opts.parse_only ||
287 sess.opts.debugging_opts.show_span.is_some() ||
288 sess.opts.debugging_opts.ast_json_noexpand {
289 return sess.compile_status();
292 compiler.register_plugins()?;
294 // Lint plugins are registered; now we can process command line flags.
295 if sess.opts.describe_lints {
296 describe_lints(&sess, &sess.lint_store.borrow(), true);
297 return sess.compile_status();
300 compiler.prepare_outputs()?;
302 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
303 && sess.opts.output_types.len() == 1
305 return sess.compile_status();
308 compiler.global_ctxt()?;
310 if sess.opts.debugging_opts.no_analysis ||
311 sess.opts.debugging_opts.ast_json {
312 return sess.compile_status();
315 if sess.opts.debugging_opts.save_analysis {
316 let expanded_crate = &compiler.expansion()?.peek().0;
317 let crate_name = compiler.crate_name()?.peek().clone();
318 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
319 let result = tcx.analysis(LOCAL_CRATE);
321 time(sess, "save analysis", || {
328 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
333 // AST will be dropped *after* the `after_analysis` callback
334 // (needed by the RLS)
337 // Drop AST after creating GlobalCtxt to free memory
338 mem::drop(compiler.expansion()?.take());
341 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
343 if !callbacks.after_analysis(compiler) {
344 return sess.compile_status();
347 if sess.opts.debugging_opts.save_analysis {
348 mem::drop(compiler.expansion()?.take());
351 compiler.ongoing_codegen()?;
353 // Drop GlobalCtxt after starting codegen to free memory
354 mem::drop(compiler.global_ctxt()?.take());
356 if sess.opts.debugging_opts.print_type_sizes {
357 sess.code_stats.borrow().print_type_sizes();
362 if sess.opts.debugging_opts.perf_stats {
363 sess.print_perf_stats();
366 if sess.print_fuel_crate.is_some() {
367 eprintln!("Fuel used by {}: {}",
368 sess.print_fuel_crate.as_ref().unwrap(),
369 sess.print_fuel.load(SeqCst));
377 pub fn set_sigpipe_handler() {
379 // Set the SIGPIPE signal handler, so that an EPIPE
380 // will cause rustc to terminate, as expected.
381 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
386 pub fn set_sigpipe_handler() {}
388 // Extract output directory and file from matches.
389 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
390 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
391 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
395 // Extract input (string or file and optional path) from matches.
396 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
397 if free_matches.len() == 1 {
398 let ifile = &free_matches[0];
400 let mut src = String::new();
401 let err = if io::stdin().read_to_string(&mut src).is_err() {
402 Some(io::Error::new(io::ErrorKind::InvalidData,
403 "couldn't read from stdin, as it did not contain valid UTF-8"))
407 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
410 Some((Input::File(PathBuf::from(ifile)),
411 Some(PathBuf::from(ifile)), None))
418 fn parse_pretty(sess: &Session,
419 matches: &getopts::Matches)
420 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
421 let pretty = if sess.opts.debugging_opts.unstable_options {
422 matches.opt_default("pretty", "normal").map(|a| {
423 // stable pretty-print variants only
424 pretty::parse_pretty(sess, &a, false)
430 if pretty.is_none() {
431 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
432 // extended with unstable pretty-print variants
433 pretty::parse_pretty(sess, &a, true)
440 // Whether to stop or continue compilation.
441 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
442 pub enum Compilation {
448 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
450 Compilation::Stop => Compilation::Stop,
451 Compilation::Continue => next(),
456 /// CompilerCalls instance for a regular rustc build.
457 #[derive(Copy, Clone)]
458 pub struct RustcDefaultCalls;
460 // FIXME remove these and use winapi 0.3 instead
461 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
463 fn stdout_isatty() -> bool {
464 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
468 fn stdout_isatty() -> bool {
471 type HANDLE = *mut u8;
472 type LPDWORD = *mut u32;
473 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
475 fn GetStdHandle(which: DWORD) -> HANDLE;
476 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
479 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
481 GetConsoleMode(handle, &mut out) != 0
485 fn handle_explain(code: &str,
486 output: ErrorOutputType) {
487 let descriptions = rustc_interface::util::diagnostics_registry();
488 let normalised = if code.starts_with("E") {
491 format!("E{0:0>4}", code)
493 match descriptions.find_description(&normalised) {
494 Some(ref description) => {
495 let mut is_in_code_block = false;
496 let mut text = String::new();
498 // Slice off the leading newline and print.
499 for line in description[1..].lines() {
500 let indent_level = line.find(|c: char| !c.is_whitespace())
501 .unwrap_or_else(|| line.len());
502 let dedented_line = &line[indent_level..];
503 if dedented_line.starts_with("```") {
504 is_in_code_block = !is_in_code_block;
505 text.push_str(&line[..(indent_level+3)]);
506 } else if is_in_code_block && dedented_line.starts_with("# ") {
515 show_content_with_pager(&text);
521 early_error(output, &format!("no extended information for {}", code));
526 fn show_content_with_pager(content: &String) {
527 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
528 OsString::from("more.com")
530 OsString::from("less")
533 let mut fallback_to_println = false;
535 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
537 if let Some(pipe) = pager.stdin.as_mut() {
538 if pipe.write_all(content.as_bytes()).is_err() {
539 fallback_to_println = true;
543 if pager.wait().is_err() {
544 fallback_to_println = true;
548 fallback_to_println = true;
552 // If pager fails for whatever reason, we should still print the content
553 // to standard output
554 if fallback_to_println {
555 print!("{}", content);
559 impl RustcDefaultCalls {
560 pub fn list_metadata(sess: &Session,
562 matches: &getopts::Matches,
565 let r = matches.opt_strs("Z");
566 if r.iter().any(|s| *s == "ls") {
568 &Input::File(ref ifile) => {
569 let path = &(*ifile);
570 let mut v = Vec::new();
571 locator::list_file_metadata(&sess.target.target,
573 &*cstore.metadata_loader,
576 println!("{}", String::from_utf8(v).unwrap());
578 &Input::Str { .. } => {
579 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
582 return Compilation::Stop;
585 Compilation::Continue
589 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
591 input: Option<&Input>,
592 odir: &Option<PathBuf>,
593 ofile: &Option<PathBuf>)
595 use rustc::session::config::PrintRequest::*;
596 // PrintRequest::NativeStaticLibs is special - printed during linking
597 // (empty iterator returns true)
598 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
599 return Compilation::Continue;
602 let attrs = match input {
605 let result = parse_crate_attrs(sess, input);
607 Ok(attrs) => Some(attrs),
608 Err(mut parse_error) => {
610 return Compilation::Stop;
615 for req in &sess.opts.prints {
618 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
620 println!("{}", targets.join("\n"));
622 Sysroot => println!("{}", sess.sysroot.display()),
623 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
624 FileNames | CrateName => {
625 let input = input.unwrap_or_else(||
626 early_error(ErrorOutputType::default(), "no input file provided"));
627 let attrs = attrs.as_ref().unwrap();
628 let t_outputs = rustc_interface::util::build_output_filenames(
635 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
636 if *req == PrintRequest::CrateName {
640 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
641 for &style in &crate_types {
642 let fname = rustc_codegen_utils::link::filename_for_input(
648 println!("{}", fname.file_name().unwrap().to_string_lossy());
652 let allow_unstable_cfg = UnstableFeatures::from_environment()
655 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
656 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
657 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
658 node: ast::MetaItemKind::Word,
662 // Note that crt-static is a specially recognized cfg
663 // directive that's printed out here as part of
664 // rust-lang/rust#37406, but in general the
665 // `target_feature` cfg is gated under
666 // rust-lang/rust#29717. For now this is just
667 // specifically allowing the crt-static cfg and that's
668 // it, this is intended to get into Cargo and then go
669 // through to build scripts.
670 let value = value.as_ref().map(|s| s.as_str());
671 let value = value.as_ref().map(|s| s.as_ref());
672 if name != "target_feature" || value != Some("crt-static") {
673 if !allow_unstable_cfg && gated_cfg.is_some() {
678 if let Some(value) = value {
679 Some(format!("{}=\"{}\"", name, value))
681 Some(name.to_string())
683 }).collect::<Vec<String>>();
690 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
691 codegen_backend.print(*req, sess);
693 // Any output here interferes with Cargo's parsing of other printed output
694 PrintRequest::NativeStaticLibs => {}
697 return Compilation::Stop;
701 /// Returns a version string such as "0.12.0-dev".
702 fn release_str() -> Option<&'static str> {
703 option_env!("CFG_RELEASE")
706 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
707 fn commit_hash_str() -> Option<&'static str> {
708 option_env!("CFG_VER_HASH")
711 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
712 fn commit_date_str() -> Option<&'static str> {
713 option_env!("CFG_VER_DATE")
716 /// Prints version information
717 pub fn version(binary: &str, matches: &getopts::Matches) {
718 let verbose = matches.opt_present("verbose");
720 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
723 fn unw(x: Option<&str>) -> &str {
724 x.unwrap_or("unknown")
726 println!("binary: {}", binary);
727 println!("commit-hash: {}", unw(commit_hash_str()));
728 println!("commit-date: {}", unw(commit_date_str()));
729 println!("host: {}", config::host_triple());
730 println!("release: {}", unw(release_str()));
731 get_codegen_sysroot("llvm")().print_version();
735 fn usage(verbose: bool, include_unstable_options: bool) {
736 let groups = if verbose {
737 config::rustc_optgroups()
739 config::rustc_short_optgroups()
741 let mut options = getopts::Options::new();
742 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
743 (option.apply)(&mut options);
745 let message = "Usage: rustc [OPTIONS] INPUT";
746 let nightly_help = if nightly_options::is_nightly_build() {
747 "\n -Z help Print unstable compiler options"
751 let verbose_help = if verbose {
754 "\n --help -v Print the full set of options rustc accepts"
756 println!("{}\nAdditional help:
757 -C help Print codegen options
759 Print 'lint' options and default settings{}{}\n",
760 options.usage(message),
765 fn print_wall_help() {
767 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
768 default. Use `rustc -W help` to see all available lints. It's more common to put
769 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
770 the command line flag directly.
774 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
776 Available lint options:
777 -W <foo> Warn about <foo>
781 -F <foo> Forbid <foo> \
782 (deny <foo> and all attempts to override)
786 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
787 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
788 // The sort doesn't case-fold but it's doubtful we care.
789 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
793 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
794 -> Vec<(&'static str, Vec<lint::LintId>)> {
795 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
796 lints.sort_by_key(|l| l.0);
800 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
803 .partition(|&(_, p)| p);
804 let plugin = sort_lints(sess, plugin);
805 let builtin = sort_lints(sess, builtin);
807 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
810 .partition(|&(.., p)| p);
811 let plugin_groups = sort_lint_groups(plugin_groups);
812 let builtin_groups = sort_lint_groups(builtin_groups);
814 let max_name_len = plugin.iter()
816 .map(|&s| s.name.chars().count())
819 let padded = |x: &str| {
820 let mut s = " ".repeat(max_name_len - x.chars().count());
825 println!("Lint checks provided by rustc:\n");
826 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
827 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
829 let print_lints = |lints: Vec<&Lint>| {
831 let name = lint.name_lower().replace("_", "-");
832 println!(" {} {:7.7} {}",
834 lint.default_level.as_str(),
840 print_lints(builtin);
842 let max_name_len = max("warnings".len(),
844 .chain(&builtin_groups)
845 .map(|&(s, _)| s.chars().count())
849 let padded = |x: &str| {
850 let mut s = " ".repeat(max_name_len - x.chars().count());
855 println!("Lint groups provided by rustc:\n");
856 println!(" {} {}", padded("name"), "sub-lints");
857 println!(" {} {}", padded("----"), "---------");
858 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
860 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
861 for (name, to) in lints {
862 let name = name.to_lowercase().replace("_", "-");
863 let desc = to.into_iter()
864 .map(|x| x.to_string().replace("_", "-"))
865 .collect::<Vec<String>>()
867 println!(" {} {}", padded(&name), desc);
872 print_lint_groups(builtin_groups);
874 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
875 (false, 0, _) | (false, _, 0) => {
876 println!("Compiler plugins can provide additional lints and lint groups. To see a \
877 listing of these, re-run `rustc -W help` with a crate filename.");
879 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
880 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
883 println!("Lint checks provided by plugins loaded by this crate:\n");
887 println!("Lint groups provided by plugins loaded by this crate:\n");
888 print_lint_groups(plugin_groups);
894 fn describe_debug_flags() {
895 println!("\nAvailable options:\n");
896 print_flag_list("-Z", config::DB_OPTIONS);
899 fn describe_codegen_flags() {
900 println!("\nAvailable codegen options:\n");
901 print_flag_list("-C", config::CG_OPTIONS);
904 fn print_flag_list<T>(cmdline_opt: &str,
905 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
906 let max_len = flag_list.iter()
907 .map(|&(name, _, opt_type_desc, _)| {
908 let extra_len = match opt_type_desc {
912 name.chars().count() + extra_len
917 for &(name, _, opt_type_desc, desc) in flag_list {
918 let (width, extra) = match opt_type_desc {
919 Some(..) => (max_len - 4, "=val"),
920 None => (max_len, ""),
922 println!(" {} {:>width$}{} -- {}",
924 name.replace("_", "-"),
931 /// Process command line options. Emits messages as appropriate. If compilation
932 /// should continue, returns a getopts::Matches object parsed from args,
933 /// otherwise returns `None`.
935 /// The compiler's handling of options is a little complicated as it ties into
936 /// our stability story, and it's even *more* complicated by historical
937 /// accidents. The current intention of each compiler option is to have one of
940 /// 1. An option is stable and can be used everywhere.
941 /// 2. An option is unstable, but was historically allowed on the stable
943 /// 3. An option is unstable, and can only be used on nightly.
945 /// Like unstable library and language features, however, unstable options have
946 /// always required a form of "opt in" to indicate that you're using them. This
947 /// provides the easy ability to scan a code base to check to see if anything
948 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
950 /// All options behind `-Z` are considered unstable by default. Other top-level
951 /// options can also be considered unstable, and they were unlocked through the
952 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
953 /// instability in both cases, though.
955 /// So with all that in mind, the comments below have some more detail about the
956 /// contortions done here to get things to work out correctly.
957 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
958 // Throw away the first argument, the name of the binary
959 let args = &args[1..];
962 // user did not write `-v` nor `-Z unstable-options`, so do not
963 // include that extra information.
968 // Parse with *all* options defined in the compiler, we don't worry about
969 // option stability here we just want to parse as much as possible.
970 let mut options = getopts::Options::new();
971 for option in config::rustc_optgroups() {
972 (option.apply)(&mut options);
974 let matches = options.parse(args).unwrap_or_else(|f|
975 early_error(ErrorOutputType::default(), &f.to_string()));
977 // For all options we just parsed, we check a few aspects:
979 // * If the option is stable, we're all good
980 // * If the option wasn't passed, we're all good
981 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
982 // ourselves), then we require the `-Z unstable-options` flag to unlock
983 // this option that was passed.
984 // * If we're a nightly compiler, then unstable options are now unlocked, so
986 // * Otherwise, if we're a truly unstable option then we generate an error
987 // (unstable option being used on stable)
988 // * If we're a historically stable-but-should-be-unstable option then we
989 // emit a warning that we're going to turn this into an error soon.
990 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
992 if matches.opt_present("h") || matches.opt_present("help") {
993 // Only show unstable options in --help if we *really* accept unstable
994 // options, which catches the case where we got `-Z unstable-options` on
995 // the stable channel of Rust which was accidentally allowed
997 usage(matches.opt_present("verbose"),
998 nightly_options::is_unstable_enabled(&matches));
1002 // Handle the special case of -Wall.
1003 let wall = matches.opt_strs("W");
1004 if wall.iter().any(|x| *x == "all") {
1009 // Don't handle -W help here, because we might first load plugins.
1010 let r = matches.opt_strs("Z");
1011 if r.iter().any(|x| *x == "help") {
1012 describe_debug_flags();
1016 let cg_flags = matches.opt_strs("C");
1018 if cg_flags.iter().any(|x| *x == "help") {
1019 describe_codegen_flags();
1023 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1024 early_warn(ErrorOutputType::default(),
1025 "the --no-stack-check flag is deprecated and does nothing");
1028 if cg_flags.iter().any(|x| *x == "passes=list") {
1029 get_codegen_sysroot("llvm")().print_passes();
1033 if matches.opt_present("version") {
1034 version("rustc", &matches);
1041 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1043 Input::File(ref ifile) => {
1044 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1046 Input::Str { ref name, ref input } => {
1047 parse::parse_crate_attrs_from_source_str(name.clone(),
1054 /// Gets a list of extra command-line flags provided by the user, as strings.
1056 /// This function is used during ICEs to show more information useful for
1057 /// debugging, since some ICEs only happens with non-default compiler flags
1058 /// (and the users don't always report them).
1059 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1060 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1062 // Avoid printing help because of empty args. This can suggest the compiler
1063 // itself is not the program root (consider RLS).
1068 let matches = if let Some(matches) = handle_options(&args) {
1074 let mut result = Vec::new();
1075 let mut excluded_cargo_defaults = false;
1076 for flag in ICE_REPORT_COMPILER_FLAGS {
1077 let prefix = if flag.len() == 1 { "-" } else { "--" };
1079 for content in &matches.opt_strs(flag) {
1080 // Split always returns the first element
1081 let name = if let Some(first) = content.split('=').next() {
1087 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1093 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1094 result.push(format!("{}{} {}", prefix, flag, content));
1096 excluded_cargo_defaults = true;
1101 if !result.is_empty() {
1102 Some((result, excluded_cargo_defaults))
1108 /// Runs a procedure which will detect panics in the compiler and print nicer
1109 /// error messages rather than just failing the test.
1111 /// The diagnostic emitter yielded to the procedure should be used for reporting
1112 /// errors of the compiler.
1113 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1114 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1115 if value.is::<errors::FatalErrorMarker>() {
1118 // Thread panicked without emitting a fatal diagnostic
1122 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1126 let handler = errors::Handler::with_emitter(true, None, emitter);
1128 // a .span_bug or .bug call has already printed what
1129 // it wants to print.
1130 if !value.is::<errors::ExplicitBug>() {
1131 handler.emit(&MultiSpan::new(),
1133 errors::Level::Bug);
1136 let mut xs: Vec<Cow<'static, str>> = vec![
1137 "the compiler unexpectedly panicked. this is a bug.".into(),
1138 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1139 format!("rustc {} running on {}",
1140 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1141 config::host_triple()).into(),
1144 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1145 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1147 if excluded_cargo_defaults {
1148 xs.push("some of the compiler flags provided by cargo are hidden".into());
1153 handler.emit(&MultiSpan::new(),
1155 errors::Level::Note);
1158 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1163 /// This allows tools to enable rust logging without having to magically match rustc's
1164 /// log crate version
1165 pub fn init_rustc_env_logger() {
1166 env_logger::init_from_env("RUSTC_LOG");
1170 init_rustc_env_logger();
1171 let result = report_ices_to_stderr_if_any(|| {
1172 let args = env::args_os().enumerate()
1173 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1174 early_error(ErrorOutputType::default(),
1175 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1177 .collect::<Vec<_>>();
1178 run_compiler(&args, &mut DefaultCallbacks, None, None)
1179 }).and_then(|result| result);
1180 process::exit(match result {
1181 Ok(_) => EXIT_SUCCESS,
1182 Err(_) => EXIT_FAILURE,