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