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