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