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