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