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