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