5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![recursion_limit = "256"]
15 pub extern crate rustc_plugin_impl as plugin;
18 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
19 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
20 use rustc_data_structures::sync::SeqCst;
21 use rustc_errors::registry::{InvalidErrorCode, Registry};
22 use rustc_errors::{ErrorReported, PResult};
23 use rustc_feature::find_gated_cfg;
24 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
25 use rustc_interface::{interface, Queries};
26 use rustc_lint::LintStore;
27 use rustc_metadata::locator;
28 use rustc_save_analysis as save;
29 use rustc_save_analysis::DumpHandler;
30 use rustc_serialize::json::{self, ToJson};
31 use rustc_session::config::{nightly_options, CG_OPTIONS, DB_OPTIONS};
32 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
33 use rustc_session::cstore::MetadataLoader;
34 use rustc_session::getopts;
35 use rustc_session::lint::{Lint, LintId};
36 use rustc_session::{config, DiagnosticOutput, Session};
37 use rustc_session::{early_error, early_error_no_abort, early_warn};
38 use rustc_span::source_map::{FileLoader, FileName};
39 use rustc_span::symbol::sym;
43 use std::default::Default;
45 use std::ffi::OsString;
47 use std::io::{self, Read, Write};
48 use std::lazy::SyncLazy;
49 use std::panic::{self, catch_unwind};
50 use std::path::PathBuf;
51 use std::process::{self, Command, Stdio};
53 use std::time::Instant;
58 /// Exit status code used for successful compilation and help output.
59 pub const EXIT_SUCCESS: i32 = 0;
61 /// Exit status code used for compilation failures and invalid flags.
62 pub const EXIT_FAILURE: i32 = 1;
64 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
65 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
67 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
69 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
71 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
73 pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
76 sess.abort_if_errors();
77 panic!("error reported but abort_if_errors didn't abort???");
84 /// Called before creating the compiler instance
85 fn config(&mut self, _config: &mut interface::Config) {}
86 /// Called after parsing. Return value instructs the compiler whether to
87 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
88 fn after_parsing<'tcx>(
90 _compiler: &interface::Compiler,
91 _queries: &'tcx Queries<'tcx>,
95 /// Called after expansion. Return value instructs the compiler whether to
96 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
97 fn after_expansion<'tcx>(
99 _compiler: &interface::Compiler,
100 _queries: &'tcx Queries<'tcx>,
102 Compilation::Continue
104 /// Called after analysis. Return value instructs the compiler whether to
105 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
106 fn after_analysis<'tcx>(
108 _compiler: &interface::Compiler,
109 _queries: &'tcx Queries<'tcx>,
111 Compilation::Continue
116 pub struct TimePassesCallbacks {
120 impl Callbacks for TimePassesCallbacks {
121 fn config(&mut self, config: &mut interface::Config) {
122 // If a --prints=... option has been given, we don't print the "total"
123 // time because it will mess up the --prints output. See #64339.
124 self.time_passes = config.opts.prints.is_empty()
125 && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
126 config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
130 pub fn diagnostics_registry() -> Registry {
131 Registry::new(rustc_error_codes::DIAGNOSTICS)
134 /// This is the primary entry point for rustc.
135 pub struct RunCompiler<'a, 'b> {
136 at_args: &'a [String],
137 callbacks: &'b mut (dyn Callbacks + Send),
138 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
139 emitter: Option<Box<dyn Write + Send>>,
140 make_codegen_backend:
141 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
144 impl<'a, 'b> RunCompiler<'a, 'b> {
145 pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
146 Self { at_args, callbacks, file_loader: None, emitter: None, make_codegen_backend: None }
149 /// Set a custom codegen backend.
152 pub fn set_make_codegen_backend(
154 make_codegen_backend: Option<
155 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
158 self.make_codegen_backend = make_codegen_backend;
162 /// Emit diagnostics to the specified location.
165 pub fn set_emitter(&mut self, emitter: Option<Box<dyn Write + Send>>) -> &mut Self {
166 self.emitter = emitter;
170 /// Load files from sources other than the file system.
173 pub fn set_file_loader(
175 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
177 self.file_loader = file_loader;
181 /// Parse args and run the compiler.
182 pub fn run(self) -> interface::Result<()> {
188 self.make_codegen_backend,
194 callbacks: &mut (dyn Callbacks + Send),
195 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
196 emitter: Option<Box<dyn Write + Send>>,
197 make_codegen_backend: Option<
198 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
200 ) -> interface::Result<()> {
201 let args = args::arg_expand_all(at_args);
203 let diagnostic_output = emitter.map_or(DiagnosticOutput::Default, DiagnosticOutput::Raw);
204 let matches = match handle_options(&args) {
205 Some(matches) => matches,
206 None => return Ok(()),
209 let sopts = config::build_session_options(&matches);
211 if let Some(ref code) = matches.opt_str("explain") {
212 handle_explain(diagnostics_registry(), code, sopts.error_format);
216 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
217 let (odir, ofile) = make_output(&matches);
218 let mut config = interface::Config {
221 input: Input::File(PathBuf::new()),
228 lint_caps: Default::default(),
229 parse_sess_created: None,
230 register_lints: None,
231 override_queries: None,
232 make_codegen_backend,
233 registry: diagnostics_registry(),
236 match make_input(config.opts.error_format, &matches.free) {
237 Err(ErrorReported) => return Err(ErrorReported),
238 Ok(Some((input, input_file_path))) => {
239 config.input = input;
240 config.input_path = input_file_path;
242 callbacks.config(&mut config);
244 Ok(None) => match matches.free.len() {
246 callbacks.config(&mut config);
247 interface::run_compiler(config, |compiler| {
248 let sopts = &compiler.session().opts;
249 if sopts.describe_lints {
250 let mut lint_store = rustc_lint::new_lint_store(
251 sopts.debugging_opts.no_interleave_lints,
252 compiler.session().unstable_options(),
254 let registered_lints =
255 if let Some(register_lints) = compiler.register_lints() {
256 register_lints(compiler.session(), &mut lint_store);
261 describe_lints(compiler.session(), &lint_store, registered_lints);
264 let should_stop = RustcDefaultCalls::print_crate_info(
265 &***compiler.codegen_backend(),
268 compiler.output_dir(),
269 compiler.output_file(),
270 compiler.temps_dir(),
273 if should_stop == Compilation::Stop {
276 early_error(sopts.error_format, "no input filename given")
280 1 => panic!("make_input should have provided valid inputs"),
282 config.opts.error_format,
284 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
285 matches.free[0], matches.free[1],
291 interface::run_compiler(config, |compiler| {
292 let sess = compiler.session();
293 let should_stop = RustcDefaultCalls::print_crate_info(
294 &***compiler.codegen_backend(),
296 Some(compiler.input()),
297 compiler.output_dir(),
298 compiler.output_file(),
299 compiler.temps_dir(),
302 RustcDefaultCalls::list_metadata(
304 &*compiler.codegen_backend().metadata_loader(),
308 .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
310 if should_stop == Compilation::Stop {
311 return sess.compile_status();
314 let linker = compiler.enter(|queries| {
315 let early_exit = || sess.compile_status().map(|_| None);
318 if let Some(ppm) = &sess.opts.pretty {
319 if ppm.needs_ast_map() {
320 let expanded_crate = queries.expansion()?.peek().0.clone();
321 queries.global_ctxt()?.peek_mut().enter(|tcx| {
322 pretty::print_after_hir_lowering(
327 compiler.output_file().as_ref().map(|p| &**p),
332 let krate = queries.parse()?.take();
333 pretty::print_after_parsing(
338 compiler.output_file().as_ref().map(|p| &**p),
341 trace!("finished pretty-printing");
345 if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
349 if sess.opts.debugging_opts.parse_only
350 || sess.opts.debugging_opts.show_span.is_some()
351 || sess.opts.debugging_opts.ast_json_noexpand
357 let (_, lint_store) = &*queries.register_plugins()?.peek();
359 // Lint plugins are registered; now we can process command line flags.
360 if sess.opts.describe_lints {
361 describe_lints(sess, lint_store, true);
366 queries.expansion()?;
367 if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
371 queries.prepare_outputs()?;
373 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
374 && sess.opts.output_types.len() == 1
379 queries.global_ctxt()?;
381 if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
385 queries.global_ctxt()?.peek_mut().enter(|tcx| {
386 let result = tcx.analysis(());
387 if sess.opts.debugging_opts.save_analysis {
388 let crate_name = queries.crate_name()?.peek().clone();
389 sess.time("save_analysis", || {
396 compiler.output_dir().as_ref().map(|p| &**p),
405 if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
409 queries.ongoing_codegen()?;
411 if sess.opts.debugging_opts.print_type_sizes {
412 sess.code_stats.print_type_sizes();
415 let linker = queries.linker()?;
419 if let Some(linker) = linker {
420 let _timer = sess.timer("link");
424 if sess.opts.debugging_opts.perf_stats {
425 sess.print_perf_stats();
428 if sess.opts.debugging_opts.print_fuel.is_some() {
430 "Fuel used by {}: {}",
431 sess.opts.debugging_opts.print_fuel.as_ref().unwrap(),
432 sess.print_fuel.load(SeqCst)
441 pub fn set_sigpipe_handler() {
443 // Set the SIGPIPE signal handler, so that an EPIPE
444 // will cause rustc to terminate, as expected.
445 assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
450 pub fn set_sigpipe_handler() {}
452 // Extract output directory and file from matches.
453 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
454 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
455 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
459 // Extract input (string or file and optional path) from matches.
461 error_format: ErrorOutputType,
462 free_matches: &[String],
463 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorReported> {
464 if free_matches.len() == 1 {
465 let ifile = &free_matches[0];
467 let mut src = String::new();
468 if io::stdin().read_to_string(&mut src).is_err() {
469 // Immediately stop compilation if there was an issue reading
470 // the input (for example if the input stream is not UTF-8).
471 early_error_no_abort(
473 "couldn't read from stdin, as it did not contain valid UTF-8",
475 return Err(ErrorReported);
477 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
478 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
479 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
480 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
482 let line = isize::from_str_radix(&line, 10)
483 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
484 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
485 Ok(Some((Input::Str { name: file_name, input: src }, None)))
487 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
490 Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
497 /// Whether to stop or continue compilation.
498 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
499 pub enum Compilation {
505 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
507 Compilation::Stop => Compilation::Stop,
508 Compilation::Continue => next(),
513 /// CompilerCalls instance for a regular rustc build.
514 #[derive(Copy, Clone)]
515 pub struct RustcDefaultCalls;
517 fn stdout_isatty() -> bool {
518 atty::is(atty::Stream::Stdout)
521 fn stderr_isatty() -> bool {
522 atty::is(atty::Stream::Stderr)
525 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
526 let upper_cased_code = code.to_ascii_uppercase();
527 let normalised = if upper_cased_code.starts_with('E') {
530 format!("E{0:0>4}", code)
532 match registry.try_find_description(&normalised) {
533 Ok(Some(description)) => {
534 let mut is_in_code_block = false;
535 let mut text = String::new();
536 // Slice off the leading newline and print.
537 for line in description.lines() {
539 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
540 let dedented_line = &line[indent_level..];
541 if dedented_line.starts_with("```") {
542 is_in_code_block = !is_in_code_block;
543 text.push_str(&line[..(indent_level + 3)]);
544 } else if is_in_code_block && dedented_line.starts_with("# ") {
552 show_content_with_pager(&text);
558 early_error(output, &format!("no extended information for {}", code));
560 Err(InvalidErrorCode) => {
561 early_error(output, &format!("{} is not a valid error code", code));
566 fn show_content_with_pager(content: &str) {
567 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
568 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
571 let mut fallback_to_println = false;
573 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
575 if let Some(pipe) = pager.stdin.as_mut() {
576 if pipe.write_all(content.as_bytes()).is_err() {
577 fallback_to_println = true;
581 if pager.wait().is_err() {
582 fallback_to_println = true;
586 fallback_to_println = true;
590 // If pager fails for whatever reason, we should still print the content
591 // to standard output
592 if fallback_to_println {
593 print!("{}", content);
597 impl RustcDefaultCalls {
598 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
599 if sess.opts.debugging_opts.link_only {
600 if let Input::File(file) = compiler.input() {
601 // FIXME: #![crate_type] and #![crate_name] support not implemented yet
602 sess.init_crate_types(collect_crate_types(sess, &[]));
603 let outputs = compiler.build_output_filenames(sess, &[]);
604 let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
605 sess.fatal(&format!("failed to read rlink file: {}", err));
607 let codegen_results: CodegenResults =
608 json::decode(&rlink_data).unwrap_or_else(|err| {
609 sess.fatal(&format!("failed to decode rlink: {}", err));
611 let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
612 abort_on_err(result, sess);
614 sess.fatal("rlink must be a file")
618 Compilation::Continue
622 pub fn list_metadata(
624 metadata_loader: &dyn MetadataLoader,
627 if sess.opts.debugging_opts.ls {
629 Input::File(ref ifile) => {
630 let path = &(*ifile);
631 let mut v = Vec::new();
632 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v)
634 println!("{}", String::from_utf8(v).unwrap());
636 Input::Str { .. } => {
637 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
640 return Compilation::Stop;
643 Compilation::Continue
647 codegen_backend: &dyn CodegenBackend,
649 input: Option<&Input>,
650 odir: &Option<PathBuf>,
651 ofile: &Option<PathBuf>,
652 temps_dir: &Option<PathBuf>,
654 use rustc_session::config::PrintRequest::*;
655 // PrintRequest::NativeStaticLibs is special - printed during linking
656 // (empty iterator returns true)
657 if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
658 return Compilation::Continue;
661 let attrs = match input {
664 let result = parse_crate_attrs(sess, input);
666 Ok(attrs) => Some(attrs),
667 Err(mut parse_error) => {
669 return Compilation::Stop;
674 for req in &sess.opts.prints {
678 rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
679 targets.sort_unstable();
680 println!("{}", targets.join("\n"));
682 Sysroot => println!("{}", sess.sysroot.display()),
683 TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
684 TargetSpec => println!("{}", sess.target.to_json().pretty()),
685 FileNames | CrateName => {
686 let input = input.unwrap_or_else(|| {
687 early_error(ErrorOutputType::default(), "no input file provided")
689 let attrs = attrs.as_ref().unwrap();
690 let t_outputs = rustc_interface::util::build_output_filenames(
691 input, odir, ofile, temps_dir, attrs, sess,
693 let id = rustc_session::output::find_crate_name(sess, attrs, input);
694 if *req == PrintRequest::CrateName {
698 let crate_types = collect_crate_types(sess, attrs);
699 for &style in &crate_types {
701 rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
702 println!("{}", fname.file_name().unwrap().to_string_lossy());
710 .filter_map(|&(name, value)| {
711 // Note that crt-static is a specially recognized cfg
712 // directive that's printed out here as part of
713 // rust-lang/rust#37406, but in general the
714 // `target_feature` cfg is gated under
715 // rust-lang/rust#29717. For now this is just
716 // specifically allowing the crt-static cfg and that's
717 // it, this is intended to get into Cargo and then go
718 // through to build scripts.
719 if (name != sym::target_feature || value != Some(sym::crt_dash_static))
720 && !sess.is_nightly_build()
721 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
726 if let Some(value) = value {
727 Some(format!("{}=\"{}\"", name, value))
729 Some(name.to_string())
732 .collect::<Vec<String>>();
739 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
740 codegen_backend.print(*req, sess);
742 // Any output here interferes with Cargo's parsing of other printed output
743 PrintRequest::NativeStaticLibs => {}
750 /// Prints version information
751 pub fn version(binary: &str, matches: &getopts::Matches) {
752 let verbose = matches.opt_present("verbose");
754 println!("{} {}", binary, util::version_str().unwrap_or("unknown version"));
757 fn unw(x: Option<&str>) -> &str {
758 x.unwrap_or("unknown")
760 println!("binary: {}", binary);
761 println!("commit-hash: {}", unw(util::commit_hash_str()));
762 println!("commit-date: {}", unw(util::commit_date_str()));
763 println!("host: {}", config::host_triple());
764 println!("release: {}", unw(util::release_str()));
766 let debug_flags = matches.opt_strs("Z");
767 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
768 get_codegen_backend(&None, backend_name).print_version();
772 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
773 let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
774 let mut options = getopts::Options::new();
775 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
776 (option.apply)(&mut options);
778 let message = "Usage: rustc [OPTIONS] INPUT";
779 let nightly_help = if nightly_build {
780 "\n -Z help Print unstable compiler options"
784 let verbose_help = if verbose {
787 "\n --help -v Print the full set of options rustc accepts"
789 let at_path = if verbose {
790 " @path Read newline separated options from `path`\n"
795 "{options}{at_path}\nAdditional help:
796 -C help Print codegen options
798 Print 'lint' options and default settings{nightly}{verbose}\n",
799 options = options.usage(message),
801 nightly = nightly_help,
802 verbose = verbose_help
806 fn print_wall_help() {
809 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
810 default. Use `rustc -W help` to see all available lints. It's more common to put
811 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
812 the command line flag directly.
817 /// Write to stdout lint command options, together with a list of all available lints
818 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
821 Available lint options:
822 -W <foo> Warn about <foo>
826 -F <foo> Forbid <foo> \
827 (deny <foo> and all attempts to override)
832 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
833 // The sort doesn't case-fold but it's doubtful we care.
834 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
839 lints: Vec<(&'static str, Vec<LintId>, bool)>,
840 ) -> Vec<(&'static str, Vec<LintId>)> {
841 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
842 lints.sort_by_key(|l| l.0);
846 let (plugin, builtin): (Vec<_>, _) =
847 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
848 let plugin = sort_lints(sess, plugin);
849 let builtin = sort_lints(sess, builtin);
851 let (plugin_groups, builtin_groups): (Vec<_>, _) =
852 lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
853 let plugin_groups = sort_lint_groups(plugin_groups);
854 let builtin_groups = sort_lint_groups(builtin_groups);
857 plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
858 let padded = |x: &str| {
859 let mut s = " ".repeat(max_name_len - x.chars().count());
864 println!("Lint checks provided by rustc:\n");
865 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
866 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
868 let print_lints = |lints: Vec<&Lint>| {
870 let name = lint.name_lower().replace("_", "-");
874 lint.default_level(sess.edition()).as_str(),
881 print_lints(builtin);
883 let max_name_len = max(
887 .chain(&builtin_groups)
888 .map(|&(s, _)| s.chars().count())
893 let padded = |x: &str| {
894 let mut s = " ".repeat(max_name_len - x.chars().count());
899 println!("Lint groups provided by rustc:\n");
900 println!(" {} sub-lints", padded("name"));
901 println!(" {} ---------", padded("----"));
902 println!(" {} all lints that are set to issue warnings", padded("warnings"));
904 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
905 for (name, to) in lints {
906 let name = name.to_lowercase().replace("_", "-");
909 .map(|x| x.to_string().replace("_", "-"))
910 .collect::<Vec<String>>()
912 println!(" {} {}", padded(&name), desc);
917 print_lint_groups(builtin_groups);
919 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
920 (false, 0, _) | (false, _, 0) => {
921 println!("Lint tools like Clippy can provide additional lints and lint groups.");
923 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
924 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
927 println!("Lint checks provided by plugins loaded by this crate:\n");
931 println!("Lint groups provided by plugins loaded by this crate:\n");
932 print_lint_groups(plugin_groups);
938 fn describe_debug_flags() {
939 println!("\nAvailable options:\n");
940 print_flag_list("-Z", config::DB_OPTIONS);
943 fn describe_codegen_flags() {
944 println!("\nAvailable codegen options:\n");
945 print_flag_list("-C", config::CG_OPTIONS);
948 fn print_flag_list<T>(
950 flag_list: &[(&'static str, T, &'static str, &'static str)],
952 let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
954 for &(name, _, _, desc) in flag_list {
956 " {} {:>width$}=val -- {}",
958 name.replace("_", "-"),
965 /// Process command line options. Emits messages as appropriate. If compilation
966 /// should continue, returns a getopts::Matches object parsed from args,
967 /// otherwise returns `None`.
969 /// The compiler's handling of options is a little complicated as it ties into
970 /// our stability story. The current intention of each compiler option is to
971 /// have one of two modes:
973 /// 1. An option is stable and can be used everywhere.
974 /// 2. An option is unstable, and can only be used on nightly.
976 /// Like unstable library and language features, however, unstable options have
977 /// always required a form of "opt in" to indicate that you're using them. This
978 /// provides the easy ability to scan a code base to check to see if anything
979 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
981 /// All options behind `-Z` are considered unstable by default. Other top-level
982 /// options can also be considered unstable, and they were unlocked through the
983 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
984 /// instability in both cases, though.
986 /// So with all that in mind, the comments below have some more detail about the
987 /// contortions done here to get things to work out correctly.
988 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
989 // Throw away the first argument, the name of the binary
990 let args = &args[1..];
993 // user did not write `-v` nor `-Z unstable-options`, so do not
994 // include that extra information.
996 rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
997 usage(false, false, nightly_build);
1001 // Parse with *all* options defined in the compiler, we don't worry about
1002 // option stability here we just want to parse as much as possible.
1003 let mut options = getopts::Options::new();
1004 for option in config::rustc_optgroups() {
1005 (option.apply)(&mut options);
1007 let matches = options.parse(args).unwrap_or_else(|e| {
1009 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1011 .map(|&(name, ..)| ('C', name))
1012 .chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1013 .find(|&(_, name)| *opt == name.replace("_", "-"))
1014 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
1017 early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1020 // For all options we just parsed, we check a few aspects:
1022 // * If the option is stable, we're all good
1023 // * If the option wasn't passed, we're all good
1024 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1025 // ourselves), then we require the `-Z unstable-options` flag to unlock
1026 // this option that was passed.
1027 // * If we're a nightly compiler, then unstable options are now unlocked, so
1028 // we're good to go.
1029 // * Otherwise, if we're an unstable option then we generate an error
1030 // (unstable option being used on stable)
1031 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1033 if matches.opt_present("h") || matches.opt_present("help") {
1034 // Only show unstable options in --help if we accept unstable options.
1035 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1036 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1037 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1041 // Handle the special case of -Wall.
1042 let wall = matches.opt_strs("W");
1043 if wall.iter().any(|x| *x == "all") {
1048 // Don't handle -W help here, because we might first load plugins.
1049 let debug_flags = matches.opt_strs("Z");
1050 if debug_flags.iter().any(|x| *x == "help") {
1051 describe_debug_flags();
1055 let cg_flags = matches.opt_strs("C");
1057 if cg_flags.iter().any(|x| *x == "help") {
1058 describe_codegen_flags();
1062 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1064 ErrorOutputType::default(),
1065 "the --no-stack-check flag is deprecated and does nothing",
1069 if cg_flags.iter().any(|x| *x == "passes=list") {
1070 let backend_name = debug_flags.iter().find_map(|x| {
1071 if x.starts_with("codegen-backend=") {
1072 Some(&x["codegen-backends=".len()..])
1077 get_codegen_backend(&None, backend_name).print_passes();
1081 if matches.opt_present("version") {
1082 version("rustc", &matches);
1089 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1091 Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1092 Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1100 /// Gets a list of extra command-line flags provided by the user, as strings.
1102 /// This function is used during ICEs to show more information useful for
1103 /// debugging, since some ICEs only happens with non-default compiler flags
1104 /// (and the users don't always report them).
1105 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1106 let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
1108 // Avoid printing help because of empty args. This can suggest the compiler
1109 // itself is not the program root (consider RLS).
1114 let matches = handle_options(&args)?;
1115 let mut result = Vec::new();
1116 let mut excluded_cargo_defaults = false;
1117 for flag in ICE_REPORT_COMPILER_FLAGS {
1118 let prefix = if flag.len() == 1 { "-" } else { "--" };
1120 for content in &matches.opt_strs(flag) {
1121 // Split always returns the first element
1122 let name = if let Some(first) = content.split('=').next() { first } else { &content };
1125 if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
1127 if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
1128 result.push(format!("{}{} {}", prefix, flag, content));
1130 excluded_cargo_defaults = true;
1135 if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1138 /// Runs a closure and catches unwinds triggered by fatal errors.
1140 /// The compiler currently unwinds with a special sentinel value to abort
1141 /// compilation on fatal errors. This function catches that sentinel and turns
1142 /// the panic into a `Result` instead.
1143 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
1144 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1145 if value.is::<rustc_errors::FatalErrorMarker>() {
1148 panic::resume_unwind(value);
1153 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1154 /// that also computes the exit code.
1155 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1156 let result = catch_fatal_errors(f).and_then(|result| result);
1158 Ok(()) => EXIT_SUCCESS,
1159 Err(_) => EXIT_FAILURE,
1163 static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1165 let hook = panic::take_hook();
1166 panic::set_hook(Box::new(|info| {
1167 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1168 (*DEFAULT_HOOK)(info);
1170 // Separate the output with an empty line
1173 // Print the ICE message
1174 report_ice(info, BUG_REPORT_URL);
1179 /// Prints the ICE message, including query stack, but without backtrace.
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 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1187 rustc_errors::ColorConfig::Auto,
1194 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1196 // a .span_bug or .bug call has already printed what
1197 // it wants to print.
1198 if !info.payload().is::<rustc_errors::ExplicitBug>() {
1199 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1200 handler.emit_diagnostic(&d);
1203 let mut xs: Vec<Cow<'static, str>> = vec![
1204 "the compiler unexpectedly panicked. this is a bug.".into(),
1205 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1207 "rustc {} running on {}",
1208 util::version_str().unwrap_or("unknown_version"),
1209 config::host_triple()
1214 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1215 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1217 if excluded_cargo_defaults {
1218 xs.push("some of the compiler flags provided by cargo are hidden".into());
1223 handler.note_without_error(note);
1226 // If backtraces are enabled, also print the query stack
1227 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1229 let num_frames = if backtrace { None } else { Some(2) };
1231 interface::try_print_query_stack(&handler, num_frames);
1235 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1236 // Trigger a debugger if we crashed during bootstrap
1237 winapi::um::debugapi::DebugBreak();
1242 /// Installs a panic hook that will print the ICE message on unexpected panics.
1244 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1245 pub fn install_ice_hook() {
1246 SyncLazy::force(&DEFAULT_HOOK);
1249 /// This allows tools to enable rust logging without having to magically match rustc's
1250 /// tracing crate version.
1251 pub fn init_rustc_env_logger() {
1252 init_env_logger("RUSTC_LOG")
1255 /// This allows tools to enable rust logging without having to magically match rustc's
1256 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1257 /// other than `RUSTC_LOG`.
1258 pub fn init_env_logger(env: &str) {
1259 use tracing_subscriber::{
1260 filter::{self, EnvFilter, LevelFilter},
1261 layer::SubscriberExt,
1264 let filter = match std::env::var(env) {
1265 Ok(env) => EnvFilter::new(env),
1266 _ => EnvFilter::default().add_directive(filter::Directive::from(LevelFilter::WARN)),
1269 let color_logs = match std::env::var(String::from(env) + "_COLOR") {
1270 Ok(value) => match value.as_ref() {
1273 "auto" => stderr_isatty(),
1275 ErrorOutputType::default(),
1277 "invalid log color value '{}': expected one of always, never, or auto",
1282 Err(std::env::VarError::NotPresent) => stderr_isatty(),
1283 Err(std::env::VarError::NotUnicode(_value)) => early_error(
1284 ErrorOutputType::default(),
1285 "non-Unicode log color value: expected one of always, never, or auto",
1289 let layer = tracing_tree::HierarchicalLayer::default()
1290 .with_writer(io::stderr)
1291 .with_indent_lines(true)
1292 .with_ansi(color_logs)
1294 .with_indent_amount(2);
1295 #[cfg(parallel_compiler)]
1296 let layer = layer.with_thread_ids(true).with_thread_names(true);
1298 let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
1299 tracing::subscriber::set_global_default(subscriber).unwrap();
1302 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1303 mod signal_handler {
1305 fn backtrace_symbols_fd(
1306 buffer: *const *mut libc::c_void,
1312 extern "C" fn print_stack_trace(_: libc::c_int) {
1313 const MAX_FRAMES: usize = 256;
1314 static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1315 [std::ptr::null_mut(); MAX_FRAMES];
1317 let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1321 backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1325 // When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1326 // process, print a stack trace and then exit.
1327 pub(super) fn install() {
1329 const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1330 let mut alt_stack: libc::stack_t = std::mem::zeroed();
1332 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1333 as *mut libc::c_void;
1334 alt_stack.ss_size = ALT_STACK_SIZE;
1335 libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1337 let mut sa: libc::sigaction = std::mem::zeroed();
1338 sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1339 sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1340 libc::sigemptyset(&mut sa.sa_mask);
1341 libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1346 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1347 mod signal_handler {
1348 pub(super) fn install() {}
1351 pub fn main() -> ! {
1352 let start_time = Instant::now();
1353 let start_rss = get_resident_set_size();
1354 init_rustc_env_logger();
1355 signal_handler::install();
1356 let mut callbacks = TimePassesCallbacks::default();
1358 let exit_code = catch_with_exit_code(|| {
1359 let args = env::args_os()
1362 arg.into_string().unwrap_or_else(|arg| {
1364 ErrorOutputType::default(),
1365 &format!("argument {} is not valid Unicode: {:?}", i, arg),
1369 .collect::<Vec<_>>();
1370 RunCompiler::new(&args, &mut callbacks).run()
1373 if callbacks.time_passes {
1374 let end_rss = get_resident_set_size();
1375 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1378 process::exit(exit_code)