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 #![deny(unused_lifetimes)]
23 pub extern crate getopts;
29 use pretty::{PpMode, UserIdentifiedItem};
31 //use rustc_resolve as resolve;
32 use rustc_save_analysis as save;
33 use rustc_save_analysis::DumpHandler;
34 use rustc::session::{config, Session, DiagnosticOutput};
35 use rustc::session::config::{Input, PrintRequest, ErrorOutputType, OutputType};
36 use rustc::session::config::nightly_options;
37 use rustc::session::{early_error, early_warn};
38 use rustc::lint::Lint;
40 use rustc::hir::def_id::LOCAL_CRATE;
41 use rustc::util::common::{time, ErrorReported, install_panic_hook};
42 use rustc_metadata::locator;
43 use rustc_metadata::cstore::CStore;
44 use rustc_codegen_utils::codegen_backend::CodegenBackend;
45 use rustc_interface::interface;
46 use rustc_interface::util::get_codegen_sysroot;
47 use rustc_data_structures::sync::SeqCst;
49 use serialize::json::ToJson;
53 use std::default::Default;
55 use std::ffi::OsString;
56 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};
64 use syntax::source_map::FileLoader;
65 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
66 use syntax::parse::{self, PResult};
67 use syntax::symbol::sym;
68 use syntax_pos::{DUMMY_SP, MultiSpan, 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 and returns true to continue execution
108 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> bool {
111 /// Called after analysis and returns true to continue execution
112 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> bool {
117 pub struct DefaultCallbacks;
119 impl Callbacks for DefaultCallbacks {}
121 // Parse args and run the compiler. This is the primary entry point for rustc.
122 // See comments on CompilerCalls below for details about the callbacks argument.
123 // The FileLoader provides a way to load files from sources other than the file system.
126 callbacks: &mut (dyn Callbacks + Send),
127 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
128 emitter: Option<Box<dyn Write + Send>>
129 ) -> interface::Result<()> {
130 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
131 .unwrap_or(DiagnosticOutput::Default);
132 let matches = match handle_options(args) {
133 Some(matches) => matches,
134 None => return Ok(()),
137 install_panic_hook();
139 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
141 let mut dummy_config = |sopts, cfg, diagnostic_output| {
142 let mut config = interface::Config {
145 input: Input::File(PathBuf::new()),
153 lint_caps: Default::default(),
155 callbacks.config(&mut config);
159 if let Some(ref code) = matches.opt_str("explain") {
160 handle_explain(code, sopts.error_format);
164 let (odir, ofile) = make_output(&matches);
165 let (input, input_file_path, input_err) = match make_input(&matches.free) {
168 match matches.free.len() {
170 let config = dummy_config(sopts, cfg, diagnostic_output);
171 interface::run_compiler(config, |compiler| {
172 let sopts = &compiler.session().opts;
173 if sopts.describe_lints {
176 &*compiler.session().lint_store.borrow(),
181 let should_stop = RustcDefaultCalls::print_crate_info(
182 &***compiler.codegen_backend(),
189 if should_stop == Compilation::Stop {
192 early_error(sopts.error_format, "no input filename given")
196 1 => panic!("make_input should have provided valid inputs"),
197 _ => early_error(sopts.error_format, &format!(
198 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
206 if let Some(err) = input_err {
207 // Immediately stop compilation if there was an issue reading
208 // the input (for example if the input stream is not UTF-8).
209 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
210 compiler.session().err(&err.to_string());
212 return Err(ErrorReported);
215 let mut config = interface::Config {
219 input_path: input_file_path,
226 lint_caps: Default::default(),
229 callbacks.config(&mut config);
231 interface::run_compiler(config, |compiler| {
232 let sess = compiler.session();
233 let should_stop = RustcDefaultCalls::print_crate_info(
234 &***compiler.codegen_backend(),
236 Some(compiler.input()),
237 compiler.output_dir(),
238 compiler.output_file(),
239 ).and_then(|| RustcDefaultCalls::list_metadata(
246 if should_stop == Compilation::Stop {
247 return sess.compile_status();
250 let pretty_info = parse_pretty(sess, &matches);
254 if let Some((ppm, opt_uii)) = pretty_info {
255 if ppm.needs_ast_map(&opt_uii) {
256 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
257 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
258 let expanded_crate = compiler.expansion()?.take().0;
259 pretty::print_after_hir_lowering(
265 compiler.output_file().as_ref().map(|p| &**p),
269 return sess.compile_status();
271 let mut krate = compiler.parse()?.take();
272 pretty::visit_crate(sess, &mut krate, ppm);
273 pretty::print_after_parsing(
278 compiler.output_file().as_ref().map(|p| &**p),
280 return sess.compile_status();
284 if !callbacks.after_parsing(compiler) {
285 return sess.compile_status();
288 if sess.opts.debugging_opts.parse_only ||
289 sess.opts.debugging_opts.show_span.is_some() ||
290 sess.opts.debugging_opts.ast_json_noexpand {
291 return sess.compile_status();
294 compiler.register_plugins()?;
296 // Lint plugins are registered; now we can process command line flags.
297 if sess.opts.describe_lints {
298 describe_lints(&sess, &sess.lint_store.borrow(), true);
299 return sess.compile_status();
302 compiler.prepare_outputs()?;
304 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
305 && sess.opts.output_types.len() == 1
307 return sess.compile_status();
310 compiler.global_ctxt()?;
312 if sess.opts.debugging_opts.no_analysis ||
313 sess.opts.debugging_opts.ast_json {
314 return sess.compile_status();
317 if sess.opts.debugging_opts.save_analysis {
318 let expanded_crate = &compiler.expansion()?.peek().0;
319 let crate_name = compiler.crate_name()?.peek().clone();
320 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
321 let result = tcx.analysis(LOCAL_CRATE);
323 time(sess, "save analysis", || {
330 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
335 // AST will be dropped *after* the `after_analysis` callback
336 // (needed by the RLS)
339 // Drop AST after creating GlobalCtxt to free memory
340 mem::drop(compiler.expansion()?.take());
343 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
345 if !callbacks.after_analysis(compiler) {
346 return sess.compile_status();
349 if sess.opts.debugging_opts.save_analysis {
350 mem::drop(compiler.expansion()?.take());
353 compiler.ongoing_codegen()?;
355 // Drop GlobalCtxt after starting codegen to free memory
356 mem::drop(compiler.global_ctxt()?.take());
358 if sess.opts.debugging_opts.print_type_sizes {
359 sess.code_stats.borrow().print_type_sizes();
364 if sess.opts.debugging_opts.perf_stats {
365 sess.print_perf_stats();
368 if sess.print_fuel_crate.is_some() {
369 eprintln!("Fuel used by {}: {}",
370 sess.print_fuel_crate.as_ref().unwrap(),
371 sess.print_fuel.load(SeqCst));
379 pub fn set_sigpipe_handler() {
381 // Set the SIGPIPE signal handler, so that an EPIPE
382 // will cause rustc to terminate, as expected.
383 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
388 pub fn set_sigpipe_handler() {}
390 // Extract output directory and file from matches.
391 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
392 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
393 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
397 // Extract input (string or file and optional path) from matches.
398 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
399 if free_matches.len() == 1 {
400 let ifile = &free_matches[0];
402 let mut src = String::new();
403 let err = if io::stdin().read_to_string(&mut src).is_err() {
404 Some(io::Error::new(io::ErrorKind::InvalidData,
405 "couldn't read from stdin, as it did not contain valid UTF-8"))
409 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
412 Some((Input::File(PathBuf::from(ifile)),
413 Some(PathBuf::from(ifile)), None))
420 fn parse_pretty(sess: &Session,
421 matches: &getopts::Matches)
422 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
423 let pretty = if sess.opts.debugging_opts.unstable_options {
424 matches.opt_default("pretty", "normal").map(|a| {
425 // stable pretty-print variants only
426 pretty::parse_pretty(sess, &a, false)
432 if pretty.is_none() {
433 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
434 // extended with unstable pretty-print variants
435 pretty::parse_pretty(sess, &a, true)
442 // Whether to stop or continue compilation.
443 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
444 pub enum Compilation {
450 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
452 Compilation::Stop => Compilation::Stop,
453 Compilation::Continue => next(),
458 /// CompilerCalls instance for a regular rustc build.
459 #[derive(Copy, Clone)]
460 pub struct RustcDefaultCalls;
462 // FIXME remove these and use winapi 0.3 instead
463 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
465 fn stdout_isatty() -> bool {
466 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
470 fn stdout_isatty() -> bool {
473 type HANDLE = *mut u8;
474 type LPDWORD = *mut u32;
475 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
477 fn GetStdHandle(which: DWORD) -> HANDLE;
478 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
481 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
483 GetConsoleMode(handle, &mut out) != 0
487 fn handle_explain(code: &str,
488 output: ErrorOutputType) {
489 let descriptions = rustc_interface::util::diagnostics_registry();
490 let normalised = if code.starts_with("E") {
493 format!("E{0:0>4}", code)
495 match descriptions.find_description(&normalised) {
496 Some(ref description) => {
497 let mut is_in_code_block = false;
498 let mut text = String::new();
500 // Slice off the leading newline and print.
501 for line in description[1..].lines() {
502 let indent_level = line.find(|c: char| !c.is_whitespace())
503 .unwrap_or_else(|| line.len());
504 let dedented_line = &line[indent_level..];
505 if dedented_line.starts_with("```") {
506 is_in_code_block = !is_in_code_block;
507 text.push_str(&line[..(indent_level+3)]);
508 } else if is_in_code_block && dedented_line.starts_with("# ") {
517 show_content_with_pager(&text);
523 early_error(output, &format!("no extended information for {}", code));
528 fn show_content_with_pager(content: &String) {
529 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
530 OsString::from("more.com")
532 OsString::from("less")
535 let mut fallback_to_println = false;
537 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
539 if let Some(pipe) = pager.stdin.as_mut() {
540 if pipe.write_all(content.as_bytes()).is_err() {
541 fallback_to_println = true;
545 if pager.wait().is_err() {
546 fallback_to_println = true;
550 fallback_to_println = true;
554 // If pager fails for whatever reason, we should still print the content
555 // to standard output
556 if fallback_to_println {
557 print!("{}", content);
561 impl RustcDefaultCalls {
562 pub fn list_metadata(sess: &Session,
564 matches: &getopts::Matches,
567 let r = matches.opt_strs("Z");
568 if r.iter().any(|s| *s == "ls") {
570 &Input::File(ref ifile) => {
571 let path = &(*ifile);
572 let mut v = Vec::new();
573 locator::list_file_metadata(&sess.target.target,
575 &*cstore.metadata_loader,
578 println!("{}", String::from_utf8(v).unwrap());
580 &Input::Str { .. } => {
581 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
584 return Compilation::Stop;
587 Compilation::Continue
591 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
593 input: Option<&Input>,
594 odir: &Option<PathBuf>,
595 ofile: &Option<PathBuf>)
597 use rustc::session::config::PrintRequest::*;
598 // PrintRequest::NativeStaticLibs is special - printed during linking
599 // (empty iterator returns true)
600 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
601 return Compilation::Continue;
604 let attrs = match input {
607 let result = parse_crate_attrs(sess, input);
609 Ok(attrs) => Some(attrs),
610 Err(mut parse_error) => {
612 return Compilation::Stop;
617 for req in &sess.opts.prints {
620 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
622 println!("{}", targets.join("\n"));
624 Sysroot => println!("{}", sess.sysroot.display()),
625 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
626 FileNames | CrateName => {
627 let input = input.unwrap_or_else(||
628 early_error(ErrorOutputType::default(), "no input file provided"));
629 let attrs = attrs.as_ref().unwrap();
630 let t_outputs = rustc_interface::util::build_output_filenames(
637 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
638 if *req == PrintRequest::CrateName {
642 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
643 for &style in &crate_types {
644 let fname = rustc_codegen_utils::link::filename_for_input(
650 println!("{}", fname.file_name().unwrap().to_string_lossy());
654 let allow_unstable_cfg = UnstableFeatures::from_environment()
657 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
658 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
659 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
660 node: ast::MetaItemKind::Word,
664 // Note that crt-static is a specially recognized cfg
665 // directive that's printed out here as part of
666 // rust-lang/rust#37406, but in general the
667 // `target_feature` cfg is gated under
668 // rust-lang/rust#29717. For now this is just
669 // specifically allowing the crt-static cfg and that's
670 // it, this is intended to get into Cargo and then go
671 // through to build scripts.
672 let value = value.as_ref().map(|s| s.as_str());
673 let value = value.as_ref().map(|s| s.as_ref());
674 if name != sym::target_feature || value != Some("crt-static") {
675 if !allow_unstable_cfg && gated_cfg.is_some() {
680 if let Some(value) = value {
681 Some(format!("{}=\"{}\"", name, value))
683 Some(name.to_string())
685 }).collect::<Vec<String>>();
692 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
693 codegen_backend.print(*req, sess);
695 // Any output here interferes with Cargo's parsing of other printed output
696 PrintRequest::NativeStaticLibs => {}
699 return Compilation::Stop;
703 /// Returns a version string such as "0.12.0-dev".
704 fn release_str() -> Option<&'static str> {
705 option_env!("CFG_RELEASE")
708 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
709 fn commit_hash_str() -> Option<&'static str> {
710 option_env!("CFG_VER_HASH")
713 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
714 fn commit_date_str() -> Option<&'static str> {
715 option_env!("CFG_VER_DATE")
718 /// Prints version information
719 pub fn version(binary: &str, matches: &getopts::Matches) {
720 let verbose = matches.opt_present("verbose");
722 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
725 fn unw(x: Option<&str>) -> &str {
726 x.unwrap_or("unknown")
728 println!("binary: {}", binary);
729 println!("commit-hash: {}", unw(commit_hash_str()));
730 println!("commit-date: {}", unw(commit_date_str()));
731 println!("host: {}", config::host_triple());
732 println!("release: {}", unw(release_str()));
733 get_codegen_sysroot("llvm")().print_version();
737 fn usage(verbose: bool, include_unstable_options: bool) {
738 let groups = if verbose {
739 config::rustc_optgroups()
741 config::rustc_short_optgroups()
743 let mut options = getopts::Options::new();
744 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
745 (option.apply)(&mut options);
747 let message = "Usage: rustc [OPTIONS] INPUT";
748 let nightly_help = if nightly_options::is_nightly_build() {
749 "\n -Z help Print unstable compiler options"
753 let verbose_help = if verbose {
756 "\n --help -v Print the full set of options rustc accepts"
758 println!("{}\nAdditional help:
759 -C help Print codegen options
761 Print 'lint' options and default settings{}{}\n",
762 options.usage(message),
767 fn print_wall_help() {
769 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
770 default. Use `rustc -W help` to see all available lints. It's more common to put
771 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
772 the command line flag directly.
776 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
778 Available lint options:
779 -W <foo> Warn about <foo>
783 -F <foo> Forbid <foo> \
784 (deny <foo> and all attempts to override)
788 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
789 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
790 // The sort doesn't case-fold but it's doubtful we care.
791 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
795 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
796 -> Vec<(&'static str, Vec<lint::LintId>)> {
797 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
798 lints.sort_by_key(|l| l.0);
802 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
805 .partition(|&(_, p)| p);
806 let plugin = sort_lints(sess, plugin);
807 let builtin = sort_lints(sess, builtin);
809 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
812 .partition(|&(.., p)| p);
813 let plugin_groups = sort_lint_groups(plugin_groups);
814 let builtin_groups = sort_lint_groups(builtin_groups);
816 let max_name_len = plugin.iter()
818 .map(|&s| s.name.chars().count())
821 let padded = |x: &str| {
822 let mut s = " ".repeat(max_name_len - x.chars().count());
827 println!("Lint checks provided by rustc:\n");
828 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
829 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
831 let print_lints = |lints: Vec<&Lint>| {
833 let name = lint.name_lower().replace("_", "-");
834 println!(" {} {:7.7} {}",
836 lint.default_level.as_str(),
842 print_lints(builtin);
844 let max_name_len = max("warnings".len(),
846 .chain(&builtin_groups)
847 .map(|&(s, _)| s.chars().count())
851 let padded = |x: &str| {
852 let mut s = " ".repeat(max_name_len - x.chars().count());
857 println!("Lint groups provided by rustc:\n");
858 println!(" {} {}", padded("name"), "sub-lints");
859 println!(" {} {}", padded("----"), "---------");
860 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
862 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
863 for (name, to) in lints {
864 let name = name.to_lowercase().replace("_", "-");
865 let desc = to.into_iter()
866 .map(|x| x.to_string().replace("_", "-"))
867 .collect::<Vec<String>>()
869 println!(" {} {}", padded(&name), desc);
874 print_lint_groups(builtin_groups);
876 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
877 (false, 0, _) | (false, _, 0) => {
878 println!("Compiler plugins can provide additional lints and lint groups. To see a \
879 listing of these, re-run `rustc -W help` with a crate filename.");
881 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
882 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
885 println!("Lint checks provided by plugins loaded by this crate:\n");
889 println!("Lint groups provided by plugins loaded by this crate:\n");
890 print_lint_groups(plugin_groups);
896 fn describe_debug_flags() {
897 println!("\nAvailable options:\n");
898 print_flag_list("-Z", config::DB_OPTIONS);
901 fn describe_codegen_flags() {
902 println!("\nAvailable codegen options:\n");
903 print_flag_list("-C", config::CG_OPTIONS);
906 fn print_flag_list<T>(cmdline_opt: &str,
907 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
908 let max_len = flag_list.iter()
909 .map(|&(name, _, opt_type_desc, _)| {
910 let extra_len = match opt_type_desc {
914 name.chars().count() + extra_len
919 for &(name, _, opt_type_desc, desc) in flag_list {
920 let (width, extra) = match opt_type_desc {
921 Some(..) => (max_len - 4, "=val"),
922 None => (max_len, ""),
924 println!(" {} {:>width$}{} -- {}",
926 name.replace("_", "-"),
933 /// Process command line options. Emits messages as appropriate. If compilation
934 /// should continue, returns a getopts::Matches object parsed from args,
935 /// otherwise returns `None`.
937 /// The compiler's handling of options is a little complicated as it ties into
938 /// our stability story, and it's even *more* complicated by historical
939 /// accidents. The current intention of each compiler option is to have one of
942 /// 1. An option is stable and can be used everywhere.
943 /// 2. An option is unstable, but was historically allowed on the stable
945 /// 3. An option is unstable, and can only be used on nightly.
947 /// Like unstable library and language features, however, unstable options have
948 /// always required a form of "opt in" to indicate that you're using them. This
949 /// provides the easy ability to scan a code base to check to see if anything
950 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
952 /// All options behind `-Z` are considered unstable by default. Other top-level
953 /// options can also be considered unstable, and they were unlocked through the
954 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
955 /// instability in both cases, though.
957 /// So with all that in mind, the comments below have some more detail about the
958 /// contortions done here to get things to work out correctly.
959 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
960 // Throw away the first argument, the name of the binary
961 let args = &args[1..];
964 // user did not write `-v` nor `-Z unstable-options`, so do not
965 // include that extra information.
970 // Parse with *all* options defined in the compiler, we don't worry about
971 // option stability here we just want to parse as much as possible.
972 let mut options = getopts::Options::new();
973 for option in config::rustc_optgroups() {
974 (option.apply)(&mut options);
976 let matches = options.parse(args).unwrap_or_else(|f|
977 early_error(ErrorOutputType::default(), &f.to_string()));
979 // For all options we just parsed, we check a few aspects:
981 // * If the option is stable, we're all good
982 // * If the option wasn't passed, we're all good
983 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
984 // ourselves), then we require the `-Z unstable-options` flag to unlock
985 // this option that was passed.
986 // * If we're a nightly compiler, then unstable options are now unlocked, so
988 // * Otherwise, if we're a truly unstable option then we generate an error
989 // (unstable option being used on stable)
990 // * If we're a historically stable-but-should-be-unstable option then we
991 // emit a warning that we're going to turn this into an error soon.
992 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
994 if matches.opt_present("h") || matches.opt_present("help") {
995 // Only show unstable options in --help if we *really* accept unstable
996 // options, which catches the case where we got `-Z unstable-options` on
997 // the stable channel of Rust which was accidentally allowed
999 usage(matches.opt_present("verbose"),
1000 nightly_options::is_unstable_enabled(&matches));
1004 // Handle the special case of -Wall.
1005 let wall = matches.opt_strs("W");
1006 if wall.iter().any(|x| *x == "all") {
1011 // Don't handle -W help here, because we might first load plugins.
1012 let r = matches.opt_strs("Z");
1013 if r.iter().any(|x| *x == "help") {
1014 describe_debug_flags();
1018 let cg_flags = matches.opt_strs("C");
1020 if cg_flags.iter().any(|x| *x == "help") {
1021 describe_codegen_flags();
1025 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1026 early_warn(ErrorOutputType::default(),
1027 "the --no-stack-check flag is deprecated and does nothing");
1030 if cg_flags.iter().any(|x| *x == "passes=list") {
1031 get_codegen_sysroot("llvm")().print_passes();
1035 if matches.opt_present("version") {
1036 version("rustc", &matches);
1043 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1045 Input::File(ref ifile) => {
1046 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1048 Input::Str { ref name, ref input } => {
1049 parse::parse_crate_attrs_from_source_str(name.clone(),
1056 /// Gets a list of extra command-line flags provided by the user, as strings.
1058 /// This function is used during ICEs to show more information useful for
1059 /// debugging, since some ICEs only happens with non-default compiler flags
1060 /// (and the users don't always report them).
1061 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1062 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1064 // Avoid printing help because of empty args. This can suggest the compiler
1065 // itself is not the program root (consider RLS).
1070 let matches = if let Some(matches) = handle_options(&args) {
1076 let mut result = Vec::new();
1077 let mut excluded_cargo_defaults = false;
1078 for flag in ICE_REPORT_COMPILER_FLAGS {
1079 let prefix = if flag.len() == 1 { "-" } else { "--" };
1081 for content in &matches.opt_strs(flag) {
1082 // Split always returns the first element
1083 let name = if let Some(first) = content.split('=').next() {
1089 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1095 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1096 result.push(format!("{}{} {}", prefix, flag, content));
1098 excluded_cargo_defaults = true;
1103 if !result.is_empty() {
1104 Some((result, excluded_cargo_defaults))
1110 /// Runs a procedure which will detect panics in the compiler and print nicer
1111 /// error messages rather than just failing the test.
1113 /// The diagnostic emitter yielded to the procedure should be used for reporting
1114 /// errors of the compiler.
1115 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1116 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1117 if value.is::<errors::FatalErrorMarker>() {
1120 // Thread panicked without emitting a fatal diagnostic
1124 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1128 let handler = errors::Handler::with_emitter(true, None, emitter);
1130 // a .span_bug or .bug call has already printed what
1131 // it wants to print.
1132 if !value.is::<errors::ExplicitBug>() {
1133 handler.emit(&MultiSpan::new(),
1135 errors::Level::Bug);
1138 let mut xs: Vec<Cow<'static, str>> = vec![
1139 "the compiler unexpectedly panicked. this is a bug.".into(),
1140 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1141 format!("rustc {} running on {}",
1142 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1143 config::host_triple()).into(),
1146 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1147 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1149 if excluded_cargo_defaults {
1150 xs.push("some of the compiler flags provided by cargo are hidden".into());
1155 handler.emit(&MultiSpan::new(),
1157 errors::Level::Note);
1160 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1165 /// This allows tools to enable rust logging without having to magically match rustc's
1166 /// log crate version
1167 pub fn init_rustc_env_logger() {
1168 env_logger::init_from_env("RUSTC_LOG");
1172 init_rustc_env_logger();
1173 let result = report_ices_to_stderr_if_any(|| {
1174 let args = env::args_os().enumerate()
1175 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1176 early_error(ErrorOutputType::default(),
1177 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1179 .collect::<Vec<_>>();
1180 run_compiler(&args, &mut DefaultCallbacks, None, None)
1181 }).and_then(|result| result);
1182 process::exit(match result {
1183 Ok(_) => EXIT_SUCCESS,
1184 Err(_) => EXIT_FAILURE,