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 BackendHasZstd => {
802 let has_zstd: bool = codegen_backend.has_zstd();
803 println_info!("{has_zstd}");
804 }
805 RelocationModels
806 | CodeModels
807 | TlsModels
808 | TargetCPUs
809 | StackProtectorStrategies
810 | TargetFeatures => {
811 codegen_backend.print(req, &mut crate_info, sess);
812 }
813 NativeStaticLibs => {}
815 LinkArgs => {}
816 SplitDebuginfo => {
817 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
818
819 for split in &[Off, Packed, Unpacked] {
820 if sess.target.options.supported_split_debuginfo.contains(split) {
821 println_info!("{split}");
822 }
823 }
824 }
825 DeploymentTarget => {
826 if sess.target.is_like_darwin {
827 println_info!(
828 "{}={}",
829 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
830 sess.apple_deployment_target().fmt_pretty(),
831 )
832 } else {
833 #[allow(rustc::diagnostic_outside_of_impl)]
834 sess.dcx().fatal("only Apple targets currently support deployment version info")
835 }
836 }
837 SupportedCrateTypes => {
838 let supported_crate_types = CRATE_TYPES
839 .iter()
840 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
841 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
842 .map(|(crate_type_sym, _)| *crate_type_sym)
843 .collect::<BTreeSet<_>>();
844 for supported_crate_type in supported_crate_types {
845 println_info!("{}", supported_crate_type.as_str());
846 }
847 }
848 }
849
850 req.out.overwrite(&crate_info, sess);
851 }
852 Compilation::Stop
853}
854
855pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
859 fn unw(x: Option<&str>) -> &str {
860 x.unwrap_or("unknown")
861 }
862 $crate::version_at_macro_invocation(
863 $early_dcx,
864 $binary,
865 $matches,
866 unw(option_env!("CFG_VERSION")),
867 unw(option_env!("CFG_VER_HASH")),
868 unw(option_env!("CFG_VER_DATE")),
869 unw(option_env!("CFG_RELEASE")),
870 )
871}
872
873#[doc(hidden)] pub fn version_at_macro_invocation(
875 early_dcx: &EarlyDiagCtxt,
876 binary: &str,
877 matches: &getopts::Matches,
878 version: &str,
879 commit_hash: &str,
880 commit_date: &str,
881 release: &str,
882) {
883 let verbose = matches.opt_present("verbose");
884
885 let mut version = version;
886 let mut release = release;
887 let tmp;
888 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
889 tmp = force_version;
890 version = &tmp;
891 release = &tmp;
892 }
893
894 safe_println!("{binary} {version}");
895
896 if verbose {
897 safe_println!("binary: {binary}");
898 safe_println!("commit-hash: {commit_hash}");
899 safe_println!("commit-date: {commit_date}");
900 safe_println!("host: {}", config::host_tuple());
901 safe_println!("release: {release}");
902
903 get_backend_from_raw_matches(early_dcx, matches).print_version();
904 }
905}
906
907fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
908 let mut options = getopts::Options::new();
909 for option in config::rustc_optgroups()
910 .iter()
911 .filter(|x| verbose || !x.is_verbose_help_only)
912 .filter(|x| include_unstable_options || x.is_stable())
913 {
914 option.apply(&mut options);
915 }
916 let message = "Usage: rustc [OPTIONS] INPUT";
917 let nightly_help = if nightly_build {
918 "\n -Z help Print unstable compiler options"
919 } else {
920 ""
921 };
922 let verbose_help = if verbose {
923 ""
924 } else {
925 "\n --help -v Print the full set of options rustc accepts"
926 };
927 let at_path = if verbose {
928 " @path Read newline separated options from `path`\n"
929 } else {
930 ""
931 };
932 safe_println!(
933 "{options}{at_path}\nAdditional help:
934 -C help Print codegen options
935 -W help \
936 Print 'lint' options and default settings{nightly}{verbose}\n",
937 options = options.usage(message),
938 at_path = at_path,
939 nightly = nightly_help,
940 verbose = verbose_help
941 );
942}
943
944fn print_wall_help() {
945 safe_println!(
946 "
947The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
948default. Use `rustc -W help` to see all available lints. It's more common to put
949warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
950the command line flag directly.
951"
952 );
953}
954
955pub fn describe_lints(sess: &Session, registered_lints: bool) {
957 safe_println!(
958 "
959Available lint options:
960 -W <foo> Warn about <foo>
961 -A <foo> Allow <foo>
962 -D <foo> Deny <foo>
963 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
964
965"
966 );
967
968 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
969 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
971 lints
972 }
973
974 fn sort_lint_groups(
975 lints: Vec<(&'static str, Vec<LintId>, bool)>,
976 ) -> Vec<(&'static str, Vec<LintId>)> {
977 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
978 lints.sort_by_key(|l| l.0);
979 lints
980 }
981
982 let lint_store = unerased_lint_store(sess);
983 let (loaded, builtin): (Vec<_>, _) =
984 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
985 let loaded = sort_lints(sess, loaded);
986 let builtin = sort_lints(sess, builtin);
987
988 let (loaded_groups, builtin_groups): (Vec<_>, _) =
989 lint_store.get_lint_groups().partition(|&(.., p)| p);
990 let loaded_groups = sort_lint_groups(loaded_groups);
991 let builtin_groups = sort_lint_groups(builtin_groups);
992
993 let max_name_len =
994 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
995 let padded = |x: &str| {
996 let mut s = " ".repeat(max_name_len - x.chars().count());
997 s.push_str(x);
998 s
999 };
1000
1001 safe_println!("Lint checks provided by rustc:\n");
1002
1003 let print_lints = |lints: Vec<&Lint>| {
1004 safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1005 safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1006 for lint in lints {
1007 let name = lint.name_lower().replace('_', "-");
1008 safe_println!(
1009 " {} {:7.7} {}",
1010 padded(&name),
1011 lint.default_level(sess.edition()).as_str(),
1012 lint.desc
1013 );
1014 }
1015 safe_println!("\n");
1016 };
1017
1018 print_lints(builtin);
1019
1020 let max_name_len = max(
1021 "warnings".len(),
1022 loaded_groups
1023 .iter()
1024 .chain(&builtin_groups)
1025 .map(|&(s, _)| s.chars().count())
1026 .max()
1027 .unwrap_or(0),
1028 );
1029
1030 let padded = |x: &str| {
1031 let mut s = " ".repeat(max_name_len - x.chars().count());
1032 s.push_str(x);
1033 s
1034 };
1035
1036 safe_println!("Lint groups provided by rustc:\n");
1037
1038 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1039 safe_println!(" {} sub-lints", padded("name"));
1040 safe_println!(" {} ---------", padded("----"));
1041
1042 if all_warnings {
1043 safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1044 }
1045
1046 for (name, to) in lints {
1047 let name = name.to_lowercase().replace('_', "-");
1048 let desc = to
1049 .into_iter()
1050 .map(|x| x.to_string().replace('_', "-"))
1051 .collect::<Vec<String>>()
1052 .join(", ");
1053 safe_println!(" {} {}", padded(&name), desc);
1054 }
1055 safe_println!("\n");
1056 };
1057
1058 print_lint_groups(builtin_groups, true);
1059
1060 match (registered_lints, loaded.len(), loaded_groups.len()) {
1061 (false, 0, _) | (false, _, 0) => {
1062 safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1063 }
1064 (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1065 (true, 0, 0) => {
1066 safe_println!("This crate does not load any additional lints or lint groups.")
1067 }
1068 (true, l, g) => {
1069 if l > 0 {
1070 safe_println!("Lint checks loaded by this crate:\n");
1071 print_lints(loaded);
1072 }
1073 if g > 0 {
1074 safe_println!("Lint groups loaded by this crate:\n");
1075 print_lint_groups(loaded_groups, false);
1076 }
1077 }
1078 }
1079}
1080
1081pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1085 let wall = matches.opt_strs("W");
1087 if wall.iter().any(|x| *x == "all") {
1088 print_wall_help();
1089 return true;
1090 }
1091
1092 let debug_flags = matches.opt_strs("Z");
1094 if debug_flags.iter().any(|x| *x == "help") {
1095 describe_debug_flags();
1096 return true;
1097 }
1098
1099 let cg_flags = matches.opt_strs("C");
1100 if cg_flags.iter().any(|x| *x == "help") {
1101 describe_codegen_flags();
1102 return true;
1103 }
1104
1105 if cg_flags.iter().any(|x| *x == "passes=list") {
1106 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1107 return true;
1108 }
1109
1110 false
1111}
1112
1113fn get_backend_from_raw_matches(
1120 early_dcx: &EarlyDiagCtxt,
1121 matches: &Matches,
1122) -> Box<dyn CodegenBackend> {
1123 let debug_flags = matches.opt_strs("Z");
1124 let backend_name = debug_flags
1125 .iter()
1126 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1127 let target = parse_target_triple(early_dcx, matches);
1128 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1129 let target = config::build_target_config(early_dcx, &target, sysroot.path());
1130
1131 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1132}
1133
1134fn describe_debug_flags() {
1135 safe_println!("\nAvailable options:\n");
1136 print_flag_list("-Z", config::Z_OPTIONS);
1137}
1138
1139fn describe_codegen_flags() {
1140 safe_println!("\nAvailable codegen options:\n");
1141 print_flag_list("-C", config::CG_OPTIONS);
1142}
1143
1144fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1145 let max_len =
1146 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1147
1148 for opt_desc in flag_list {
1149 safe_println!(
1150 " {} {:>width$}=val -- {}",
1151 cmdline_opt,
1152 opt_desc.name().replace('_', "-"),
1153 opt_desc.desc(),
1154 width = max_len
1155 );
1156 }
1157}
1158
1159pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1187 let mut options = getopts::Options::new();
1190 let optgroups = config::rustc_optgroups();
1191 for option in &optgroups {
1192 option.apply(&mut options);
1193 }
1194 let matches = options.parse(args).unwrap_or_else(|e| {
1195 let msg: Option<String> = match e {
1196 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1197 .iter()
1198 .map(|opt_desc| ('C', opt_desc.name()))
1199 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1200 .find(|&(_, name)| *opt == name.replace('_', "-"))
1201 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1202 getopts::Fail::ArgumentMissing(ref opt) => {
1203 optgroups.iter().find(|option| option.name == opt).map(|option| {
1204 let mut options = getopts::Options::new();
1206 option.apply(&mut options);
1207 options.usage_with_format(|it| {
1210 it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1211 })
1212 })
1213 }
1214 _ => None,
1215 };
1216 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1217 });
1218
1219 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1231
1232 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1233 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1235 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1236 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1237 return None;
1238 }
1239
1240 if describe_flag_categories(early_dcx, &matches) {
1241 return None;
1242 }
1243
1244 if matches.opt_present("version") {
1245 version!(early_dcx, "rustc", &matches);
1246 return None;
1247 }
1248
1249 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1250
1251 Some(matches)
1252}
1253
1254fn warn_on_confusing_output_filename_flag(
1258 early_dcx: &EarlyDiagCtxt,
1259 matches: &getopts::Matches,
1260 args: &[String],
1261) {
1262 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1263 let s1 = s1.replace('-', "_");
1264 let s2 = s2.replace('-', "_");
1265 s1 == s2
1266 }
1267
1268 if let Some(name) = matches.opt_str("o")
1269 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1270 {
1271 let filename = suspect.trim_prefix("-");
1272 let optgroups = config::rustc_optgroups();
1273 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1274
1275 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1282 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1283 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1284 {
1285 early_dcx.early_warn(
1286 "option `-o` has no space between flag name and value, which can be confusing",
1287 );
1288 early_dcx.early_note(format!(
1289 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1290 ));
1291 early_dcx.early_help(format!(
1292 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1293 ));
1294 }
1295 }
1296}
1297
1298fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1299 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1300 Input::File(file) => {
1301 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1302 }
1303 Input::Str { name, input } => new_parser_from_source_str(
1304 &sess.psess,
1305 name.clone(),
1306 input.clone(),
1307 StripTokens::ShebangAndFrontmatter,
1308 ),
1309 });
1310 parser.parse_inner_attributes()
1311}
1312
1313pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1319 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1320 if value.is::<rustc_errors::FatalErrorMarker>() {
1321 FatalError
1322 } else {
1323 panic::resume_unwind(value);
1324 }
1325 })
1326}
1327
1328pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1331 match catch_fatal_errors(f) {
1332 Ok(()) => EXIT_SUCCESS,
1333 _ => EXIT_FAILURE,
1334 }
1335}
1336
1337static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1338
1339fn ice_path() -> &'static Option<PathBuf> {
1347 ice_path_with_config(None)
1348}
1349
1350fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1351 if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1352 tracing::warn!(
1353 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1354 )
1355 }
1356
1357 ICE_PATH.get_or_init(|| {
1358 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1359 return None;
1360 }
1361 let mut path = match std::env::var_os("RUSTC_ICE") {
1362 Some(s) => {
1363 if s == "0" {
1364 return None;
1366 }
1367 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1368 tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1369 }
1370 PathBuf::from(s)
1371 }
1372 None => config
1373 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1374 .or_else(|| std::env::current_dir().ok())
1375 .unwrap_or_default(),
1376 };
1377 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1379 let pid = std::process::id();
1380 path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1381 Some(path)
1382 })
1383}
1384
1385pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1386
1387pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1399 if env::var_os("RUST_BACKTRACE").is_none() {
1406 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1408 if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1409 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1410 } else {
1411 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1412 }
1413 }
1414
1415 panic::update_hook(Box::new(
1416 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1417 info: &PanicHookInfo<'_>| {
1418 let _guard = io::stderr().lock();
1420 #[cfg(windows)]
1423 if let Some(msg) = info.payload().downcast_ref::<String>() {
1424 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1425 {
1426 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1428 let _ = early_dcx.early_err(msg.clone());
1429 return;
1430 }
1431 };
1432
1433 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1436 default_hook(info);
1437 eprintln!();
1439
1440 if let Some(ice_path) = ice_path()
1441 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1442 {
1443 let location = info.location().unwrap();
1445 let msg = match info.payload().downcast_ref::<&'static str>() {
1446 Some(s) => *s,
1447 None => match info.payload().downcast_ref::<String>() {
1448 Some(s) => &s[..],
1449 None => "Box<dyn Any>",
1450 },
1451 };
1452 let thread = std::thread::current();
1453 let name = thread.name().unwrap_or("<unnamed>");
1454 let _ = write!(
1455 &mut out,
1456 "thread '{name}' panicked at {location}:\n\
1457 {msg}\n\
1458 stack backtrace:\n\
1459 {:#}",
1460 std::backtrace::Backtrace::force_capture()
1461 );
1462 }
1463 }
1464
1465 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1467 },
1468 ));
1469}
1470
1471fn report_ice(
1478 info: &panic::PanicHookInfo<'_>,
1479 bug_report_url: &str,
1480 extra_info: fn(&DiagCtxt),
1481 using_internal_features: &AtomicBool,
1482) {
1483 let translator = default_translator();
1484 let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1485 stderr_destination(rustc_errors::ColorConfig::Auto),
1486 translator,
1487 ));
1488 let dcx = rustc_errors::DiagCtxt::new(emitter);
1489 let dcx = dcx.handle();
1490
1491 if !info.payload().is::<rustc_errors::ExplicitBug>()
1494 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1495 {
1496 dcx.emit_err(session_diagnostics::Ice);
1497 }
1498
1499 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1500 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1501 } else {
1502 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1503
1504 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1506 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1507 }
1508 }
1509
1510 let version = util::version_str!().unwrap_or("unknown_version");
1511 let tuple = config::host_tuple();
1512
1513 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1514
1515 let file = if let Some(path) = ice_path() {
1516 match crate::fs::File::options().create(true).append(true).open(path) {
1518 Ok(mut file) => {
1519 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1520 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1521 let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1522 }
1523 Some(file)
1524 }
1525 Err(err) => {
1526 dcx.emit_warn(session_diagnostics::IcePathError {
1528 path: path.clone(),
1529 error: err.to_string(),
1530 env_var: std::env::var_os("RUSTC_ICE")
1531 .map(PathBuf::from)
1532 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1533 });
1534 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1535 None
1536 }
1537 }
1538 } else {
1539 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1540 None
1541 };
1542
1543 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1544 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1545 if excluded_cargo_defaults {
1546 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1547 }
1548 }
1549
1550 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1552
1553 let limit_frames = if backtrace { None } else { Some(2) };
1554
1555 interface::try_print_query_stack(dcx, limit_frames, file);
1556
1557 extra_info(&dcx);
1560
1561 #[cfg(windows)]
1562 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1563 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1565 }
1566}
1567
1568pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1571 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1572}
1573
1574pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1578 if let Err(error) = rustc_log::init_logger(cfg) {
1579 early_dcx.early_fatal(error.to_string());
1580 }
1581}
1582
1583pub fn init_logger_with_additional_layer<F, T>(
1589 early_dcx: &EarlyDiagCtxt,
1590 cfg: rustc_log::LoggerConfig,
1591 build_subscriber: F,
1592) where
1593 F: FnOnce() -> T,
1594 T: rustc_log::BuildSubscriberRet,
1595{
1596 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1597 early_dcx.early_fatal(error.to_string());
1598 }
1599}
1600
1601pub fn install_ctrlc_handler() {
1604 #[cfg(all(not(miri), not(target_family = "wasm")))]
1605 ctrlc::set_handler(move || {
1606 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1611 std::thread::sleep(std::time::Duration::from_millis(100));
1612 std::process::exit(1);
1613 })
1614 .expect("Unable to install ctrlc handler");
1615}
1616
1617pub fn main() -> ! {
1618 let start_time = Instant::now();
1619 let start_rss = get_resident_set_size();
1620
1621 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1622
1623 init_rustc_env_logger(&early_dcx);
1624 signal_handler::install();
1625 let mut callbacks = TimePassesCallbacks::default();
1626 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1627 install_ctrlc_handler();
1628
1629 let exit_code =
1630 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1631
1632 if let Some(format) = callbacks.time_passes {
1633 let end_rss = get_resident_set_size();
1634 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1635 }
1636
1637 process::exit(exit_code)
1638}