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