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)]
20 #![deny(unused_lifetimes)]
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::{ErrorReported, install_panic_hook, print_time_passes_entry};
41 use rustc::util::common::{set_time_depth, time};
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 rustc_serialize::json::ToJson;
53 use std::default::Default;
55 use std::ffi::OsString;
56 use std::io::{self, Read, Write};
58 use std::panic::{self, catch_unwind};
59 use std::path::PathBuf;
60 use std::process::{self, Command, Stdio};
62 use std::time::Instant;
65 use syntax::source_map::FileLoader;
66 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
67 use syntax::parse::{self, PResult};
68 use syntax::symbol::sym;
69 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
73 /// Exit status code used for successful compilation and help output.
74 pub const EXIT_SUCCESS: i32 = 0;
76 /// Exit status code used for compilation failures and invalid flags.
77 pub const EXIT_FAILURE: i32 = 1;
79 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
82 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
84 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
86 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
88 pub fn source_name(input: &Input) -> FileName {
90 Input::File(ref ifile) => ifile.clone().into(),
91 Input::Str { ref name, .. } => name.clone(),
95 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
98 sess.abort_if_errors();
99 panic!("error reported but abort_if_errors didn't abort???");
105 pub trait Callbacks {
106 /// Called before creating the compiler instance
107 fn config(&mut self, _config: &mut interface::Config) {}
108 /// Called after parsing. Return value instructs the compiler whether to
109 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
110 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
111 Compilation::Continue
113 /// Called after expansion. Return value instructs the compiler whether to
114 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
115 fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
116 Compilation::Continue
118 /// Called after analysis. Return value instructs the compiler whether to
119 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
120 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
121 Compilation::Continue
125 pub struct DefaultCallbacks;
127 impl Callbacks for DefaultCallbacks {}
130 pub struct TimePassesCallbacks {
134 impl Callbacks for TimePassesCallbacks {
135 fn config(&mut self, config: &mut interface::Config) {
137 config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time;
141 // Parse args and run the compiler. This is the primary entry point for rustc.
142 // See comments on CompilerCalls below for details about the callbacks argument.
143 // The FileLoader provides a way to load files from sources other than the file system.
146 callbacks: &mut (dyn Callbacks + Send),
147 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
148 emitter: Option<Box<dyn Write + Send>>
149 ) -> interface::Result<()> {
150 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
151 .unwrap_or(DiagnosticOutput::Default);
152 let matches = match handle_options(args) {
153 Some(matches) => matches,
154 None => return Ok(()),
157 install_panic_hook();
159 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
161 let mut dummy_config = |sopts, cfg, diagnostic_output| {
162 let mut config = interface::Config {
165 input: Input::File(PathBuf::new()),
173 lint_caps: Default::default(),
175 callbacks.config(&mut config);
179 if let Some(ref code) = matches.opt_str("explain") {
180 handle_explain(code, sopts.error_format);
184 let (odir, ofile) = make_output(&matches);
185 let (input, input_file_path, input_err) = match make_input(&matches.free) {
188 match matches.free.len() {
190 let config = dummy_config(sopts, cfg, diagnostic_output);
191 interface::run_compiler(config, |compiler| {
192 let sopts = &compiler.session().opts;
193 if sopts.describe_lints {
196 &*compiler.session().lint_store.borrow(),
201 let should_stop = RustcDefaultCalls::print_crate_info(
202 &***compiler.codegen_backend(),
209 if should_stop == Compilation::Stop {
212 early_error(sopts.error_format, "no input filename given")
216 1 => panic!("make_input should have provided valid inputs"),
217 _ => early_error(sopts.error_format, &format!(
218 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
226 if let Some(err) = input_err {
227 // Immediately stop compilation if there was an issue reading
228 // the input (for example if the input stream is not UTF-8).
229 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
230 compiler.session().err(&err.to_string());
232 return Err(ErrorReported);
235 let mut config = interface::Config {
239 input_path: input_file_path,
246 lint_caps: Default::default(),
249 callbacks.config(&mut config);
251 interface::run_compiler(config, |compiler| {
252 let sess = compiler.session();
253 let should_stop = RustcDefaultCalls::print_crate_info(
254 &***compiler.codegen_backend(),
256 Some(compiler.input()),
257 compiler.output_dir(),
258 compiler.output_file(),
259 ).and_then(|| RustcDefaultCalls::list_metadata(
266 if should_stop == Compilation::Stop {
267 return sess.compile_status();
270 let pretty_info = parse_pretty(sess, &matches);
274 if let Some((ppm, opt_uii)) = pretty_info {
275 if ppm.needs_ast_map(&opt_uii) {
276 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
277 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
278 let expanded_crate = compiler.expansion()?.take().0;
279 pretty::print_after_hir_lowering(
285 compiler.output_file().as_ref().map(|p| &**p),
289 return sess.compile_status();
291 let mut krate = compiler.parse()?.take();
292 pretty::visit_crate(sess, &mut krate, ppm);
293 pretty::print_after_parsing(
298 compiler.output_file().as_ref().map(|p| &**p),
300 return sess.compile_status();
304 if callbacks.after_parsing(compiler) == Compilation::Stop {
305 return sess.compile_status();
308 if sess.opts.debugging_opts.parse_only ||
309 sess.opts.debugging_opts.show_span.is_some() ||
310 sess.opts.debugging_opts.ast_json_noexpand {
311 return sess.compile_status();
314 compiler.register_plugins()?;
316 // Lint plugins are registered; now we can process command line flags.
317 if sess.opts.describe_lints {
318 describe_lints(&sess, &sess.lint_store.borrow(), true);
319 return sess.compile_status();
322 compiler.expansion()?;
323 if callbacks.after_expansion(compiler) == Compilation::Stop {
324 return sess.compile_status();
327 compiler.prepare_outputs()?;
329 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
330 && sess.opts.output_types.len() == 1
332 return sess.compile_status();
335 compiler.global_ctxt()?;
337 if sess.opts.debugging_opts.no_analysis ||
338 sess.opts.debugging_opts.ast_json {
339 return sess.compile_status();
342 if sess.opts.debugging_opts.save_analysis {
343 let expanded_crate = &compiler.expansion()?.peek().0;
344 let crate_name = compiler.crate_name()?.peek().clone();
345 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
346 let result = tcx.analysis(LOCAL_CRATE);
348 time(sess, "save analysis", || {
355 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
360 // AST will be dropped *after* the `after_analysis` callback
361 // (needed by the RLS)
364 // Drop AST after creating GlobalCtxt to free memory
365 mem::drop(compiler.expansion()?.take());
368 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
370 if callbacks.after_analysis(compiler) == Compilation::Stop {
371 return sess.compile_status();
374 if sess.opts.debugging_opts.save_analysis {
375 mem::drop(compiler.expansion()?.take());
378 compiler.ongoing_codegen()?;
380 // Drop GlobalCtxt after starting codegen to free memory
381 mem::drop(compiler.global_ctxt()?.take());
383 if sess.opts.debugging_opts.print_type_sizes {
384 sess.code_stats.borrow().print_type_sizes();
389 if sess.opts.debugging_opts.perf_stats {
390 sess.print_perf_stats();
393 if sess.print_fuel_crate.is_some() {
394 eprintln!("Fuel used by {}: {}",
395 sess.print_fuel_crate.as_ref().unwrap(),
396 sess.print_fuel.load(SeqCst));
404 pub fn set_sigpipe_handler() {
406 // Set the SIGPIPE signal handler, so that an EPIPE
407 // will cause rustc to terminate, as expected.
408 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
413 pub fn set_sigpipe_handler() {}
415 // Extract output directory and file from matches.
416 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
417 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
418 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
422 // Extract input (string or file and optional path) from matches.
423 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
424 if free_matches.len() == 1 {
425 let ifile = &free_matches[0];
427 let mut src = String::new();
428 let err = if io::stdin().read_to_string(&mut src).is_err() {
429 Some(io::Error::new(io::ErrorKind::InvalidData,
430 "couldn't read from stdin, as it did not contain valid UTF-8"))
434 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
437 Some((Input::File(PathBuf::from(ifile)),
438 Some(PathBuf::from(ifile)), None))
445 fn parse_pretty(sess: &Session,
446 matches: &getopts::Matches)
447 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
448 let pretty = if sess.opts.debugging_opts.unstable_options {
449 matches.opt_default("pretty", "normal").map(|a| {
450 // stable pretty-print variants only
451 pretty::parse_pretty(sess, &a, false)
457 if pretty.is_none() {
458 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
459 // extended with unstable pretty-print variants
460 pretty::parse_pretty(sess, &a, true)
467 // Whether to stop or continue compilation.
468 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
469 pub enum Compilation {
475 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
477 Compilation::Stop => Compilation::Stop,
478 Compilation::Continue => next(),
483 /// CompilerCalls instance for a regular rustc build.
484 #[derive(Copy, Clone)]
485 pub struct RustcDefaultCalls;
487 // FIXME remove these and use winapi 0.3 instead
488 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
490 fn stdout_isatty() -> bool {
491 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
495 fn stdout_isatty() -> bool {
498 type HANDLE = *mut u8;
499 type LPDWORD = *mut u32;
500 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
502 fn GetStdHandle(which: DWORD) -> HANDLE;
503 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
506 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
508 GetConsoleMode(handle, &mut out) != 0
512 fn handle_explain(code: &str,
513 output: ErrorOutputType) {
514 let descriptions = rustc_interface::util::diagnostics_registry();
515 let normalised = if code.starts_with("E") {
518 format!("E{0:0>4}", code)
520 match descriptions.find_description(&normalised) {
521 Some(ref description) => {
522 let mut is_in_code_block = false;
523 let mut text = String::new();
525 // Slice off the leading newline and print.
526 for line in description[1..].lines() {
527 let indent_level = line.find(|c: char| !c.is_whitespace())
528 .unwrap_or_else(|| line.len());
529 let dedented_line = &line[indent_level..];
530 if dedented_line.starts_with("```") {
531 is_in_code_block = !is_in_code_block;
532 text.push_str(&line[..(indent_level+3)]);
533 } else if is_in_code_block && dedented_line.starts_with("# ") {
542 show_content_with_pager(&text);
548 early_error(output, &format!("no extended information for {}", code));
553 fn show_content_with_pager(content: &String) {
554 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
555 OsString::from("more.com")
557 OsString::from("less")
560 let mut fallback_to_println = false;
562 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
564 if let Some(pipe) = pager.stdin.as_mut() {
565 if pipe.write_all(content.as_bytes()).is_err() {
566 fallback_to_println = true;
570 if pager.wait().is_err() {
571 fallback_to_println = true;
575 fallback_to_println = true;
579 // If pager fails for whatever reason, we should still print the content
580 // to standard output
581 if fallback_to_println {
582 print!("{}", content);
586 impl RustcDefaultCalls {
587 pub fn list_metadata(sess: &Session,
589 matches: &getopts::Matches,
592 let r = matches.opt_strs("Z");
593 if r.iter().any(|s| *s == "ls") {
595 &Input::File(ref ifile) => {
596 let path = &(*ifile);
597 let mut v = Vec::new();
598 locator::list_file_metadata(&sess.target.target,
600 &*cstore.metadata_loader,
603 println!("{}", String::from_utf8(v).unwrap());
605 &Input::Str { .. } => {
606 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
609 return Compilation::Stop;
612 Compilation::Continue
616 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
618 input: Option<&Input>,
619 odir: &Option<PathBuf>,
620 ofile: &Option<PathBuf>)
622 use rustc::session::config::PrintRequest::*;
623 // PrintRequest::NativeStaticLibs is special - printed during linking
624 // (empty iterator returns true)
625 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
626 return Compilation::Continue;
629 let attrs = match input {
632 let result = parse_crate_attrs(sess, input);
634 Ok(attrs) => Some(attrs),
635 Err(mut parse_error) => {
637 return Compilation::Stop;
642 for req in &sess.opts.prints {
645 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
647 println!("{}", targets.join("\n"));
649 Sysroot => println!("{}", sess.sysroot.display()),
650 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
651 FileNames | CrateName => {
652 let input = input.unwrap_or_else(||
653 early_error(ErrorOutputType::default(), "no input file provided"));
654 let attrs = attrs.as_ref().unwrap();
655 let t_outputs = rustc_interface::util::build_output_filenames(
662 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
663 if *req == PrintRequest::CrateName {
667 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
668 for &style in &crate_types {
669 let fname = rustc_codegen_utils::link::filename_for_input(
675 println!("{}", fname.file_name().unwrap().to_string_lossy());
679 let allow_unstable_cfg = UnstableFeatures::from_environment()
682 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
683 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
684 path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
685 node: ast::MetaItemKind::Word,
689 // Note that crt-static is a specially recognized cfg
690 // directive that's printed out here as part of
691 // rust-lang/rust#37406, but in general the
692 // `target_feature` cfg is gated under
693 // rust-lang/rust#29717. For now this is just
694 // specifically allowing the crt-static cfg and that's
695 // it, this is intended to get into Cargo and then go
696 // through to build scripts.
697 let value = value.as_ref().map(|s| s.as_str());
698 let value = value.as_ref().map(|s| s.as_ref());
699 if name != sym::target_feature || value != Some("crt-static") {
700 if !allow_unstable_cfg && gated_cfg.is_some() {
705 if let Some(value) = value {
706 Some(format!("{}=\"{}\"", name, value))
708 Some(name.to_string())
710 }).collect::<Vec<String>>();
717 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
718 codegen_backend.print(*req, sess);
720 // Any output here interferes with Cargo's parsing of other printed output
721 PrintRequest::NativeStaticLibs => {}
724 return Compilation::Stop;
728 /// Returns a version string such as "0.12.0-dev".
729 fn release_str() -> Option<&'static str> {
730 option_env!("CFG_RELEASE")
733 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
734 fn commit_hash_str() -> Option<&'static str> {
735 option_env!("CFG_VER_HASH")
738 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
739 fn commit_date_str() -> Option<&'static str> {
740 option_env!("CFG_VER_DATE")
743 /// Prints version information
744 pub fn version(binary: &str, matches: &getopts::Matches) {
745 let verbose = matches.opt_present("verbose");
747 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
750 fn unw(x: Option<&str>) -> &str {
751 x.unwrap_or("unknown")
753 println!("binary: {}", binary);
754 println!("commit-hash: {}", unw(commit_hash_str()));
755 println!("commit-date: {}", unw(commit_date_str()));
756 println!("host: {}", config::host_triple());
757 println!("release: {}", unw(release_str()));
758 get_codegen_sysroot("llvm")().print_version();
762 fn usage(verbose: bool, include_unstable_options: bool) {
763 let groups = if verbose {
764 config::rustc_optgroups()
766 config::rustc_short_optgroups()
768 let mut options = getopts::Options::new();
769 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
770 (option.apply)(&mut options);
772 let message = "Usage: rustc [OPTIONS] INPUT";
773 let nightly_help = if nightly_options::is_nightly_build() {
774 "\n -Z help Print unstable compiler options"
778 let verbose_help = if verbose {
781 "\n --help -v Print the full set of options rustc accepts"
783 println!("{}\nAdditional help:
784 -C help Print codegen options
786 Print 'lint' options and default settings{}{}\n",
787 options.usage(message),
792 fn print_wall_help() {
794 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
795 default. Use `rustc -W help` to see all available lints. It's more common to put
796 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
797 the command line flag directly.
801 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
803 Available lint options:
804 -W <foo> Warn about <foo>
808 -F <foo> Forbid <foo> \
809 (deny <foo> and all attempts to override)
813 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
814 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
815 // The sort doesn't case-fold but it's doubtful we care.
816 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
820 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
821 -> Vec<(&'static str, Vec<lint::LintId>)> {
822 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
823 lints.sort_by_key(|l| l.0);
827 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
830 .partition(|&(_, p)| p);
831 let plugin = sort_lints(sess, plugin);
832 let builtin = sort_lints(sess, builtin);
834 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
837 .partition(|&(.., p)| p);
838 let plugin_groups = sort_lint_groups(plugin_groups);
839 let builtin_groups = sort_lint_groups(builtin_groups);
841 let max_name_len = plugin.iter()
843 .map(|&s| s.name.chars().count())
846 let padded = |x: &str| {
847 let mut s = " ".repeat(max_name_len - x.chars().count());
852 println!("Lint checks provided by rustc:\n");
853 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
854 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
856 let print_lints = |lints: Vec<&Lint>| {
858 let name = lint.name_lower().replace("_", "-");
859 println!(" {} {:7.7} {}",
861 lint.default_level.as_str(),
867 print_lints(builtin);
869 let max_name_len = max("warnings".len(),
871 .chain(&builtin_groups)
872 .map(|&(s, _)| s.chars().count())
876 let padded = |x: &str| {
877 let mut s = " ".repeat(max_name_len - x.chars().count());
882 println!("Lint groups provided by rustc:\n");
883 println!(" {} {}", padded("name"), "sub-lints");
884 println!(" {} {}", padded("----"), "---------");
885 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
887 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
888 for (name, to) in lints {
889 let name = name.to_lowercase().replace("_", "-");
890 let desc = to.into_iter()
891 .map(|x| x.to_string().replace("_", "-"))
892 .collect::<Vec<String>>()
894 println!(" {} {}", padded(&name), desc);
899 print_lint_groups(builtin_groups);
901 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
902 (false, 0, _) | (false, _, 0) => {
903 println!("Compiler plugins can provide additional lints and lint groups. To see a \
904 listing of these, re-run `rustc -W help` with a crate filename.");
906 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
907 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
910 println!("Lint checks provided by plugins loaded by this crate:\n");
914 println!("Lint groups provided by plugins loaded by this crate:\n");
915 print_lint_groups(plugin_groups);
921 fn describe_debug_flags() {
922 println!("\nAvailable options:\n");
923 print_flag_list("-Z", config::DB_OPTIONS);
926 fn describe_codegen_flags() {
927 println!("\nAvailable codegen options:\n");
928 print_flag_list("-C", config::CG_OPTIONS);
931 fn print_flag_list<T>(cmdline_opt: &str,
932 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
933 let max_len = flag_list.iter()
934 .map(|&(name, _, opt_type_desc, _)| {
935 let extra_len = match opt_type_desc {
939 name.chars().count() + extra_len
944 for &(name, _, opt_type_desc, desc) in flag_list {
945 let (width, extra) = match opt_type_desc {
946 Some(..) => (max_len - 4, "=val"),
947 None => (max_len, ""),
949 println!(" {} {:>width$}{} -- {}",
951 name.replace("_", "-"),
958 /// Process command line options. Emits messages as appropriate. If compilation
959 /// should continue, returns a getopts::Matches object parsed from args,
960 /// otherwise returns `None`.
962 /// The compiler's handling of options is a little complicated as it ties into
963 /// our stability story, and it's even *more* complicated by historical
964 /// accidents. The current intention of each compiler option is to have one of
967 /// 1. An option is stable and can be used everywhere.
968 /// 2. An option is unstable, but was historically allowed on the stable
970 /// 3. An option is unstable, and can only be used on nightly.
972 /// Like unstable library and language features, however, unstable options have
973 /// always required a form of "opt in" to indicate that you're using them. This
974 /// provides the easy ability to scan a code base to check to see if anything
975 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
977 /// All options behind `-Z` are considered unstable by default. Other top-level
978 /// options can also be considered unstable, and they were unlocked through the
979 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
980 /// instability in both cases, though.
982 /// So with all that in mind, the comments below have some more detail about the
983 /// contortions done here to get things to work out correctly.
984 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
985 // Throw away the first argument, the name of the binary
986 let args = &args[1..];
989 // user did not write `-v` nor `-Z unstable-options`, so do not
990 // include that extra information.
995 // Parse with *all* options defined in the compiler, we don't worry about
996 // option stability here we just want to parse as much as possible.
997 let mut options = getopts::Options::new();
998 for option in config::rustc_optgroups() {
999 (option.apply)(&mut options);
1001 let matches = options.parse(args).unwrap_or_else(|f|
1002 early_error(ErrorOutputType::default(), &f.to_string()));
1004 // For all options we just parsed, we check a few aspects:
1006 // * If the option is stable, we're all good
1007 // * If the option wasn't passed, we're all good
1008 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1009 // ourselves), then we require the `-Z unstable-options` flag to unlock
1010 // this option that was passed.
1011 // * If we're a nightly compiler, then unstable options are now unlocked, so
1012 // we're good to go.
1013 // * Otherwise, if we're a truly unstable option then we generate an error
1014 // (unstable option being used on stable)
1015 // * If we're a historically stable-but-should-be-unstable option then we
1016 // emit a warning that we're going to turn this into an error soon.
1017 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1019 if matches.opt_present("h") || matches.opt_present("help") {
1020 // Only show unstable options in --help if we *really* accept unstable
1021 // options, which catches the case where we got `-Z unstable-options` on
1022 // the stable channel of Rust which was accidentally allowed
1024 usage(matches.opt_present("verbose"),
1025 nightly_options::is_unstable_enabled(&matches));
1029 // Handle the special case of -Wall.
1030 let wall = matches.opt_strs("W");
1031 if wall.iter().any(|x| *x == "all") {
1036 // Don't handle -W help here, because we might first load plugins.
1037 let r = matches.opt_strs("Z");
1038 if r.iter().any(|x| *x == "help") {
1039 describe_debug_flags();
1043 let cg_flags = matches.opt_strs("C");
1045 if cg_flags.iter().any(|x| *x == "help") {
1046 describe_codegen_flags();
1050 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1051 early_warn(ErrorOutputType::default(),
1052 "the --no-stack-check flag is deprecated and does nothing");
1055 if cg_flags.iter().any(|x| *x == "passes=list") {
1056 get_codegen_sysroot("llvm")().print_passes();
1060 if matches.opt_present("version") {
1061 version("rustc", &matches);
1068 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1070 Input::File(ref ifile) => {
1071 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1073 Input::Str { ref name, ref input } => {
1074 parse::parse_crate_attrs_from_source_str(name.clone(),
1081 /// Gets a list of extra command-line flags provided by the user, as strings.
1083 /// This function is used during ICEs to show more information useful for
1084 /// debugging, since some ICEs only happens with non-default compiler flags
1085 /// (and the users don't always report them).
1086 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1087 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1089 // Avoid printing help because of empty args. This can suggest the compiler
1090 // itself is not the program root (consider RLS).
1095 let matches = if let Some(matches) = handle_options(&args) {
1101 let mut result = Vec::new();
1102 let mut excluded_cargo_defaults = false;
1103 for flag in ICE_REPORT_COMPILER_FLAGS {
1104 let prefix = if flag.len() == 1 { "-" } else { "--" };
1106 for content in &matches.opt_strs(flag) {
1107 // Split always returns the first element
1108 let name = if let Some(first) = content.split('=').next() {
1114 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1120 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1121 result.push(format!("{}{} {}", prefix, flag, content));
1123 excluded_cargo_defaults = true;
1128 if !result.is_empty() {
1129 Some((result, excluded_cargo_defaults))
1135 /// Runs a procedure which will detect panics in the compiler and print nicer
1136 /// error messages rather than just failing the test.
1138 /// The diagnostic emitter yielded to the procedure should be used for reporting
1139 /// errors of the compiler.
1140 pub fn report_ices_to_stderr_if_any<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1141 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1142 if value.is::<errors::FatalErrorMarker>() {
1145 // Thread panicked without emitting a fatal diagnostic
1149 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1153 let handler = errors::Handler::with_emitter(true, None, emitter);
1155 // a .span_bug or .bug call has already printed what
1156 // it wants to print.
1157 if !value.is::<errors::ExplicitBug>() {
1158 handler.emit(&MultiSpan::new(),
1160 errors::Level::Bug);
1163 let mut xs: Vec<Cow<'static, str>> = vec![
1164 "the compiler unexpectedly panicked. this is a bug.".into(),
1165 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1166 format!("rustc {} running on {}",
1167 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1168 config::host_triple()).into(),
1171 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1172 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1174 if excluded_cargo_defaults {
1175 xs.push("some of the compiler flags provided by cargo are hidden".into());
1180 handler.emit(&MultiSpan::new(),
1182 errors::Level::Note);
1185 panic::resume_unwind(Box::new(errors::FatalErrorMarker));
1190 /// This allows tools to enable rust logging without having to magically match rustc's
1191 /// log crate version
1192 pub fn init_rustc_env_logger() {
1193 env_logger::init_from_env("RUSTC_LOG");
1197 let start = Instant::now();
1198 init_rustc_env_logger();
1199 let mut callbacks = TimePassesCallbacks::default();
1200 let result = report_ices_to_stderr_if_any(|| {
1201 let args = env::args_os().enumerate()
1202 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1203 early_error(ErrorOutputType::default(),
1204 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1206 .collect::<Vec<_>>();
1207 run_compiler(&args, &mut callbacks, None, None)
1208 }).and_then(|result| result);
1209 let exit_code = match result {
1210 Ok(_) => EXIT_SUCCESS,
1211 Err(_) => EXIT_FAILURE,
1213 // The extra `\t` is necessary to align this label with the others.
1215 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1216 process::exit(exit_code);