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
109rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
110
111pub fn default_translator() -> Translator {
112 Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
113}
114
115pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
116 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(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 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 = 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(format!(
450 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
451 ifile1, ifile2
452 )),
453 }
454}
455
456#[derive(Copy, Clone, Debug, Eq, PartialEq)]
458pub enum Compilation {
459 Stop,
460 Continue,
461}
462
463fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
464 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 safe_print!("{text}");
490 }
491 } else {
492 early_dcx.early_fatal(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 cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
503 });
504
505 let mut cmd = Command::new(&pager_name);
506 if pager_name == "less" {
507 cmd.arg("-R"); }
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 safe_print!("{content}");
553}
554
555fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
556 assert!(sess.opts.unstable_opts.link_only);
557 let dcx = sess.dcx();
558 if let Input::File(file) = &sess.io.input {
559 let rlink_data = fs::read(file).unwrap_or_else(|err| {
560 dcx.emit_fatal(RlinkUnableToRead { err });
561 });
562 let (codegen_results, metadata, outputs) =
563 match CodegenResults::deserialize_rlink(sess, rlink_data) {
564 Ok((codegen, metadata, outputs)) => (codegen, metadata, outputs),
565 Err(err) => {
566 match err {
567 CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
568 CodegenErrors::EmptyVersionNumber => {
569 dcx.emit_fatal(RLinkEmptyVersionNumber)
570 }
571 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
572 dcx.emit_fatal(RLinkEncodingVersionMismatch {
573 version_array,
574 rlink_version,
575 })
576 }
577 CodegenErrors::RustcVersionMismatch { rustc_version } => {
578 dcx.emit_fatal(RLinkRustcVersionMismatch {
579 rustc_version,
580 current_version: sess.cfg_version,
581 })
582 }
583 CodegenErrors::CorruptFile => {
584 dcx.emit_fatal(RlinkCorruptFile { file });
585 }
586 };
587 }
588 };
589 compiler.codegen_backend.link(sess, codegen_results, metadata, &outputs);
590 } else {
591 dcx.emit_fatal(RlinkNotAFile {});
592 }
593}
594
595fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
596 match sess.io.input {
597 Input::File(ref path) => {
598 let mut v = Vec::new();
599 locator::list_file_metadata(
600 &sess.target,
601 path,
602 metadata_loader,
603 &mut v,
604 &sess.opts.unstable_opts.ls,
605 sess.cfg_version,
606 )
607 .unwrap();
608 safe_println!("{}", String::from_utf8(v).unwrap());
609 }
610 Input::Str { .. } => {
611 #[allow(rustc::diagnostic_outside_of_impl)]
612 sess.dcx().fatal("cannot list metadata for stdin");
613 }
614 }
615}
616
617fn print_crate_info(
618 codegen_backend: &dyn CodegenBackend,
619 sess: &Session,
620 parse_attrs: bool,
621) -> Compilation {
622 use rustc_session::config::PrintKind::*;
623 #[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 println_info!("{}", targets.join("\n"));
659 }
660 HostTuple => println_info!("{}", rustc_session::config::host_tuple()),
661 Sysroot => println_info!("{}", sess.opts.sysroot.path().display()),
662 TargetLibdir => println_info!("{}", sess.target_tlib_path.dir.display()),
663 TargetSpecJson => {
664 println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
665 }
666 TargetSpecJsonSchema => {
667 let schema = rustc_target::spec::json_schema();
668 println_info!("{}", serde_json::to_string_pretty(&schema).unwrap());
669 }
670 AllTargetSpecsJson => {
671 let mut targets = BTreeMap::new();
672 for name in rustc_target::spec::TARGETS {
673 let triple = TargetTuple::from_tuple(name);
674 let target = Target::expect_builtin(&triple);
675 targets.insert(name, target.to_json());
676 }
677 println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
678 }
679 FileNames => {
680 let Some(attrs) = attrs.as_ref() else {
681 return Compilation::Continue;
683 };
684 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
685 let crate_name = passes::get_crate_name(sess, attrs);
686 let crate_types = collect_crate_types(
687 sess,
688 &codegen_backend.supported_crate_types(sess),
689 codegen_backend.name(),
690 attrs,
691 );
692 for &style in &crate_types {
693 let fname = rustc_session::output::filename_for_input(
694 sess, style, crate_name, &t_outputs,
695 );
696 println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
697 }
698 }
699 CrateName => {
700 let Some(attrs) = attrs.as_ref() else {
701 return Compilation::Continue;
703 };
704 println_info!("{}", passes::get_crate_name(sess, attrs));
705 }
706 CrateRootLintLevels => {
707 let Some(attrs) = attrs.as_ref() else {
708 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 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(format!("{name}=\"{value}\""))
749 } else {
750 Some(name.to_string())
751 }
752 })
753 .collect::<Vec<String>>();
754
755 cfgs.sort();
756 for cfg in cfgs {
757 println_info!("{cfg}");
758 }
759 }
760 CheckCfg => {
761 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
762
763 #[allow(rustc::potential_query_instability)]
765 for (name, expected_values) in &sess.psess.check_config.expecteds {
766 use crate::config::ExpectedValues;
767 match expected_values {
768 ExpectedValues::Any => check_cfgs.push(format!("{name}=any()")),
769 ExpectedValues::Some(values) => {
770 if !values.is_empty() {
771 check_cfgs.extend(values.iter().map(|value| {
772 if let Some(value) = value {
773 format!("{name}=\"{value}\"")
774 } else {
775 name.to_string()
776 }
777 }))
778 } else {
779 check_cfgs.push(format!("{name}="))
780 }
781 }
782 }
783 }
784
785 check_cfgs.sort_unstable();
786 if !sess.psess.check_config.exhaustive_names {
787 if !sess.psess.check_config.exhaustive_values {
788 println_info!("any()=any()");
789 } else {
790 println_info!("any()");
791 }
792 }
793 for check_cfg in check_cfgs {
794 println_info!("{check_cfg}");
795 }
796 }
797 CallingConventions => {
798 let calling_conventions = rustc_abi::all_names();
799 println_info!("{}", calling_conventions.join("\n"));
800 }
801 RelocationModels
802 | BackendHasZstd
803 | CodeModels
804 | TlsModels
805 | TargetCPUs
806 | StackProtectorStrategies
807 | TargetFeatures => {
808 codegen_backend.print(req, &mut crate_info, sess);
809 }
810 NativeStaticLibs => {}
812 LinkArgs => {}
813 SplitDebuginfo => {
814 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
815
816 for split in &[Off, Packed, Unpacked] {
817 if sess.target.options.supported_split_debuginfo.contains(split) {
818 println_info!("{split}");
819 }
820 }
821 }
822 DeploymentTarget => {
823 if sess.target.is_like_darwin {
824 println_info!(
825 "{}={}",
826 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
827 sess.apple_deployment_target().fmt_pretty(),
828 )
829 } else {
830 #[allow(rustc::diagnostic_outside_of_impl)]
831 sess.dcx().fatal("only Apple targets currently support deployment version info")
832 }
833 }
834 SupportedCrateTypes => {
835 let supported_crate_types = CRATE_TYPES
836 .iter()
837 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
838 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
839 .map(|(crate_type_sym, _)| *crate_type_sym)
840 .collect::<BTreeSet<_>>();
841 for supported_crate_type in supported_crate_types {
842 println_info!("{}", supported_crate_type.as_str());
843 }
844 }
845 }
846
847 req.out.overwrite(&crate_info, sess);
848 }
849 Compilation::Stop
850}
851
852pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
856 fn unw(x: Option<&str>) -> &str {
857 x.unwrap_or("unknown")
858 }
859 $crate::version_at_macro_invocation(
860 $early_dcx,
861 $binary,
862 $matches,
863 unw(option_env!("CFG_VERSION")),
864 unw(option_env!("CFG_VER_HASH")),
865 unw(option_env!("CFG_VER_DATE")),
866 unw(option_env!("CFG_RELEASE")),
867 )
868}
869
870#[doc(hidden)] pub fn version_at_macro_invocation(
872 early_dcx: &EarlyDiagCtxt,
873 binary: &str,
874 matches: &getopts::Matches,
875 version: &str,
876 commit_hash: &str,
877 commit_date: &str,
878 release: &str,
879) {
880 let verbose = matches.opt_present("verbose");
881
882 let mut version = version;
883 let mut release = release;
884 let tmp;
885 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
886 tmp = force_version;
887 version = &tmp;
888 release = &tmp;
889 }
890
891 safe_println!("{binary} {version}");
892
893 if verbose {
894 safe_println!("binary: {binary}");
895 safe_println!("commit-hash: {commit_hash}");
896 safe_println!("commit-date: {commit_date}");
897 safe_println!("host: {}", config::host_tuple());
898 safe_println!("release: {release}");
899
900 get_backend_from_raw_matches(early_dcx, matches).print_version();
901 }
902}
903
904fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
905 let mut options = getopts::Options::new();
906 for option in config::rustc_optgroups()
907 .iter()
908 .filter(|x| verbose || !x.is_verbose_help_only)
909 .filter(|x| include_unstable_options || x.is_stable())
910 {
911 option.apply(&mut options);
912 }
913 let message = "Usage: rustc [OPTIONS] INPUT";
914 let nightly_help = if nightly_build {
915 "\n -Z help Print unstable compiler options"
916 } else {
917 ""
918 };
919 let verbose_help = if verbose {
920 ""
921 } else {
922 "\n --help -v Print the full set of options rustc accepts"
923 };
924 let at_path = if verbose {
925 " @path Read newline separated options from `path`\n"
926 } else {
927 ""
928 };
929 safe_println!(
930 "{options}{at_path}\nAdditional help:
931 -C help Print codegen options
932 -W help \
933 Print 'lint' options and default settings{nightly}{verbose}\n",
934 options = options.usage(message),
935 at_path = at_path,
936 nightly = nightly_help,
937 verbose = verbose_help
938 );
939}
940
941fn print_wall_help() {
942 safe_println!(
943 "
944The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
945default. Use `rustc -W help` to see all available lints. It's more common to put
946warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
947the command line flag directly.
948"
949 );
950}
951
952pub fn describe_lints(sess: &Session, registered_lints: bool) {
954 safe_println!(
955 "
956Available lint options:
957 -W <foo> Warn about <foo>
958 -A <foo> Allow <foo>
959 -D <foo> Deny <foo>
960 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
961
962"
963 );
964
965 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
966 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
968 lints
969 }
970
971 fn sort_lint_groups(
972 lints: Vec<(&'static str, Vec<LintId>, bool)>,
973 ) -> Vec<(&'static str, Vec<LintId>)> {
974 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
975 lints.sort_by_key(|l| l.0);
976 lints
977 }
978
979 let lint_store = unerased_lint_store(sess);
980 let (loaded, builtin): (Vec<_>, _) =
981 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
982 let loaded = sort_lints(sess, loaded);
983 let builtin = sort_lints(sess, builtin);
984
985 let (loaded_groups, builtin_groups): (Vec<_>, _) =
986 lint_store.get_lint_groups().partition(|&(.., p)| p);
987 let loaded_groups = sort_lint_groups(loaded_groups);
988 let builtin_groups = sort_lint_groups(builtin_groups);
989
990 let max_name_len =
991 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
992 let padded = |x: &str| {
993 let mut s = " ".repeat(max_name_len - x.chars().count());
994 s.push_str(x);
995 s
996 };
997
998 safe_println!("Lint checks provided by rustc:\n");
999
1000 let print_lints = |lints: Vec<&Lint>| {
1001 safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1002 safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1003 for lint in lints {
1004 let name = lint.name_lower().replace('_', "-");
1005 safe_println!(
1006 " {} {:7.7} {}",
1007 padded(&name),
1008 lint.default_level(sess.edition()).as_str(),
1009 lint.desc
1010 );
1011 }
1012 safe_println!("\n");
1013 };
1014
1015 print_lints(builtin);
1016
1017 let max_name_len = max(
1018 "warnings".len(),
1019 loaded_groups
1020 .iter()
1021 .chain(&builtin_groups)
1022 .map(|&(s, _)| s.chars().count())
1023 .max()
1024 .unwrap_or(0),
1025 );
1026
1027 let padded = |x: &str| {
1028 let mut s = " ".repeat(max_name_len - x.chars().count());
1029 s.push_str(x);
1030 s
1031 };
1032
1033 safe_println!("Lint groups provided by rustc:\n");
1034
1035 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1036 safe_println!(" {} sub-lints", padded("name"));
1037 safe_println!(" {} ---------", padded("----"));
1038
1039 if all_warnings {
1040 safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1041 }
1042
1043 for (name, to) in lints {
1044 let name = name.to_lowercase().replace('_', "-");
1045 let desc = to
1046 .into_iter()
1047 .map(|x| x.to_string().replace('_', "-"))
1048 .collect::<Vec<String>>()
1049 .join(", ");
1050 safe_println!(" {} {}", padded(&name), desc);
1051 }
1052 safe_println!("\n");
1053 };
1054
1055 print_lint_groups(builtin_groups, true);
1056
1057 match (registered_lints, loaded.len(), loaded_groups.len()) {
1058 (false, 0, _) | (false, _, 0) => {
1059 safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1060 }
1061 (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1062 (true, 0, 0) => {
1063 safe_println!("This crate does not load any additional lints or lint groups.")
1064 }
1065 (true, l, g) => {
1066 if l > 0 {
1067 safe_println!("Lint checks loaded by this crate:\n");
1068 print_lints(loaded);
1069 }
1070 if g > 0 {
1071 safe_println!("Lint groups loaded by this crate:\n");
1072 print_lint_groups(loaded_groups, false);
1073 }
1074 }
1075 }
1076}
1077
1078pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1082 let wall = matches.opt_strs("W");
1084 if wall.iter().any(|x| *x == "all") {
1085 print_wall_help();
1086 return true;
1087 }
1088
1089 let debug_flags = matches.opt_strs("Z");
1091 if debug_flags.iter().any(|x| *x == "help") {
1092 describe_debug_flags();
1093 return true;
1094 }
1095
1096 let cg_flags = matches.opt_strs("C");
1097 if cg_flags.iter().any(|x| *x == "help") {
1098 describe_codegen_flags();
1099 return true;
1100 }
1101
1102 if cg_flags.iter().any(|x| *x == "passes=list") {
1103 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1104 return true;
1105 }
1106
1107 false
1108}
1109
1110fn get_backend_from_raw_matches(
1117 early_dcx: &EarlyDiagCtxt,
1118 matches: &Matches,
1119) -> Box<dyn CodegenBackend> {
1120 let debug_flags = matches.opt_strs("Z");
1121 let backend_name = debug_flags
1122 .iter()
1123 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1124 let target = parse_target_triple(early_dcx, matches);
1125 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1126 let target = config::build_target_config(early_dcx, &target, sysroot.path());
1127
1128 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1129}
1130
1131fn describe_debug_flags() {
1132 safe_println!("\nAvailable options:\n");
1133 print_flag_list("-Z", config::Z_OPTIONS);
1134}
1135
1136fn describe_codegen_flags() {
1137 safe_println!("\nAvailable codegen options:\n");
1138 print_flag_list("-C", config::CG_OPTIONS);
1139}
1140
1141fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1142 let max_len =
1143 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1144
1145 for opt_desc in flag_list {
1146 safe_println!(
1147 " {} {:>width$}=val -- {}",
1148 cmdline_opt,
1149 opt_desc.name().replace('_', "-"),
1150 opt_desc.desc(),
1151 width = max_len
1152 );
1153 }
1154}
1155
1156pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1184 let mut options = getopts::Options::new();
1187 let optgroups = config::rustc_optgroups();
1188 for option in &optgroups {
1189 option.apply(&mut options);
1190 }
1191 let matches = options.parse(args).unwrap_or_else(|e| {
1192 let msg: Option<String> = match e {
1193 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1194 .iter()
1195 .map(|opt_desc| ('C', opt_desc.name()))
1196 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1197 .find(|&(_, name)| *opt == name.replace('_', "-"))
1198 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1199 getopts::Fail::ArgumentMissing(ref opt) => {
1200 optgroups.iter().find(|option| option.name == opt).map(|option| {
1201 let mut options = getopts::Options::new();
1203 option.apply(&mut options);
1204 options.usage_with_format(|it| {
1207 it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1208 })
1209 })
1210 }
1211 _ => None,
1212 };
1213 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1214 });
1215
1216 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1228
1229 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1230 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1232 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1233 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1234 return None;
1235 }
1236
1237 if describe_flag_categories(early_dcx, &matches) {
1238 return None;
1239 }
1240
1241 if matches.opt_present("version") {
1242 version!(early_dcx, "rustc", &matches);
1243 return None;
1244 }
1245
1246 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1247
1248 Some(matches)
1249}
1250
1251fn warn_on_confusing_output_filename_flag(
1255 early_dcx: &EarlyDiagCtxt,
1256 matches: &getopts::Matches,
1257 args: &[String],
1258) {
1259 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1260 let s1 = s1.replace('-', "_");
1261 let s2 = s2.replace('-', "_");
1262 s1 == s2
1263 }
1264
1265 if let Some(name) = matches.opt_str("o")
1266 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1267 {
1268 let filename = suspect.trim_prefix("-");
1269 let optgroups = config::rustc_optgroups();
1270 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1271
1272 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1279 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1280 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1281 {
1282 early_dcx.early_warn(
1283 "option `-o` has no space between flag name and value, which can be confusing",
1284 );
1285 early_dcx.early_note(format!(
1286 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1287 ));
1288 early_dcx.early_help(format!(
1289 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1290 ));
1291 }
1292 }
1293}
1294
1295fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1296 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1297 Input::File(file) => {
1298 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1299 }
1300 Input::Str { name, input } => new_parser_from_source_str(
1301 &sess.psess,
1302 name.clone(),
1303 input.clone(),
1304 StripTokens::ShebangAndFrontmatter,
1305 ),
1306 });
1307 parser.parse_inner_attributes()
1308}
1309
1310pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1316 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1317 if value.is::<rustc_errors::FatalErrorMarker>() {
1318 FatalError
1319 } else {
1320 panic::resume_unwind(value);
1321 }
1322 })
1323}
1324
1325pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1328 match catch_fatal_errors(f) {
1329 Ok(()) => EXIT_SUCCESS,
1330 _ => EXIT_FAILURE,
1331 }
1332}
1333
1334static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1335
1336fn ice_path() -> &'static Option<PathBuf> {
1344 ice_path_with_config(None)
1345}
1346
1347fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1348 if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1349 tracing::warn!(
1350 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1351 )
1352 }
1353
1354 ICE_PATH.get_or_init(|| {
1355 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1356 return None;
1357 }
1358 let mut path = match std::env::var_os("RUSTC_ICE") {
1359 Some(s) => {
1360 if s == "0" {
1361 return None;
1363 }
1364 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1365 tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1366 }
1367 PathBuf::from(s)
1368 }
1369 None => config
1370 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1371 .or_else(|| std::env::current_dir().ok())
1372 .unwrap_or_default(),
1373 };
1374 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1376 let pid = std::process::id();
1377 path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1378 Some(path)
1379 })
1380}
1381
1382pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1383
1384pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1396 if env::var_os("RUST_BACKTRACE").is_none() {
1403 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1405 if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1406 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1407 } else {
1408 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1409 }
1410 }
1411
1412 panic::update_hook(Box::new(
1413 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1414 info: &PanicHookInfo<'_>| {
1415 let _guard = io::stderr().lock();
1417 #[cfg(windows)]
1420 if let Some(msg) = info.payload().downcast_ref::<String>() {
1421 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1422 {
1423 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1425 let _ = early_dcx.early_err(msg.clone());
1426 return;
1427 }
1428 };
1429
1430 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1433 default_hook(info);
1434 eprintln!();
1436
1437 if let Some(ice_path) = ice_path()
1438 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1439 {
1440 let location = info.location().unwrap();
1442 let msg = match info.payload().downcast_ref::<&'static str>() {
1443 Some(s) => *s,
1444 None => match info.payload().downcast_ref::<String>() {
1445 Some(s) => &s[..],
1446 None => "Box<dyn Any>",
1447 },
1448 };
1449 let thread = std::thread::current();
1450 let name = thread.name().unwrap_or("<unnamed>");
1451 let _ = write!(
1452 &mut out,
1453 "thread '{name}' panicked at {location}:\n\
1454 {msg}\n\
1455 stack backtrace:\n\
1456 {:#}",
1457 std::backtrace::Backtrace::force_capture()
1458 );
1459 }
1460 }
1461
1462 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1464 },
1465 ));
1466}
1467
1468fn report_ice(
1475 info: &panic::PanicHookInfo<'_>,
1476 bug_report_url: &str,
1477 extra_info: fn(&DiagCtxt),
1478 using_internal_features: &AtomicBool,
1479) {
1480 let translator = default_translator();
1481 let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1482 stderr_destination(rustc_errors::ColorConfig::Auto),
1483 translator,
1484 ));
1485 let dcx = rustc_errors::DiagCtxt::new(emitter);
1486 let dcx = dcx.handle();
1487
1488 if !info.payload().is::<rustc_errors::ExplicitBug>()
1491 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1492 {
1493 dcx.emit_err(session_diagnostics::Ice);
1494 }
1495
1496 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1497 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1498 } else {
1499 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1500
1501 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1503 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1504 }
1505 }
1506
1507 let version = util::version_str!().unwrap_or("unknown_version");
1508 let tuple = config::host_tuple();
1509
1510 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1511
1512 let file = if let Some(path) = ice_path() {
1513 match crate::fs::File::options().create(true).append(true).open(path) {
1515 Ok(mut file) => {
1516 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1517 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1518 let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1519 }
1520 Some(file)
1521 }
1522 Err(err) => {
1523 dcx.emit_warn(session_diagnostics::IcePathError {
1525 path: path.clone(),
1526 error: err.to_string(),
1527 env_var: std::env::var_os("RUSTC_ICE")
1528 .map(PathBuf::from)
1529 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1530 });
1531 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1532 None
1533 }
1534 }
1535 } else {
1536 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1537 None
1538 };
1539
1540 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1541 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1542 if excluded_cargo_defaults {
1543 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1544 }
1545 }
1546
1547 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1549
1550 let limit_frames = if backtrace { None } else { Some(2) };
1551
1552 interface::try_print_query_stack(dcx, limit_frames, file);
1553
1554 extra_info(&dcx);
1557
1558 #[cfg(windows)]
1559 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1560 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1562 }
1563}
1564
1565pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1568 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1569}
1570
1571pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1575 if let Err(error) = rustc_log::init_logger(cfg) {
1576 early_dcx.early_fatal(error.to_string());
1577 }
1578}
1579
1580pub fn init_logger_with_additional_layer<F, T>(
1586 early_dcx: &EarlyDiagCtxt,
1587 cfg: rustc_log::LoggerConfig,
1588 build_subscriber: F,
1589) where
1590 F: FnOnce() -> T,
1591 T: rustc_log::BuildSubscriberRet,
1592{
1593 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1594 early_dcx.early_fatal(error.to_string());
1595 }
1596}
1597
1598pub fn install_ctrlc_handler() {
1601 #[cfg(all(not(miri), not(target_family = "wasm")))]
1602 ctrlc::set_handler(move || {
1603 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1608 std::thread::sleep(std::time::Duration::from_millis(100));
1609 std::process::exit(1);
1610 })
1611 .expect("Unable to install ctrlc handler");
1612}
1613
1614pub fn main() -> ! {
1615 let start_time = Instant::now();
1616 let start_rss = get_resident_set_size();
1617
1618 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1619
1620 init_rustc_env_logger(&early_dcx);
1621 signal_handler::install();
1622 let mut callbacks = TimePassesCallbacks::default();
1623 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1624 install_ctrlc_handler();
1625
1626 let exit_code =
1627 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1628
1629 if let Some(format) = callbacks.time_passes {
1630 let end_rss = get_resident_set_size();
1631 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1632 }
1633
1634 process::exit(exit_code)
1635}