5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(is_terminal)]
10 #![feature(decl_macro)]
11 #![recursion_limit = "256"]
12 #![allow(rustc::potential_query_instability)]
13 #![deny(rustc::untranslatable_diagnostic)]
14 #![deny(rustc::diagnostic_outside_of_impl)]
19 pub extern crate rustc_plugin_impl as plugin;
22 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenErrors, CodegenResults};
23 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
24 use rustc_data_structures::sync::SeqCst;
25 use rustc_errors::registry::{InvalidErrorCode, Registry};
26 use rustc_errors::{ErrorGuaranteed, PResult};
27 use rustc_feature::find_gated_cfg;
28 use rustc_hir::def_id::LOCAL_CRATE;
29 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
30 use rustc_interface::{interface, Queries};
31 use rustc_lint::LintStore;
32 use rustc_metadata::locator;
33 use rustc_save_analysis as save;
34 use rustc_save_analysis::DumpHandler;
35 use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS};
36 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
37 use rustc_session::cstore::MetadataLoader;
38 use rustc_session::getopts;
39 use rustc_session::lint::{Lint, LintId};
40 use rustc_session::{config, Session};
41 use rustc_session::{early_error, early_error_no_abort, early_warn};
42 use rustc_span::source_map::{FileLoader, FileName};
43 use rustc_span::symbol::sym;
44 use rustc_target::json::ToJson;
49 use std::ffi::OsString;
51 use std::io::{self, IsTerminal, Read, Write};
52 use std::panic::{self, catch_unwind};
53 use std::path::PathBuf;
54 use std::process::{self, Command, Stdio};
56 use std::sync::LazyLock;
57 use std::time::Instant;
61 mod session_diagnostics;
63 use crate::session_diagnostics::{
64 RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
65 RLinkWrongFileType, RlinkNotAFile, RlinkUnableToRead,
68 /// Exit status code used for successful compilation and help output.
69 pub const EXIT_SUCCESS: i32 = 0;
71 /// Exit status code used for compilation failures and invalid flags.
72 pub const EXIT_FAILURE: i32 = 1;
74 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
75 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
77 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
79 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
81 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
83 pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
86 sess.abort_if_errors();
87 panic!("error reported but abort_if_errors didn't abort???");
94 /// Called before creating the compiler instance
95 fn config(&mut self, _config: &mut interface::Config) {}
96 /// Called after parsing. Return value instructs the compiler whether to
97 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
98 fn after_parsing<'tcx>(
100 _compiler: &interface::Compiler,
101 _queries: &'tcx Queries<'tcx>,
103 Compilation::Continue
105 /// Called after expansion. Return value instructs the compiler whether to
106 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
107 fn after_expansion<'tcx>(
109 _compiler: &interface::Compiler,
110 _queries: &'tcx Queries<'tcx>,
112 Compilation::Continue
114 /// Called after analysis. Return value instructs the compiler whether to
115 /// continue the compilation afterwards (defaults to `Compilation::Continue`)
116 fn after_analysis<'tcx>(
118 _compiler: &interface::Compiler,
119 _queries: &'tcx Queries<'tcx>,
121 Compilation::Continue
126 pub struct TimePassesCallbacks {
130 impl Callbacks for TimePassesCallbacks {
131 // JUSTIFICATION: the session doesn't exist at this point.
132 #[allow(rustc::bad_opt_access)]
133 fn config(&mut self, config: &mut interface::Config) {
134 // If a --print=... option has been given, we don't print the "total"
135 // time because it will mess up the --print output. See #64339.
137 self.time_passes = config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes;
138 config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
142 pub fn diagnostics_registry() -> Registry {
143 Registry::new(rustc_error_codes::DIAGNOSTICS)
146 /// This is the primary entry point for rustc.
147 pub struct RunCompiler<'a, 'b> {
148 at_args: &'a [String],
149 callbacks: &'b mut (dyn Callbacks + Send),
150 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
151 make_codegen_backend:
152 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
155 impl<'a, 'b> RunCompiler<'a, 'b> {
156 pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
157 Self { at_args, callbacks, file_loader: None, make_codegen_backend: None }
160 /// Set a custom codegen backend.
162 /// Has no uses within this repository, but is used by bjorn3 for "the
163 /// hotswapping branch of cg_clif" for "setting the codegen backend from a
164 /// custom driver where the custom codegen backend has arbitrary data."
166 pub fn set_make_codegen_backend(
168 make_codegen_backend: Option<
169 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
172 self.make_codegen_backend = make_codegen_backend;
176 /// Load files from sources other than the file system.
178 /// Has no uses within this repository, but may be used in the future by
179 /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
180 /// running rustc without having to save". (See #102759.)
181 pub fn set_file_loader(
183 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
185 self.file_loader = file_loader;
189 /// Parse args and run the compiler.
190 pub fn run(self) -> interface::Result<()> {
191 run_compiler(self.at_args, self.callbacks, self.file_loader, self.make_codegen_backend)
197 callbacks: &mut (dyn Callbacks + Send),
198 file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
199 make_codegen_backend: Option<
200 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
202 ) -> interface::Result<()> {
203 let args = args::arg_expand_all(at_args);
205 let Some(matches) = handle_options(&args) else { return Ok(()) };
207 let sopts = config::build_session_options(&matches);
209 if let Some(ref code) = matches.opt_str("explain") {
210 handle_explain(diagnostics_registry(), code, sopts.error_format);
214 let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
215 let check_cfg = interface::parse_check_cfg(matches.opt_strs("check-cfg"));
216 let (odir, ofile) = make_output(&matches);
217 let mut config = interface::Config {
220 crate_check_cfg: check_cfg,
221 input: Input::File(PathBuf::new()),
226 lint_caps: Default::default(),
227 parse_sess_created: None,
228 register_lints: None,
229 override_queries: None,
230 make_codegen_backend,
231 registry: diagnostics_registry(),
234 match make_input(config.opts.error_format, &matches.free) {
235 Err(reported) => return Err(reported),
236 Ok(Some((input, input_file_path))) => {
237 config.input = input;
238 config.input_path = input_file_path;
240 callbacks.config(&mut config);
242 Ok(None) => match matches.free.len() {
244 callbacks.config(&mut config);
245 interface::run_compiler(config, |compiler| {
246 let sopts = &compiler.session().opts;
247 if sopts.describe_lints {
249 rustc_lint::new_lint_store(compiler.session().enable_internal_lints());
250 let registered_lints =
251 if let Some(register_lints) = compiler.register_lints() {
252 register_lints(compiler.session(), &mut lint_store);
257 describe_lints(compiler.session(), &lint_store, registered_lints);
260 let should_stop = print_crate_info(
261 &***compiler.codegen_backend(),
264 compiler.output_dir(),
265 compiler.output_file(),
266 compiler.temps_dir(),
269 if should_stop == Compilation::Stop {
272 early_error(sopts.error_format, "no input filename given")
276 1 => panic!("make_input should have provided valid inputs"),
278 config.opts.error_format,
280 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
281 matches.free[0], matches.free[1],
287 interface::run_compiler(config, |compiler| {
288 let sess = compiler.session();
289 let should_stop = print_crate_info(
290 &***compiler.codegen_backend(),
292 Some(compiler.input()),
293 compiler.output_dir(),
294 compiler.output_file(),
295 compiler.temps_dir(),
298 list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input())
300 .and_then(|| try_process_rlink(sess, compiler));
302 if should_stop == Compilation::Stop {
303 return sess.compile_status();
306 let linker = compiler.enter(|queries| {
307 let early_exit = || sess.compile_status().map(|_| None);
310 if let Some(ppm) = &sess.opts.pretty {
311 if ppm.needs_ast_map() {
312 let expanded_crate = queries.expansion()?.peek().0.clone();
313 queries.global_ctxt()?.peek_mut().enter(|tcx| {
314 pretty::print_after_hir_lowering(
319 compiler.output_file().as_deref(),
324 let krate = queries.parse()?.take();
325 pretty::print_after_parsing(
330 compiler.output_file().as_deref(),
333 trace!("finished pretty-printing");
337 if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
341 if sess.opts.unstable_opts.parse_only || sess.opts.unstable_opts.show_span.is_some() {
346 let (_, lint_store) = &*queries.register_plugins()?.peek();
348 // Lint plugins are registered; now we can process command line flags.
349 if sess.opts.describe_lints {
350 describe_lints(sess, lint_store, true);
355 queries.expansion()?;
356 if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
360 queries.prepare_outputs()?;
362 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
363 && sess.opts.output_types.len() == 1
368 queries.global_ctxt()?;
370 if sess.opts.unstable_opts.no_analysis {
374 queries.global_ctxt()?.peek_mut().enter(|tcx| {
375 let result = tcx.analysis(());
376 if sess.opts.unstable_opts.save_analysis {
377 let crate_name = tcx.crate_name(LOCAL_CRATE);
378 sess.time("save_analysis", || {
384 DumpHandler::new(compiler.output_dir().as_deref(), crate_name),
391 if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
395 queries.ongoing_codegen()?;
397 if sess.opts.unstable_opts.print_type_sizes {
398 sess.code_stats.print_type_sizes();
401 let linker = queries.linker()?;
405 if let Some(linker) = linker {
406 let _timer = sess.timer("link");
410 if sess.opts.unstable_opts.perf_stats {
411 sess.print_perf_stats();
414 if sess.opts.unstable_opts.print_fuel.is_some() {
416 "Fuel used by {}: {}",
417 sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
418 sess.print_fuel.load(SeqCst)
426 // Extract output directory and file from matches.
427 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
428 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
429 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
433 // Extract input (string or file and optional path) from matches.
435 error_format: ErrorOutputType,
436 free_matches: &[String],
437 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorGuaranteed> {
438 if free_matches.len() == 1 {
439 let ifile = &free_matches[0];
441 let mut src = String::new();
442 if io::stdin().read_to_string(&mut src).is_err() {
443 // Immediately stop compilation if there was an issue reading
444 // the input (for example if the input stream is not UTF-8).
445 let reported = early_error_no_abort(
447 "couldn't read from stdin, as it did not contain valid UTF-8",
449 return Err(reported);
451 if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
452 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
453 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
454 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
456 let line = isize::from_str_radix(&line, 10)
457 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
458 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
459 Ok(Some((Input::Str { name: file_name, input: src }, None)))
461 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
464 Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
471 /// Whether to stop or continue compilation.
472 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
473 pub enum Compilation {
479 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
481 Compilation::Stop => Compilation::Stop,
482 Compilation::Continue => next(),
487 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
488 let upper_cased_code = code.to_ascii_uppercase();
489 let normalised = if upper_cased_code.starts_with('E') {
492 format!("E{0:0>4}", code)
494 match registry.try_find_description(&normalised) {
495 Ok(Some(description)) => {
496 let mut is_in_code_block = false;
497 let mut text = String::new();
498 // Slice off the leading newline and print.
499 for line in description.lines() {
501 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
502 let dedented_line = &line[indent_level..];
503 if dedented_line.starts_with("```") {
504 is_in_code_block = !is_in_code_block;
505 text.push_str(&line[..(indent_level + 3)]);
506 } else if is_in_code_block && dedented_line.starts_with("# ") {
513 if io::stdout().is_terminal() {
514 show_content_with_pager(&text);
520 early_error(output, &format!("no extended information for {}", code));
522 Err(InvalidErrorCode) => {
523 early_error(output, &format!("{} is not a valid error code", code));
528 fn show_content_with_pager(content: &str) {
529 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
530 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
533 let mut fallback_to_println = false;
535 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
537 if let Some(pipe) = pager.stdin.as_mut() {
538 if pipe.write_all(content.as_bytes()).is_err() {
539 fallback_to_println = true;
543 if pager.wait().is_err() {
544 fallback_to_println = true;
548 fallback_to_println = true;
552 // If pager fails for whatever reason, we should still print the content
553 // to standard output
554 if fallback_to_println {
555 print!("{}", content);
559 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
560 if sess.opts.unstable_opts.link_only {
561 if let Input::File(file) = compiler.input() {
562 // FIXME: #![crate_type] and #![crate_name] support not implemented yet
563 sess.init_crate_types(collect_crate_types(sess, &[]));
564 let outputs = compiler.build_output_filenames(sess, &[]);
565 let rlink_data = fs::read(file).unwrap_or_else(|err| {
566 sess.emit_fatal(RlinkUnableToRead { err });
568 let codegen_results = match CodegenResults::deserialize_rlink(rlink_data) {
569 Ok(codegen) => codegen,
572 CodegenErrors::WrongFileType => sess.emit_fatal(RLinkWrongFileType),
573 CodegenErrors::EmptyVersionNumber => {
574 sess.emit_fatal(RLinkEmptyVersionNumber)
576 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
577 sess.emit_fatal(RLinkEncodingVersionMismatch {
582 CodegenErrors::RustcVersionMismatch { rustc_version, current_version } => {
583 sess.emit_fatal(RLinkRustcVersionMismatch {
591 let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
592 abort_on_err(result, sess);
594 sess.emit_fatal(RlinkNotAFile {})
598 Compilation::Continue
602 pub fn list_metadata(
604 metadata_loader: &dyn MetadataLoader,
607 if sess.opts.unstable_opts.ls {
609 Input::File(ref ifile) => {
610 let path = &(*ifile);
611 let mut v = Vec::new();
612 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
613 println!("{}", String::from_utf8(v).unwrap());
615 Input::Str { .. } => {
616 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
619 return Compilation::Stop;
622 Compilation::Continue
626 codegen_backend: &dyn CodegenBackend,
628 input: Option<&Input>,
629 odir: &Option<PathBuf>,
630 ofile: &Option<PathBuf>,
631 temps_dir: &Option<PathBuf>,
633 use rustc_session::config::PrintRequest::*;
634 // NativeStaticLibs and LinkArgs are special - printed during linking
635 // (empty iterator returns true)
636 if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
637 return Compilation::Continue;
640 let attrs = match input {
643 let result = parse_crate_attrs(sess, input);
645 Ok(attrs) => Some(attrs),
646 Err(mut parse_error) => {
648 return Compilation::Stop;
653 for req in &sess.opts.prints {
656 let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
657 targets.sort_unstable();
658 println!("{}", targets.join("\n"));
660 Sysroot => println!("{}", sess.sysroot.display()),
661 TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
663 println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
665 FileNames | CrateName => {
666 let input = input.unwrap_or_else(|| {
667 early_error(ErrorOutputType::default(), "no input file provided")
669 let attrs = attrs.as_ref().unwrap();
670 let t_outputs = rustc_interface::util::build_output_filenames(
671 input, odir, ofile, temps_dir, attrs, sess,
673 let id = rustc_session::output::find_crate_name(sess, attrs, input);
674 if *req == PrintRequest::CrateName {
678 let crate_types = collect_crate_types(sess, attrs);
679 for &style in &crate_types {
681 rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
682 println!("{}", fname.file_name().unwrap().to_string_lossy());
690 .filter_map(|&(name, value)| {
691 // Note that crt-static is a specially recognized cfg
692 // directive that's printed out here as part of
693 // rust-lang/rust#37406, but in general the
694 // `target_feature` cfg is gated under
695 // rust-lang/rust#29717. For now this is just
696 // specifically allowing the crt-static cfg and that's
697 // it, this is intended to get into Cargo and then go
698 // through to build scripts.
699 if (name != sym::target_feature || value != Some(sym::crt_dash_static))
700 && !sess.is_nightly_build()
701 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
706 if let Some(value) = value {
707 Some(format!("{}=\"{}\"", name, value))
709 Some(name.to_string())
712 .collect::<Vec<String>>();
719 CallingConventions => {
720 let mut calling_conventions = rustc_target::spec::abi::all_names();
721 calling_conventions.sort_unstable();
722 println!("{}", calling_conventions.join("\n"));
728 | StackProtectorStrategies
729 | TargetFeatures => {
730 codegen_backend.print(*req, sess);
732 // Any output here interferes with Cargo's parsing of other printed output
733 NativeStaticLibs => {}
736 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
738 for split in &[Off, Packed, Unpacked] {
739 let stable = sess.target.options.supported_split_debuginfo.contains(split);
740 let unstable_ok = sess.unstable_options();
741 if stable || unstable_ok {
742 println!("{}", split);
751 /// Prints version information
753 /// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
754 pub macro version($binary: literal, $matches: expr) {
755 fn unw(x: Option<&str>) -> &str {
756 x.unwrap_or("unknown")
758 $crate::version_at_macro_invocation(
761 unw(option_env!("CFG_VERSION")),
762 unw(option_env!("CFG_VER_HASH")),
763 unw(option_env!("CFG_VER_DATE")),
764 unw(option_env!("CFG_RELEASE")),
768 #[doc(hidden)] // use the macro instead
769 pub fn version_at_macro_invocation(
771 matches: &getopts::Matches,
777 let verbose = matches.opt_present("verbose");
779 println!("{} {}", binary, version);
782 println!("binary: {}", binary);
783 println!("commit-hash: {}", commit_hash);
784 println!("commit-date: {}", commit_date);
785 println!("host: {}", config::host_triple());
786 println!("release: {}", release);
788 let debug_flags = matches.opt_strs("Z");
789 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
790 get_codegen_backend(&None, backend_name).print_version();
794 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
795 let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
796 let mut options = getopts::Options::new();
797 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
798 (option.apply)(&mut options);
800 let message = "Usage: rustc [OPTIONS] INPUT";
801 let nightly_help = if nightly_build {
802 "\n -Z help Print unstable compiler options"
806 let verbose_help = if verbose {
809 "\n --help -v Print the full set of options rustc accepts"
811 let at_path = if verbose {
812 " @path Read newline separated options from `path`\n"
817 "{options}{at_path}\nAdditional help:
818 -C help Print codegen options
820 Print 'lint' options and default settings{nightly}{verbose}\n",
821 options = options.usage(message),
823 nightly = nightly_help,
824 verbose = verbose_help
828 fn print_wall_help() {
831 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
832 default. Use `rustc -W help` to see all available lints. It's more common to put
833 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
834 the command line flag directly.
839 /// Write to stdout lint command options, together with a list of all available lints
840 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
843 Available lint options:
844 -W <foo> Warn about <foo>
848 -F <foo> Forbid <foo> \
849 (deny <foo> and all attempts to override)
854 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
855 // The sort doesn't case-fold but it's doubtful we care.
856 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
861 lints: Vec<(&'static str, Vec<LintId>, bool)>,
862 ) -> Vec<(&'static str, Vec<LintId>)> {
863 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
864 lints.sort_by_key(|l| l.0);
868 let (plugin, builtin): (Vec<_>, _) =
869 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
870 let plugin = sort_lints(sess, plugin);
871 let builtin = sort_lints(sess, builtin);
873 let (plugin_groups, builtin_groups): (Vec<_>, _) =
874 lint_store.get_lint_groups().partition(|&(.., p)| p);
875 let plugin_groups = sort_lint_groups(plugin_groups);
876 let builtin_groups = sort_lint_groups(builtin_groups);
879 plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
880 let padded = |x: &str| {
881 let mut s = " ".repeat(max_name_len - x.chars().count());
886 println!("Lint checks provided by rustc:\n");
888 let print_lints = |lints: Vec<&Lint>| {
889 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
890 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
892 let name = lint.name_lower().replace('_', "-");
896 lint.default_level(sess.edition()).as_str(),
903 print_lints(builtin);
905 let max_name_len = max(
909 .chain(&builtin_groups)
910 .map(|&(s, _)| s.chars().count())
915 let padded = |x: &str| {
916 let mut s = " ".repeat(max_name_len - x.chars().count());
921 println!("Lint groups provided by rustc:\n");
923 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
924 println!(" {} sub-lints", padded("name"));
925 println!(" {} ---------", padded("----"));
928 println!(" {} all lints that are set to issue warnings", padded("warnings"));
931 for (name, to) in lints {
932 let name = name.to_lowercase().replace('_', "-");
935 .map(|x| x.to_string().replace('_', "-"))
936 .collect::<Vec<String>>()
938 println!(" {} {}", padded(&name), desc);
943 print_lint_groups(builtin_groups, true);
945 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
946 (false, 0, _) | (false, _, 0) => {
947 println!("Lint tools like Clippy can provide additional lints and lint groups.");
949 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
950 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
953 println!("Lint checks provided by plugins loaded by this crate:\n");
957 println!("Lint groups provided by plugins loaded by this crate:\n");
958 print_lint_groups(plugin_groups, false);
964 fn describe_debug_flags() {
965 println!("\nAvailable options:\n");
966 print_flag_list("-Z", config::Z_OPTIONS);
969 fn describe_codegen_flags() {
970 println!("\nAvailable codegen options:\n");
971 print_flag_list("-C", config::CG_OPTIONS);
974 pub fn print_flag_list<T>(
976 flag_list: &[(&'static str, T, &'static str, &'static str)],
978 let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
980 for &(name, _, _, desc) in flag_list {
982 " {} {:>width$}=val -- {}",
984 name.replace('_', "-"),
991 /// Process command line options. Emits messages as appropriate. If compilation
992 /// should continue, returns a getopts::Matches object parsed from args,
993 /// otherwise returns `None`.
995 /// The compiler's handling of options is a little complicated as it ties into
996 /// our stability story. The current intention of each compiler option is to
997 /// have one of two modes:
999 /// 1. An option is stable and can be used everywhere.
1000 /// 2. An option is unstable, and can only be used on nightly.
1002 /// Like unstable library and language features, however, unstable options have
1003 /// always required a form of "opt in" to indicate that you're using them. This
1004 /// provides the easy ability to scan a code base to check to see if anything
1005 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1007 /// All options behind `-Z` are considered unstable by default. Other top-level
1008 /// options can also be considered unstable, and they were unlocked through the
1009 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1010 /// instability in both cases, though.
1012 /// So with all that in mind, the comments below have some more detail about the
1013 /// contortions done here to get things to work out correctly.
1014 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1015 // Throw away the first argument, the name of the binary
1016 let args = &args[1..];
1018 if args.is_empty() {
1019 // user did not write `-v` nor `-Z unstable-options`, so do not
1020 // include that extra information.
1022 rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
1023 usage(false, false, nightly_build);
1027 // Parse with *all* options defined in the compiler, we don't worry about
1028 // option stability here we just want to parse as much as possible.
1029 let mut options = getopts::Options::new();
1030 for option in config::rustc_optgroups() {
1031 (option.apply)(&mut options);
1033 let matches = options.parse(args).unwrap_or_else(|e| {
1035 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1037 .map(|&(name, ..)| ('C', name))
1038 .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1039 .find(|&(_, name)| *opt == name.replace('_', "-"))
1040 .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
1043 early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1046 // For all options we just parsed, we check a few aspects:
1048 // * If the option is stable, we're all good
1049 // * If the option wasn't passed, we're all good
1050 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1051 // ourselves), then we require the `-Z unstable-options` flag to unlock
1052 // this option that was passed.
1053 // * If we're a nightly compiler, then unstable options are now unlocked, so
1054 // we're good to go.
1055 // * Otherwise, if we're an unstable option then we generate an error
1056 // (unstable option being used on stable)
1057 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1059 if matches.opt_present("h") || matches.opt_present("help") {
1060 // Only show unstable options in --help if we accept unstable options.
1061 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1062 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1063 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1067 // Handle the special case of -Wall.
1068 let wall = matches.opt_strs("W");
1069 if wall.iter().any(|x| *x == "all") {
1071 rustc_errors::FatalError.raise();
1074 // Don't handle -W help here, because we might first load plugins.
1075 let debug_flags = matches.opt_strs("Z");
1076 if debug_flags.iter().any(|x| *x == "help") {
1077 describe_debug_flags();
1081 let cg_flags = matches.opt_strs("C");
1083 if cg_flags.iter().any(|x| *x == "help") {
1084 describe_codegen_flags();
1088 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1090 ErrorOutputType::default(),
1091 "the --no-stack-check flag is deprecated and does nothing",
1095 if cg_flags.iter().any(|x| *x == "passes=list") {
1096 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1097 get_codegen_backend(&None, backend_name).print_passes();
1101 if matches.opt_present("version") {
1102 version!("rustc", &matches);
1109 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::AttrVec> {
1111 Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1112 Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1120 /// Gets a list of extra command-line flags provided by the user, as strings.
1122 /// This function is used during ICEs to show more information useful for
1123 /// debugging, since some ICEs only happens with non-default compiler flags
1124 /// (and the users don't always report them).
1125 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1126 let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
1128 let mut result = Vec::new();
1129 let mut excluded_cargo_defaults = false;
1130 while let Some(arg) = args.next() {
1131 if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
1132 let content = if arg.len() == a.len() {
1133 // A space-separated option, like `-C incremental=foo` or `--crate-type rlib`
1135 Some(arg) => arg.to_string(),
1138 } else if arg.get(a.len()..a.len() + 1) == Some("=") {
1139 // An equals option, like `--crate-type=rlib`
1140 arg[a.len() + 1..].to_string()
1142 // A non-space option, like `-Cincremental=foo`
1143 arg[a.len()..].to_string()
1145 let option = content.split_once('=').map(|s| s.0).unwrap_or(&content);
1146 if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| option == *exc) {
1147 excluded_cargo_defaults = true;
1149 result.push(a.to_string());
1150 match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) {
1151 Some(s) => result.push(format!("{}=[REDACTED]", s)),
1152 None => result.push(content),
1158 if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1161 /// Runs a closure and catches unwinds triggered by fatal errors.
1163 /// The compiler currently unwinds with a special sentinel value to abort
1164 /// compilation on fatal errors. This function catches that sentinel and turns
1165 /// the panic into a `Result` instead.
1166 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed> {
1167 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1168 if value.is::<rustc_errors::FatalErrorMarker>() {
1169 ErrorGuaranteed::unchecked_claim_error_was_emitted()
1171 panic::resume_unwind(value);
1176 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1177 /// that also computes the exit code.
1178 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1179 let result = catch_fatal_errors(f).and_then(|result| result);
1181 Ok(()) => EXIT_SUCCESS,
1182 Err(_) => EXIT_FAILURE,
1186 static DEFAULT_HOOK: LazyLock<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1188 let hook = panic::take_hook();
1189 panic::set_hook(Box::new(|info| {
1190 // If the error was caused by a broken pipe then this is not a bug.
1191 // Write the error and return immediately. See #98700.
1193 if let Some(msg) = info.payload().downcast_ref::<String>() {
1194 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1196 early_error_no_abort(ErrorOutputType::default(), &msg);
1201 // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1202 (*DEFAULT_HOOK)(info);
1204 // Separate the output with an empty line
1207 // Print the ICE message
1208 report_ice(info, BUG_REPORT_URL);
1213 /// Prints the ICE message, including query stack, but without backtrace.
1215 /// The message will point the user at `bug_report_url` to report the ICE.
1217 /// When `install_ice_hook` is called, this function will be called as the panic
1219 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1220 let fallback_bundle =
1221 rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1222 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1223 rustc_errors::ColorConfig::Auto,
1233 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1235 // a .span_bug or .bug call has already printed what
1236 // it wants to print.
1237 if !info.payload().is::<rustc_errors::ExplicitBug>() {
1238 let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1239 handler.emit_diagnostic(&mut d);
1242 let mut xs: Vec<Cow<'static, str>> = vec![
1243 "the compiler unexpectedly panicked. this is a bug.".into(),
1244 format!("we would appreciate a bug report: {}", bug_report_url).into(),
1246 "rustc {} running on {}",
1247 util::version_str!().unwrap_or("unknown_version"),
1248 config::host_triple()
1253 if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1254 xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1256 if excluded_cargo_defaults {
1257 xs.push("some of the compiler flags provided by cargo are hidden".into());
1262 handler.note_without_error(note.as_ref());
1265 // If backtraces are enabled, also print the query stack
1266 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1268 let num_frames = if backtrace { None } else { Some(2) };
1270 interface::try_print_query_stack(&handler, num_frames);
1274 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1275 // Trigger a debugger if we crashed during bootstrap
1276 winapi::um::debugapi::DebugBreak();
1281 /// Installs a panic hook that will print the ICE message on unexpected panics.
1283 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1284 pub fn install_ice_hook() {
1285 // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1286 // full backtraces. When a compiler ICE happens, we want to gather
1287 // as much information as possible to present in the issue opened
1288 // by the user. Compiler developers and other rustc users can
1289 // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1290 // (e.g. `RUST_BACKTRACE=1`)
1291 if std::env::var("RUST_BACKTRACE").is_err() {
1292 std::env::set_var("RUST_BACKTRACE", "full");
1294 LazyLock::force(&DEFAULT_HOOK);
1297 /// This allows tools to enable rust logging without having to magically match rustc's
1298 /// tracing crate version.
1299 pub fn init_rustc_env_logger() {
1300 if let Err(error) = rustc_log::init_rustc_env_logger() {
1301 early_error(ErrorOutputType::default(), &error.to_string());
1305 /// This allows tools to enable rust logging without having to magically match rustc's
1306 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1307 /// other than `RUSTC_LOG`.
1308 pub fn init_env_logger(env: &str) {
1309 if let Err(error) = rustc_log::init_env_logger(env) {
1310 early_error(ErrorOutputType::default(), &error.to_string());
1314 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1315 mod signal_handler {
1317 fn backtrace_symbols_fd(
1318 buffer: *const *mut libc::c_void,
1324 extern "C" fn print_stack_trace(_: libc::c_int) {
1325 const MAX_FRAMES: usize = 256;
1326 static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1327 [std::ptr::null_mut(); MAX_FRAMES];
1329 let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1333 backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1337 /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1338 /// process, print a stack trace and then exit.
1339 pub(super) fn install() {
1341 const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1342 let mut alt_stack: libc::stack_t = std::mem::zeroed();
1344 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1345 as *mut libc::c_void;
1346 alt_stack.ss_size = ALT_STACK_SIZE;
1347 libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1349 let mut sa: libc::sigaction = std::mem::zeroed();
1350 sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1351 sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1352 libc::sigemptyset(&mut sa.sa_mask);
1353 libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1358 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1359 mod signal_handler {
1360 pub(super) fn install() {}
1363 pub fn main() -> ! {
1364 let start_time = Instant::now();
1365 let start_rss = get_resident_set_size();
1366 init_rustc_env_logger();
1367 signal_handler::install();
1368 let mut callbacks = TimePassesCallbacks::default();
1370 let exit_code = catch_with_exit_code(|| {
1371 let args = env::args_os()
1374 arg.into_string().unwrap_or_else(|arg| {
1376 ErrorOutputType::default(),
1377 &format!("argument {} is not valid Unicode: {:?}", i, arg),
1381 .collect::<Vec<_>>();
1382 RunCompiler::new(&args, &mut callbacks).run()
1385 if callbacks.time_passes {
1386 let end_rss = get_resident_set_size();
1387 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1390 process::exit(exit_code)