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