Skip to main content

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