1#![allow(rustc::untranslatable_diagnostic)] #![feature(decl_macro)]
10#![feature(panic_backtrace_config)]
11#![feature(panic_update_hook)]
12#![feature(trim_prefix_suffix)]
13#![feature(try_blocks)]
14use 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;
41use 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#[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#[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 pub(super) fn install() {}
102}
103
104use crate::session_diagnostics::{
105 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
106 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
107};
108
109#[allow(non_upper_case_globals)]
#[doc(hidden)]
#[doc =
r" Auto-generated constants for type-checked references to Fluent messages."]
pub(crate) mod fluent_generated {
#[doc =
"Constant referring to Fluent message `driver_impl_cant_emit_mir` from `driver_impl`"]
pub const driver_impl_cant_emit_mir: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_cant_emit_mir"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice` from `driver_impl`"]
pub const driver_impl_ice: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report` from `driver_impl`"]
pub const driver_impl_ice_bug_report: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report_internal_feature` from `driver_impl`"]
pub const driver_impl_ice_bug_report_internal_feature:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report_internal_feature"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report_update_note` from `driver_impl`"]
pub const driver_impl_ice_bug_report_update_note:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report_update_note"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_exclude_cargo_defaults` from `driver_impl`"]
pub const driver_impl_ice_exclude_cargo_defaults:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_exclude_cargo_defaults"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_flags` from `driver_impl`"]
pub const driver_impl_ice_flags: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_flags"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path` from `driver_impl`"]
pub const driver_impl_ice_path: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path_error` from `driver_impl`"]
pub const driver_impl_ice_path_error: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path_error"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path_error_env` from `driver_impl`"]
pub const driver_impl_ice_path_error_env: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path_error_env"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_version` from `driver_impl`"]
pub const driver_impl_ice_version: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_version"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_corrupt_file` from `driver_impl`"]
pub const driver_impl_rlink_corrupt_file: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_corrupt_file"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_empty_version_number` from `driver_impl`"]
pub const driver_impl_rlink_empty_version_number:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_empty_version_number"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_encoding_version_mismatch` from `driver_impl`"]
pub const driver_impl_rlink_encoding_version_mismatch:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_encoding_version_mismatch"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_no_a_file` from `driver_impl`"]
pub const driver_impl_rlink_no_a_file: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_no_a_file"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_rustc_version_mismatch` from `driver_impl`"]
pub const driver_impl_rlink_rustc_version_mismatch:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_rustc_version_mismatch"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_unable_to_read` from `driver_impl`"]
pub const driver_impl_rlink_unable_to_read: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_unable_to_read"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_wrong_file_type` from `driver_impl`"]
pub const driver_impl_rlink_wrong_file_type: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_wrong_file_type"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_unstable_feature_usage` from `driver_impl`"]
pub const driver_impl_unstable_feature_usage: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_unstable_feature_usage"),
None);
#[doc =
r" Constants expected to exist by the diagnostic derive macros to use as default Fluent"]
#[doc = r" identifiers for different subdiagnostic kinds."]
pub mod _subdiag {
#[doc = r" Default for `#[help]`"]
pub const help: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("help"));
#[doc = r" Default for `#[note]`"]
pub const note: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("note"));
#[doc = r" Default for `#[warn]`"]
pub const warn: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("warn"));
#[doc = r" Default for `#[label]`"]
pub const label: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label"));
#[doc = r" Default for `#[suggestion]`"]
pub const suggestion: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("suggestion"));
}
}rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
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 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 ];
150
151pub const EXIT_SUCCESS: i32 = 0;
153
154pub 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 fn config(&mut self, _config: &mut interface::Config) {}
163 fn after_crate_root_parsing(
167 &mut self,
168 _compiler: &interface::Compiler,
169 _krate: &mut ast::Crate,
170 ) -> Compilation {
171 Compilation::Continue
172 }
173 fn after_expansion<'tcx>(
176 &mut self,
177 _compiler: &interface::Compiler,
178 _tcx: TyCtxt<'tcx>,
179 ) -> Compilation {
180 Compilation::Continue
181 }
182 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(#[automatically_derived]
impl ::core::default::Default for TimePassesCallbacks {
#[inline]
fn default() -> TimePassesCallbacks {
TimePassesCallbacks {
time_passes: ::core::default::Default::default(),
}
}
}Default)]
194pub struct TimePassesCallbacks {
195 time_passes: Option<TimePassesFormat>,
196}
197
198impl Callbacks for TimePassesCallbacks {
199 #[allow(rustc::bad_opt_access)]
201 fn config(&mut self, config: &mut interface::Config) {
202 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
215pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
217 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
218
219 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 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 let early_exit = || {
283 sess.dcx().abort_if_errors();
284 };
285
286 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"); }
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 let mut krate = passes::parse(sess);
316
317 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 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:328",
"rustc_driver_impl", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(328u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("finished pretty-printing")
as &dyn Value))])
});
} else { ; }
};trace!("finished pretty-printing");
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 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 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 = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unstable_feature_usage_metrics-{0}-{1}.json",
crate_name, hash))
})format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
398 let metrics_path = metrics_dir.join(metrics_file_name);
399 if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
400 tcxt.dcx().emit_err(UnstableFeatureUsage { error });
404 }
405}
406
407fn 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
417fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
420 match free_matches {
421 [] => None, [ifile] if ifile == "-" => {
423 let mut input = String::new();
425 if io::stdin().read_to_string(&mut input).is_err() {
426 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(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple input filenames provided (first two filenames are `{0}` and `{1}`)",
ifile1, ifile2))
})format!(
450 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
451 ifile1, ifile2
452 )),
453 }
454}
455
456#[derive(#[automatically_derived]
impl ::core::marker::Copy for Compilation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Compilation {
#[inline]
fn clone(&self) -> Compilation { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Compilation {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Compilation::Stop => "Stop",
Compilation::Continue => "Continue",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Compilation {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Compilation {
#[inline]
fn eq(&self, other: &Compilation) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
458pub enum Compilation {
459 Stop,
460 Continue,
461}
462
463fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
464 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 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 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
490 }
491 } else {
492 early_dcx.early_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a valid error code",
code))
})format!("{code} is not a valid error code"));
493 }
494}
495
496fn show_md_content_with_pager(content: &str, color: ColorConfig) {
501 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
502 if falsecfg!(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"); }
509
510 let pretty_on_pager = match color {
511 ColorConfig::Auto => {
512 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
514 }
515 ColorConfig::Always => true,
516 ColorConfig::Never => false,
517 };
518
519 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 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 if let Some((bufwtr, mdbuf)) = &mut pretty_data
546 && bufwtr.write_all(&mdbuf).is_ok()
547 {
548 return;
549 }
550
551 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
553}
554
555fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
556 if !sess.opts.unstable_opts.link_only {
::core::panicking::panic("assertion failed: sess.opts.unstable_opts.link_only")
};assert!(sess.opts.unstable_opts.link_only);
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 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};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 #[allow(unused_imports)]
627 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
628
629 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 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
659 }
660 HostTuple => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
rustc_session::config::host_tuple()))).unwrap()println_info!("{}", rustc_session::config::host_tuple()),
661 Sysroot => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", sess.opts.sysroot.path().display()))).unwrap()println_info!("{}", sess.opts.sysroot.path().display()),
662 TargetLibdir => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
sess.target_tlib_path.dir.display()))).unwrap()println_info!("{}", sess.target_tlib_path.dir.display()),
663 TargetSpecJson => {
664 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&sess.target.to_json()).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
665 }
666 TargetSpecJsonSchema => {
667 let schema = rustc_target::spec::json_schema();
668 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&schema).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&schema).unwrap());
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 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&targets).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
678 }
679 FileNames => {
680 let Some(attrs) = attrs.as_ref() else {
681 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 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
fname.as_path().file_name().unwrap().to_string_lossy()))).unwrap();println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
697 }
698 }
699 CrateName => {
700 let Some(attrs) = attrs.as_ref() else {
701 return Compilation::Continue;
703 };
704 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
passes::get_crate_name(sess, attrs)))).unwrap();println_info!("{}", passes::get_crate_name(sess, attrs));
705 }
706 CrateRootLintLevels => {
707 let Some(attrs) = attrs.as_ref() else {
708 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 ®istered_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 continue;
729 }
730 let level = lint_levels.lint_level(lint).level;
731 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}", lint.name_lower(),
level.as_str()))).unwrap();println_info!("{}={}", lint.name_lower(), level.as_str());
732 }
733 }
734 Cfg => {
735 let mut cfgs = sess
736 .psess
737 .config
738 .iter()
739 .filter_map(|&(name, value)| {
740 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(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})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 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
758 }
759 }
760 CheckCfg => {
761 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
762
763 #[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 => {
769 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
770 }
771 ExpectedValues::Some(values) => {
772 let mut values: Vec<_> = values
773 .iter()
774 .map(|value| {
775 if let Some(value) = value {
776 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
777 } else {
778 "none()".to_string()
779 }
780 })
781 .collect();
782
783 values.sort_unstable();
784
785 let values = values.join(", ");
786
787 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
788 }
789 }
790 }
791
792 check_cfgs.sort_unstable();
793 if !sess.psess.check_config.exhaustive_names
794 && sess.psess.check_config.exhaustive_values
795 {
796 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
797 }
798 for check_cfg in check_cfgs {
799 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
800 }
801 }
802 CallingConventions => {
803 let calling_conventions = rustc_abi::all_names();
804 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
805 }
806 BackendHasZstd => {
807 let has_zstd: bool = codegen_backend.has_zstd();
808 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
809 }
810 RelocationModels
811 | CodeModels
812 | TlsModels
813 | TargetCPUs
814 | StackProtectorStrategies
815 | TargetFeatures => {
816 codegen_backend.print(req, &mut crate_info, sess);
817 }
818 NativeStaticLibs => {}
820 LinkArgs => {}
821 SplitDebuginfo => {
822 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
823
824 for split in &[Off, Packed, Unpacked] {
825 if sess.target.options.supported_split_debuginfo.contains(split) {
826 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
827 }
828 }
829 }
830 DeploymentTarget => {
831 if sess.target.is_like_darwin {
832 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}",
rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
sess.apple_deployment_target().fmt_pretty()))).unwrap()println_info!(
833 "{}={}",
834 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
835 sess.apple_deployment_target().fmt_pretty(),
836 )
837 } else {
838 #[allow(rustc::diagnostic_outside_of_impl)]
839 sess.dcx().fatal("only Apple targets currently support deployment version info")
840 }
841 }
842 SupportedCrateTypes => {
843 let supported_crate_types = CRATE_TYPES
844 .iter()
845 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
846 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
847 .map(|(crate_type_sym, _)| *crate_type_sym)
848 .collect::<BTreeSet<_>>();
849 for supported_crate_type in supported_crate_types {
850 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
851 }
852 }
853 }
854
855 req.out.overwrite(&crate_info, sess);
856 }
857 Compilation::Stop
858}
859
860pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
864 fn unw(x: Option<&str>) -> &str {
865 x.unwrap_or("unknown")
866 }
867 $crate::version_at_macro_invocation(
868 $early_dcx,
869 $binary,
870 $matches,
871 unw(option_env!("CFG_VERSION")),
872 unw(option_env!("CFG_VER_HASH")),
873 unw(option_env!("CFG_VER_DATE")),
874 unw(option_env!("CFG_RELEASE")),
875 )
876}
877
878#[doc(hidden)] pub fn version_at_macro_invocation(
880 early_dcx: &EarlyDiagCtxt,
881 binary: &str,
882 matches: &getopts::Matches,
883 version: &str,
884 commit_hash: &str,
885 commit_date: &str,
886 release: &str,
887) {
888 let verbose = matches.opt_present("verbose");
889
890 let mut version = version;
891 let mut release = release;
892 let tmp;
893 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
894 tmp = force_version;
895 version = &tmp;
896 release = &tmp;
897 }
898
899 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
900
901 if verbose {
902 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
903 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
904 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
905 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
906 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
907
908 get_backend_from_raw_matches(early_dcx, matches).print_version();
909 }
910}
911
912fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
913 let mut options = getopts::Options::new();
914 for option in config::rustc_optgroups()
915 .iter()
916 .filter(|x| verbose || !x.is_verbose_help_only)
917 .filter(|x| include_unstable_options || x.is_stable())
918 {
919 option.apply(&mut options);
920 }
921 let message = "Usage: rustc [OPTIONS] INPUT";
922 let nightly_help = if nightly_build {
923 "\n -Z help Print unstable compiler options"
924 } else {
925 ""
926 };
927 let verbose_help = if verbose {
928 ""
929 } else {
930 "\n --help -v Print the full set of options rustc accepts"
931 };
932 let at_path = if verbose {
933 " @path Read newline separated options from `path`\n"
934 } else {
935 ""
936 };
937 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}{1}\nAdditional help:\n -C help Print codegen options\n -W help Print \'lint\' options and default settings{2}{3}\n",
options.usage(message), at_path, nightly_help,
verbose_help)));
};safe_println!(
938 "{options}{at_path}\nAdditional help:
939 -C help Print codegen options
940 -W help \
941 Print 'lint' options and default settings{nightly}{verbose}\n",
942 options = options.usage(message),
943 at_path = at_path,
944 nightly = nightly_help,
945 verbose = verbose_help
946 );
947}
948
949fn print_wall_help() {
950 {
crate::print::print(format_args!("{0}\n",
format_args!("\nThe flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by\ndefault. Use `rustc -W help` to see all available lints. It\'s more common to put\nwarning settings in the crate root using `#![warn(LINT_NAME)]` instead of using\nthe command line flag directly.\n")));
};safe_println!(
951 "
952The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
953default. Use `rustc -W help` to see all available lints. It's more common to put
954warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
955the command line flag directly.
956"
957 );
958}
959
960pub fn describe_lints(sess: &Session, registered_lints: bool) {
962 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable lint options:\n -W <foo> Warn about <foo>\n -A <foo> Allow <foo>\n -D <foo> Deny <foo>\n -F <foo> Forbid <foo> (deny <foo> and all attempts to override)\n\n")));
};safe_println!(
963 "
964Available lint options:
965 -W <foo> Warn about <foo>
966 -A <foo> Allow <foo>
967 -D <foo> Deny <foo>
968 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
969
970"
971 );
972
973 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
974 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
976 lints
977 }
978
979 fn sort_lint_groups(
980 lints: Vec<(&'static str, Vec<LintId>, bool)>,
981 ) -> Vec<(&'static str, Vec<LintId>)> {
982 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
983 lints.sort_by_key(|l| l.0);
984 lints
985 }
986
987 let lint_store = unerased_lint_store(sess);
988 let (loaded, builtin): (Vec<_>, _) =
989 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
990 let loaded = sort_lints(sess, loaded);
991 let builtin = sort_lints(sess, builtin);
992
993 let (loaded_groups, builtin_groups): (Vec<_>, _) =
994 lint_store.get_lint_groups().partition(|&(.., p)| p);
995 let loaded_groups = sort_lint_groups(loaded_groups);
996 let builtin_groups = sort_lint_groups(builtin_groups);
997
998 let max_name_len =
999 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
1000 let padded = |x: &str| {
1001 let mut s = " ".repeat(max_name_len - x.chars().count());
1002 s.push_str(x);
1003 s
1004 };
1005
1006 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1007
1008 let print_lints = |lints: Vec<&Lint>| {
1009 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("name"), "default",
"meaning")));
};safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1010 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1011 for lint in lints {
1012 let name = lint.name_lower().replace('_', "-");
1013 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded(&name),
lint.default_level(sess.edition()).as_str(), lint.desc)));
};safe_println!(
1014 " {} {:7.7} {}",
1015 padded(&name),
1016 lint.default_level(sess.edition()).as_str(),
1017 lint.desc
1018 );
1019 }
1020 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1021 };
1022
1023 print_lints(builtin);
1024
1025 let max_name_len = max(
1026 "warnings".len(),
1027 loaded_groups
1028 .iter()
1029 .chain(&builtin_groups)
1030 .map(|&(s, _)| s.chars().count())
1031 .max()
1032 .unwrap_or(0),
1033 );
1034
1035 let padded = |x: &str| {
1036 let mut s = " ".repeat(max_name_len - x.chars().count());
1037 s.push_str(x);
1038 s
1039 };
1040
1041 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1042
1043 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1044 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1045 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1046
1047 if all_warnings {
1048 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} all lints that are set to issue warnings",
padded("warnings"))));
};safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1049 }
1050
1051 for (name, to) in lints {
1052 let name = name.to_lowercase().replace('_', "-");
1053 let desc = to
1054 .into_iter()
1055 .map(|x| x.to_string().replace('_', "-"))
1056 .collect::<Vec<String>>()
1057 .join(", ");
1058 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1059 }
1060 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1061 };
1062
1063 print_lint_groups(builtin_groups, true);
1064
1065 match (registered_lints, loaded.len(), loaded_groups.len()) {
1066 (false, 0, _) | (false, _, 0) => {
1067 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint tools like Clippy can load additional lints and lint groups.")));
};safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1068 }
1069 (false, ..) => {
::core::panicking::panic_fmt(format_args!("didn\'t load additional lints but got them anyway!"));
}panic!("didn't load additional lints but got them anyway!"),
1070 (true, 0, 0) => {
1071 {
crate::print::print(format_args!("{0}\n",
format_args!("This crate does not load any additional lints or lint groups.")));
}safe_println!("This crate does not load any additional lints or lint groups.")
1072 }
1073 (true, l, g) => {
1074 if l > 0 {
1075 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks loaded by this crate:\n")));
};safe_println!("Lint checks loaded by this crate:\n");
1076 print_lints(loaded);
1077 }
1078 if g > 0 {
1079 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups loaded by this crate:\n")));
};safe_println!("Lint groups loaded by this crate:\n");
1080 print_lint_groups(loaded_groups, false);
1081 }
1082 }
1083 }
1084}
1085
1086pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1090 let wall = matches.opt_strs("W");
1092 if wall.iter().any(|x| *x == "all") {
1093 print_wall_help();
1094 return true;
1095 }
1096
1097 let debug_flags = matches.opt_strs("Z");
1099 if debug_flags.iter().any(|x| *x == "help") {
1100 describe_debug_flags();
1101 return true;
1102 }
1103
1104 let cg_flags = matches.opt_strs("C");
1105 if cg_flags.iter().any(|x| *x == "help") {
1106 describe_codegen_flags();
1107 return true;
1108 }
1109
1110 if cg_flags.iter().any(|x| *x == "passes=list") {
1111 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1112 return true;
1113 }
1114
1115 false
1116}
1117
1118fn get_backend_from_raw_matches(
1125 early_dcx: &EarlyDiagCtxt,
1126 matches: &Matches,
1127) -> Box<dyn CodegenBackend> {
1128 let debug_flags = matches.opt_strs("Z");
1129 let backend_name = debug_flags
1130 .iter()
1131 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1132 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1133 let target = parse_target_triple(early_dcx, matches);
1134 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1135 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1136
1137 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1138}
1139
1140fn describe_debug_flags() {
1141 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable options:\n")));
};safe_println!("\nAvailable options:\n");
1142 print_flag_list("-Z", config::Z_OPTIONS);
1143}
1144
1145fn describe_codegen_flags() {
1146 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1147 print_flag_list("-C", config::CG_OPTIONS);
1148}
1149
1150fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1151 let max_len =
1152 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1153
1154 for opt_desc in flag_list {
1155 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:>3$}=val -- {2}", cmdline_opt,
opt_desc.name().replace('_', "-"), opt_desc.desc(),
max_len)));
};safe_println!(
1156 " {} {:>width$}=val -- {}",
1157 cmdline_opt,
1158 opt_desc.name().replace('_', "-"),
1159 opt_desc.desc(),
1160 width = max_len
1161 );
1162 }
1163}
1164
1165pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1193 let mut options = getopts::Options::new();
1196 let optgroups = config::rustc_optgroups();
1197 for option in &optgroups {
1198 option.apply(&mut options);
1199 }
1200 let matches = options.parse(args).unwrap_or_else(|e| {
1201 let msg: Option<String> = match e {
1202 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1203 .iter()
1204 .map(|opt_desc| ('C', opt_desc.name()))
1205 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1206 .find(|&(_, name)| *opt == name.replace('_', "-"))
1207 .map(|(flag, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}. Did you mean `-{1} {2}`?", e,
flag, opt))
})format!("{e}. Did you mean `-{flag} {opt}`?")),
1208 getopts::Fail::ArgumentMissing(ref opt) => {
1209 optgroups.iter().find(|option| option.name == opt).map(|option| {
1210 let mut options = getopts::Options::new();
1212 option.apply(&mut options);
1213 options.usage_with_format(|it| {
1216 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1217 })
1218 })
1219 }
1220 _ => None,
1221 };
1222 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1223 });
1224
1225 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1237
1238 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1239 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1241 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1242 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1243 return None;
1244 }
1245
1246 if describe_flag_categories(early_dcx, &matches) {
1247 return None;
1248 }
1249
1250 if matches.opt_present("version") {
1251 fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
crate::version_at_macro_invocation(early_dcx, "rustc", &matches,
unw(::core::option::Option::Some("1.94.0-beta.2 (23a44d3c7 2026-01-25)")),
unw(::core::option::Option::Some("23a44d3c70448c08dc6a2fc13c1afceab49f2bb9")),
unw(::core::option::Option::Some("2026-01-25")),
unw(::core::option::Option::Some("1.94.0-beta.2")));version!(early_dcx, "rustc", &matches);
1252 return None;
1253 }
1254
1255 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1256
1257 Some(matches)
1258}
1259
1260fn warn_on_confusing_output_filename_flag(
1264 early_dcx: &EarlyDiagCtxt,
1265 matches: &getopts::Matches,
1266 args: &[String],
1267) {
1268 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1269 let s1 = s1.replace('-', "_");
1270 let s2 = s2.replace('-', "_");
1271 s1 == s2
1272 }
1273
1274 if let Some(name) = matches.opt_str("o")
1275 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1276 {
1277 let filename = suspect.trim_prefix("-");
1278 let optgroups = config::rustc_optgroups();
1279 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1280
1281 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1288 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1289 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1290 {
1291 early_dcx.early_warn(
1292 "option `-o` has no space between flag name and value, which can be confusing",
1293 );
1294 early_dcx.early_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("output filename `-o {0}` is applied instead of a flag named `o{0}`",
name))
})format!(
1295 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1296 ));
1297 early_dcx.early_help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("insert a space between `-o` and `{0}` if this is intentional: `-o {0}`",
name))
})format!(
1298 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1299 ));
1300 }
1301 }
1302}
1303
1304fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1305 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1306 Input::File(file) => {
1307 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1308 }
1309 Input::Str { name, input } => new_parser_from_source_str(
1310 &sess.psess,
1311 name.clone(),
1312 input.clone(),
1313 StripTokens::ShebangAndFrontmatter,
1314 ),
1315 });
1316 parser.parse_inner_attributes()
1317}
1318
1319pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1325 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1326 if value.is::<rustc_errors::FatalErrorMarker>() {
1327 FatalError
1328 } else {
1329 panic::resume_unwind(value);
1330 }
1331 })
1332}
1333
1334pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1337 match catch_fatal_errors(f) {
1338 Ok(()) => EXIT_SUCCESS,
1339 _ => EXIT_FAILURE,
1340 }
1341}
1342
1343static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1344
1345fn ice_path() -> &'static Option<PathBuf> {
1353 ice_path_with_config(None)
1354}
1355
1356fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1357 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1358 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1358",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1358u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ICE_PATH has already been initialized -- files may be emitted at unintended paths")
as &dyn Value))])
});
} else { ; }
}tracing::warn!(
1359 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1360 )
1361 }
1362
1363 ICE_PATH.get_or_init(|| {
1364 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1365 return None;
1366 }
1367 let mut path = match std::env::var_os("RUSTC_ICE") {
1368 Some(s) => {
1369 if s == "0" {
1370 return None;
1372 }
1373 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1374 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1374",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1374u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files")
as &dyn Value))])
});
} else { ; }
};tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1375 }
1376 PathBuf::from(s)
1377 }
1378 None => config
1379 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1380 .or_else(|| std::env::current_dir().ok())
1381 .unwrap_or_default(),
1382 };
1383 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1385 let pid = std::process::id();
1386 path.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc-ice-{0}-{1}.txt", file_now,
pid))
})format!("rustc-ice-{file_now}-{pid}.txt"));
1387 Some(path)
1388 })
1389}
1390
1391pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1392
1393pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1405 if env::var_os("RUST_BACKTRACE").is_none() {
1412 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1414 if "beta"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1415 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1416 } else {
1417 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1418 }
1419 }
1420
1421 panic::update_hook(Box::new(
1422 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1423 info: &PanicHookInfo<'_>| {
1424 let _guard = io::stderr().lock();
1426 #[cfg(windows)]
1429 if let Some(msg) = info.payload().downcast_ref::<String>() {
1430 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1431 {
1432 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1434 let _ = early_dcx.early_err(msg.clone());
1435 return;
1436 }
1437 };
1438
1439 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1442 default_hook(info);
1443 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1445
1446 if let Some(ice_path) = ice_path()
1447 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1448 {
1449 let location = info.location().unwrap();
1451 let msg = match info.payload().downcast_ref::<&'static str>() {
1452 Some(s) => *s,
1453 None => match info.payload().downcast_ref::<String>() {
1454 Some(s) => &s[..],
1455 None => "Box<dyn Any>",
1456 },
1457 };
1458 let thread = std::thread::current();
1459 let name = thread.name().unwrap_or("<unnamed>");
1460 let _ = (&mut out).write_fmt(format_args!("thread \'{1}\' panicked at {2}:\n{3}\nstack backtrace:\n{0:#}",
std::backtrace::Backtrace::force_capture(), name, location, msg))write!(
1461 &mut out,
1462 "thread '{name}' panicked at {location}:\n\
1463 {msg}\n\
1464 stack backtrace:\n\
1465 {:#}",
1466 std::backtrace::Backtrace::force_capture()
1467 );
1468 }
1469 }
1470
1471 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1473 },
1474 ));
1475}
1476
1477fn report_ice(
1484 info: &panic::PanicHookInfo<'_>,
1485 bug_report_url: &str,
1486 extra_info: fn(&DiagCtxt),
1487 using_internal_features: &AtomicBool,
1488) {
1489 let translator = default_translator();
1490 let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1491 stderr_destination(rustc_errors::ColorConfig::Auto),
1492 translator,
1493 ));
1494 let dcx = rustc_errors::DiagCtxt::new(emitter);
1495 let dcx = dcx.handle();
1496
1497 if !info.payload().is::<rustc_errors::ExplicitBug>()
1500 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1501 {
1502 dcx.emit_err(session_diagnostics::Ice);
1503 }
1504
1505 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1506 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1507 } else {
1508 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1509
1510 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1512 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1513 }
1514 }
1515
1516 let version = ::core::option::Option::Some("1.94.0-beta.2 (23a44d3c7 2026-01-25)")util::version_str!().unwrap_or("unknown_version");
1517 let tuple = config::host_tuple();
1518
1519 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1520
1521 let file = if let Some(path) = ice_path() {
1522 match crate::fs::File::options().create(true).append(true).open(path) {
1524 Ok(mut file) => {
1525 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1526 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1527 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1528 }
1529 Some(file)
1530 }
1531 Err(err) => {
1532 dcx.emit_warn(session_diagnostics::IcePathError {
1534 path: path.clone(),
1535 error: err.to_string(),
1536 env_var: std::env::var_os("RUSTC_ICE")
1537 .map(PathBuf::from)
1538 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1539 });
1540 None
1541 }
1542 }
1543 } else {
1544 None
1545 };
1546
1547 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1548
1549 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1550 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1551 if excluded_cargo_defaults {
1552 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1553 }
1554 }
1555
1556 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1558
1559 let limit_frames = if backtrace { None } else { Some(2) };
1560
1561 interface::try_print_query_stack(dcx, limit_frames, file);
1562
1563 extra_info(&dcx);
1566
1567 #[cfg(windows)]
1568 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1569 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1571 }
1572}
1573
1574pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1577 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1578}
1579
1580pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1584 if let Err(error) = rustc_log::init_logger(cfg) {
1585 early_dcx.early_fatal(error.to_string());
1586 }
1587}
1588
1589pub fn init_logger_with_additional_layer<F, T>(
1595 early_dcx: &EarlyDiagCtxt,
1596 cfg: rustc_log::LoggerConfig,
1597 build_subscriber: F,
1598) where
1599 F: FnOnce() -> T,
1600 T: rustc_log::BuildSubscriberRet,
1601{
1602 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1603 early_dcx.early_fatal(error.to_string());
1604 }
1605}
1606
1607pub fn install_ctrlc_handler() {
1610 #[cfg(all(not(miri), not(target_family = "wasm")))]
1611 ctrlc::set_handler(move || {
1612 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1617 std::thread::sleep(std::time::Duration::from_millis(100));
1618 std::process::exit(1);
1619 })
1620 .expect("Unable to install ctrlc handler");
1621}
1622
1623pub fn main() -> ! {
1624 let start_time = Instant::now();
1625 let start_rss = get_resident_set_size();
1626
1627 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1628
1629 init_rustc_env_logger(&early_dcx);
1630 signal_handler::install();
1631 let mut callbacks = TimePassesCallbacks::default();
1632 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1633 install_ctrlc_handler();
1634
1635 let exit_code =
1636 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1637
1638 if let Some(format) = callbacks.time_passes {
1639 let end_rss = get_resident_set_size();
1640 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1641 }
1642
1643 process::exit(exit_code)
1644}