5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![recursion_limit = "256"]
11 pub extern crate getopts;
17 extern crate lazy_static;
19 pub extern crate rustc_plugin_impl as plugin;
21 use rustc::lint::{Lint, LintId};
22 use rustc::middle::cstore::MetadataLoader;
23 use rustc::session::config::nightly_options;
24 use rustc::session::config::{ErrorOutputType, Input, OutputType, PrintRequest};
25 use rustc::session::{config, DiagnosticOutput, Session};
26 use rustc::session::{early_error, early_warn};
27 use rustc::ty::TyCtxt;
28 use rustc::util::common::ErrorReported;
29 use rustc_codegen_ssa::CodegenResults;
30 use rustc_codegen_utils::codegen_backend::CodegenBackend;
31 use rustc_data_structures::profiling::print_time_passes_entry;
32 use rustc_data_structures::sync::SeqCst;
34 registry::{InvalidErrorCode, Registry},
37 use rustc_feature::{find_gated_cfg, UnstableFeatures};
38 use rustc_hir::def_id::LOCAL_CRATE;
39 use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend};
40 use rustc_interface::{interface, Queries};
41 use rustc_lint::LintStore;
42 use rustc_metadata::locator;
43 use rustc_save_analysis as save;
44 use rustc_save_analysis::DumpHandler;
45 use rustc_serialize::json::{self, ToJson};
49 use std::default::Default;
51 use std::ffi::OsString;
53 use std::io::{self, Read, Write};
55 use std::panic::{self, catch_unwind};
56 use std::path::PathBuf;
57 use std::process::{self, Command, Stdio};
59 use std::time::Instant;
62 use rustc_span::source_map::FileLoader;
63 use rustc_span::symbol::sym;
64 use rustc_span::FileName;
69 /// Exit status code used for successful compilation and help output.
70 pub const EXIT_SUCCESS: i32 = 0;
72 /// Exit status code used for compilation failures and invalid flags.
73 pub const EXIT_FAILURE: i32 = 1;
75 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
78 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
80 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
82 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
84 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
87 sess.abort_if_errors();
88 panic!("error reported but abort_if_errors didn't abort???");
95 /// Called before creating the compiler instance
96 fn config(&mut self, _config: &mut interface::Config) {}
97 /// Called after parsing. Return value instructs the compiler whether to
98 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
99 fn after_parsing<'tcx>(
101 _compiler: &interface::Compiler,
102 _queries: &'tcx Queries<'tcx>,
104 Compilation::Continue
106 /// Called after expansion. Return value instructs the compiler whether to
107 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
108 fn after_expansion<'tcx>(
110 _compiler: &interface::Compiler,
111 _queries: &'tcx Queries<'tcx>,
113 Compilation::Continue
115 /// Called after analysis. Return value instructs the compiler whether to
116 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
117 fn after_analysis<'tcx>(
119 _compiler: &interface::Compiler,
120 _queries: &'tcx Queries<'tcx>,
122 Compilation::Continue
127 pub struct TimePassesCallbacks {
131 impl Callbacks for TimePassesCallbacks {
132 fn config(&mut self, config: &mut interface::Config) {
133 // If a --prints=... option has been given, we don't print the "total"
134 // time because it will mess up the --prints output. See #64339.
135 self.time_passes = config.opts.prints.is_empty()
136 && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
140 pub fn diagnostics_registry() -> Registry {
141 Registry::new(&rustc_error_codes::DIAGNOSTICS)
144 // Parse args and run the compiler. This is the primary entry point for rustc.
145 // See comments on CompilerCalls below for details about the callbacks argument.
146 // The FileLoader provides a way to load files from sources other than the file system.
149 callbacks: &mut (dyn Callbacks + Send),
150 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
151 emitter: Option<Box<dyn Write + Send>>,
152 ) -> interface::Result<()> {
153 let mut args = Vec::new();
155 match args::arg_expand(arg.clone()) {
156 Ok(arg) => args.extend(arg),
157 Err(err) => early_error(
158 ErrorOutputType::default(),
159 &format!("Failed to load argument file: {}", err),
163 let diagnostic_output =
164 emitter.map(|emitter| DiagnosticOutput::Raw(emitter)).unwrap_or(DiagnosticOutput::Default);
165 let matches = match handle_options(&args) {
166 Some(matches) => matches,
167 None => return Ok(()),
170 let sopts = config::build_session_options(&matches);
171 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
173 let mut dummy_config = |sopts, cfg, diagnostic_output| {
174 let mut config = interface::Config {
177 input: Input::File(PathBuf::new()),
185 lint_caps: Default::default(),
186 register_lints: None,
187 override_queries: None,
188 registry: diagnostics_registry(),
190 callbacks.config(&mut config);
194 if let Some(ref code) = matches.opt_str("explain") {
195 handle_explain(diagnostics_registry(), code, sopts.error_format);
199 let (odir, ofile) = make_output(&matches);
200 let (input, input_file_path, input_err) = match make_input(&matches.free) {
202 None => match matches.free.len() {
204 let config = dummy_config(sopts, cfg, diagnostic_output);
205 interface::run_compiler(config, |compiler| {
206 let sopts = &compiler.session().opts;
207 if sopts.describe_lints {
208 let lint_store = rustc_lint::new_lint_store(
209 sopts.debugging_opts.no_interleave_lints,
210 compiler.session().unstable_options(),
212 describe_lints(compiler.session(), &lint_store, false);
215 let should_stop = RustcDefaultCalls::print_crate_info(
216 &***compiler.codegen_backend(),
223 if should_stop == Compilation::Stop {
226 early_error(sopts.error_format, "no input filename given")
230 1 => panic!("make_input should have provided valid inputs"),
234 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
235 matches.free[0], matches.free[1],
241 if let Some(err) = input_err {
242 // Immediately stop compilation if there was an issue reading
243 // the input (for example if the input stream is not UTF-8).
244 interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
245 compiler.session().err(&err.to_string());
247 return Err(ErrorReported);
250 let mut config = interface::Config {
254 input_path: input_file_path,
261 lint_caps: Default::default(),
262 register_lints: None,
263 override_queries: None,
264 registry: diagnostics_registry(),
267 callbacks.config(&mut config);
269 interface::run_compiler(config, |compiler| {
270 let sess = compiler.session();
271 let should_stop = RustcDefaultCalls::print_crate_info(
272 &***compiler.codegen_backend(),
274 Some(compiler.input()),
275 compiler.output_dir(),
276 compiler.output_file(),
279 RustcDefaultCalls::list_metadata(
281 &*compiler.codegen_backend().metadata_loader(),
286 .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
288 if should_stop == Compilation::Stop {
289 return sess.compile_status();
292 let linker = compiler.enter(|queries| {
293 let early_exit = || sess.compile_status().map(|_| None);
296 if let Some(ppm) = &sess.opts.pretty {
297 if ppm.needs_ast_map() {
298 queries.global_ctxt()?.peek_mut().enter(|tcx| {
299 let expanded_crate = queries.expansion()?.take().0;
300 pretty::print_after_hir_lowering(
305 compiler.output_file().as_ref().map(|p| &**p),
310 let krate = queries.parse()?.take();
311 pretty::print_after_parsing(
316 compiler.output_file().as_ref().map(|p| &**p),
322 if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
326 if sess.opts.debugging_opts.parse_only
327 || sess.opts.debugging_opts.show_span.is_some()
328 || sess.opts.debugging_opts.ast_json_noexpand
334 let (_, lint_store) = &*queries.register_plugins()?.peek();
336 // Lint plugins are registered; now we can process command line flags.
337 if sess.opts.describe_lints {
338 describe_lints(&sess, &lint_store, true);
343 queries.expansion()?;
344 if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
348 queries.prepare_outputs()?;
350 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
351 && sess.opts.output_types.len() == 1
356 queries.global_ctxt()?;
358 if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
362 if sess.opts.debugging_opts.save_analysis {
363 let expanded_crate = &queries.expansion()?.peek().0;
364 let crate_name = queries.crate_name()?.peek().clone();
365 queries.global_ctxt()?.peek_mut().enter(|tcx| {
366 let result = tcx.analysis(LOCAL_CRATE);
368 sess.time("save_analysis", || {
376 compiler.output_dir().as_ref().map(|p| &**p),
383 // AST will be dropped *after* the `after_analysis` callback
384 // (needed by the RLS)
387 // Drop AST after creating GlobalCtxt to free memory
388 let _timer = sess.prof.generic_activity("drop_ast");
389 mem::drop(queries.expansion()?.take());
392 queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
394 if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
398 if sess.opts.debugging_opts.save_analysis {
399 mem::drop(queries.expansion()?.take());
402 queries.ongoing_codegen()?;
404 if sess.opts.debugging_opts.print_type_sizes {
405 sess.code_stats.print_type_sizes();
408 let linker = queries.linker()?;
412 if let Some(linker) = linker {
413 let _timer = sess.timer("link");
417 if sess.opts.debugging_opts.perf_stats {
418 sess.print_perf_stats();
421 if sess.print_fuel_crate.is_some() {
423 "Fuel used by {}: {}",
424 sess.print_fuel_crate.as_ref().unwrap(),
425 sess.print_fuel.load(SeqCst)
434 pub fn set_sigpipe_handler() {
436 // Set the SIGPIPE signal handler, so that an EPIPE
437 // will cause rustc to terminate, as expected.
438 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
443 pub fn set_sigpipe_handler() {}
445 // Extract output directory and file from matches.
446 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
447 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
448 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
452 // Extract input (string or file and optional path) from matches.
453 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
454 if free_matches.len() == 1 {
455 let ifile = &free_matches[0];
457 let mut src = String::new();
458 let err = if io::stdin().read_to_string(&mut src).is_err() {
460 io::ErrorKind::InvalidData,
461 "couldn't read from stdin, as it did not contain valid UTF-8",
466 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
467 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
468 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
469 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
471 let line = isize::from_str_radix(&line, 10)
472 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
473 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
474 return Some((Input::Str { name: file_name, input: src }, None, err));
476 Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err))
478 Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None))
485 // Whether to stop or continue compilation.
486 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
487 pub enum Compilation {
493 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
495 Compilation::Stop => Compilation::Stop,
496 Compilation::Continue => next(),
501 /// CompilerCalls instance for a regular rustc build.
502 #[derive(Copy, Clone)]
503 pub struct RustcDefaultCalls;
505 // FIXME remove these and use winapi 0.3 instead
506 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
508 fn stdout_isatty() -> bool {
509 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
513 fn stdout_isatty() -> bool {
514 use winapi::um::consoleapi::GetConsoleMode;
515 use winapi::um::processenv::GetStdHandle;
516 use winapi::um::winbase::STD_OUTPUT_HANDLE;
519 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
521 GetConsoleMode(handle, &mut out) != 0
525 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
527 if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) };
528 match registry.try_find_description(&normalised) {
529 Ok(Some(description)) => {
530 let mut is_in_code_block = false;
531 let mut text = String::new();
532 // Slice off the leading newline and print.
533 for line in description.lines() {
535 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
536 let dedented_line = &line[indent_level..];
537 if dedented_line.starts_with("```") {
538 is_in_code_block = !is_in_code_block;
539 text.push_str(&line[..(indent_level + 3)]);
540 } else if is_in_code_block && dedented_line.starts_with("# ") {
548 show_content_with_pager(&text);
554 early_error(output, &format!("no extended information for {}", code));
556 Err(InvalidErrorCode) => {
557 early_error(output, &format!("{} is not a valid error code", code));
562 fn show_content_with_pager(content: &String) {
563 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
564 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
567 let mut fallback_to_println = false;
569 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
571 if let Some(pipe) = pager.stdin.as_mut() {
572 if pipe.write_all(content.as_bytes()).is_err() {
573 fallback_to_println = true;
577 if pager.wait().is_err() {
578 fallback_to_println = true;
582 fallback_to_println = true;
586 // If pager fails for whatever reason, we should still print the content
587 // to standard output
588 if fallback_to_println {
589 print!("{}", content);
593 impl RustcDefaultCalls {
594 fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> {
595 if let Input::File(file) = compiler.input() {
596 // FIXME: #![crate_type] and #![crate_name] support not implemented yet
598 sess.crate_types.set(collect_crate_types(sess, &attrs));
599 let outputs = compiler.build_output_filenames(&sess, &attrs);
600 let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
601 sess.fatal(&format!("failed to read rlink file: {}", err));
603 let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| {
604 sess.fatal(&format!("failed to decode rlink: {}", err));
606 compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs)
608 sess.fatal("rlink must be a file")
612 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
613 if sess.opts.debugging_opts.link_only {
614 let result = RustcDefaultCalls::process_rlink(sess, compiler);
615 abort_on_err(result, sess);
618 Compilation::Continue
622 pub fn list_metadata(
624 metadata_loader: &dyn MetadataLoader,
625 matches: &getopts::Matches,
628 let r = matches.opt_strs("Z");
629 if r.iter().any(|s| *s == "ls") {
631 &Input::File(ref ifile) => {
632 let path = &(*ifile);
633 let mut v = Vec::new();
634 locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v)
636 println!("{}", String::from_utf8(v).unwrap());
638 &Input::Str { .. } => {
639 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
642 return Compilation::Stop;
645 Compilation::Continue
649 codegen_backend: &dyn CodegenBackend,
651 input: Option<&Input>,
652 odir: &Option<PathBuf>,
653 ofile: &Option<PathBuf>,
655 use rustc::session::config::PrintRequest::*;
656 // PrintRequest::NativeStaticLibs is special - printed during linking
657 // (empty iterator returns true)
658 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
659 return Compilation::Continue;
662 let attrs = match input {
665 let result = parse_crate_attrs(sess, input);
667 Ok(attrs) => Some(attrs),
668 Err(mut parse_error) => {
670 return Compilation::Stop;
675 for req in &sess.opts.prints {
678 let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
680 println!("{}", targets.join("\n"));
682 Sysroot => println!("{}", sess.sysroot.display()),
683 TargetLibdir => println!(
685 sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display()
687 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
688 FileNames | CrateName => {
689 let input = input.unwrap_or_else(|| {
690 early_error(ErrorOutputType::default(), "no input file provided")
692 let attrs = attrs.as_ref().unwrap();
693 let t_outputs = rustc_interface::util::build_output_filenames(
694 input, odir, ofile, attrs, sess,
696 let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
697 if *req == PrintRequest::CrateName {
701 let crate_types = collect_crate_types(sess, attrs);
702 for &style in &crate_types {
703 let fname = rustc_codegen_utils::link::filename_for_input(
704 sess, style, &id, &t_outputs,
706 println!("{}", fname.file_name().unwrap().to_string_lossy());
710 let allow_unstable_cfg =
711 UnstableFeatures::from_environment().is_nightly_build();
717 .filter_map(|&(name, ref value)| {
718 // Note that crt-static is a specially recognized cfg
719 // directive that's printed out here as part of
720 // rust-lang/rust#37406, but in general the
721 // `target_feature` cfg is gated under
722 // rust-lang/rust#29717. For now this is just
723 // specifically allowing the crt-static cfg and that's
724 // it, this is intended to get into Cargo and then go
725 // through to build scripts.
726 let value = value.as_ref().map(|s| s.as_str());
727 let value = value.as_ref().map(|s| s.as_ref());
728 if (name != sym::target_feature || value != Some("crt-static"))
729 && !allow_unstable_cfg
730 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
735 if let Some(value) = value {
736 Some(format!("{}=\"{}\"", name, value))
738 Some(name.to_string())
741 .collect::<Vec<String>>();
748 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
749 codegen_backend.print(*req, sess);
751 // Any output here interferes with Cargo's parsing of other printed output
752 PrintRequest::NativeStaticLibs => {}
755 return Compilation::Stop;
759 /// Returns a version string such as "0.12.0-dev".
760 fn release_str() -> Option<&'static str> {
761 option_env!("CFG_RELEASE")
764 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
765 fn commit_hash_str() -> Option<&'static str> {
766 option_env!("CFG_VER_HASH")
769 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
770 fn commit_date_str() -> Option<&'static str> {
771 option_env!("CFG_VER_DATE")
774 /// Prints version information
775 pub fn version(binary: &str, matches: &getopts::Matches) {
776 let verbose = matches.opt_present("verbose");
778 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
781 fn unw(x: Option<&str>) -> &str {
782 x.unwrap_or("unknown")
784 println!("binary: {}", binary);
785 println!("commit-hash: {}", unw(commit_hash_str()));
786 println!("commit-date: {}", unw(commit_date_str()));
787 println!("host: {}", config::host_triple());
788 println!("release: {}", unw(release_str()));
789 get_builtin_codegen_backend("llvm")().print_version();
793 fn usage(verbose: bool, include_unstable_options: bool) {
794 let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
795 let mut options = getopts::Options::new();
796 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
797 (option.apply)(&mut options);
799 let message = "Usage: rustc [OPTIONS] INPUT";
800 let nightly_help = if nightly_options::is_nightly_build() {
801 "\n -Z help Print unstable compiler options"
805 let verbose_help = if verbose {
808 "\n --help -v Print the full set of options rustc accepts"
810 let at_path = if verbose && nightly_options::is_nightly_build() {
811 " @path Read newline separated options from `path`\n"
816 "{options}{at_path}\nAdditional help:
817 -C help Print codegen options
819 Print 'lint' options and default settings{nightly}{verbose}\n",
820 options = options.usage(message),
822 nightly = nightly_help,
823 verbose = verbose_help
827 fn print_wall_help() {
830 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
831 default. Use `rustc -W help` to see all available lints. It's more common to put
832 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
833 the command line flag directly.
838 fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
841 Available lint options:
842 -W <foo> Warn about <foo>
846 -F <foo> Forbid <foo> \
847 (deny <foo> and all attempts to override)
852 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
853 // The sort doesn't case-fold but it's doubtful we care.
854 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
859 lints: Vec<(&'static str, Vec<LintId>, bool)>,
860 ) -> Vec<(&'static str, Vec<LintId>)> {
861 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
862 lints.sort_by_key(|l| l.0);
866 let (plugin, builtin): (Vec<_>, _) =
867 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
868 let plugin = sort_lints(sess, plugin);
869 let builtin = sort_lints(sess, builtin);
871 let (plugin_groups, builtin_groups): (Vec<_>, _) =
872 lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
873 let plugin_groups = sort_lint_groups(plugin_groups);
874 let builtin_groups = sort_lint_groups(builtin_groups);
877 plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
878 let padded = |x: &str| {
879 let mut s = " ".repeat(max_name_len - x.chars().count());
884 println!("Lint checks provided by rustc:\n");
885 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
886 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
888 let print_lints = |lints: Vec<&Lint>| {
890 let name = lint.name_lower().replace("_", "-");
891 println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc);
896 print_lints(builtin);
898 let max_name_len = max(
902 .chain(&builtin_groups)
903 .map(|&(s, _)| s.chars().count())
908 let padded = |x: &str| {
909 let mut s = " ".repeat(max_name_len - x.chars().count());
914 println!("Lint groups provided by rustc:\n");
915 println!(" {} {}", padded("name"), "sub-lints");
916 println!(" {} {}", padded("----"), "---------");
917 println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
919 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
920 for (name, to) in lints {
921 let name = name.to_lowercase().replace("_", "-");
924 .map(|x| x.to_string().replace("_", "-"))
925 .collect::<Vec<String>>()
927 println!(" {} {}", padded(&name), desc);
932 print_lint_groups(builtin_groups);
934 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
935 (false, 0, _) | (false, _, 0) => {
937 "Compiler plugins can provide additional lints and lint groups. To see a \
938 listing of these, re-run `rustc -W help` with a crate filename."
941 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
942 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
945 println!("Lint checks provided by plugins loaded by this crate:\n");
949 println!("Lint groups provided by plugins loaded by this crate:\n");
950 print_lint_groups(plugin_groups);
956 fn describe_debug_flags() {
957 println!("\nAvailable options:\n");
958 print_flag_list("-Z", config::DB_OPTIONS);
961 fn describe_codegen_flags() {
962 println!("\nAvailable codegen options:\n");
963 print_flag_list("-C", config::CG_OPTIONS);
966 fn print_flag_list<T>(
968 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)],
970 let max_len = flag_list
972 .map(|&(name, _, opt_type_desc, _)| {
973 let extra_len = match opt_type_desc {
977 name.chars().count() + extra_len
982 for &(name, _, opt_type_desc, desc) in flag_list {
983 let (width, extra) = match opt_type_desc {
984 Some(..) => (max_len - 4, "=val"),
985 None => (max_len, ""),
988 " {} {:>width$}{} -- {}",
990 name.replace("_", "-"),
998 /// Process command line options. Emits messages as appropriate. If compilation
999 /// should continue, returns a getopts::Matches object parsed from args,
1000 /// otherwise returns `None`.
1002 /// The compiler's handling of options is a little complicated as it ties into
1003 /// our stability story. The current intention of each compiler option is to
1004 /// have one of two modes:
1006 /// 1. An option is stable and can be used everywhere.
1007 /// 2. An option is unstable, and can only be used on nightly.
1009 /// Like unstable library and language features, however, unstable options have
1010 /// always required a form of "opt in" to indicate that you're using them. This
1011 /// provides the easy ability to scan a code base to check to see if anything
1012 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1014 /// All options behind `-Z` are considered unstable by default. Other top-level
1015 /// options can also be considered unstable, and they were unlocked through the
1016 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1017 /// instability in both cases, though.
1019 /// So with all that in mind, the comments below have some more detail about the
1020 /// contortions done here to get things to work out correctly.
1021 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1022 // Throw away the first argument, the name of the binary
1023 let args = &args[1..];
1025 if args.is_empty() {
1026 // user did not write `-v` nor `-Z unstable-options`, so do not
1027 // include that extra information.
1028 usage(false, false);
1032 // Parse with *all* options defined in the compiler, we don't worry about
1033 // option stability here we just want to parse as much as possible.
1034 let mut options = getopts::Options::new();
1035 for option in config::rustc_optgroups() {
1036 (option.apply)(&mut options);
1038 let matches = options
1040 .unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string()));
1042 // For all options we just parsed, we check a few aspects:
1044 // * If the option is stable, we're all good
1045 // * If the option wasn't passed, we're all good
1046 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1047 // ourselves), then we require the `-Z unstable-options` flag to unlock
1048 // this option that was passed.
1049 // * If we're a nightly compiler, then unstable options are now unlocked, so
1050 // we're good to go.
1051 // * Otherwise, if we're an unstable option then we generate an error
1052 // (unstable option being used on stable)
1053 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1055 if matches.opt_present("h") || matches.opt_present("help") {
1056 // Only show unstable options in --help if we accept unstable options.
1057 usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
1061 // Handle the special case of -Wall.
1062 let wall = matches.opt_strs("W");
1063 if wall.iter().any(|x| *x == "all") {
1068 // Don't handle -W help here, because we might first load plugins.
1069 let r = matches.opt_strs("Z");
1070 if r.iter().any(|x| *x == "help") {
1071 describe_debug_flags();
1075 let cg_flags = matches.opt_strs("C");
1077 if cg_flags.iter().any(|x| *x == "help") {
1078 describe_codegen_flags();
1082 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1084 ErrorOutputType::default(),
1085 "the --no-stack-check flag is deprecated and does nothing",
1089 if cg_flags.iter().any(|x| *x == "passes=list") {
1090 get_builtin_codegen_backend("llvm")().print_passes();
1094 if matches.opt_present("version") {
1095 version("rustc", &matches);
1102 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1104 Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1105 Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1113 /// Gets a list of extra command-line flags provided by the user, as strings.
1115 /// This function is used during ICEs to show more information useful for
1116 /// debugging, since some ICEs only happens with non-default compiler flags
1117 /// (and the users don't always report them).
1118 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1119 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1121 // Avoid printing help because of empty args. This can suggest the compiler
1122 // itself is not the program root (consider RLS).
1127 let matches = if let Some(matches) = handle_options(&args) {
1133 let mut result = Vec::new();
1134 let mut excluded_cargo_defaults = false;
1135 for flag in ICE_REPORT_COMPILER_FLAGS {
1136 let prefix = if flag.len() == 1 { "-" } else { "--" };
1138 for content in &matches.opt_strs(flag) {
1139 // Split always returns the first element
1140 let name = if let Some(first) = content.split('=').next() { first } else { &content };
1143 if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
1145 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1146 result.push(format!("{}{} {}", prefix, flag, content));
1148 excluded_cargo_defaults = true;
1153 if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1156 /// Runs a closure and catches unwinds triggered by fatal errors.
1158 /// The compiler currently unwinds with a special sentinel value to abort
1159 /// compilation on fatal errors. This function catches that sentinel and turns
1160 /// the panic into a `Result` instead.
1161 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1162 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1163 if value.is::<rustc_errors::FatalErrorMarker>() {
1166 panic::resume_unwind(value);
1172 static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
1173 let hook = panic::take_hook();
1174 panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
1179 /// Prints the ICE message, including backtrace and query stack.
1181 /// The message will point the user at `bug_report_url` to report the ICE.
1183 /// When `install_ice_hook` is called, this function will be called as the panic
1185 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1186 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1187 (*DEFAULT_HOOK)(info);
1189 // Separate the output with an empty line
1192 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1193 rustc_errors::ColorConfig::Auto,
1200 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1202 // a .span_bug or .bug call has already printed what
1203 // it wants to print.
1204 if !info.payload().is::<rustc_errors::ExplicitBug>() {
1205 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1206 handler.emit_diagnostic(&d);
1209 let mut xs: Vec<Cow<'static, str>> = vec![
1210 "the compiler unexpectedly panicked. this is a bug.".into(),
1211 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1213 "rustc {} running on {}",
1214 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1215 config::host_triple()
1220 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1221 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1223 if excluded_cargo_defaults {
1224 xs.push("some of the compiler flags provided by cargo are hidden".into());
1229 handler.note_without_error(¬e);
1232 // If backtraces are enabled, also print the query stack
1233 let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
1236 TyCtxt::try_print_query_stack(&handler);
1241 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1242 // Trigger a debugger if we crashed during bootstrap
1243 winapi::um::debugapi::DebugBreak();
1248 /// Installs a panic hook that will print the ICE message on unexpected panics.
1250 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1251 pub fn install_ice_hook() {
1252 lazy_static::initialize(&DEFAULT_HOOK);
1255 /// This allows tools to enable rust logging without having to magically match rustc's
1256 /// log crate version
1257 pub fn init_rustc_env_logger() {
1258 env_logger::init_from_env("RUSTC_LOG");
1262 let start = Instant::now();
1263 init_rustc_env_logger();
1264 let mut callbacks = TimePassesCallbacks::default();
1266 let result = catch_fatal_errors(|| {
1267 let args = env::args_os()
1270 arg.into_string().unwrap_or_else(|arg| {
1272 ErrorOutputType::default(),
1273 &format!("Argument {} is not valid Unicode: {:?}", i, arg),
1277 .collect::<Vec<_>>();
1278 run_compiler(&args, &mut callbacks, None, None)
1280 .and_then(|result| result);
1281 let exit_code = match result {
1282 Ok(_) => EXIT_SUCCESS,
1283 Err(_) => EXIT_FAILURE,
1285 // The extra `\t` is necessary to align this label with the others.
1286 print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
1287 process::exit(exit_code);