rustc_driver_impl/
lib.rs

1//! The Rust compiler.
2//!
3//! # Note
4//!
5//! This API is completely unstable and subject to change.
6
7// tidy-alphabetical-start
8#![allow(internal_features)]
9#![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
10#![cfg_attr(bootstrap, feature(let_chains))]
11#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
12#![doc(rust_logo)]
13#![feature(decl_macro)]
14#![feature(panic_backtrace_config)]
15#![feature(panic_update_hook)]
16#![feature(result_flattening)]
17#![feature(rustdoc_internals)]
18#![feature(try_blocks)]
19// tidy-alphabetical-end
20
21use std::cmp::max;
22use std::collections::{BTreeMap, BTreeSet};
23use std::ffi::OsString;
24use std::fmt::Write as _;
25use std::fs::{self, File};
26use std::io::{self, IsTerminal, Read, Write};
27use std::panic::{self, PanicHookInfo, catch_unwind};
28use std::path::{Path, PathBuf};
29use std::process::{self, Command, Stdio};
30use std::sync::OnceLock;
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::time::Instant;
33use std::{env, str};
34
35use rustc_ast as ast;
36use rustc_codegen_ssa::traits::CodegenBackend;
37use rustc_codegen_ssa::{CodegenErrors, CodegenResults};
38use rustc_data_structures::profiling::{
39    TimePassesFormat, get_resident_set_size, print_time_passes_entry,
40};
41use rustc_errors::emitter::stderr_destination;
42use rustc_errors::registry::Registry;
43use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
44use rustc_feature::find_gated_cfg;
45// This avoids a false positive with `-Wunused_crate_dependencies`.
46// `rust_index` isn't used in this crate's code, but it must be named in the
47// `Cargo.toml` for the `rustc_randomized_layouts` feature.
48use rustc_index as _;
49use rustc_interface::util::{self, get_codegen_backend};
50use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
51use rustc_lint::unerased_lint_store;
52use rustc_metadata::creader::MetadataLoader;
53use rustc_metadata::locator;
54use rustc_middle::ty::TyCtxt;
55use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
56use rustc_session::config::{
57    CG_OPTIONS, CrateType, ErrorOutputType, Input, OptionDesc, OutFileName, OutputType,
58    UnstableOptions, Z_OPTIONS, nightly_options, parse_target_triple,
59};
60use rustc_session::getopts::{self, Matches};
61use rustc_session::lint::{Lint, LintId};
62use rustc_session::output::{CRATE_TYPES, collect_crate_types, invalid_output_for_target};
63use rustc_session::{EarlyDiagCtxt, Session, config, filesearch};
64use rustc_span::FileName;
65use rustc_span::def_id::LOCAL_CRATE;
66use rustc_target::json::ToJson;
67use rustc_target::spec::{Target, TargetTuple};
68use tracing::trace;
69
70#[allow(unused_macros)]
71macro do_not_use_print($($t:tt)*) {
72    std::compile_error!(
73        "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
74    )
75}
76
77#[allow(unused_macros)]
78macro do_not_use_safe_print($($t:tt)*) {
79    std::compile_error!("Don't use `safe_print` or `safe_println` here, use `println_info` instead")
80}
81
82// This import blocks the use of panicking `print` and `println` in all the code
83// below. Please use `safe_print` and `safe_println` to avoid ICE when
84// encountering an I/O error during print.
85#[allow(unused_imports)]
86use {do_not_use_print as print, do_not_use_print as println};
87
88pub mod args;
89pub mod pretty;
90#[macro_use]
91mod print;
92mod session_diagnostics;
93
94// Keep the OS parts of this `cfg` in sync with the `cfg` on the `libc`
95// dependency in `compiler/rustc_driver/Cargo.toml`, to keep
96// `-Wunused-crated-dependencies` satisfied.
97#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
98mod signal_handler;
99
100#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
101mod signal_handler {
102    /// On platforms which don't support our signal handler's requirements,
103    /// simply use the default signal handler provided by std.
104    pub(super) fn install() {}
105}
106
107use crate::session_diagnostics::{
108    CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
109    RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
110};
111
112rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
113
114pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
115    // tidy-alphabetical-start
116    crate::DEFAULT_LOCALE_RESOURCE,
117    rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
118    rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
119    rustc_attr_parsing::DEFAULT_LOCALE_RESOURCE,
120    rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
121    rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
122    rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
123    rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
124    rustc_errors::DEFAULT_LOCALE_RESOURCE,
125    rustc_expand::DEFAULT_LOCALE_RESOURCE,
126    rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
127    rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
128    rustc_incremental::DEFAULT_LOCALE_RESOURCE,
129    rustc_infer::DEFAULT_LOCALE_RESOURCE,
130    rustc_interface::DEFAULT_LOCALE_RESOURCE,
131    rustc_lint::DEFAULT_LOCALE_RESOURCE,
132    rustc_metadata::DEFAULT_LOCALE_RESOURCE,
133    rustc_middle::DEFAULT_LOCALE_RESOURCE,
134    rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
135    rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
136    rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
137    rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
138    rustc_parse::DEFAULT_LOCALE_RESOURCE,
139    rustc_passes::DEFAULT_LOCALE_RESOURCE,
140    rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE,
141    rustc_privacy::DEFAULT_LOCALE_RESOURCE,
142    rustc_query_system::DEFAULT_LOCALE_RESOURCE,
143    rustc_resolve::DEFAULT_LOCALE_RESOURCE,
144    rustc_session::DEFAULT_LOCALE_RESOURCE,
145    rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
146    rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
147    // tidy-alphabetical-end
148];
149
150/// Exit status code used for successful compilation and help output.
151pub const EXIT_SUCCESS: i32 = 0;
152
153/// Exit status code used for compilation failures and invalid flags.
154pub const EXIT_FAILURE: i32 = 1;
155
156pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
157    ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
158
159pub trait Callbacks {
160    /// Called before creating the compiler instance
161    fn config(&mut self, _config: &mut interface::Config) {}
162    /// Called after parsing the crate root. Submodules are not yet parsed when
163    /// this callback is called. Return value instructs the compiler whether to
164    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
165    fn after_crate_root_parsing(
166        &mut self,
167        _compiler: &interface::Compiler,
168        _krate: &mut ast::Crate,
169    ) -> Compilation {
170        Compilation::Continue
171    }
172    /// Called after expansion. Return value instructs the compiler whether to
173    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
174    fn after_expansion<'tcx>(
175        &mut self,
176        _compiler: &interface::Compiler,
177        _tcx: TyCtxt<'tcx>,
178    ) -> Compilation {
179        Compilation::Continue
180    }
181    /// Called after analysis. Return value instructs the compiler whether to
182    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
183    fn after_analysis<'tcx>(
184        &mut self,
185        _compiler: &interface::Compiler,
186        _tcx: TyCtxt<'tcx>,
187    ) -> Compilation {
188        Compilation::Continue
189    }
190}
191
192#[derive(Default)]
193pub struct TimePassesCallbacks {
194    time_passes: Option<TimePassesFormat>,
195}
196
197impl Callbacks for TimePassesCallbacks {
198    // JUSTIFICATION: the session doesn't exist at this point.
199    #[allow(rustc::bad_opt_access)]
200    fn config(&mut self, config: &mut interface::Config) {
201        // If a --print=... option has been given, we don't print the "total"
202        // time because it will mess up the --print output. See #64339.
203        //
204        self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
205            .then(|| config.opts.unstable_opts.time_passes_format);
206        config.opts.trimmed_def_paths = true;
207    }
208}
209
210pub fn diagnostics_registry() -> Registry {
211    Registry::new(rustc_errors::codes::DIAGNOSTICS)
212}
213
214/// This is the primary entry point for rustc.
215pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
216    let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
217
218    // Throw away the first argument, the name of the binary.
219    // In case of at_args being empty, as might be the case by
220    // passing empty argument array to execve under some platforms,
221    // just use an empty slice.
222    //
223    // This situation was possible before due to arg_expand_all being
224    // called before removing the argument, enabling a crash by calling
225    // the compiler with @empty_file as argv[0] and no more arguments.
226    let at_args = at_args.get(1..).unwrap_or_default();
227
228    let args = args::arg_expand_all(&default_early_dcx, at_args);
229
230    let Some(matches) = handle_options(&default_early_dcx, &args) else {
231        return;
232    };
233
234    let sopts = config::build_session_options(&mut default_early_dcx, &matches);
235    // fully initialize ice path static once unstable options are available as context
236    let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
237
238    if let Some(ref code) = matches.opt_str("explain") {
239        handle_explain(&default_early_dcx, diagnostics_registry(), code, sopts.color);
240        return;
241    }
242
243    let input = make_input(&default_early_dcx, &matches.free);
244    let has_input = input.is_some();
245    let (odir, ofile) = make_output(&matches);
246
247    drop(default_early_dcx);
248
249    let mut config = interface::Config {
250        opts: sopts,
251        crate_cfg: matches.opt_strs("cfg"),
252        crate_check_cfg: matches.opt_strs("check-cfg"),
253        input: input.unwrap_or(Input::File(PathBuf::new())),
254        output_file: ofile,
255        output_dir: odir,
256        ice_file,
257        file_loader: None,
258        locale_resources: DEFAULT_LOCALE_RESOURCES.to_vec(),
259        lint_caps: Default::default(),
260        psess_created: None,
261        hash_untracked_state: None,
262        register_lints: None,
263        override_queries: None,
264        extra_symbols: Vec::new(),
265        make_codegen_backend: None,
266        registry: diagnostics_registry(),
267        using_internal_features: &USING_INTERNAL_FEATURES,
268        expanded_args: args,
269    };
270
271    callbacks.config(&mut config);
272
273    let registered_lints = config.register_lints.is_some();
274
275    interface::run_compiler(config, |compiler| {
276        let sess = &compiler.sess;
277        let codegen_backend = &*compiler.codegen_backend;
278
279        // This is used for early exits unrelated to errors. E.g. when just
280        // printing some information without compiling, or exiting immediately
281        // after parsing, etc.
282        let early_exit = || {
283            sess.dcx().abort_if_errors();
284        };
285
286        // This implements `-Whelp`. It should be handled very early, like
287        // `--help`/`-Zhelp`/`-Chelp`. This is the earliest it can run, because
288        // it must happen after lints are registered, during session creation.
289        if sess.opts.describe_lints {
290            describe_lints(sess, registered_lints);
291            return early_exit();
292        }
293
294        if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
295            return early_exit();
296        }
297
298        if !has_input {
299            #[allow(rustc::diagnostic_outside_of_impl)]
300            sess.dcx().fatal("no input filename given"); // this is fatal
301        }
302
303        if !sess.opts.unstable_opts.ls.is_empty() {
304            list_metadata(sess, &*codegen_backend.metadata_loader());
305            return early_exit();
306        }
307
308        if sess.opts.unstable_opts.link_only {
309            process_rlink(sess, compiler);
310            return early_exit();
311        }
312
313        // Parse the crate root source code (doesn't parse submodules yet)
314        // Everything else is parsed during macro expansion.
315        let mut krate = passes::parse(sess);
316
317        // If pretty printing is requested: Figure out the representation, print it and exit
318        if let Some(pp_mode) = sess.opts.pretty {
319            if pp_mode.needs_ast_map() {
320                create_and_enter_global_ctxt(compiler, krate, |tcx| {
321                    tcx.ensure_ok().early_lint_checks(());
322                    pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
323                    passes::write_dep_info(tcx);
324                });
325            } else {
326                pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
327            }
328            trace!("finished pretty-printing");
329            return early_exit();
330        }
331
332        if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
333            return early_exit();
334        }
335
336        if sess.opts.unstable_opts.parse_crate_root_only {
337            return early_exit();
338        }
339
340        let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
341            let early_exit = || {
342                sess.dcx().abort_if_errors();
343                None
344            };
345
346            // Make sure name resolution and macro expansion is run.
347            let _ = tcx.resolver_for_lowering();
348
349            if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
350                return early_exit();
351            }
352
353            passes::write_dep_info(tcx);
354
355            passes::write_interface(tcx);
356
357            if sess.opts.output_types.contains_key(&OutputType::DepInfo)
358                && sess.opts.output_types.len() == 1
359            {
360                return early_exit();
361            }
362
363            if sess.opts.unstable_opts.no_analysis {
364                return early_exit();
365            }
366
367            tcx.ensure_ok().analysis(());
368
369            if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
370                dump_feature_usage_metrics(tcx, metrics_dir);
371            }
372
373            if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
374                return early_exit();
375            }
376
377            if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
378                if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
379                    tcx.dcx().emit_fatal(CantEmitMIR { error });
380                }
381            }
382
383            Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
384        });
385
386        // Linking is done outside the `compiler.enter()` so that the
387        // `GlobalCtxt` within `Queries` can be freed as early as possible.
388        if let Some(linker) = linker {
389            linker.link(sess, codegen_backend);
390        }
391    })
392}
393
394fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
395    let hash = tcxt.crate_hash(LOCAL_CRATE);
396    let crate_name = tcxt.crate_name(LOCAL_CRATE);
397    let metrics_file_name = format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
398    let metrics_path = metrics_dir.join(metrics_file_name);
399    if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
400        // FIXME(yaahc): once metrics can be enabled by default we will want "failure to emit
401        // default metrics" to only produce a warning when metrics are enabled by default and emit
402        // an error only when the user manually enables metrics
403        tcxt.dcx().emit_err(UnstableFeatureUsage { error });
404    }
405}
406
407/// Extract output directory and file from matches.
408fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
409    let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
410    let ofile = matches.opt_str("o").map(|o| match o.as_str() {
411        "-" => OutFileName::Stdout,
412        path => OutFileName::Real(PathBuf::from(path)),
413    });
414    (odir, ofile)
415}
416
417/// Extract input (string or file and optional path) from matches.
418/// This handles reading from stdin if `-` is provided.
419fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
420    match free_matches {
421        [] => None, // no input: we will exit early,
422        [ifile] if ifile == "-" => {
423            // read from stdin as `Input::Str`
424            let mut input = String::new();
425            if io::stdin().read_to_string(&mut input).is_err() {
426                // Immediately stop compilation if there was an issue reading
427                // the input (for example if the input stream is not UTF-8).
428                early_dcx
429                    .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
430            }
431
432            let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
433                Ok(path) => {
434                    let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
435                        "when UNSTABLE_RUSTDOC_TEST_PATH is set \
436                                    UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
437                    );
438                    let line = isize::from_str_radix(&line, 10)
439                        .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
440                    FileName::doc_test_source_code(PathBuf::from(path), line)
441                }
442                Err(_) => FileName::anon_source_code(&input),
443            };
444
445            Some(Input::Str { name, input })
446        }
447        [ifile] => Some(Input::File(PathBuf::from(ifile))),
448        [ifile1, ifile2, ..] => early_dcx.early_fatal(format!(
449            "multiple input filenames provided (first two filenames are `{}` and `{}`)",
450            ifile1, ifile2
451        )),
452    }
453}
454
455/// Whether to stop or continue compilation.
456#[derive(Copy, Clone, Debug, Eq, PartialEq)]
457pub enum Compilation {
458    Stop,
459    Continue,
460}
461
462fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
463    // Allow "E0123" or "0123" form.
464    let upper_cased_code = code.to_ascii_uppercase();
465    if let Ok(code) = upper_cased_code.strip_prefix('E').unwrap_or(&upper_cased_code).parse::<u32>()
466        && code <= ErrCode::MAX_AS_U32
467        && let Ok(description) = registry.try_find_description(ErrCode::from_u32(code))
468    {
469        let mut is_in_code_block = false;
470        let mut text = String::new();
471        // Slice off the leading newline and print.
472        for line in description.lines() {
473            let indent_level =
474                line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
475            let dedented_line = &line[indent_level..];
476            if dedented_line.starts_with("```") {
477                is_in_code_block = !is_in_code_block;
478                text.push_str(&line[..(indent_level + 3)]);
479            } else if is_in_code_block && dedented_line.starts_with("# ") {
480                continue;
481            } else {
482                text.push_str(line);
483            }
484            text.push('\n');
485        }
486        if io::stdout().is_terminal() {
487            show_md_content_with_pager(&text, color);
488        } else {
489            safe_print!("{text}");
490        }
491    } else {
492        early_dcx.early_fatal(format!("{code} is not a valid error code"));
493    }
494}
495
496/// If `color` is `always` or `auto`, try to print pretty (formatted & colorized) markdown. If
497/// that fails or `color` is `never`, print the raw markdown.
498///
499/// Uses a pager if possible, falls back to stdout.
500fn show_md_content_with_pager(content: &str, color: ColorConfig) {
501    let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
502        if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
503    });
504
505    let mut cmd = Command::new(&pager_name);
506    if pager_name == "less" {
507        cmd.arg("-R"); // allows color escape sequences
508    }
509
510    let pretty_on_pager = match color {
511        ColorConfig::Auto => {
512            // Add other pagers that accept color escape sequences here.
513            ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
514        }
515        ColorConfig::Always => true,
516        ColorConfig::Never => false,
517    };
518
519    // Try to prettify the raw markdown text. The result can be used by the pager or on stdout.
520    let pretty_data = {
521        let mdstream = markdown::MdStream::parse_str(content);
522        let bufwtr = markdown::create_stdout_bufwtr();
523        let mut mdbuf = bufwtr.buffer();
524        if mdstream.write_termcolor_buf(&mut mdbuf).is_ok() { Some((bufwtr, mdbuf)) } else { None }
525    };
526
527    // Try to print via the pager, pretty output if possible.
528    let pager_res: Option<()> = try {
529        let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
530
531        let pager_stdin = pager.stdin.as_mut()?;
532        if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
533            pager_stdin.write_all(mdbuf.as_slice()).ok()?;
534        } else {
535            pager_stdin.write_all(content.as_bytes()).ok()?;
536        };
537
538        pager.wait().ok()?;
539    };
540    if pager_res.is_some() {
541        return;
542    }
543
544    // The pager failed. Try to print pretty output to stdout.
545    if let Some((bufwtr, mdbuf)) = &pretty_data
546        && bufwtr.print(&mdbuf).is_ok()
547    {
548        return;
549    }
550
551    // Everything failed. Print the raw markdown text.
552    safe_print!("{content}");
553}
554
555fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
556    assert!(sess.opts.unstable_opts.link_only);
557    let dcx = sess.dcx();
558    if let Input::File(file) = &sess.io.input {
559        let rlink_data = fs::read(file).unwrap_or_else(|err| {
560            dcx.emit_fatal(RlinkUnableToRead { err });
561        });
562        let (codegen_results, outputs) = match CodegenResults::deserialize_rlink(sess, rlink_data) {
563            Ok((codegen, outputs)) => (codegen, outputs),
564            Err(err) => {
565                match err {
566                    CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
567                    CodegenErrors::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
568                    CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => dcx
569                        .emit_fatal(RLinkEncodingVersionMismatch { version_array, rlink_version }),
570                    CodegenErrors::RustcVersionMismatch { rustc_version } => {
571                        dcx.emit_fatal(RLinkRustcVersionMismatch {
572                            rustc_version,
573                            current_version: sess.cfg_version,
574                        })
575                    }
576                    CodegenErrors::CorruptFile => {
577                        dcx.emit_fatal(RlinkCorruptFile { file });
578                    }
579                };
580            }
581        };
582        compiler.codegen_backend.link(sess, codegen_results, &outputs);
583    } else {
584        dcx.emit_fatal(RlinkNotAFile {});
585    }
586}
587
588fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
589    match sess.io.input {
590        Input::File(ref ifile) => {
591            let path = &(*ifile);
592            let mut v = Vec::new();
593            locator::list_file_metadata(
594                &sess.target,
595                path,
596                metadata_loader,
597                &mut v,
598                &sess.opts.unstable_opts.ls,
599                sess.cfg_version,
600            )
601            .unwrap();
602            safe_println!("{}", String::from_utf8(v).unwrap());
603        }
604        Input::Str { .. } => {
605            #[allow(rustc::diagnostic_outside_of_impl)]
606            sess.dcx().fatal("cannot list metadata for stdin");
607        }
608    }
609}
610
611fn print_crate_info(
612    codegen_backend: &dyn CodegenBackend,
613    sess: &Session,
614    parse_attrs: bool,
615) -> Compilation {
616    use rustc_session::config::PrintKind::*;
617    // This import prevents the following code from using the printing macros
618    // used by the rest of the module. Within this function, we only write to
619    // the output specified by `sess.io.output_file`.
620    #[allow(unused_imports)]
621    use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
622
623    // NativeStaticLibs and LinkArgs are special - printed during linking
624    // (empty iterator returns true)
625    if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
626        return Compilation::Continue;
627    }
628
629    let attrs = if parse_attrs {
630        let result = parse_crate_attrs(sess);
631        match result {
632            Ok(attrs) => Some(attrs),
633            Err(parse_error) => {
634                parse_error.emit();
635                return Compilation::Stop;
636            }
637        }
638    } else {
639        None
640    };
641
642    for req in &sess.opts.prints {
643        let mut crate_info = String::new();
644        macro println_info($($arg:tt)*) {
645            crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
646        }
647
648        match req.kind {
649            TargetList => {
650                let mut targets = rustc_target::spec::TARGETS.to_vec();
651                targets.sort_unstable();
652                println_info!("{}", targets.join("\n"));
653            }
654            HostTuple => println_info!("{}", rustc_session::config::host_tuple()),
655            Sysroot => println_info!("{}", sess.sysroot.display()),
656            TargetLibdir => println_info!("{}", sess.target_tlib_path.dir.display()),
657            TargetSpecJson => {
658                println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
659            }
660            AllTargetSpecsJson => {
661                let mut targets = BTreeMap::new();
662                for name in rustc_target::spec::TARGETS {
663                    let triple = TargetTuple::from_tuple(name);
664                    let target = Target::expect_builtin(&triple);
665                    targets.insert(name, target.to_json());
666                }
667                println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
668            }
669            FileNames => {
670                let Some(attrs) = attrs.as_ref() else {
671                    // no crate attributes, print out an error and exit
672                    return Compilation::Continue;
673                };
674                let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
675                let crate_name = passes::get_crate_name(sess, attrs);
676                let crate_types = collect_crate_types(sess, attrs);
677                for &style in &crate_types {
678                    let fname = rustc_session::output::filename_for_input(
679                        sess, style, crate_name, &t_outputs,
680                    );
681                    println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
682                }
683            }
684            CrateName => {
685                let Some(attrs) = attrs.as_ref() else {
686                    // no crate attributes, print out an error and exit
687                    return Compilation::Continue;
688                };
689                println_info!("{}", passes::get_crate_name(sess, attrs));
690            }
691            CrateRootLintLevels => {
692                let Some(attrs) = attrs.as_ref() else {
693                    // no crate attributes, print out an error and exit
694                    return Compilation::Continue;
695                };
696                let crate_name = passes::get_crate_name(sess, attrs);
697                let lint_store = crate::unerased_lint_store(sess);
698                let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
699                let features = rustc_expand::config::features(sess, attrs, crate_name);
700                let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
701                    sess,
702                    &features,
703                    true,
704                    lint_store,
705                    &registered_tools,
706                    attrs,
707                );
708                for lint in lint_store.get_lints() {
709                    if let Some(feature_symbol) = lint.feature_gate
710                        && !features.enabled(feature_symbol)
711                    {
712                        // lint is unstable and feature gate isn't active, don't print
713                        continue;
714                    }
715                    let level = lint_levels.lint_level(lint).level;
716                    println_info!("{}={}", lint.name_lower(), level.as_str());
717                }
718            }
719            Cfg => {
720                let mut cfgs = sess
721                    .psess
722                    .config
723                    .iter()
724                    .filter_map(|&(name, value)| {
725                        // On stable, exclude unstable flags.
726                        if !sess.is_nightly_build()
727                            && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
728                        {
729                            return None;
730                        }
731
732                        if let Some(value) = value {
733                            Some(format!("{name}=\"{value}\""))
734                        } else {
735                            Some(name.to_string())
736                        }
737                    })
738                    .collect::<Vec<String>>();
739
740                cfgs.sort();
741                for cfg in cfgs {
742                    println_info!("{cfg}");
743                }
744            }
745            CheckCfg => {
746                let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
747
748                // INSTABILITY: We are sorting the output below.
749                #[allow(rustc::potential_query_instability)]
750                for (name, expected_values) in &sess.psess.check_config.expecteds {
751                    use crate::config::ExpectedValues;
752                    match expected_values {
753                        ExpectedValues::Any => check_cfgs.push(format!("{name}=any()")),
754                        ExpectedValues::Some(values) => {
755                            if !values.is_empty() {
756                                check_cfgs.extend(values.iter().map(|value| {
757                                    if let Some(value) = value {
758                                        format!("{name}=\"{value}\"")
759                                    } else {
760                                        name.to_string()
761                                    }
762                                }))
763                            } else {
764                                check_cfgs.push(format!("{name}="))
765                            }
766                        }
767                    }
768                }
769
770                check_cfgs.sort_unstable();
771                if !sess.psess.check_config.exhaustive_names {
772                    if !sess.psess.check_config.exhaustive_values {
773                        println_info!("any()=any()");
774                    } else {
775                        println_info!("any()");
776                    }
777                }
778                for check_cfg in check_cfgs {
779                    println_info!("{check_cfg}");
780                }
781            }
782            CallingConventions => {
783                let calling_conventions = rustc_abi::all_names();
784                println_info!("{}", calling_conventions.join("\n"));
785            }
786            RelocationModels
787            | CodeModels
788            | TlsModels
789            | TargetCPUs
790            | StackProtectorStrategies
791            | TargetFeatures => {
792                codegen_backend.print(req, &mut crate_info, sess);
793            }
794            // Any output here interferes with Cargo's parsing of other printed output
795            NativeStaticLibs => {}
796            LinkArgs => {}
797            SplitDebuginfo => {
798                use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
799
800                for split in &[Off, Packed, Unpacked] {
801                    if sess.target.options.supported_split_debuginfo.contains(split) {
802                        println_info!("{split}");
803                    }
804                }
805            }
806            DeploymentTarget => {
807                if sess.target.is_like_darwin {
808                    println_info!(
809                        "{}={}",
810                        rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
811                        sess.apple_deployment_target().fmt_pretty(),
812                    )
813                } else {
814                    #[allow(rustc::diagnostic_outside_of_impl)]
815                    sess.dcx().fatal("only Apple targets currently support deployment version info")
816                }
817            }
818            SupportedCrateTypes => {
819                let supported_crate_types = CRATE_TYPES
820                    .iter()
821                    .filter(|(_, crate_type)| !invalid_output_for_target(&sess, *crate_type))
822                    .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
823                    .map(|(crate_type_sym, _)| *crate_type_sym)
824                    .collect::<BTreeSet<_>>();
825                for supported_crate_type in supported_crate_types {
826                    println_info!("{}", supported_crate_type.as_str());
827                }
828            }
829        }
830
831        req.out.overwrite(&crate_info, sess);
832    }
833    Compilation::Stop
834}
835
836/// Prints version information
837///
838/// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
839pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
840    fn unw(x: Option<&str>) -> &str {
841        x.unwrap_or("unknown")
842    }
843    $crate::version_at_macro_invocation(
844        $early_dcx,
845        $binary,
846        $matches,
847        unw(option_env!("CFG_VERSION")),
848        unw(option_env!("CFG_VER_HASH")),
849        unw(option_env!("CFG_VER_DATE")),
850        unw(option_env!("CFG_RELEASE")),
851    )
852}
853
854#[doc(hidden)] // use the macro instead
855pub fn version_at_macro_invocation(
856    early_dcx: &EarlyDiagCtxt,
857    binary: &str,
858    matches: &getopts::Matches,
859    version: &str,
860    commit_hash: &str,
861    commit_date: &str,
862    release: &str,
863) {
864    let verbose = matches.opt_present("verbose");
865
866    let mut version = version;
867    let mut release = release;
868    let tmp;
869    if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
870        tmp = force_version;
871        version = &tmp;
872        release = &tmp;
873    }
874
875    safe_println!("{binary} {version}");
876
877    if verbose {
878        safe_println!("binary: {binary}");
879        safe_println!("commit-hash: {commit_hash}");
880        safe_println!("commit-date: {commit_date}");
881        safe_println!("host: {}", config::host_tuple());
882        safe_println!("release: {release}");
883
884        get_backend_from_raw_matches(early_dcx, matches).print_version();
885    }
886}
887
888fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
889    let mut options = getopts::Options::new();
890    for option in config::rustc_optgroups()
891        .iter()
892        .filter(|x| verbose || !x.is_verbose_help_only)
893        .filter(|x| include_unstable_options || x.is_stable())
894    {
895        option.apply(&mut options);
896    }
897    let message = "Usage: rustc [OPTIONS] INPUT";
898    let nightly_help = if nightly_build {
899        "\n    -Z help             Print unstable compiler options"
900    } else {
901        ""
902    };
903    let verbose_help = if verbose {
904        ""
905    } else {
906        "\n    --help -v           Print the full set of options rustc accepts"
907    };
908    let at_path = if verbose {
909        "    @path               Read newline separated options from `path`\n"
910    } else {
911        ""
912    };
913    safe_println!(
914        "{options}{at_path}\nAdditional help:
915    -C help             Print codegen options
916    -W help             \
917              Print 'lint' options and default settings{nightly}{verbose}\n",
918        options = options.usage(message),
919        at_path = at_path,
920        nightly = nightly_help,
921        verbose = verbose_help
922    );
923}
924
925fn print_wall_help() {
926    safe_println!(
927        "
928The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
929default. Use `rustc -W help` to see all available lints. It's more common to put
930warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
931the command line flag directly.
932"
933    );
934}
935
936/// Write to stdout lint command options, together with a list of all available lints
937pub fn describe_lints(sess: &Session, registered_lints: bool) {
938    safe_println!(
939        "
940Available lint options:
941    -W <foo>           Warn about <foo>
942    -A <foo>           Allow <foo>
943    -D <foo>           Deny <foo>
944    -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
945
946"
947    );
948
949    fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
950        // The sort doesn't case-fold but it's doubtful we care.
951        lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
952        lints
953    }
954
955    fn sort_lint_groups(
956        lints: Vec<(&'static str, Vec<LintId>, bool)>,
957    ) -> Vec<(&'static str, Vec<LintId>)> {
958        let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
959        lints.sort_by_key(|l| l.0);
960        lints
961    }
962
963    let lint_store = unerased_lint_store(sess);
964    let (loaded, builtin): (Vec<_>, _) =
965        lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
966    let loaded = sort_lints(sess, loaded);
967    let builtin = sort_lints(sess, builtin);
968
969    let (loaded_groups, builtin_groups): (Vec<_>, _) =
970        lint_store.get_lint_groups().partition(|&(.., p)| p);
971    let loaded_groups = sort_lint_groups(loaded_groups);
972    let builtin_groups = sort_lint_groups(builtin_groups);
973
974    let max_name_len =
975        loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
976    let padded = |x: &str| {
977        let mut s = " ".repeat(max_name_len - x.chars().count());
978        s.push_str(x);
979        s
980    };
981
982    safe_println!("Lint checks provided by rustc:\n");
983
984    let print_lints = |lints: Vec<&Lint>| {
985        safe_println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
986        safe_println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
987        for lint in lints {
988            let name = lint.name_lower().replace('_', "-");
989            safe_println!(
990                "    {}  {:7.7}  {}",
991                padded(&name),
992                lint.default_level(sess.edition()).as_str(),
993                lint.desc
994            );
995        }
996        safe_println!("\n");
997    };
998
999    print_lints(builtin);
1000
1001    let max_name_len = max(
1002        "warnings".len(),
1003        loaded_groups
1004            .iter()
1005            .chain(&builtin_groups)
1006            .map(|&(s, _)| s.chars().count())
1007            .max()
1008            .unwrap_or(0),
1009    );
1010
1011    let padded = |x: &str| {
1012        let mut s = " ".repeat(max_name_len - x.chars().count());
1013        s.push_str(x);
1014        s
1015    };
1016
1017    safe_println!("Lint groups provided by rustc:\n");
1018
1019    let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1020        safe_println!("    {}  sub-lints", padded("name"));
1021        safe_println!("    {}  ---------", padded("----"));
1022
1023        if all_warnings {
1024            safe_println!("    {}  all lints that are set to issue warnings", padded("warnings"));
1025        }
1026
1027        for (name, to) in lints {
1028            let name = name.to_lowercase().replace('_', "-");
1029            let desc = to
1030                .into_iter()
1031                .map(|x| x.to_string().replace('_', "-"))
1032                .collect::<Vec<String>>()
1033                .join(", ");
1034            safe_println!("    {}  {}", padded(&name), desc);
1035        }
1036        safe_println!("\n");
1037    };
1038
1039    print_lint_groups(builtin_groups, true);
1040
1041    match (registered_lints, loaded.len(), loaded_groups.len()) {
1042        (false, 0, _) | (false, _, 0) => {
1043            safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1044        }
1045        (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1046        (true, 0, 0) => {
1047            safe_println!("This crate does not load any additional lints or lint groups.")
1048        }
1049        (true, l, g) => {
1050            if l > 0 {
1051                safe_println!("Lint checks loaded by this crate:\n");
1052                print_lints(loaded);
1053            }
1054            if g > 0 {
1055                safe_println!("Lint groups loaded by this crate:\n");
1056                print_lint_groups(loaded_groups, false);
1057            }
1058        }
1059    }
1060}
1061
1062/// Show help for flag categories shared between rustdoc and rustc.
1063///
1064/// Returns whether a help option was printed.
1065pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1066    // Handle the special case of -Wall.
1067    let wall = matches.opt_strs("W");
1068    if wall.iter().any(|x| *x == "all") {
1069        print_wall_help();
1070        return true;
1071    }
1072
1073    // Don't handle -W help here, because we might first load additional lints.
1074    let debug_flags = matches.opt_strs("Z");
1075    if debug_flags.iter().any(|x| *x == "help") {
1076        describe_debug_flags();
1077        return true;
1078    }
1079
1080    let cg_flags = matches.opt_strs("C");
1081    if cg_flags.iter().any(|x| *x == "help") {
1082        describe_codegen_flags();
1083        return true;
1084    }
1085
1086    if cg_flags.iter().any(|x| *x == "passes=list") {
1087        get_backend_from_raw_matches(early_dcx, matches).print_passes();
1088        return true;
1089    }
1090
1091    false
1092}
1093
1094/// Get the codegen backend based on the raw [`Matches`].
1095///
1096/// `rustc -vV` and `rustc -Cpasses=list` need to get the codegen backend before we have parsed all
1097/// arguments and created a [`Session`]. This function reads `-Zcodegen-backend`, `--target` and
1098/// `--sysroot` without validating any other arguments and loads the codegen backend based on these
1099/// arguments.
1100fn get_backend_from_raw_matches(
1101    early_dcx: &EarlyDiagCtxt,
1102    matches: &Matches,
1103) -> Box<dyn CodegenBackend> {
1104    let debug_flags = matches.opt_strs("Z");
1105    let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1106    let target = parse_target_triple(early_dcx, matches);
1107    let sysroot = filesearch::materialize_sysroot(matches.opt_str("sysroot").map(PathBuf::from));
1108    let target = config::build_target_config(early_dcx, &target, &sysroot);
1109
1110    get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1111}
1112
1113fn describe_debug_flags() {
1114    safe_println!("\nAvailable options:\n");
1115    print_flag_list("-Z", config::Z_OPTIONS);
1116}
1117
1118fn describe_codegen_flags() {
1119    safe_println!("\nAvailable codegen options:\n");
1120    print_flag_list("-C", config::CG_OPTIONS);
1121}
1122
1123fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1124    let max_len =
1125        flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1126
1127    for opt_desc in flag_list {
1128        safe_println!(
1129            "    {} {:>width$}=val -- {}",
1130            cmdline_opt,
1131            opt_desc.name().replace('_', "-"),
1132            opt_desc.desc(),
1133            width = max_len
1134        );
1135    }
1136}
1137
1138/// Process command line options. Emits messages as appropriate. If compilation
1139/// should continue, returns a getopts::Matches object parsed from args,
1140/// otherwise returns `None`.
1141///
1142/// The compiler's handling of options is a little complicated as it ties into
1143/// our stability story. The current intention of each compiler option is to
1144/// have one of two modes:
1145///
1146/// 1. An option is stable and can be used everywhere.
1147/// 2. An option is unstable, and can only be used on nightly.
1148///
1149/// Like unstable library and language features, however, unstable options have
1150/// always required a form of "opt in" to indicate that you're using them. This
1151/// provides the easy ability to scan a code base to check to see if anything
1152/// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1153///
1154/// All options behind `-Z` are considered unstable by default. Other top-level
1155/// options can also be considered unstable, and they were unlocked through the
1156/// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1157/// instability in both cases, though.
1158///
1159/// So with all that in mind, the comments below have some more detail about the
1160/// contortions done here to get things to work out correctly.
1161///
1162/// This does not need to be `pub` for rustc itself, but @chaosite needs it to
1163/// be public when using rustc as a library, see
1164/// <https://github.com/rust-lang/rust/commit/2b4c33817a5aaecabf4c6598d41e190080ec119e>
1165pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1166    // Parse with *all* options defined in the compiler, we don't worry about
1167    // option stability here we just want to parse as much as possible.
1168    let mut options = getopts::Options::new();
1169    let optgroups = config::rustc_optgroups();
1170    for option in &optgroups {
1171        option.apply(&mut options);
1172    }
1173    let matches = options.parse(args).unwrap_or_else(|e| {
1174        let msg: Option<String> = match e {
1175            getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1176                .iter()
1177                .map(|opt_desc| ('C', opt_desc.name()))
1178                .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1179                .find(|&(_, name)| *opt == name.replace('_', "-"))
1180                .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1181            getopts::Fail::ArgumentMissing(ref opt) => {
1182                optgroups.iter().find(|option| option.name == opt).map(|option| {
1183                    // Print the help just for the option in question.
1184                    let mut options = getopts::Options::new();
1185                    option.apply(&mut options);
1186                    // getopt requires us to pass a function for joining an iterator of
1187                    // strings, even though in this case we expect exactly one string.
1188                    options.usage_with_format(|it| {
1189                        it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1190                    })
1191                })
1192            }
1193            _ => None,
1194        };
1195        early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1196    });
1197
1198    // For all options we just parsed, we check a few aspects:
1199    //
1200    // * If the option is stable, we're all good
1201    // * If the option wasn't passed, we're all good
1202    // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1203    //   ourselves), then we require the `-Z unstable-options` flag to unlock
1204    //   this option that was passed.
1205    // * If we're a nightly compiler, then unstable options are now unlocked, so
1206    //   we're good to go.
1207    // * Otherwise, if we're an unstable option then we generate an error
1208    //   (unstable option being used on stable)
1209    nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1210
1211    if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1212        // Only show unstable options in --help if we accept unstable options.
1213        let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1214        let nightly_build = nightly_options::match_is_nightly_build(&matches);
1215        usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1216        return None;
1217    }
1218
1219    if describe_flag_categories(early_dcx, &matches) {
1220        return None;
1221    }
1222
1223    if matches.opt_present("version") {
1224        version!(early_dcx, "rustc", &matches);
1225        return None;
1226    }
1227
1228    Some(matches)
1229}
1230
1231fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1232    let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1233        Input::File(file) => new_parser_from_file(&sess.psess, file, None),
1234        Input::Str { name, input } => {
1235            new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
1236        }
1237    });
1238    parser.parse_inner_attributes()
1239}
1240
1241/// Runs a closure and catches unwinds triggered by fatal errors.
1242///
1243/// The compiler currently unwinds with a special sentinel value to abort
1244/// compilation on fatal errors. This function catches that sentinel and turns
1245/// the panic into a `Result` instead.
1246pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1247    catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1248        if value.is::<rustc_errors::FatalErrorMarker>() {
1249            FatalError
1250        } else {
1251            panic::resume_unwind(value);
1252        }
1253    })
1254}
1255
1256/// Variant of `catch_fatal_errors` for the `interface::Result` return type
1257/// that also computes the exit code.
1258pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1259    match catch_fatal_errors(f) {
1260        Ok(()) => EXIT_SUCCESS,
1261        _ => EXIT_FAILURE,
1262    }
1263}
1264
1265static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1266
1267// This function should only be called from the ICE hook.
1268//
1269// The intended behavior is that `run_compiler` will invoke `ice_path_with_config` early in the
1270// initialization process to properly initialize the ICE_PATH static based on parsed CLI flags.
1271//
1272// Subsequent calls to either function will then return the proper ICE path as configured by
1273// the environment and cli flags
1274fn ice_path() -> &'static Option<PathBuf> {
1275    ice_path_with_config(None)
1276}
1277
1278fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1279    if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1280        tracing::warn!(
1281            "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1282        )
1283    }
1284
1285    ICE_PATH.get_or_init(|| {
1286        if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1287            return None;
1288        }
1289        let mut path = match std::env::var_os("RUSTC_ICE") {
1290            Some(s) => {
1291                if s == "0" {
1292                    // Explicitly opting out of writing ICEs to disk.
1293                    return None;
1294                }
1295                if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1296                    tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1297                }
1298                PathBuf::from(s)
1299            }
1300            None => config
1301                .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1302                .or_else(|| std::env::current_dir().ok())
1303                .unwrap_or_default(),
1304        };
1305        // Don't use a standard datetime format because Windows doesn't support `:` in paths
1306        let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1307        let pid = std::process::id();
1308        path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1309        Some(path)
1310    })
1311}
1312
1313pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1314
1315/// Installs a panic hook that will print the ICE message on unexpected panics.
1316///
1317/// The hook is intended to be useable even by external tools. You can pass a custom
1318/// `bug_report_url`, or report arbitrary info in `extra_info`. Note that `extra_info` is called in
1319/// a context where *the thread is currently panicking*, so it must not panic or the process will
1320/// abort.
1321///
1322/// If you have no extra info to report, pass the empty closure `|_| ()` as the argument to
1323/// extra_info.
1324///
1325/// A custom rustc driver can skip calling this to set up a custom ICE hook.
1326pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1327    // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1328    // full backtraces. When a compiler ICE happens, we want to gather
1329    // as much information as possible to present in the issue opened
1330    // by the user. Compiler developers and other rustc users can
1331    // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1332    // (e.g. `RUST_BACKTRACE=1`)
1333    if env::var_os("RUST_BACKTRACE").is_none() {
1334        // HACK: this check is extremely dumb, but we don't really need it to be smarter since this should only happen in the test suite anyway.
1335        let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1336        if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1337            panic::set_backtrace_style(panic::BacktraceStyle::Short);
1338        } else {
1339            panic::set_backtrace_style(panic::BacktraceStyle::Full);
1340        }
1341    }
1342
1343    panic::update_hook(Box::new(
1344        move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1345              info: &PanicHookInfo<'_>| {
1346            // Lock stderr to prevent interleaving of concurrent panics.
1347            let _guard = io::stderr().lock();
1348            // If the error was caused by a broken pipe then this is not a bug.
1349            // Write the error and return immediately. See #98700.
1350            #[cfg(windows)]
1351            if let Some(msg) = info.payload().downcast_ref::<String>() {
1352                if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1353                {
1354                    // the error code is already going to be reported when the panic unwinds up the stack
1355                    let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1356                    let _ = early_dcx.early_err(msg.clone());
1357                    return;
1358                }
1359            };
1360
1361            // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1362            // Don't do this for delayed bugs, which already emit their own more useful backtrace.
1363            if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1364                default_hook(info);
1365                // Separate the output with an empty line
1366                eprintln!();
1367
1368                if let Some(ice_path) = ice_path()
1369                    && let Ok(mut out) = File::options().create(true).append(true).open(&ice_path)
1370                {
1371                    // The current implementation always returns `Some`.
1372                    let location = info.location().unwrap();
1373                    let msg = match info.payload().downcast_ref::<&'static str>() {
1374                        Some(s) => *s,
1375                        None => match info.payload().downcast_ref::<String>() {
1376                            Some(s) => &s[..],
1377                            None => "Box<dyn Any>",
1378                        },
1379                    };
1380                    let thread = std::thread::current();
1381                    let name = thread.name().unwrap_or("<unnamed>");
1382                    let _ = write!(
1383                        &mut out,
1384                        "thread '{name}' panicked at {location}:\n\
1385                        {msg}\n\
1386                        stack backtrace:\n\
1387                        {:#}",
1388                        std::backtrace::Backtrace::force_capture()
1389                    );
1390                }
1391            }
1392
1393            // Print the ICE message
1394            report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1395        },
1396    ));
1397}
1398
1399/// Prints the ICE message, including query stack, but without backtrace.
1400///
1401/// The message will point the user at `bug_report_url` to report the ICE.
1402///
1403/// When `install_ice_hook` is called, this function will be called as the panic
1404/// hook.
1405fn report_ice(
1406    info: &panic::PanicHookInfo<'_>,
1407    bug_report_url: &str,
1408    extra_info: fn(&DiagCtxt),
1409    using_internal_features: &AtomicBool,
1410) {
1411    let fallback_bundle =
1412        rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1413    let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1414        stderr_destination(rustc_errors::ColorConfig::Auto),
1415        fallback_bundle,
1416    ));
1417    let dcx = rustc_errors::DiagCtxt::new(emitter);
1418    let dcx = dcx.handle();
1419
1420    // a .span_bug or .bug call has already printed what
1421    // it wants to print.
1422    if !info.payload().is::<rustc_errors::ExplicitBug>()
1423        && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1424    {
1425        dcx.emit_err(session_diagnostics::Ice);
1426    }
1427
1428    if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1429        dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1430    } else {
1431        dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1432
1433        // Only emit update nightly hint for users on nightly builds.
1434        if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1435            dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1436        }
1437    }
1438
1439    let version = util::version_str!().unwrap_or("unknown_version");
1440    let tuple = config::host_tuple();
1441
1442    static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1443
1444    let file = if let Some(path) = ice_path() {
1445        // Create the ICE dump target file.
1446        match crate::fs::File::options().create(true).append(true).open(&path) {
1447            Ok(mut file) => {
1448                dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1449                if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1450                    let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1451                }
1452                Some(file)
1453            }
1454            Err(err) => {
1455                // The path ICE couldn't be written to disk, provide feedback to the user as to why.
1456                dcx.emit_warn(session_diagnostics::IcePathError {
1457                    path: path.clone(),
1458                    error: err.to_string(),
1459                    env_var: std::env::var_os("RUSTC_ICE")
1460                        .map(PathBuf::from)
1461                        .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1462                });
1463                dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1464                None
1465            }
1466        }
1467    } else {
1468        dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1469        None
1470    };
1471
1472    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1473        dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1474        if excluded_cargo_defaults {
1475            dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1476        }
1477    }
1478
1479    // If backtraces are enabled, also print the query stack
1480    let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1481
1482    let limit_frames = if backtrace { None } else { Some(2) };
1483
1484    interface::try_print_query_stack(dcx, limit_frames, file);
1485
1486    // We don't trust this callback not to panic itself, so run it at the end after we're sure we've
1487    // printed all the relevant info.
1488    extra_info(&dcx);
1489
1490    #[cfg(windows)]
1491    if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1492        // Trigger a debugger if we crashed during bootstrap
1493        unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1494    }
1495}
1496
1497/// This allows tools to enable rust logging without having to magically match rustc's
1498/// tracing crate version.
1499pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1500    init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1501}
1502
1503/// This allows tools to enable rust logging without having to magically match rustc's
1504/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose
1505/// the values directly rather than having to set an environment variable.
1506pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1507    if let Err(error) = rustc_log::init_logger(cfg) {
1508        early_dcx.early_fatal(error.to_string());
1509    }
1510}
1511
1512/// Install our usual `ctrlc` handler, which sets [`rustc_const_eval::CTRL_C_RECEIVED`].
1513/// Making this handler optional lets tools can install a different handler, if they wish.
1514pub fn install_ctrlc_handler() {
1515    #[cfg(all(not(miri), not(target_family = "wasm")))]
1516    ctrlc::set_handler(move || {
1517        // Indicate that we have been signaled to stop, then give the rest of the compiler a bit of
1518        // time to check CTRL_C_RECEIVED and run its own shutdown logic, but after a short amount
1519        // of time exit the process. This sleep+exit ensures that even if nobody is checking
1520        // CTRL_C_RECEIVED, the compiler exits reasonably promptly.
1521        rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1522        std::thread::sleep(std::time::Duration::from_millis(100));
1523        std::process::exit(1);
1524    })
1525    .expect("Unable to install ctrlc handler");
1526}
1527
1528pub fn main() -> ! {
1529    let start_time = Instant::now();
1530    let start_rss = get_resident_set_size();
1531
1532    let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1533
1534    init_rustc_env_logger(&early_dcx);
1535    signal_handler::install();
1536    let mut callbacks = TimePassesCallbacks::default();
1537    install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1538    install_ctrlc_handler();
1539
1540    let exit_code =
1541        catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1542
1543    if let Some(format) = callbacks.time_passes {
1544        let end_rss = get_resident_set_size();
1545        print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1546    }
1547
1548    process::exit(exit_code)
1549}