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