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 pub extern crate getopts;
25 extern crate lazy_static;
27 pub extern crate rustc_plugin_impl as plugin;
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::ty::TyCtxt;
42 use rustc::util::common::{set_time_depth, time, print_time_passes_entry, ErrorReported};
43 use rustc_metadata::locator;
44 use rustc_metadata::cstore::CStore;
45 use rustc_codegen_utils::codegen_backend::CodegenBackend;
46 use rustc_interface::interface;
47 use rustc_interface::util::get_codegen_sysroot;
48 use rustc_data_structures::sync::SeqCst;
50 use rustc_serialize::json::ToJson;
54 use std::default::Default;
56 use std::ffi::OsString;
57 use std::io::{self, Read, Write};
59 use std::panic::{self, catch_unwind};
60 use std::path::PathBuf;
61 use std::process::{self, Command, Stdio};
63 use std::time::Instant;
66 use syntax::source_map::FileLoader;
67 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
68 use syntax::parse::{self, PResult};
69 use syntax::symbol::sym;
70 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
75 /// Exit status code used for successful compilation and help output.
76 pub const EXIT_SUCCESS: i32 = 0;
78 /// Exit status code used for compilation failures and invalid flags.
79 pub const EXIT_FAILURE: i32 = 1;
81 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
84 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
86 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
88 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
90 pub fn source_name(input: &Input) -> FileName {
92 Input::File(ref ifile) => ifile.clone().into(),
93 Input::Str { ref name, .. } => name.clone(),
97 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
100 sess.abort_if_errors();
101 panic!("error reported but abort_if_errors didn't abort???");
107 pub trait Callbacks {
108 /// Called before creating the compiler instance
109 fn config(&mut self, _config: &mut interface::Config) {}
110 /// Called after parsing. Return value instructs the compiler whether to
111 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
112 fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
113 Compilation::Continue
115 /// Called after expansion. Return value instructs the compiler whether to
116 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
117 fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
118 Compilation::Continue
120 /// Called after analysis. Return value instructs the compiler whether to
121 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
122 fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
123 Compilation::Continue
127 pub struct DefaultCallbacks;
129 impl Callbacks for DefaultCallbacks {}
132 pub struct TimePassesCallbacks {
136 impl Callbacks for TimePassesCallbacks {
137 fn config(&mut self, config: &mut interface::Config) {
139 config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time;
143 // Parse args and run the compiler. This is the primary entry point for rustc.
144 // See comments on CompilerCalls below for details about the callbacks argument.
145 // The FileLoader provides a way to load files from sources other than the file system.
148 callbacks: &mut (dyn Callbacks + Send),
149 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
150 emitter: Option<Box<dyn Write + Send>>
151 ) -> interface::Result<()> {
152 let mut args = Vec::new();
154 match args::arg_expand(arg.clone()) {
155 Ok(arg) => args.extend(arg),
156 Err(err) => early_error(ErrorOutputType::default(),
157 &format!("Failed to load argument file: {}", err)),
160 let diagnostic_output = emitter.map(|emitter| DiagnosticOutput::Raw(emitter))
161 .unwrap_or(DiagnosticOutput::Default);
162 let matches = match handle_options(&args) {
163 Some(matches) => matches,
164 None => return Ok(()),
167 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
169 let mut dummy_config = |sopts, cfg, diagnostic_output| {
170 let mut config = interface::Config {
173 input: Input::File(PathBuf::new()),
181 lint_caps: Default::default(),
183 callbacks.config(&mut config);
187 if let Some(ref code) = matches.opt_str("explain") {
188 handle_explain(code, sopts.error_format);
192 let (odir, ofile) = make_output(&matches);
193 let (input, input_file_path, input_err) = match make_input(&matches.free) {
196 match matches.free.len() {
198 let config = dummy_config(sopts, cfg, diagnostic_output);
199 interface::run_compiler(config, |compiler| {
200 let sopts = &compiler.session().opts;
201 if sopts.describe_lints {
204 &*compiler.session().lint_store.borrow(),
209 let should_stop = RustcDefaultCalls::print_crate_info(
210 &***compiler.codegen_backend(),
217 if should_stop == Compilation::Stop {
220 early_error(sopts.error_format, "no input filename given")
224 1 => panic!("make_input should have provided valid inputs"),
225 _ => early_error(sopts.error_format, &format!(
226 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
234 if let Some(err) = input_err {
235 // Immediately stop compilation if there was an issue reading
236 // the input (for example if the input stream is not UTF-8).
237 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
238 compiler.session().err(&err.to_string());
240 return Err(ErrorReported);
243 let mut config = interface::Config {
247 input_path: input_file_path,
254 lint_caps: Default::default(),
257 callbacks.config(&mut config);
259 interface::run_compiler(config, |compiler| {
260 let sess = compiler.session();
261 let should_stop = RustcDefaultCalls::print_crate_info(
262 &***compiler.codegen_backend(),
264 Some(compiler.input()),
265 compiler.output_dir(),
266 compiler.output_file(),
267 ).and_then(|| RustcDefaultCalls::list_metadata(
274 if should_stop == Compilation::Stop {
275 return sess.compile_status();
278 let pretty_info = parse_pretty(sess, &matches);
282 if let Some((ppm, opt_uii)) = pretty_info {
283 if ppm.needs_ast_map(&opt_uii) {
284 pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
285 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
286 let expanded_crate = compiler.expansion()?.take().0;
287 pretty::print_after_hir_lowering(
293 compiler.output_file().as_ref().map(|p| &**p),
297 return sess.compile_status();
299 let mut krate = compiler.parse()?.take();
300 pretty::visit_crate(sess, &mut krate, ppm);
301 pretty::print_after_parsing(
306 compiler.output_file().as_ref().map(|p| &**p),
308 return sess.compile_status();
312 if callbacks.after_parsing(compiler) == Compilation::Stop {
313 return sess.compile_status();
316 if sess.opts.debugging_opts.parse_only ||
317 sess.opts.debugging_opts.show_span.is_some() ||
318 sess.opts.debugging_opts.ast_json_noexpand {
319 return sess.compile_status();
322 compiler.register_plugins()?;
324 // Lint plugins are registered; now we can process command line flags.
325 if sess.opts.describe_lints {
326 describe_lints(&sess, &sess.lint_store.borrow(), true);
327 return sess.compile_status();
330 compiler.expansion()?;
331 if callbacks.after_expansion(compiler) == Compilation::Stop {
332 return sess.compile_status();
335 compiler.prepare_outputs()?;
337 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
338 && sess.opts.output_types.len() == 1
340 return sess.compile_status();
343 compiler.global_ctxt()?;
345 if sess.opts.debugging_opts.no_analysis ||
346 sess.opts.debugging_opts.ast_json {
347 return sess.compile_status();
350 if sess.opts.debugging_opts.save_analysis {
351 let expanded_crate = &compiler.expansion()?.peek().0;
352 let crate_name = compiler.crate_name()?.peek().clone();
353 compiler.global_ctxt()?.peek_mut().enter(|tcx| {
354 let result = tcx.analysis(LOCAL_CRATE);
356 time(sess, "save analysis", || {
363 DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
368 // AST will be dropped *after* the `after_analysis` callback
369 // (needed by the RLS)
372 // Drop AST after creating GlobalCtxt to free memory
373 mem::drop(compiler.expansion()?.take());
376 compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
378 if callbacks.after_analysis(compiler) == Compilation::Stop {
379 return sess.compile_status();
382 if sess.opts.debugging_opts.save_analysis {
383 mem::drop(compiler.expansion()?.take());
386 compiler.ongoing_codegen()?;
388 // Drop GlobalCtxt after starting codegen to free memory
389 mem::drop(compiler.global_ctxt()?.take());
391 if sess.opts.debugging_opts.print_type_sizes {
392 sess.code_stats.borrow().print_type_sizes();
397 if sess.opts.debugging_opts.perf_stats {
398 sess.print_perf_stats();
401 if sess.print_fuel_crate.is_some() {
402 eprintln!("Fuel used by {}: {}",
403 sess.print_fuel_crate.as_ref().unwrap(),
404 sess.print_fuel.load(SeqCst));
412 pub fn set_sigpipe_handler() {
414 // Set the SIGPIPE signal handler, so that an EPIPE
415 // will cause rustc to terminate, as expected.
416 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
421 pub fn set_sigpipe_handler() {}
423 // Extract output directory and file from matches.
424 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
425 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
426 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
430 // Extract input (string or file and optional path) from matches.
431 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
432 if free_matches.len() == 1 {
433 let ifile = &free_matches[0];
435 let mut src = String::new();
436 let err = if io::stdin().read_to_string(&mut src).is_err() {
437 Some(io::Error::new(io::ErrorKind::InvalidData,
438 "couldn't read from stdin, as it did not contain valid UTF-8"))
442 Some((Input::Str { name: FileName::anon_source_code(&src), input: src },
445 Some((Input::File(PathBuf::from(ifile)),
446 Some(PathBuf::from(ifile)), None))
453 fn parse_pretty(sess: &Session,
454 matches: &getopts::Matches)
455 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
456 let pretty = if sess.opts.debugging_opts.unstable_options {
457 matches.opt_default("pretty", "normal").map(|a| {
458 // stable pretty-print variants only
459 pretty::parse_pretty(sess, &a, false)
465 if pretty.is_none() {
466 sess.opts.debugging_opts.unpretty.as_ref().map(|a| {
467 // extended with unstable pretty-print variants
468 pretty::parse_pretty(sess, &a, true)
475 // Whether to stop or continue compilation.
476 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
477 pub enum Compilation {
483 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
485 Compilation::Stop => Compilation::Stop,
486 Compilation::Continue => next(),
491 /// CompilerCalls instance for a regular rustc build.
492 #[derive(Copy, Clone)]
493 pub struct RustcDefaultCalls;
495 // FIXME remove these and use winapi 0.3 instead
496 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
498 fn stdout_isatty() -> bool {
499 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
503 fn stdout_isatty() -> bool {
506 type HANDLE = *mut u8;
507 type LPDWORD = *mut u32;
508 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
510 fn GetStdHandle(which: DWORD) -> HANDLE;
511 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
514 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
516 GetConsoleMode(handle, &mut out) != 0
520 fn handle_explain(code: &str,
521 output: ErrorOutputType) {
522 let descriptions = rustc_interface::util::diagnostics_registry();
523 let normalised = if code.starts_with("E") {
526 format!("E{0:0>4}", code)
528 match descriptions.find_description(&normalised) {
529 Some(ref description) => {
530 let mut is_in_code_block = false;
531 let mut text = String::new();
533 // Slice off the leading newline and print.
534 for line in description[1..].lines() {
535 let indent_level = line.find(|c: char| !c.is_whitespace())
536 .unwrap_or_else(|| line.len());
537 let dedented_line = &line[indent_level..];
538 if dedented_line.starts_with("```") {
539 is_in_code_block = !is_in_code_block;
540 text.push_str(&line[..(indent_level+3)]);
541 } else if is_in_code_block && dedented_line.starts_with("# ") {
550 show_content_with_pager(&text);
556 early_error(output, &format!("no extended information for {}", code));
561 fn show_content_with_pager(content: &String) {
562 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
563 OsString::from("more.com")
565 OsString::from("less")
568 let mut fallback_to_println = false;
570 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
572 if let Some(pipe) = pager.stdin.as_mut() {
573 if pipe.write_all(content.as_bytes()).is_err() {
574 fallback_to_println = true;
578 if pager.wait().is_err() {
579 fallback_to_println = true;
583 fallback_to_println = true;
587 // If pager fails for whatever reason, we should still print the content
588 // to standard output
589 if fallback_to_println {
590 print!("{}", content);
594 impl RustcDefaultCalls {
595 pub fn list_metadata(sess: &Session,
597 matches: &getopts::Matches,
600 let r = matches.opt_strs("Z");
601 if r.iter().any(|s| *s == "ls") {
603 &Input::File(ref ifile) => {
604 let path = &(*ifile);
605 let mut v = Vec::new();
606 locator::list_file_metadata(&sess.target.target,
608 &*cstore.metadata_loader,
611 println!("{}", String::from_utf8(v).unwrap());
613 &Input::Str { .. } => {
614 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
617 return Compilation::Stop;
620 Compilation::Continue
624 fn print_crate_info(codegen_backend: &dyn CodegenBackend,
626 input: Option<&Input>,
627 odir: &Option<PathBuf>,
628 ofile: &Option<PathBuf>)
630 use rustc::session::config::PrintRequest::*;
631 // PrintRequest::NativeStaticLibs is special - printed during linking
632 // (empty iterator returns true)
633 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
634 return Compilation::Continue;
637 let attrs = match input {
640 let result = parse_crate_attrs(sess, input);
642 Ok(attrs) => Some(attrs),
643 Err(mut parse_error) => {
645 return Compilation::Stop;
650 for req in &sess.opts.prints {
653 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
655 println!("{}", targets.join("\n"));
657 Sysroot => println!("{}", sess.sysroot.display()),
658 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
659 FileNames | CrateName => {
660 let input = input.unwrap_or_else(||
661 early_error(ErrorOutputType::default(), "no input file provided"));
662 let attrs = attrs.as_ref().unwrap();
663 let t_outputs = rustc_interface::util::build_output_filenames(
670 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
671 if *req == PrintRequest::CrateName {
675 let crate_types = rustc_interface::util::collect_crate_types(sess, attrs);
676 for &style in &crate_types {
677 let fname = rustc_codegen_utils::link::filename_for_input(
683 println!("{}", fname.file_name().unwrap().to_string_lossy());
687 let allow_unstable_cfg = UnstableFeatures::from_environment()
690 let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
691 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
692 path: ast::Path::from_ident(ast::Ident::with_dummy_span(name)),
693 node: ast::MetaItemKind::Word,
697 // Note that crt-static is a specially recognized cfg
698 // directive that's printed out here as part of
699 // rust-lang/rust#37406, but in general the
700 // `target_feature` cfg is gated under
701 // rust-lang/rust#29717. For now this is just
702 // specifically allowing the crt-static cfg and that's
703 // it, this is intended to get into Cargo and then go
704 // through to build scripts.
705 let value = value.as_ref().map(|s| s.as_str());
706 let value = value.as_ref().map(|s| s.as_ref());
707 if name != sym::target_feature || value != Some("crt-static") {
708 if !allow_unstable_cfg && gated_cfg.is_some() {
713 if let Some(value) = value {
714 Some(format!("{}=\"{}\"", name, value))
716 Some(name.to_string())
718 }).collect::<Vec<String>>();
725 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
726 codegen_backend.print(*req, sess);
728 // Any output here interferes with Cargo's parsing of other printed output
729 PrintRequest::NativeStaticLibs => {}
732 return Compilation::Stop;
736 /// Returns a version string such as "0.12.0-dev".
737 fn release_str() -> Option<&'static str> {
738 option_env!("CFG_RELEASE")
741 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
742 fn commit_hash_str() -> Option<&'static str> {
743 option_env!("CFG_VER_HASH")
746 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
747 fn commit_date_str() -> Option<&'static str> {
748 option_env!("CFG_VER_DATE")
751 /// Prints version information
752 pub fn version(binary: &str, matches: &getopts::Matches) {
753 let verbose = matches.opt_present("verbose");
755 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
758 fn unw(x: Option<&str>) -> &str {
759 x.unwrap_or("unknown")
761 println!("binary: {}", binary);
762 println!("commit-hash: {}", unw(commit_hash_str()));
763 println!("commit-date: {}", unw(commit_date_str()));
764 println!("host: {}", config::host_triple());
765 println!("release: {}", unw(release_str()));
766 get_codegen_sysroot("llvm")().print_version();
770 fn usage(verbose: bool, include_unstable_options: bool) {
771 let groups = if verbose {
772 config::rustc_optgroups()
774 config::rustc_short_optgroups()
776 let mut options = getopts::Options::new();
777 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
778 (option.apply)(&mut options);
780 let message = "Usage: rustc [OPTIONS] INPUT";
781 let nightly_help = if nightly_options::is_nightly_build() {
782 "\n -Z help Print unstable compiler options"
786 let verbose_help = if verbose {
789 "\n --help -v Print the full set of options rustc accepts"
791 let at_path = if verbose && nightly_options::is_nightly_build() {
792 " @path Read newline separated options from `path`\n"
796 println!("{options}{at_path}\nAdditional help:
797 -C help Print codegen options
799 Print 'lint' options and default settings{nightly}{verbose}\n",
800 options = options.usage(message),
802 nightly = nightly_help,
803 verbose = verbose_help);
806 fn print_wall_help() {
808 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
809 default. Use `rustc -W help` to see all available lints. It's more common to put
810 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
811 the command line flag directly.
815 fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) {
817 Available lint options:
818 -W <foo> Warn about <foo>
822 -F <foo> Forbid <foo> \
823 (deny <foo> and all attempts to override)
827 fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
828 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
829 // The sort doesn't case-fold but it's doubtful we care.
830 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
834 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
835 -> Vec<(&'static str, Vec<lint::LintId>)> {
836 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
837 lints.sort_by_key(|l| l.0);
841 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
844 .partition(|&(_, p)| p);
845 let plugin = sort_lints(sess, plugin);
846 let builtin = sort_lints(sess, builtin);
848 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
851 .partition(|&(.., p)| p);
852 let plugin_groups = sort_lint_groups(plugin_groups);
853 let builtin_groups = sort_lint_groups(builtin_groups);
855 let max_name_len = plugin.iter()
857 .map(|&s| s.name.chars().count())
860 let padded = |x: &str| {
861 let mut s = " ".repeat(max_name_len - x.chars().count());
866 println!("Lint checks provided by rustc:\n");
867 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
868 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
870 let print_lints = |lints: Vec<&Lint>| {
872 let name = lint.name_lower().replace("_", "-");
873 println!(" {} {:7.7} {}",
875 lint.default_level.as_str(),
881 print_lints(builtin);
883 let max_name_len = max("warnings".len(),
885 .chain(&builtin_groups)
886 .map(|&(s, _)| s.chars().count())
890 let padded = |x: &str| {
891 let mut s = " ".repeat(max_name_len - x.chars().count());
896 println!("Lint groups provided by rustc:\n");
897 println!(" {} {}", padded("name"), "sub-lints");
898 println!(" {} {}", padded("----"), "---------");
899 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
901 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
902 for (name, to) in lints {
903 let name = name.to_lowercase().replace("_", "-");
904 let desc = to.into_iter()
905 .map(|x| x.to_string().replace("_", "-"))
906 .collect::<Vec<String>>()
908 println!(" {} {}", padded(&name), desc);
913 print_lint_groups(builtin_groups);
915 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
916 (false, 0, _) | (false, _, 0) => {
917 println!("Compiler plugins can provide additional lints and lint groups. To see a \
918 listing of these, re-run `rustc -W help` with a crate filename.");
920 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
921 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
924 println!("Lint checks provided by plugins loaded by this crate:\n");
928 println!("Lint groups provided by plugins loaded by this crate:\n");
929 print_lint_groups(plugin_groups);
935 fn describe_debug_flags() {
936 println!("\nAvailable options:\n");
937 print_flag_list("-Z", config::DB_OPTIONS);
940 fn describe_codegen_flags() {
941 println!("\nAvailable codegen options:\n");
942 print_flag_list("-C", config::CG_OPTIONS);
945 fn print_flag_list<T>(cmdline_opt: &str,
946 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
947 let max_len = flag_list.iter()
948 .map(|&(name, _, opt_type_desc, _)| {
949 let extra_len = match opt_type_desc {
953 name.chars().count() + extra_len
958 for &(name, _, opt_type_desc, desc) in flag_list {
959 let (width, extra) = match opt_type_desc {
960 Some(..) => (max_len - 4, "=val"),
961 None => (max_len, ""),
963 println!(" {} {:>width$}{} -- {}",
965 name.replace("_", "-"),
972 /// Process command line options. Emits messages as appropriate. If compilation
973 /// should continue, returns a getopts::Matches object parsed from args,
974 /// otherwise returns `None`.
976 /// The compiler's handling of options is a little complicated as it ties into
977 /// our stability story. The current intention of each compiler option is to
978 /// have one of two modes:
980 /// 1. An option is stable and can be used everywhere.
981 /// 2. An option is unstable, and can only be used on nightly.
983 /// Like unstable library and language features, however, unstable options have
984 /// always required a form of "opt in" to indicate that you're using them. This
985 /// provides the easy ability to scan a code base to check to see if anything
986 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
988 /// All options behind `-Z` are considered unstable by default. Other top-level
989 /// options can also be considered unstable, and they were unlocked through the
990 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
991 /// instability in both cases, though.
993 /// So with all that in mind, the comments below have some more detail about the
994 /// contortions done here to get things to work out correctly.
995 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
996 // Throw away the first argument, the name of the binary
997 let args = &args[1..];
1000 // user did not write `-v` nor `-Z unstable-options`, so do not
1001 // include that extra information.
1002 usage(false, false);
1006 // Parse with *all* options defined in the compiler, we don't worry about
1007 // option stability here we just want to parse as much as possible.
1008 let mut options = getopts::Options::new();
1009 for option in config::rustc_optgroups() {
1010 (option.apply)(&mut options);
1012 let matches = options.parse(args).unwrap_or_else(|f|
1013 early_error(ErrorOutputType::default(), &f.to_string()));
1015 // For all options we just parsed, we check a few aspects:
1017 // * If the option is stable, we're all good
1018 // * If the option wasn't passed, we're all good
1019 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1020 // ourselves), then we require the `-Z unstable-options` flag to unlock
1021 // this option that was passed.
1022 // * If we're a nightly compiler, then unstable options are now unlocked, so
1023 // we're good to go.
1024 // * Otherwise, if we're an unstable option then we generate an error
1025 // (unstable option being used on stable)
1026 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1028 // Late check to see if @file was used without unstable options enabled
1029 if crate::args::used_unstable_argsfile() && !nightly_options::is_unstable_enabled(&matches) {
1030 early_error(ErrorOutputType::default(),
1031 "@path is unstable - use -Z unstable-options to enable its use");
1034 if matches.opt_present("h") || matches.opt_present("help") {
1035 // Only show unstable options in --help if we accept unstable options.
1036 usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
1040 // Handle the special case of -Wall.
1041 let wall = matches.opt_strs("W");
1042 if wall.iter().any(|x| *x == "all") {
1047 // Don't handle -W help here, because we might first load plugins.
1048 let r = matches.opt_strs("Z");
1049 if r.iter().any(|x| *x == "help") {
1050 describe_debug_flags();
1054 let cg_flags = matches.opt_strs("C");
1056 if cg_flags.iter().any(|x| *x == "help") {
1057 describe_codegen_flags();
1061 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1062 early_warn(ErrorOutputType::default(),
1063 "the --no-stack-check flag is deprecated and does nothing");
1066 if cg_flags.iter().any(|x| *x == "passes=list") {
1067 get_codegen_sysroot("llvm")().print_passes();
1071 if matches.opt_present("version") {
1072 version("rustc", &matches);
1079 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1081 Input::File(ref ifile) => {
1082 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1084 Input::Str { ref name, ref input } => {
1085 parse::parse_crate_attrs_from_source_str(name.clone(),
1092 /// Gets a list of extra command-line flags provided by the user, as strings.
1094 /// This function is used during ICEs to show more information useful for
1095 /// debugging, since some ICEs only happens with non-default compiler flags
1096 /// (and the users don't always report them).
1097 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1098 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1100 // Avoid printing help because of empty args. This can suggest the compiler
1101 // itself is not the program root (consider RLS).
1106 let matches = if let Some(matches) = handle_options(&args) {
1112 let mut result = Vec::new();
1113 let mut excluded_cargo_defaults = false;
1114 for flag in ICE_REPORT_COMPILER_FLAGS {
1115 let prefix = if flag.len() == 1 { "-" } else { "--" };
1117 for content in &matches.opt_strs(flag) {
1118 // Split always returns the first element
1119 let name = if let Some(first) = content.split('=').next() {
1125 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
1131 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1132 result.push(format!("{}{} {}", prefix, flag, content));
1134 excluded_cargo_defaults = true;
1139 if !result.is_empty() {
1140 Some((result, excluded_cargo_defaults))
1146 /// Runs a closure and catches unwinds triggered by fatal errors.
1148 /// The compiler currently unwinds with a special sentinel value to abort
1149 /// compilation on fatal errors. This function catches that sentinel and turns
1150 /// the panic into a `Result` instead.
1151 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1152 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1153 if value.is::<errors::FatalErrorMarker>() {
1156 panic::resume_unwind(value);
1162 static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
1163 let hook = panic::take_hook();
1164 panic::set_hook(Box::new(report_ice));
1169 pub fn report_ice(info: &panic::PanicInfo<'_>) {
1170 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1171 (*DEFAULT_HOOK)(info);
1173 // Print the infamous ICE message
1176 let emitter = Box::new(errors::emitter::EmitterWriter::stderr(
1177 errors::ColorConfig::Auto,
1183 let handler = errors::Handler::with_emitter(true, None, emitter);
1185 // a .span_bug or .bug call has already printed what
1186 // it wants to print.
1187 if !info.payload().is::<errors::ExplicitBug>() {
1188 handler.emit(&MultiSpan::new(),
1190 errors::Level::Bug);
1193 let mut xs: Vec<Cow<'static, str>> = vec![
1194 "the compiler unexpectedly panicked. this is a bug.".into(),
1195 format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
1196 format!("rustc {} running on {}",
1197 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1198 config::host_triple()).into(),
1201 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1202 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1204 if excluded_cargo_defaults {
1205 xs.push("some of the compiler flags provided by cargo are hidden".into());
1210 handler.emit(&MultiSpan::new(),
1212 errors::Level::Note);
1215 // If backtraces are enabled, also print the query stack
1216 let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
1219 TyCtxt::try_print_query_stack();
1224 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1228 // Trigger a debugger if we crashed during bootstrap
1234 pub fn install_ice_hook() {
1235 lazy_static::initialize(&DEFAULT_HOOK);
1238 /// This allows tools to enable rust logging without having to magically match rustc's
1239 /// log crate version
1240 pub fn init_rustc_env_logger() {
1241 env_logger::init_from_env("RUSTC_LOG");
1245 let start = Instant::now();
1246 init_rustc_env_logger();
1247 let mut callbacks = TimePassesCallbacks::default();
1249 let result = catch_fatal_errors(|| {
1250 let args = env::args_os().enumerate()
1251 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1252 early_error(ErrorOutputType::default(),
1253 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1255 .collect::<Vec<_>>();
1256 run_compiler(&args, &mut callbacks, None, None)
1257 }).and_then(|result| result);
1258 let exit_code = match result {
1259 Ok(_) => EXIT_SUCCESS,
1260 Err(_) => EXIT_FAILURE,
1262 // The extra `\t` is necessary to align this label with the others.
1264 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1265 process::exit(exit_code);