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