1#![feature(decl_macro)]
9#![feature(panic_backtrace_config)]
10#![feature(panic_update_hook)]
11#![feature(trim_prefix_suffix)]
12#![feature(try_blocks)]
13use std::cmp::max;
16use std::collections::{BTreeMap, BTreeSet};
17use std::ffi::OsString;
18use std::fmt::Write as _;
19use std::fs::{self, File};
20use std::io::{self, IsTerminal, Read, Write};
21use std::panic::{self, PanicHookInfo};
22use std::path::{Path, PathBuf};
23use std::process::{self, Command, Stdio};
24use std::sync::OnceLock;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::time::Instant;
27use std::{env, str};
28
29use rustc_ast as ast;
30use rustc_codegen_ssa::traits::CodegenBackend;
31use rustc_codegen_ssa::{CodegenErrors, CodegenResults};
32use rustc_data_structures::profiling::{
33 TimePassesFormat, get_resident_set_size, print_time_passes_entry,
34};
35pub use rustc_errors::catch_fatal_errors;
36use rustc_errors::emitter::stderr_destination;
37use rustc_errors::registry::Registry;
38use rustc_errors::translation::Translator;
39use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, PResult, markdown};
40use rustc_feature::find_gated_cfg;
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;
89pub mod highlighter;
90mod session_diagnostics;
91
92#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
96mod signal_handler;
97
98#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
99mod signal_handler {
100 pub(super) fn install() {}
103}
104
105use crate::session_diagnostics::{
106 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
107 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
108};
109
110#[allow(non_upper_case_globals)]
#[doc(hidden)]
#[doc =
r" Auto-generated constants for type-checked references to Fluent messages."]
pub(crate) mod fluent_generated {
#[doc =
"Constant referring to Fluent message `driver_impl_cant_emit_mir` from `driver_impl`"]
pub const driver_impl_cant_emit_mir: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_cant_emit_mir"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice` from `driver_impl`"]
pub const driver_impl_ice: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report` from `driver_impl`"]
pub const driver_impl_ice_bug_report: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report_internal_feature` from `driver_impl`"]
pub const driver_impl_ice_bug_report_internal_feature:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report_internal_feature"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_bug_report_update_note` from `driver_impl`"]
pub const driver_impl_ice_bug_report_update_note:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_bug_report_update_note"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_exclude_cargo_defaults` from `driver_impl`"]
pub const driver_impl_ice_exclude_cargo_defaults:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_exclude_cargo_defaults"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_flags` from `driver_impl`"]
pub const driver_impl_ice_flags: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_flags"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path` from `driver_impl`"]
pub const driver_impl_ice_path: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path_error` from `driver_impl`"]
pub const driver_impl_ice_path_error: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path_error"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_path_error_env` from `driver_impl`"]
pub const driver_impl_ice_path_error_env: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_path_error_env"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_ice_version` from `driver_impl`"]
pub const driver_impl_ice_version: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_ice_version"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_corrupt_file` from `driver_impl`"]
pub const driver_impl_rlink_corrupt_file: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_corrupt_file"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_empty_version_number` from `driver_impl`"]
pub const driver_impl_rlink_empty_version_number:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_empty_version_number"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_encoding_version_mismatch` from `driver_impl`"]
pub const driver_impl_rlink_encoding_version_mismatch:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_encoding_version_mismatch"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_no_a_file` from `driver_impl`"]
pub const driver_impl_rlink_no_a_file: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_no_a_file"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_rustc_version_mismatch` from `driver_impl`"]
pub const driver_impl_rlink_rustc_version_mismatch:
rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_rustc_version_mismatch"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_unable_to_read` from `driver_impl`"]
pub const driver_impl_rlink_unable_to_read: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_unable_to_read"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_rlink_wrong_file_type` from `driver_impl`"]
pub const driver_impl_rlink_wrong_file_type: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_rlink_wrong_file_type"),
None);
#[doc =
"Constant referring to Fluent message `driver_impl_unstable_feature_usage` from `driver_impl`"]
pub const driver_impl_unstable_feature_usage: rustc_errors::DiagMessage =
rustc_errors::DiagMessage::FluentIdentifier(std::borrow::Cow::Borrowed("driver_impl_unstable_feature_usage"),
None);
#[doc =
r" Constants expected to exist by the diagnostic derive macros to use as default Fluent"]
#[doc = r" identifiers for different subdiagnostic kinds."]
pub mod _subdiag {
#[doc = r" Default for `#[help]`"]
pub const help: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("help"));
#[doc = r" Default for `#[note]`"]
pub const note: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("note"));
#[doc = r" Default for `#[warn]`"]
pub const warn: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("warn"));
#[doc = r" Default for `#[label]`"]
pub const label: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("label"));
#[doc = r" Default for `#[suggestion]`"]
pub const suggestion: rustc_errors::SubdiagMessage =
rustc_errors::SubdiagMessage::FluentAttr(std::borrow::Cow::Borrowed("suggestion"));
}
}rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
111
112pub fn default_translator() -> Translator {
113 Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
114}
115
116pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
117 crate::DEFAULT_LOCALE_RESOURCE,
119 rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
120 rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
121 rustc_attr_parsing::DEFAULT_LOCALE_RESOURCE,
122 rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
123 rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
124 rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
125 rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
126 rustc_errors::DEFAULT_LOCALE_RESOURCE,
127 rustc_expand::DEFAULT_LOCALE_RESOURCE,
128 rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
129 rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
130 rustc_incremental::DEFAULT_LOCALE_RESOURCE,
131 rustc_infer::DEFAULT_LOCALE_RESOURCE,
132 rustc_interface::DEFAULT_LOCALE_RESOURCE,
133 rustc_lint::DEFAULT_LOCALE_RESOURCE,
134 rustc_metadata::DEFAULT_LOCALE_RESOURCE,
135 rustc_middle::DEFAULT_LOCALE_RESOURCE,
136 rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
137 rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
138 rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
139 rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
140 rustc_parse::DEFAULT_LOCALE_RESOURCE,
141 rustc_passes::DEFAULT_LOCALE_RESOURCE,
142 rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE,
143 rustc_privacy::DEFAULT_LOCALE_RESOURCE,
144 rustc_query_system::DEFAULT_LOCALE_RESOURCE,
145 rustc_resolve::DEFAULT_LOCALE_RESOURCE,
146 rustc_session::DEFAULT_LOCALE_RESOURCE,
147 rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
148 rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
149 ];
151
152pub const EXIT_SUCCESS: i32 = 0;
154
155pub const EXIT_FAILURE: i32 = 1;
157
158pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
159 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
160
161pub trait Callbacks {
162 fn config(&mut self, _config: &mut interface::Config) {}
164 fn after_crate_root_parsing(
168 &mut self,
169 _compiler: &interface::Compiler,
170 _krate: &mut ast::Crate,
171 ) -> Compilation {
172 Compilation::Continue
173 }
174 fn after_expansion<'tcx>(
177 &mut self,
178 _compiler: &interface::Compiler,
179 _tcx: TyCtxt<'tcx>,
180 ) -> Compilation {
181 Compilation::Continue
182 }
183 fn after_analysis<'tcx>(
186 &mut self,
187 _compiler: &interface::Compiler,
188 _tcx: TyCtxt<'tcx>,
189 ) -> Compilation {
190 Compilation::Continue
191 }
192}
193
194#[derive(#[automatically_derived]
impl ::core::default::Default for TimePassesCallbacks {
#[inline]
fn default() -> TimePassesCallbacks {
TimePassesCallbacks {
time_passes: ::core::default::Default::default(),
}
}
}Default)]
195pub struct TimePassesCallbacks {
196 time_passes: Option<TimePassesFormat>,
197}
198
199impl Callbacks for TimePassesCallbacks {
200 #[allow(rustc::bad_opt_access)]
202 fn config(&mut self, config: &mut interface::Config) {
203 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
207 .then_some(config.opts.unstable_opts.time_passes_format);
208 config.opts.trimmed_def_paths = true;
209 }
210}
211
212pub fn diagnostics_registry() -> Registry {
213 Registry::new(rustc_errors::codes::DIAGNOSTICS)
214}
215
216pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
218 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
219
220 let at_args = at_args.get(1..).unwrap_or_default();
229
230 let args = args::arg_expand_all(&default_early_dcx, at_args);
231
232 let (matches, help_only) = match handle_options(&default_early_dcx, &args) {
233 HandledOptions::None => return,
234 HandledOptions::Normal(matches) => (matches, false),
235 HandledOptions::HelpOnly(matches) => (matches, true),
236 };
237
238 let sopts = config::build_session_options(&mut default_early_dcx, &matches);
239 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 let early_exit = || {
286 sess.dcx().abort_if_errors();
287 };
288
289 if sess.opts.describe_lints {
293 describe_lints(sess, registered_lints);
294 return early_exit();
295 }
296
297 if help_only {
299 return early_exit();
300 }
301
302 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
303 return early_exit();
304 }
305
306 if !has_input {
307 sess.dcx().fatal("no input filename given"); }
309
310 if !sess.opts.unstable_opts.ls.is_empty() {
311 list_metadata(sess, &*codegen_backend.metadata_loader());
312 return early_exit();
313 }
314
315 if sess.opts.unstable_opts.link_only {
316 process_rlink(sess, compiler);
317 return early_exit();
318 }
319
320 let mut krate = passes::parse(sess);
323
324 if let Some(pp_mode) = sess.opts.pretty {
326 if pp_mode.needs_ast_map() {
327 create_and_enter_global_ctxt(compiler, krate, |tcx| {
328 tcx.ensure_ok().early_lint_checks(());
329 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
330 passes::write_dep_info(tcx);
331 });
332 } else {
333 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
334 }
335 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:335",
"rustc_driver_impl", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(335u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("finished pretty-printing")
as &dyn Value))])
});
} else { ; }
};trace!("finished pretty-printing");
336 return early_exit();
337 }
338
339 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
340 return early_exit();
341 }
342
343 if sess.opts.unstable_opts.parse_crate_root_only {
344 return early_exit();
345 }
346
347 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
348 let early_exit = || {
349 sess.dcx().abort_if_errors();
350 None
351 };
352
353 let _ = tcx.resolver_for_lowering();
355
356 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
357 return early_exit();
358 }
359
360 passes::write_dep_info(tcx);
361
362 passes::write_interface(tcx);
363
364 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
365 && sess.opts.output_types.len() == 1
366 {
367 return early_exit();
368 }
369
370 if sess.opts.unstable_opts.no_analysis {
371 return early_exit();
372 }
373
374 tcx.ensure_ok().analysis(());
375
376 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
377 dump_feature_usage_metrics(tcx, metrics_dir);
378 }
379
380 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
381 return early_exit();
382 }
383
384 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
385 if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
386 tcx.dcx().emit_fatal(CantEmitMIR { error });
387 }
388 }
389
390 Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
391 });
392
393 if let Some(linker) = linker {
396 linker.link(sess, codegen_backend);
397 }
398 })
399}
400
401fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
402 let hash = tcxt.crate_hash(LOCAL_CRATE);
403 let crate_name = tcxt.crate_name(LOCAL_CRATE);
404 let metrics_file_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unstable_feature_usage_metrics-{0}-{1}.json",
crate_name, hash))
})format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
405 let metrics_path = metrics_dir.join(metrics_file_name);
406 if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
407 tcxt.dcx().emit_err(UnstableFeatureUsage { error });
411 }
412}
413
414fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
416 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
417 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
418 "-" => OutFileName::Stdout,
419 path => OutFileName::Real(PathBuf::from(path)),
420 });
421 (odir, ofile)
422}
423
424fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
427 match free_matches {
428 [] => None, [ifile] if ifile == "-" => {
430 let mut input = String::new();
432 if io::stdin().read_to_string(&mut input).is_err() {
433 early_dcx
436 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
437 }
438
439 let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
440 Ok(path) => {
441 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
442 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
443 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
444 );
445 let line = line
446 .parse::<isize>()
447 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be a number");
448 FileName::doc_test_source_code(PathBuf::from(path), line)
449 }
450 Err(_) => FileName::anon_source_code(&input),
451 };
452
453 Some(Input::Str { name, input })
454 }
455 [ifile] => Some(Input::File(PathBuf::from(ifile))),
456 [ifile1, ifile2, ..] => early_dcx.early_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple input filenames provided (first two filenames are `{0}` and `{1}`)",
ifile1, ifile2))
})format!(
457 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
458 ifile1, ifile2
459 )),
460 }
461}
462
463#[derive(#[automatically_derived]
impl ::core::marker::Copy for Compilation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Compilation {
#[inline]
fn clone(&self) -> Compilation { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Compilation {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Compilation::Stop => "Stop",
Compilation::Continue => "Continue",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Compilation {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Compilation {
#[inline]
fn eq(&self, other: &Compilation) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
465pub enum Compilation {
466 Stop,
467 Continue,
468}
469
470fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
471 let upper_cased_code = code.to_ascii_uppercase();
473 if let Ok(code) = upper_cased_code.trim_prefix('E').parse::<u32>()
474 && code <= ErrCode::MAX_AS_U32
475 && let Ok(description) = registry.try_find_description(ErrCode::from_u32(code))
476 {
477 let mut is_in_code_block = false;
478 let mut text = String::new();
479 for line in description.lines() {
481 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
482 let dedented_line = &line[indent_level..];
483 if dedented_line.starts_with("```") {
484 is_in_code_block = !is_in_code_block;
485 text.push_str(&line[..(indent_level + 3)]);
486 } else if is_in_code_block && dedented_line.starts_with("# ") {
487 continue;
488 } else {
489 text.push_str(line);
490 }
491 text.push('\n');
492 }
493 if io::stdout().is_terminal() {
494 show_md_content_with_pager(&text, color);
495 } else {
496 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
497 }
498 } else {
499 early_dcx.early_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a valid error code",
code))
})format!("{code} is not a valid error code"));
500 }
501}
502
503fn show_md_content_with_pager(content: &str, color: ColorConfig) {
508 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
509 if falsecfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
510 });
511
512 let mut cmd = Command::new(&pager_name);
513 if pager_name == "less" {
514 cmd.arg("-R"); }
516
517 let pretty_on_pager = match color {
518 ColorConfig::Auto => {
519 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
521 }
522 ColorConfig::Always => true,
523 ColorConfig::Never => false,
524 };
525
526 let mut pretty_data = {
528 let mdstream = markdown::MdStream::parse_str(content);
529 let bufwtr = markdown::create_stdout_bufwtr();
530 let mut mdbuf = Vec::new();
531 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
532 Some((bufwtr, mdbuf))
533 } else {
534 None
535 }
536 };
537
538 let pager_res: Option<()> = try {
540 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
541
542 let pager_stdin = pager.stdin.as_mut()?;
543 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
544 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
545 } else {
546 pager_stdin.write_all(content.as_bytes()).ok()?;
547 };
548
549 pager.wait().ok()?;
550 };
551 if pager_res.is_some() {
552 return;
553 }
554
555 if let Some((bufwtr, mdbuf)) = &mut pretty_data
557 && bufwtr.write_all(&mdbuf).is_ok()
558 {
559 return;
560 }
561
562 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
564}
565
566fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
567 if !sess.opts.unstable_opts.link_only {
::core::panicking::panic("assertion failed: sess.opts.unstable_opts.link_only")
};assert!(sess.opts.unstable_opts.link_only);
568 let dcx = sess.dcx();
569 if let Input::File(file) = &sess.io.input {
570 let rlink_data = fs::read(file).unwrap_or_else(|err| {
571 dcx.emit_fatal(RlinkUnableToRead { err });
572 });
573 let (codegen_results, metadata, outputs) =
574 match CodegenResults::deserialize_rlink(sess, rlink_data) {
575 Ok((codegen, metadata, outputs)) => (codegen, metadata, outputs),
576 Err(err) => {
577 match err {
578 CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
579 CodegenErrors::EmptyVersionNumber => {
580 dcx.emit_fatal(RLinkEmptyVersionNumber)
581 }
582 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
583 dcx.emit_fatal(RLinkEncodingVersionMismatch {
584 version_array,
585 rlink_version,
586 })
587 }
588 CodegenErrors::RustcVersionMismatch { rustc_version } => {
589 dcx.emit_fatal(RLinkRustcVersionMismatch {
590 rustc_version,
591 current_version: sess.cfg_version,
592 })
593 }
594 CodegenErrors::CorruptFile => {
595 dcx.emit_fatal(RlinkCorruptFile { file });
596 }
597 };
598 }
599 };
600 compiler.codegen_backend.link(sess, codegen_results, metadata, &outputs);
601 } else {
602 dcx.emit_fatal(RlinkNotAFile {});
603 }
604}
605
606fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
607 match sess.io.input {
608 Input::File(ref path) => {
609 let mut v = Vec::new();
610 locator::list_file_metadata(
611 &sess.target,
612 path,
613 metadata_loader,
614 &mut v,
615 &sess.opts.unstable_opts.ls,
616 sess.cfg_version,
617 )
618 .unwrap();
619 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
620 }
621 Input::Str { .. } => {
622 sess.dcx().fatal("cannot list metadata for stdin");
623 }
624 }
625}
626
627fn print_crate_info(
628 codegen_backend: &dyn CodegenBackend,
629 sess: &Session,
630 parse_attrs: bool,
631) -> Compilation {
632 use rustc_session::config::PrintKind::*;
633 #[allow(unused_imports)]
637 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
638
639 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
642 return Compilation::Continue;
643 }
644
645 let attrs = if parse_attrs {
646 let result = parse_crate_attrs(sess);
647 match result {
648 Ok(attrs) => Some(attrs),
649 Err(parse_error) => {
650 parse_error.emit();
651 return Compilation::Stop;
652 }
653 }
654 } else {
655 None
656 };
657
658 for req in &sess.opts.prints {
659 let mut crate_info = String::new();
660 macro println_info($($arg:tt)*) {
661 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
662 }
663
664 match req.kind {
665 TargetList => {
666 let mut targets = rustc_target::spec::TARGETS.to_vec();
667 targets.sort_unstable();
668 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
669 }
670 HostTuple => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
rustc_session::config::host_tuple()))).unwrap()println_info!("{}", rustc_session::config::host_tuple()),
671 Sysroot => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", sess.opts.sysroot.path().display()))).unwrap()println_info!("{}", sess.opts.sysroot.path().display()),
672 TargetLibdir => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
sess.target_tlib_path.dir.display()))).unwrap()println_info!("{}", sess.target_tlib_path.dir.display()),
673 TargetSpecJson => {
674 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&sess.target.to_json()).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
675 }
676 TargetSpecJsonSchema => {
677 let schema = rustc_target::spec::json_schema();
678 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&schema).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&schema).unwrap());
679 }
680 AllTargetSpecsJson => {
681 let mut targets = BTreeMap::new();
682 for name in rustc_target::spec::TARGETS {
683 let triple = TargetTuple::from_tuple(name);
684 let target = Target::expect_builtin(&triple);
685 targets.insert(name, target.to_json());
686 }
687 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&targets).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
688 }
689 FileNames => {
690 let Some(attrs) = attrs.as_ref() else {
691 return Compilation::Continue;
693 };
694 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
695 let crate_name = passes::get_crate_name(sess, attrs);
696 let crate_types = collect_crate_types(
697 sess,
698 &codegen_backend.supported_crate_types(sess),
699 codegen_backend.name(),
700 attrs,
701 );
702 for &style in &crate_types {
703 let fname = rustc_session::output::filename_for_input(
704 sess, style, crate_name, &t_outputs,
705 );
706 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
fname.as_path().file_name().unwrap().to_string_lossy()))).unwrap();println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
707 }
708 }
709 CrateName => {
710 let Some(attrs) = attrs.as_ref() else {
711 return Compilation::Continue;
713 };
714 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
passes::get_crate_name(sess, attrs)))).unwrap();println_info!("{}", passes::get_crate_name(sess, attrs));
715 }
716 CrateRootLintLevels => {
717 let Some(attrs) = attrs.as_ref() else {
718 return Compilation::Continue;
720 };
721 let crate_name = passes::get_crate_name(sess, attrs);
722 let lint_store = crate::unerased_lint_store(sess);
723 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
724 let features = rustc_expand::config::features(sess, attrs, crate_name);
725 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
726 sess,
727 &features,
728 true,
729 lint_store,
730 ®istered_tools,
731 attrs,
732 );
733 for lint in lint_store.get_lints() {
734 if let Some(feature_symbol) = lint.feature_gate
735 && !features.enabled(feature_symbol)
736 {
737 continue;
739 }
740 let level = lint_levels.lint_level(lint).level;
741 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}", lint.name_lower(),
level.as_str()))).unwrap();println_info!("{}={}", lint.name_lower(), level.as_str());
742 }
743 }
744 Cfg => {
745 let mut cfgs = sess
746 .psess
747 .config
748 .iter()
749 .filter_map(|&(name, value)| {
750 if !sess.is_nightly_build()
752 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
753 {
754 return None;
755 }
756
757 if let Some(value) = value {
758 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
759 } else {
760 Some(name.to_string())
761 }
762 })
763 .collect::<Vec<String>>();
764
765 cfgs.sort();
766 for cfg in cfgs {
767 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
768 }
769 }
770 CheckCfg => {
771 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
772
773 #[allow(rustc::potential_query_instability)]
775 for (name, expected_values) in &sess.psess.check_config.expecteds {
776 use crate::config::ExpectedValues;
777 match expected_values {
778 ExpectedValues::Any => {
779 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
780 }
781 ExpectedValues::Some(values) => {
782 let mut values: Vec<_> = values
783 .iter()
784 .map(|value| {
785 if let Some(value) = value {
786 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
787 } else {
788 "none()".to_string()
789 }
790 })
791 .collect();
792
793 values.sort_unstable();
794
795 let values = values.join(", ");
796
797 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
798 }
799 }
800 }
801
802 check_cfgs.sort_unstable();
803 if !sess.psess.check_config.exhaustive_names
804 && sess.psess.check_config.exhaustive_values
805 {
806 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
807 }
808 for check_cfg in check_cfgs {
809 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
810 }
811 }
812 CallingConventions => {
813 let calling_conventions = rustc_abi::all_names();
814 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
815 }
816 BackendHasZstd => {
817 let has_zstd: bool = codegen_backend.has_zstd();
818 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
819 }
820 RelocationModels
821 | CodeModels
822 | TlsModels
823 | TargetCPUs
824 | StackProtectorStrategies
825 | TargetFeatures => {
826 codegen_backend.print(req, &mut crate_info, sess);
827 }
828 NativeStaticLibs => {}
830 LinkArgs => {}
831 SplitDebuginfo => {
832 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
833
834 for split in &[Off, Packed, Unpacked] {
835 if sess.target.options.supported_split_debuginfo.contains(split) {
836 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
837 }
838 }
839 }
840 DeploymentTarget => {
841 if sess.target.is_like_darwin {
842 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}",
rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
sess.apple_deployment_target().fmt_pretty()))).unwrap()println_info!(
843 "{}={}",
844 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
845 sess.apple_deployment_target().fmt_pretty(),
846 )
847 } else {
848 sess.dcx().fatal("only Apple targets currently support deployment version info")
849 }
850 }
851 SupportedCrateTypes => {
852 let supported_crate_types = CRATE_TYPES
853 .iter()
854 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
855 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
856 .map(|(crate_type_sym, _)| *crate_type_sym)
857 .collect::<BTreeSet<_>>();
858 for supported_crate_type in supported_crate_types {
859 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
860 }
861 }
862 }
863
864 req.out.overwrite(&crate_info, sess);
865 }
866 Compilation::Stop
867}
868
869pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
873 fn unw(x: Option<&str>) -> &str {
874 x.unwrap_or("unknown")
875 }
876 $crate::version_at_macro_invocation(
877 $early_dcx,
878 $binary,
879 $matches,
880 unw(option_env!("CFG_VERSION")),
881 unw(option_env!("CFG_VER_HASH")),
882 unw(option_env!("CFG_VER_DATE")),
883 unw(option_env!("CFG_RELEASE")),
884 )
885}
886
887#[doc(hidden)] pub fn version_at_macro_invocation(
889 early_dcx: &EarlyDiagCtxt,
890 binary: &str,
891 matches: &getopts::Matches,
892 version: &str,
893 commit_hash: &str,
894 commit_date: &str,
895 release: &str,
896) {
897 let verbose = matches.opt_present("verbose");
898
899 let mut version = version;
900 let mut release = release;
901 let tmp;
902 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
903 tmp = force_version;
904 version = &tmp;
905 release = &tmp;
906 }
907
908 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
909
910 if verbose {
911 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
912 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
913 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
914 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
915 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
916
917 get_backend_from_raw_matches(early_dcx, matches).print_version();
918 }
919}
920
921fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
922 let mut options = getopts::Options::new();
923 for option in config::rustc_optgroups()
924 .iter()
925 .filter(|x| verbose || !x.is_verbose_help_only)
926 .filter(|x| include_unstable_options || x.is_stable())
927 {
928 option.apply(&mut options);
929 }
930 let message = "Usage: rustc [OPTIONS] INPUT";
931 let nightly_help = if nightly_build {
932 "\n -Z help Print unstable compiler options"
933 } else {
934 ""
935 };
936 let verbose_help = if verbose {
937 ""
938 } else {
939 "\n --help -v Print the full set of options rustc accepts"
940 };
941 let at_path = if verbose {
942 " @path Read newline separated options from `path`\n"
943 } else {
944 ""
945 };
946 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}{1}\nAdditional help:\n -C help Print codegen options\n -W help Print \'lint\' options and default settings{2}{3}\n",
options.usage(message), at_path, nightly_help,
verbose_help)));
};safe_println!(
947 "{options}{at_path}\nAdditional help:
948 -C help Print codegen options
949 -W help \
950 Print 'lint' options and default settings{nightly}{verbose}\n",
951 options = options.usage(message),
952 at_path = at_path,
953 nightly = nightly_help,
954 verbose = verbose_help
955 );
956}
957
958fn print_wall_help() {
959 {
crate::print::print(format_args!("{0}\n",
format_args!("\nThe flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by\ndefault. Use `rustc -W help` to see all available lints. It\'s more common to put\nwarning settings in the crate root using `#![warn(LINT_NAME)]` instead of using\nthe command line flag directly.\n")));
};safe_println!(
960 "
961The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
962default. Use `rustc -W help` to see all available lints. It's more common to put
963warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
964the command line flag directly.
965"
966 );
967}
968
969pub fn describe_lints(sess: &Session, registered_lints: bool) {
971 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable lint options:\n -W <foo> Warn about <foo>\n -A <foo> Allow <foo>\n -D <foo> Deny <foo>\n -F <foo> Forbid <foo> (deny <foo> and all attempts to override)\n\n")));
};safe_println!(
972 "
973Available lint options:
974 -W <foo> Warn about <foo>
975 -A <foo> Allow <foo>
976 -D <foo> Deny <foo>
977 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
978
979"
980 );
981
982 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
983 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
985 lints
986 }
987
988 fn sort_lint_groups(
989 lints: Vec<(&'static str, Vec<LintId>, bool)>,
990 ) -> Vec<(&'static str, Vec<LintId>)> {
991 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
992 lints.sort_by_key(|l| l.0);
993 lints
994 }
995
996 let lint_store = unerased_lint_store(sess);
997 let (loaded, builtin): (Vec<_>, _) =
998 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
999 let loaded = sort_lints(sess, loaded);
1000 let builtin = sort_lints(sess, builtin);
1001
1002 let (loaded_groups, builtin_groups): (Vec<_>, _) =
1003 lint_store.get_lint_groups().partition(|&(.., p)| p);
1004 let loaded_groups = sort_lint_groups(loaded_groups);
1005 let builtin_groups = sort_lint_groups(builtin_groups);
1006
1007 let max_name_len =
1008 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
1009 let padded = |x: &str| {
1010 let mut s = " ".repeat(max_name_len - x.chars().count());
1011 s.push_str(x);
1012 s
1013 };
1014
1015 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1016
1017 let print_lints = |lints: Vec<&Lint>| {
1018 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("name"), "default",
"meaning")));
};safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1019 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1020 for lint in lints {
1021 let name = lint.name_lower().replace('_', "-");
1022 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded(&name),
lint.default_level(sess.edition()).as_str(), lint.desc)));
};safe_println!(
1023 " {} {:7.7} {}",
1024 padded(&name),
1025 lint.default_level(sess.edition()).as_str(),
1026 lint.desc
1027 );
1028 }
1029 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1030 };
1031
1032 print_lints(builtin);
1033
1034 let max_name_len = max(
1035 "warnings".len(),
1036 loaded_groups
1037 .iter()
1038 .chain(&builtin_groups)
1039 .map(|&(s, _)| s.chars().count())
1040 .max()
1041 .unwrap_or(0),
1042 );
1043
1044 let padded = |x: &str| {
1045 let mut s = " ".repeat(max_name_len - x.chars().count());
1046 s.push_str(x);
1047 s
1048 };
1049
1050 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1051
1052 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1053 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1054 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1055
1056 if all_warnings {
1057 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} all lints that are set to issue warnings",
padded("warnings"))));
};safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1058 }
1059
1060 for (name, to) in lints {
1061 let name = name.to_lowercase().replace('_', "-");
1062 let desc = to
1063 .into_iter()
1064 .map(|x| x.to_string().replace('_', "-"))
1065 .collect::<Vec<String>>()
1066 .join(", ");
1067 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1068 }
1069 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1070 };
1071
1072 print_lint_groups(builtin_groups, true);
1073
1074 match (registered_lints, loaded.len(), loaded_groups.len()) {
1075 (false, 0, _) | (false, _, 0) => {
1076 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint tools like Clippy can load additional lints and lint groups.")));
};safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1077 }
1078 (false, ..) => {
::core::panicking::panic_fmt(format_args!("didn\'t load additional lints but got them anyway!"));
}panic!("didn't load additional lints but got them anyway!"),
1079 (true, 0, 0) => {
1080 {
crate::print::print(format_args!("{0}\n",
format_args!("This crate does not load any additional lints or lint groups.")));
}safe_println!("This crate does not load any additional lints or lint groups.")
1081 }
1082 (true, l, g) => {
1083 if l > 0 {
1084 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks loaded by this crate:\n")));
};safe_println!("Lint checks loaded by this crate:\n");
1085 print_lints(loaded);
1086 }
1087 if g > 0 {
1088 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups loaded by this crate:\n")));
};safe_println!("Lint groups loaded by this crate:\n");
1089 print_lint_groups(loaded_groups, false);
1090 }
1091 }
1092 }
1093}
1094
1095pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1099 let wall = matches.opt_strs("W");
1101 if wall.iter().any(|x| *x == "all") {
1102 print_wall_help();
1103 return true;
1104 }
1105
1106 let debug_flags = matches.opt_strs("Z");
1108 if debug_flags.iter().any(|x| *x == "help") {
1109 describe_unstable_flags();
1110 return true;
1111 }
1112
1113 let cg_flags = matches.opt_strs("C");
1114 if cg_flags.iter().any(|x| *x == "help") {
1115 describe_codegen_flags();
1116 return true;
1117 }
1118
1119 if cg_flags.iter().any(|x| *x == "passes=list") {
1120 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1121 return true;
1122 }
1123
1124 false
1125}
1126
1127fn get_backend_from_raw_matches(
1134 early_dcx: &EarlyDiagCtxt,
1135 matches: &Matches,
1136) -> Box<dyn CodegenBackend> {
1137 let debug_flags = matches.opt_strs("Z");
1138 let backend_name = debug_flags
1139 .iter()
1140 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1141 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1142 let target = parse_target_triple(early_dcx, matches);
1143 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1144 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1145
1146 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1147}
1148
1149fn describe_unstable_flags() {
1150 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1151 print_flag_list("-Z", config::Z_OPTIONS);
1152}
1153
1154fn describe_codegen_flags() {
1155 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1156 print_flag_list("-C", config::CG_OPTIONS);
1157}
1158
1159fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1160 let max_len =
1161 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1162
1163 for opt_desc in flag_list {
1164 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:>3$}=val -- {2}", cmdline_opt,
opt_desc.name().replace('_', "-"), opt_desc.desc(),
max_len)));
};safe_println!(
1165 " {} {:>width$}=val -- {}",
1166 cmdline_opt,
1167 opt_desc.name().replace('_', "-"),
1168 opt_desc.desc(),
1169 width = max_len
1170 );
1171 }
1172}
1173
1174pub enum HandledOptions {
1175 None,
1177 Normal(getopts::Matches),
1179 HelpOnly(getopts::Matches),
1182}
1183
1184pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1212 let mut options = getopts::Options::new();
1215 let optgroups = config::rustc_optgroups();
1216 for option in &optgroups {
1217 option.apply(&mut options);
1218 }
1219 let matches = options.parse(args).unwrap_or_else(|e| {
1220 let msg: Option<String> = match e {
1221 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1222 .iter()
1223 .map(|opt_desc| ('C', opt_desc.name()))
1224 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1225 .find(|&(_, name)| *opt == name.replace('_', "-"))
1226 .map(|(flag, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}. Did you mean `-{1} {2}`?", e,
flag, opt))
})format!("{e}. Did you mean `-{flag} {opt}`?")),
1227 getopts::Fail::ArgumentMissing(ref opt) => {
1228 optgroups.iter().find(|option| option.name == opt).map(|option| {
1229 let mut options = getopts::Options::new();
1231 option.apply(&mut options);
1232 options.usage_with_format(|it| {
1235 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1236 })
1237 })
1238 }
1239 _ => None,
1240 };
1241 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1242 });
1243
1244 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1256
1257 let wall = matches.opt_strs("W");
1259 if wall.iter().any(|x| *x == "all") {
1260 print_wall_help();
1261 return HandledOptions::None;
1262 }
1263
1264 if handle_help(&matches, args) {
1265 return HandledOptions::HelpOnly(matches);
1266 }
1267
1268 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1269 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1270 return HandledOptions::None;
1271 }
1272
1273 if matches.opt_present("version") {
1274 fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
crate::version_at_macro_invocation(early_dcx, "rustc", &matches,
unw(::core::option::Option::Some("1.95.0-nightly (eda76d9d1 2026-01-21)")),
unw(::core::option::Option::Some("eda76d9d1d133effbf7facb28168fd78d75fd434")),
unw(::core::option::Option::Some("2026-01-21")),
unw(::core::option::Option::Some("1.95.0-nightly")));version!(early_dcx, "rustc", &matches);
1275 return HandledOptions::None;
1276 }
1277
1278 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1279
1280 HandledOptions::Normal(matches)
1281}
1282
1283pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1290 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1291 let opt_help_pos = |opt| {
1292 matches
1293 .opt_strs_pos(opt)
1294 .iter()
1295 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1296 .next()
1297 };
1298 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1299 let zhelp_pos = opt_help_pos("Z");
1300 let chelp_pos = opt_help_pos("C");
1301 let print_help = || {
1302 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1304 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1305 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1306 };
1307
1308 let mut helps = [
1309 (help_pos, &print_help as &dyn Fn()),
1310 (zhelp_pos, &describe_unstable_flags),
1311 (chelp_pos, &describe_codegen_flags),
1312 ];
1313 helps.sort_by_key(|(pos, _)| pos.clone());
1314 let mut printed_any = false;
1315 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1316 printer();
1317 printed_any = true;
1318 }
1319 printed_any
1320}
1321
1322fn warn_on_confusing_output_filename_flag(
1326 early_dcx: &EarlyDiagCtxt,
1327 matches: &getopts::Matches,
1328 args: &[String],
1329) {
1330 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1331 let s1 = s1.replace('-', "_");
1332 let s2 = s2.replace('-', "_");
1333 s1 == s2
1334 }
1335
1336 if let Some(name) = matches.opt_str("o")
1337 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1338 {
1339 let filename = suspect.trim_prefix("-");
1340 let optgroups = config::rustc_optgroups();
1341 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1342
1343 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1350 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1351 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1352 {
1353 early_dcx.early_warn(
1354 "option `-o` has no space between flag name and value, which can be confusing",
1355 );
1356 early_dcx.early_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("output filename `-o {0}` is applied instead of a flag named `o{0}`",
name))
})format!(
1357 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1358 ));
1359 early_dcx.early_help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("insert a space between `-o` and `{0}` if this is intentional: `-o {0}`",
name))
})format!(
1360 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1361 ));
1362 }
1363 }
1364}
1365
1366fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1367 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1368 Input::File(file) => {
1369 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1370 }
1371 Input::Str { name, input } => new_parser_from_source_str(
1372 &sess.psess,
1373 name.clone(),
1374 input.clone(),
1375 StripTokens::ShebangAndFrontmatter,
1376 ),
1377 });
1378 parser.parse_inner_attributes()
1379}
1380
1381pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1384 match catch_fatal_errors(f) {
1385 Ok(()) => EXIT_SUCCESS,
1386 _ => EXIT_FAILURE,
1387 }
1388}
1389
1390static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1391
1392fn ice_path() -> &'static Option<PathBuf> {
1400 ice_path_with_config(None)
1401}
1402
1403fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1404 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1405 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1405",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1405u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ICE_PATH has already been initialized -- files may be emitted at unintended paths")
as &dyn Value))])
});
} else { ; }
}tracing::warn!(
1406 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1407 )
1408 }
1409
1410 ICE_PATH.get_or_init(|| {
1411 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1412 return None;
1413 }
1414 let mut path = match std::env::var_os("RUSTC_ICE") {
1415 Some(s) => {
1416 if s == "0" {
1417 return None;
1419 }
1420 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1421 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1421",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1421u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files")
as &dyn Value))])
});
} else { ; }
};tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1422 }
1423 PathBuf::from(s)
1424 }
1425 None => config
1426 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1427 .or_else(|| std::env::current_dir().ok())
1428 .unwrap_or_default(),
1429 };
1430 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1432 let pid = std::process::id();
1433 path.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc-ice-{0}-{1}.txt", file_now,
pid))
})format!("rustc-ice-{file_now}-{pid}.txt"));
1434 Some(path)
1435 })
1436}
1437
1438pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1439
1440pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1452 if env::var_os("RUST_BACKTRACE").is_none() {
1459 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1461 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1462 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1463 } else {
1464 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1465 }
1466 }
1467
1468 panic::update_hook(Box::new(
1469 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1470 info: &PanicHookInfo<'_>| {
1471 let _guard = io::stderr().lock();
1473 #[cfg(windows)]
1476 if let Some(msg) = info.payload().downcast_ref::<String>() {
1477 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1478 {
1479 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1481 let _ = early_dcx.early_err(msg.clone());
1482 return;
1483 }
1484 };
1485
1486 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1489 default_hook(info);
1490 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1492
1493 if let Some(ice_path) = ice_path()
1494 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1495 {
1496 let location = info.location().unwrap();
1498 let msg = match info.payload().downcast_ref::<&'static str>() {
1499 Some(s) => *s,
1500 None => match info.payload().downcast_ref::<String>() {
1501 Some(s) => &s[..],
1502 None => "Box<dyn Any>",
1503 },
1504 };
1505 let thread = std::thread::current();
1506 let name = thread.name().unwrap_or("<unnamed>");
1507 let _ = (&mut out).write_fmt(format_args!("thread \'{1}\' panicked at {2}:\n{3}\nstack backtrace:\n{0:#}",
std::backtrace::Backtrace::force_capture(), name, location, msg))write!(
1508 &mut out,
1509 "thread '{name}' panicked at {location}:\n\
1510 {msg}\n\
1511 stack backtrace:\n\
1512 {:#}",
1513 std::backtrace::Backtrace::force_capture()
1514 );
1515 }
1516 }
1517
1518 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1520 },
1521 ));
1522}
1523
1524fn report_ice(
1531 info: &panic::PanicHookInfo<'_>,
1532 bug_report_url: &str,
1533 extra_info: fn(&DiagCtxt),
1534 using_internal_features: &AtomicBool,
1535) {
1536 let translator = default_translator();
1537 let emitter =
1538 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1539 stderr_destination(rustc_errors::ColorConfig::Auto),
1540 translator,
1541 ));
1542 let dcx = rustc_errors::DiagCtxt::new(emitter);
1543 let dcx = dcx.handle();
1544
1545 if !info.payload().is::<rustc_errors::ExplicitBug>()
1548 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1549 {
1550 dcx.emit_err(session_diagnostics::Ice);
1551 }
1552
1553 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1554 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1555 } else {
1556 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1557
1558 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1560 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1561 }
1562 }
1563
1564 let version = ::core::option::Option::Some("1.95.0-nightly (eda76d9d1 2026-01-21)")util::version_str!().unwrap_or("unknown_version");
1565 let tuple = config::host_tuple();
1566
1567 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1568
1569 let file = if let Some(path) = ice_path() {
1570 match crate::fs::File::options().create(true).append(true).open(path) {
1572 Ok(mut file) => {
1573 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1574 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1575 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1576 }
1577 Some(file)
1578 }
1579 Err(err) => {
1580 dcx.emit_warn(session_diagnostics::IcePathError {
1582 path: path.clone(),
1583 error: err.to_string(),
1584 env_var: std::env::var_os("RUSTC_ICE")
1585 .map(PathBuf::from)
1586 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1587 });
1588 None
1589 }
1590 }
1591 } else {
1592 None
1593 };
1594
1595 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1596
1597 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1598 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1599 if excluded_cargo_defaults {
1600 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1601 }
1602 }
1603
1604 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1606
1607 let limit_frames = if backtrace { None } else { Some(2) };
1608
1609 interface::try_print_query_stack(dcx, limit_frames, file);
1610
1611 extra_info(&dcx);
1614
1615 #[cfg(windows)]
1616 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1617 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1619 }
1620}
1621
1622pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1625 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1626}
1627
1628pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1632 if let Err(error) = rustc_log::init_logger(cfg) {
1633 early_dcx.early_fatal(error.to_string());
1634 }
1635}
1636
1637pub fn init_logger_with_additional_layer<F, T>(
1643 early_dcx: &EarlyDiagCtxt,
1644 cfg: rustc_log::LoggerConfig,
1645 build_subscriber: F,
1646) where
1647 F: FnOnce() -> T,
1648 T: rustc_log::BuildSubscriberRet,
1649{
1650 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1651 early_dcx.early_fatal(error.to_string());
1652 }
1653}
1654
1655pub fn install_ctrlc_handler() {
1658 #[cfg(all(not(miri), not(target_family = "wasm")))]
1659 ctrlc::set_handler(move || {
1660 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1665 std::thread::sleep(std::time::Duration::from_millis(100));
1666 std::process::exit(1);
1667 })
1668 .expect("Unable to install ctrlc handler");
1669}
1670
1671pub fn main() -> ! {
1672 let start_time = Instant::now();
1673 let start_rss = get_resident_set_size();
1674
1675 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1676
1677 init_rustc_env_logger(&early_dcx);
1678 signal_handler::install();
1679 let mut callbacks = TimePassesCallbacks::default();
1680 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1681 install_ctrlc_handler();
1682
1683 let exit_code =
1684 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1685
1686 if let Some(format) = callbacks.time_passes {
1687 let end_rss = get_resident_set_size();
1688 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1689 }
1690
1691 process::exit(exit_code)
1692}