1#![allow(internal_features)]
9#![allow(rustc::untranslatable_diagnostic)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
11#![doc(rust_logo)]
12#![feature(decl_macro)]
13#![feature(panic_backtrace_config)]
14#![feature(panic_update_hook)]
15#![feature(rustdoc_internals)]
16#![feature(try_blocks)]
17use std::cmp::max;
20use std::collections::{BTreeMap, BTreeSet};
21use std::ffi::OsString;
22use std::fmt::Write as _;
23use std::fs::{self, File};
24use std::io::{self, IsTerminal, Read, Write};
25use std::panic::{self, PanicHookInfo, catch_unwind};
26use std::path::{Path, PathBuf};
27use std::process::{self, Command, Stdio};
28use std::sync::OnceLock;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::time::Instant;
31use std::{env, str};
32
33use rustc_ast as ast;
34use rustc_codegen_ssa::traits::CodegenBackend;
35use rustc_codegen_ssa::{CodegenErrors, CodegenResults};
36use rustc_data_structures::profiling::{
37 TimePassesFormat, get_resident_set_size, print_time_passes_entry,
38};
39use rustc_errors::emitter::stderr_destination;
40use rustc_errors::registry::Registry;
41use rustc_errors::translation::Translator;
42use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
43use rustc_feature::find_gated_cfg;
44use rustc_index as _;
48use rustc_interface::util::{self, get_codegen_backend};
49use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
50use rustc_lint::unerased_lint_store;
51use rustc_metadata::creader::MetadataLoader;
52use rustc_metadata::locator;
53use rustc_middle::ty::TyCtxt;
54use rustc_parse::lexer::StripTokens;
55use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
56use rustc_session::config::{
57 CG_OPTIONS, CrateType, ErrorOutputType, Input, OptionDesc, OutFileName, OutputType, Sysroot,
58 UnstableOptions, Z_OPTIONS, nightly_options, parse_target_triple,
59};
60use rustc_session::getopts::{self, Matches};
61use rustc_session::lint::{Lint, LintId};
62use rustc_session::output::{CRATE_TYPES, collect_crate_types, invalid_output_for_target};
63use rustc_session::{EarlyDiagCtxt, Session, config};
64use rustc_span::FileName;
65use rustc_span::def_id::LOCAL_CRATE;
66use rustc_target::json::ToJson;
67use rustc_target::spec::{Target, TargetTuple};
68use tracing::trace;
69
70#[allow(unused_macros)]
71macro do_not_use_print($($t:tt)*) {
72 std::compile_error!(
73 "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
74 )
75}
76
77#[allow(unused_macros)]
78macro do_not_use_safe_print($($t:tt)*) {
79 std::compile_error!("Don't use `safe_print` or `safe_println` here, use `println_info` instead")
80}
81
82#[allow(unused_imports)]
86use {do_not_use_print as print, do_not_use_print as println};
87
88pub mod args;
89pub mod pretty;
90#[macro_use]
91mod print;
92mod session_diagnostics;
93
94#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
98mod signal_handler;
99
100#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
101mod signal_handler {
102 pub(super) fn install() {}
105}
106
107use crate::session_diagnostics::{
108 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
109 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
110};
111
112rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
113
114pub fn default_translator() -> Translator {
115 Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
116}
117
118pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
119 crate::DEFAULT_LOCALE_RESOURCE,
121 rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
122 rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
123 rustc_attr_parsing::DEFAULT_LOCALE_RESOURCE,
124 rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
125 rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
126 rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
127 rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
128 rustc_errors::DEFAULT_LOCALE_RESOURCE,
129 rustc_expand::DEFAULT_LOCALE_RESOURCE,
130 rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
131 rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
132 rustc_incremental::DEFAULT_LOCALE_RESOURCE,
133 rustc_infer::DEFAULT_LOCALE_RESOURCE,
134 rustc_interface::DEFAULT_LOCALE_RESOURCE,
135 rustc_lint::DEFAULT_LOCALE_RESOURCE,
136 rustc_metadata::DEFAULT_LOCALE_RESOURCE,
137 rustc_middle::DEFAULT_LOCALE_RESOURCE,
138 rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
139 rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
140 rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
141 rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
142 rustc_parse::DEFAULT_LOCALE_RESOURCE,
143 rustc_passes::DEFAULT_LOCALE_RESOURCE,
144 rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE,
145 rustc_privacy::DEFAULT_LOCALE_RESOURCE,
146 rustc_query_system::DEFAULT_LOCALE_RESOURCE,
147 rustc_resolve::DEFAULT_LOCALE_RESOURCE,
148 rustc_session::DEFAULT_LOCALE_RESOURCE,
149 rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
150 rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
151 ];
153
154pub const EXIT_SUCCESS: i32 = 0;
156
157pub const EXIT_FAILURE: i32 = 1;
159
160pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
161 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
162
163pub trait Callbacks {
164 fn config(&mut self, _config: &mut interface::Config) {}
166 fn after_crate_root_parsing(
170 &mut self,
171 _compiler: &interface::Compiler,
172 _krate: &mut ast::Crate,
173 ) -> Compilation {
174 Compilation::Continue
175 }
176 fn after_expansion<'tcx>(
179 &mut self,
180 _compiler: &interface::Compiler,
181 _tcx: TyCtxt<'tcx>,
182 ) -> Compilation {
183 Compilation::Continue
184 }
185 fn after_analysis<'tcx>(
188 &mut self,
189 _compiler: &interface::Compiler,
190 _tcx: TyCtxt<'tcx>,
191 ) -> Compilation {
192 Compilation::Continue
193 }
194}
195
196#[derive(Default)]
197pub struct TimePassesCallbacks {
198 time_passes: Option<TimePassesFormat>,
199}
200
201impl Callbacks for TimePassesCallbacks {
202 #[allow(rustc::bad_opt_access)]
204 fn config(&mut self, config: &mut interface::Config) {
205 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
209 .then_some(config.opts.unstable_opts.time_passes_format);
210 config.opts.trimmed_def_paths = true;
211 }
212}
213
214pub fn diagnostics_registry() -> Registry {
215 Registry::new(rustc_errors::codes::DIAGNOSTICS)
216}
217
218pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
220 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
221
222 let at_args = at_args.get(1..).unwrap_or_default();
231
232 let args = args::arg_expand_all(&default_early_dcx, at_args);
233
234 let Some(matches) = handle_options(&default_early_dcx, &args) else {
235 return;
236 };
237
238 let sopts = config::build_session_options(&mut default_early_dcx, &matches);
239 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 expanded_args: args,
273 };
274
275 callbacks.config(&mut config);
276
277 let registered_lints = config.register_lints.is_some();
278
279 interface::run_compiler(config, |compiler| {
280 let sess = &compiler.sess;
281 let codegen_backend = &*compiler.codegen_backend;
282
283 let early_exit = || {
287 sess.dcx().abort_if_errors();
288 };
289
290 if sess.opts.describe_lints {
294 describe_lints(sess, registered_lints);
295 return early_exit();
296 }
297
298 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
299 return early_exit();
300 }
301
302 if !has_input {
303 #[allow(rustc::diagnostic_outside_of_impl)]
304 sess.dcx().fatal("no input filename given"); }
306
307 if !sess.opts.unstable_opts.ls.is_empty() {
308 list_metadata(sess, &*codegen_backend.metadata_loader());
309 return early_exit();
310 }
311
312 if sess.opts.unstable_opts.link_only {
313 process_rlink(sess, compiler);
314 return early_exit();
315 }
316
317 let mut krate = passes::parse(sess);
320
321 if let Some(pp_mode) = sess.opts.pretty {
323 if pp_mode.needs_ast_map() {
324 create_and_enter_global_ctxt(compiler, krate, |tcx| {
325 tcx.ensure_ok().early_lint_checks(());
326 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
327 passes::write_dep_info(tcx);
328 });
329 } else {
330 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
331 }
332 trace!("finished pretty-printing");
333 return early_exit();
334 }
335
336 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
337 return early_exit();
338 }
339
340 if sess.opts.unstable_opts.parse_crate_root_only {
341 return early_exit();
342 }
343
344 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
345 let early_exit = || {
346 sess.dcx().abort_if_errors();
347 None
348 };
349
350 let _ = tcx.resolver_for_lowering();
352
353 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
354 return early_exit();
355 }
356
357 passes::write_dep_info(tcx);
358
359 passes::write_interface(tcx);
360
361 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
362 && sess.opts.output_types.len() == 1
363 {
364 return early_exit();
365 }
366
367 if sess.opts.unstable_opts.no_analysis {
368 return early_exit();
369 }
370
371 tcx.ensure_ok().analysis(());
372
373 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
374 dump_feature_usage_metrics(tcx, metrics_dir);
375 }
376
377 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
378 return early_exit();
379 }
380
381 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
382 if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
383 tcx.dcx().emit_fatal(CantEmitMIR { error });
384 }
385 }
386
387 Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
388 });
389
390 if let Some(linker) = linker {
393 linker.link(sess, codegen_backend);
394 }
395 })
396}
397
398fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
399 let hash = tcxt.crate_hash(LOCAL_CRATE);
400 let crate_name = tcxt.crate_name(LOCAL_CRATE);
401 let metrics_file_name = format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
402 let metrics_path = metrics_dir.join(metrics_file_name);
403 if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
404 tcxt.dcx().emit_err(UnstableFeatureUsage { error });
408 }
409}
410
411fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
413 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
414 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
415 "-" => OutFileName::Stdout,
416 path => OutFileName::Real(PathBuf::from(path)),
417 });
418 (odir, ofile)
419}
420
421fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
424 match free_matches {
425 [] => None, [ifile] if ifile == "-" => {
427 let mut input = String::new();
429 if io::stdin().read_to_string(&mut input).is_err() {
430 early_dcx
433 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
434 }
435
436 let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
437 Ok(path) => {
438 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
439 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
440 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
441 );
442 let line = line
443 .parse::<isize>()
444 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be a number");
445 FileName::doc_test_source_code(PathBuf::from(path), line)
446 }
447 Err(_) => FileName::anon_source_code(&input),
448 };
449
450 Some(Input::Str { name, input })
451 }
452 [ifile] => Some(Input::File(PathBuf::from(ifile))),
453 [ifile1, ifile2, ..] => early_dcx.early_fatal(format!(
454 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
455 ifile1, ifile2
456 )),
457 }
458}
459
460#[derive(Copy, Clone, Debug, Eq, PartialEq)]
462pub enum Compilation {
463 Stop,
464 Continue,
465}
466
467fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
468 let upper_cased_code = code.to_ascii_uppercase();
470 if let Ok(code) = upper_cased_code.strip_prefix('E').unwrap_or(&upper_cased_code).parse::<u32>()
471 && code <= ErrCode::MAX_AS_U32
472 && let Ok(description) = registry.try_find_description(ErrCode::from_u32(code))
473 {
474 let mut is_in_code_block = false;
475 let mut text = String::new();
476 for line in description.lines() {
478 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
479 let dedented_line = &line[indent_level..];
480 if dedented_line.starts_with("```") {
481 is_in_code_block = !is_in_code_block;
482 text.push_str(&line[..(indent_level + 3)]);
483 } else if is_in_code_block && dedented_line.starts_with("# ") {
484 continue;
485 } else {
486 text.push_str(line);
487 }
488 text.push('\n');
489 }
490 if io::stdout().is_terminal() {
491 show_md_content_with_pager(&text, color);
492 } else {
493 safe_print!("{text}");
494 }
495 } else {
496 early_dcx.early_fatal(format!("{code} is not a valid error code"));
497 }
498}
499
500fn show_md_content_with_pager(content: &str, color: ColorConfig) {
505 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
506 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
507 });
508
509 let mut cmd = Command::new(&pager_name);
510 if pager_name == "less" {
511 cmd.arg("-R"); }
513
514 let pretty_on_pager = match color {
515 ColorConfig::Auto => {
516 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
518 }
519 ColorConfig::Always => true,
520 ColorConfig::Never => false,
521 };
522
523 let pretty_data = {
525 let mdstream = markdown::MdStream::parse_str(content);
526 let bufwtr = markdown::create_stdout_bufwtr();
527 let mut mdbuf = bufwtr.buffer();
528 if mdstream.write_termcolor_buf(&mut mdbuf).is_ok() { Some((bufwtr, mdbuf)) } else { None }
529 };
530
531 let pager_res: Option<()> = try {
533 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
534
535 let pager_stdin = pager.stdin.as_mut()?;
536 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
537 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
538 } else {
539 pager_stdin.write_all(content.as_bytes()).ok()?;
540 };
541
542 pager.wait().ok()?;
543 };
544 if pager_res.is_some() {
545 return;
546 }
547
548 if let Some((bufwtr, mdbuf)) = &pretty_data
550 && bufwtr.print(mdbuf).is_ok()
551 {
552 return;
553 }
554
555 safe_print!("{content}");
557}
558
559fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
560 assert!(sess.opts.unstable_opts.link_only);
561 let dcx = sess.dcx();
562 if let Input::File(file) = &sess.io.input {
563 let rlink_data = fs::read(file).unwrap_or_else(|err| {
564 dcx.emit_fatal(RlinkUnableToRead { err });
565 });
566 let (codegen_results, metadata, outputs) =
567 match CodegenResults::deserialize_rlink(sess, rlink_data) {
568 Ok((codegen, metadata, outputs)) => (codegen, metadata, outputs),
569 Err(err) => {
570 match err {
571 CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
572 CodegenErrors::EmptyVersionNumber => {
573 dcx.emit_fatal(RLinkEmptyVersionNumber)
574 }
575 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
576 dcx.emit_fatal(RLinkEncodingVersionMismatch {
577 version_array,
578 rlink_version,
579 })
580 }
581 CodegenErrors::RustcVersionMismatch { rustc_version } => {
582 dcx.emit_fatal(RLinkRustcVersionMismatch {
583 rustc_version,
584 current_version: sess.cfg_version,
585 })
586 }
587 CodegenErrors::CorruptFile => {
588 dcx.emit_fatal(RlinkCorruptFile { file });
589 }
590 };
591 }
592 };
593 compiler.codegen_backend.link(sess, codegen_results, metadata, &outputs);
594 } else {
595 dcx.emit_fatal(RlinkNotAFile {});
596 }
597}
598
599fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
600 match sess.io.input {
601 Input::File(ref path) => {
602 let mut v = Vec::new();
603 locator::list_file_metadata(
604 &sess.target,
605 path,
606 metadata_loader,
607 &mut v,
608 &sess.opts.unstable_opts.ls,
609 sess.cfg_version,
610 )
611 .unwrap();
612 safe_println!("{}", String::from_utf8(v).unwrap());
613 }
614 Input::Str { .. } => {
615 #[allow(rustc::diagnostic_outside_of_impl)]
616 sess.dcx().fatal("cannot list metadata for stdin");
617 }
618 }
619}
620
621fn print_crate_info(
622 codegen_backend: &dyn CodegenBackend,
623 sess: &Session,
624 parse_attrs: bool,
625) -> Compilation {
626 use rustc_session::config::PrintKind::*;
627 #[allow(unused_imports)]
631 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
632
633 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
636 return Compilation::Continue;
637 }
638
639 let attrs = if parse_attrs {
640 let result = parse_crate_attrs(sess);
641 match result {
642 Ok(attrs) => Some(attrs),
643 Err(parse_error) => {
644 parse_error.emit();
645 return Compilation::Stop;
646 }
647 }
648 } else {
649 None
650 };
651
652 for req in &sess.opts.prints {
653 let mut crate_info = String::new();
654 macro println_info($($arg:tt)*) {
655 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
656 }
657
658 match req.kind {
659 TargetList => {
660 let mut targets = rustc_target::spec::TARGETS.to_vec();
661 targets.sort_unstable();
662 println_info!("{}", targets.join("\n"));
663 }
664 HostTuple => println_info!("{}", rustc_session::config::host_tuple()),
665 Sysroot => println_info!("{}", sess.opts.sysroot.path().display()),
666 TargetLibdir => println_info!("{}", sess.target_tlib_path.dir.display()),
667 TargetSpecJson => {
668 println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
669 }
670 TargetSpecJsonSchema => {
671 let schema = rustc_target::spec::json_schema();
672 println_info!("{}", serde_json::to_string_pretty(&schema).unwrap());
673 }
674 AllTargetSpecsJson => {
675 let mut targets = BTreeMap::new();
676 for name in rustc_target::spec::TARGETS {
677 let triple = TargetTuple::from_tuple(name);
678 let target = Target::expect_builtin(&triple);
679 targets.insert(name, target.to_json());
680 }
681 println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
682 }
683 FileNames => {
684 let Some(attrs) = attrs.as_ref() else {
685 return Compilation::Continue;
687 };
688 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
689 let crate_name = passes::get_crate_name(sess, attrs);
690 let crate_types = collect_crate_types(sess, attrs);
691 for &style in &crate_types {
692 let fname = rustc_session::output::filename_for_input(
693 sess, style, crate_name, &t_outputs,
694 );
695 println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
696 }
697 }
698 CrateName => {
699 let Some(attrs) = attrs.as_ref() else {
700 return Compilation::Continue;
702 };
703 println_info!("{}", passes::get_crate_name(sess, attrs));
704 }
705 CrateRootLintLevels => {
706 let Some(attrs) = attrs.as_ref() else {
707 return Compilation::Continue;
709 };
710 let crate_name = passes::get_crate_name(sess, attrs);
711 let lint_store = crate::unerased_lint_store(sess);
712 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
713 let features = rustc_expand::config::features(sess, attrs, crate_name);
714 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
715 sess,
716 &features,
717 true,
718 lint_store,
719 ®istered_tools,
720 attrs,
721 );
722 for lint in lint_store.get_lints() {
723 if let Some(feature_symbol) = lint.feature_gate
724 && !features.enabled(feature_symbol)
725 {
726 continue;
728 }
729 let level = lint_levels.lint_level(lint).level;
730 println_info!("{}={}", lint.name_lower(), level.as_str());
731 }
732 }
733 Cfg => {
734 let mut cfgs = sess
735 .psess
736 .config
737 .iter()
738 .filter_map(|&(name, value)| {
739 if !sess.is_nightly_build()
741 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
742 {
743 return None;
744 }
745
746 if let Some(value) = value {
747 Some(format!("{name}=\"{value}\""))
748 } else {
749 Some(name.to_string())
750 }
751 })
752 .collect::<Vec<String>>();
753
754 cfgs.sort();
755 for cfg in cfgs {
756 println_info!("{cfg}");
757 }
758 }
759 CheckCfg => {
760 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
761
762 #[allow(rustc::potential_query_instability)]
764 for (name, expected_values) in &sess.psess.check_config.expecteds {
765 use crate::config::ExpectedValues;
766 match expected_values {
767 ExpectedValues::Any => check_cfgs.push(format!("{name}=any()")),
768 ExpectedValues::Some(values) => {
769 if !values.is_empty() {
770 check_cfgs.extend(values.iter().map(|value| {
771 if let Some(value) = value {
772 format!("{name}=\"{value}\"")
773 } else {
774 name.to_string()
775 }
776 }))
777 } else {
778 check_cfgs.push(format!("{name}="))
779 }
780 }
781 }
782 }
783
784 check_cfgs.sort_unstable();
785 if !sess.psess.check_config.exhaustive_names {
786 if !sess.psess.check_config.exhaustive_values {
787 println_info!("any()=any()");
788 } else {
789 println_info!("any()");
790 }
791 }
792 for check_cfg in check_cfgs {
793 println_info!("{check_cfg}");
794 }
795 }
796 CallingConventions => {
797 let calling_conventions = rustc_abi::all_names();
798 println_info!("{}", calling_conventions.join("\n"));
799 }
800 RelocationModels
801 | CodeModels
802 | TlsModels
803 | TargetCPUs
804 | StackProtectorStrategies
805 | TargetFeatures => {
806 codegen_backend.print(req, &mut crate_info, sess);
807 }
808 NativeStaticLibs => {}
810 LinkArgs => {}
811 SplitDebuginfo => {
812 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
813
814 for split in &[Off, Packed, Unpacked] {
815 if sess.target.options.supported_split_debuginfo.contains(split) {
816 println_info!("{split}");
817 }
818 }
819 }
820 DeploymentTarget => {
821 if sess.target.is_like_darwin {
822 println_info!(
823 "{}={}",
824 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
825 sess.apple_deployment_target().fmt_pretty(),
826 )
827 } else {
828 #[allow(rustc::diagnostic_outside_of_impl)]
829 sess.dcx().fatal("only Apple targets currently support deployment version info")
830 }
831 }
832 SupportedCrateTypes => {
833 let supported_crate_types = CRATE_TYPES
834 .iter()
835 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
836 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
837 .map(|(crate_type_sym, _)| *crate_type_sym)
838 .collect::<BTreeSet<_>>();
839 for supported_crate_type in supported_crate_types {
840 println_info!("{}", supported_crate_type.as_str());
841 }
842 }
843 }
844
845 req.out.overwrite(&crate_info, sess);
846 }
847 Compilation::Stop
848}
849
850pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
854 fn unw(x: Option<&str>) -> &str {
855 x.unwrap_or("unknown")
856 }
857 $crate::version_at_macro_invocation(
858 $early_dcx,
859 $binary,
860 $matches,
861 unw(option_env!("CFG_VERSION")),
862 unw(option_env!("CFG_VER_HASH")),
863 unw(option_env!("CFG_VER_DATE")),
864 unw(option_env!("CFG_RELEASE")),
865 )
866}
867
868#[doc(hidden)] pub fn version_at_macro_invocation(
870 early_dcx: &EarlyDiagCtxt,
871 binary: &str,
872 matches: &getopts::Matches,
873 version: &str,
874 commit_hash: &str,
875 commit_date: &str,
876 release: &str,
877) {
878 let verbose = matches.opt_present("verbose");
879
880 let mut version = version;
881 let mut release = release;
882 let tmp;
883 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
884 tmp = force_version;
885 version = &tmp;
886 release = &tmp;
887 }
888
889 safe_println!("{binary} {version}");
890
891 if verbose {
892 safe_println!("binary: {binary}");
893 safe_println!("commit-hash: {commit_hash}");
894 safe_println!("commit-date: {commit_date}");
895 safe_println!("host: {}", config::host_tuple());
896 safe_println!("release: {release}");
897
898 get_backend_from_raw_matches(early_dcx, matches).print_version();
899 }
900}
901
902fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
903 let mut options = getopts::Options::new();
904 for option in config::rustc_optgroups()
905 .iter()
906 .filter(|x| verbose || !x.is_verbose_help_only)
907 .filter(|x| include_unstable_options || x.is_stable())
908 {
909 option.apply(&mut options);
910 }
911 let message = "Usage: rustc [OPTIONS] INPUT";
912 let nightly_help = if nightly_build {
913 "\n -Z help Print unstable compiler options"
914 } else {
915 ""
916 };
917 let verbose_help = if verbose {
918 ""
919 } else {
920 "\n --help -v Print the full set of options rustc accepts"
921 };
922 let at_path = if verbose {
923 " @path Read newline separated options from `path`\n"
924 } else {
925 ""
926 };
927 safe_println!(
928 "{options}{at_path}\nAdditional help:
929 -C help Print codegen options
930 -W help \
931 Print 'lint' options and default settings{nightly}{verbose}\n",
932 options = options.usage(message),
933 at_path = at_path,
934 nightly = nightly_help,
935 verbose = verbose_help
936 );
937}
938
939fn print_wall_help() {
940 safe_println!(
941 "
942The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
943default. Use `rustc -W help` to see all available lints. It's more common to put
944warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
945the command line flag directly.
946"
947 );
948}
949
950pub fn describe_lints(sess: &Session, registered_lints: bool) {
952 safe_println!(
953 "
954Available lint options:
955 -W <foo> Warn about <foo>
956 -A <foo> Allow <foo>
957 -D <foo> Deny <foo>
958 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
959
960"
961 );
962
963 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
964 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
966 lints
967 }
968
969 fn sort_lint_groups(
970 lints: Vec<(&'static str, Vec<LintId>, bool)>,
971 ) -> Vec<(&'static str, Vec<LintId>)> {
972 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
973 lints.sort_by_key(|l| l.0);
974 lints
975 }
976
977 let lint_store = unerased_lint_store(sess);
978 let (loaded, builtin): (Vec<_>, _) =
979 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
980 let loaded = sort_lints(sess, loaded);
981 let builtin = sort_lints(sess, builtin);
982
983 let (loaded_groups, builtin_groups): (Vec<_>, _) =
984 lint_store.get_lint_groups().partition(|&(.., p)| p);
985 let loaded_groups = sort_lint_groups(loaded_groups);
986 let builtin_groups = sort_lint_groups(builtin_groups);
987
988 let max_name_len =
989 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
990 let padded = |x: &str| {
991 let mut s = " ".repeat(max_name_len - x.chars().count());
992 s.push_str(x);
993 s
994 };
995
996 safe_println!("Lint checks provided by rustc:\n");
997
998 let print_lints = |lints: Vec<&Lint>| {
999 safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1000 safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1001 for lint in lints {
1002 let name = lint.name_lower().replace('_', "-");
1003 safe_println!(
1004 " {} {:7.7} {}",
1005 padded(&name),
1006 lint.default_level(sess.edition()).as_str(),
1007 lint.desc
1008 );
1009 }
1010 safe_println!("\n");
1011 };
1012
1013 print_lints(builtin);
1014
1015 let max_name_len = max(
1016 "warnings".len(),
1017 loaded_groups
1018 .iter()
1019 .chain(&builtin_groups)
1020 .map(|&(s, _)| s.chars().count())
1021 .max()
1022 .unwrap_or(0),
1023 );
1024
1025 let padded = |x: &str| {
1026 let mut s = " ".repeat(max_name_len - x.chars().count());
1027 s.push_str(x);
1028 s
1029 };
1030
1031 safe_println!("Lint groups provided by rustc:\n");
1032
1033 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1034 safe_println!(" {} sub-lints", padded("name"));
1035 safe_println!(" {} ---------", padded("----"));
1036
1037 if all_warnings {
1038 safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1039 }
1040
1041 for (name, to) in lints {
1042 let name = name.to_lowercase().replace('_', "-");
1043 let desc = to
1044 .into_iter()
1045 .map(|x| x.to_string().replace('_', "-"))
1046 .collect::<Vec<String>>()
1047 .join(", ");
1048 safe_println!(" {} {}", padded(&name), desc);
1049 }
1050 safe_println!("\n");
1051 };
1052
1053 print_lint_groups(builtin_groups, true);
1054
1055 match (registered_lints, loaded.len(), loaded_groups.len()) {
1056 (false, 0, _) | (false, _, 0) => {
1057 safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1058 }
1059 (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1060 (true, 0, 0) => {
1061 safe_println!("This crate does not load any additional lints or lint groups.")
1062 }
1063 (true, l, g) => {
1064 if l > 0 {
1065 safe_println!("Lint checks loaded by this crate:\n");
1066 print_lints(loaded);
1067 }
1068 if g > 0 {
1069 safe_println!("Lint groups loaded by this crate:\n");
1070 print_lint_groups(loaded_groups, false);
1071 }
1072 }
1073 }
1074}
1075
1076pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1080 let wall = matches.opt_strs("W");
1082 if wall.iter().any(|x| *x == "all") {
1083 print_wall_help();
1084 return true;
1085 }
1086
1087 let debug_flags = matches.opt_strs("Z");
1089 if debug_flags.iter().any(|x| *x == "help") {
1090 describe_debug_flags();
1091 return true;
1092 }
1093
1094 let cg_flags = matches.opt_strs("C");
1095 if cg_flags.iter().any(|x| *x == "help") {
1096 describe_codegen_flags();
1097 return true;
1098 }
1099
1100 if cg_flags.iter().any(|x| *x == "passes=list") {
1101 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1102 return true;
1103 }
1104
1105 false
1106}
1107
1108fn get_backend_from_raw_matches(
1115 early_dcx: &EarlyDiagCtxt,
1116 matches: &Matches,
1117) -> Box<dyn CodegenBackend> {
1118 let debug_flags = matches.opt_strs("Z");
1119 let backend_name = debug_flags
1120 .iter()
1121 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1122 let target = parse_target_triple(early_dcx, matches);
1123 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1124 let target = config::build_target_config(early_dcx, &target, sysroot.path());
1125
1126 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1127}
1128
1129fn describe_debug_flags() {
1130 safe_println!("\nAvailable options:\n");
1131 print_flag_list("-Z", config::Z_OPTIONS);
1132}
1133
1134fn describe_codegen_flags() {
1135 safe_println!("\nAvailable codegen options:\n");
1136 print_flag_list("-C", config::CG_OPTIONS);
1137}
1138
1139fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1140 let max_len =
1141 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1142
1143 for opt_desc in flag_list {
1144 safe_println!(
1145 " {} {:>width$}=val -- {}",
1146 cmdline_opt,
1147 opt_desc.name().replace('_', "-"),
1148 opt_desc.desc(),
1149 width = max_len
1150 );
1151 }
1152}
1153
1154pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1182 let mut options = getopts::Options::new();
1185 let optgroups = config::rustc_optgroups();
1186 for option in &optgroups {
1187 option.apply(&mut options);
1188 }
1189 let matches = options.parse(args).unwrap_or_else(|e| {
1190 let msg: Option<String> = match e {
1191 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1192 .iter()
1193 .map(|opt_desc| ('C', opt_desc.name()))
1194 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1195 .find(|&(_, name)| *opt == name.replace('_', "-"))
1196 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1197 getopts::Fail::ArgumentMissing(ref opt) => {
1198 optgroups.iter().find(|option| option.name == opt).map(|option| {
1199 let mut options = getopts::Options::new();
1201 option.apply(&mut options);
1202 options.usage_with_format(|it| {
1205 it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1206 })
1207 })
1208 }
1209 _ => None,
1210 };
1211 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1212 });
1213
1214 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1226
1227 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1228 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1230 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1231 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1232 return None;
1233 }
1234
1235 if describe_flag_categories(early_dcx, &matches) {
1236 return None;
1237 }
1238
1239 if matches.opt_present("version") {
1240 version!(early_dcx, "rustc", &matches);
1241 return None;
1242 }
1243
1244 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1245
1246 Some(matches)
1247}
1248
1249fn warn_on_confusing_output_filename_flag(
1253 early_dcx: &EarlyDiagCtxt,
1254 matches: &getopts::Matches,
1255 args: &[String],
1256) {
1257 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1258 let s1 = s1.replace('-', "_");
1259 let s2 = s2.replace('-', "_");
1260 s1 == s2
1261 }
1262
1263 if let Some(name) = matches.opt_str("o")
1264 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1265 {
1266 let filename = suspect.strip_prefix("-").unwrap_or(suspect);
1267 let optgroups = config::rustc_optgroups();
1268 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1269
1270 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1277 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1278 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1279 {
1280 early_dcx.early_warn(
1281 "option `-o` has no space between flag name and value, which can be confusing",
1282 );
1283 early_dcx.early_note(format!(
1284 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1285 ));
1286 early_dcx.early_help(format!(
1287 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1288 ));
1289 }
1290 }
1291}
1292
1293fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1294 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1295 Input::File(file) => {
1296 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1297 }
1298 Input::Str { name, input } => new_parser_from_source_str(
1299 &sess.psess,
1300 name.clone(),
1301 input.clone(),
1302 StripTokens::ShebangAndFrontmatter,
1303 ),
1304 });
1305 parser.parse_inner_attributes()
1306}
1307
1308pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1314 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1315 if value.is::<rustc_errors::FatalErrorMarker>() {
1316 FatalError
1317 } else {
1318 panic::resume_unwind(value);
1319 }
1320 })
1321}
1322
1323pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1326 match catch_fatal_errors(f) {
1327 Ok(()) => EXIT_SUCCESS,
1328 _ => EXIT_FAILURE,
1329 }
1330}
1331
1332static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1333
1334fn ice_path() -> &'static Option<PathBuf> {
1342 ice_path_with_config(None)
1343}
1344
1345fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1346 if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1347 tracing::warn!(
1348 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1349 )
1350 }
1351
1352 ICE_PATH.get_or_init(|| {
1353 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1354 return None;
1355 }
1356 let mut path = match std::env::var_os("RUSTC_ICE") {
1357 Some(s) => {
1358 if s == "0" {
1359 return None;
1361 }
1362 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1363 tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1364 }
1365 PathBuf::from(s)
1366 }
1367 None => config
1368 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1369 .or_else(|| std::env::current_dir().ok())
1370 .unwrap_or_default(),
1371 };
1372 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1374 let pid = std::process::id();
1375 path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1376 Some(path)
1377 })
1378}
1379
1380pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1381
1382pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1394 if env::var_os("RUST_BACKTRACE").is_none() {
1401 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1403 if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1404 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1405 } else {
1406 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1407 }
1408 }
1409
1410 panic::update_hook(Box::new(
1411 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1412 info: &PanicHookInfo<'_>| {
1413 let _guard = io::stderr().lock();
1415 #[cfg(windows)]
1418 if let Some(msg) = info.payload().downcast_ref::<String>() {
1419 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1420 {
1421 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1423 let _ = early_dcx.early_err(msg.clone());
1424 return;
1425 }
1426 };
1427
1428 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1431 default_hook(info);
1432 eprintln!();
1434
1435 if let Some(ice_path) = ice_path()
1436 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1437 {
1438 let location = info.location().unwrap();
1440 let msg = match info.payload().downcast_ref::<&'static str>() {
1441 Some(s) => *s,
1442 None => match info.payload().downcast_ref::<String>() {
1443 Some(s) => &s[..],
1444 None => "Box<dyn Any>",
1445 },
1446 };
1447 let thread = std::thread::current();
1448 let name = thread.name().unwrap_or("<unnamed>");
1449 let _ = write!(
1450 &mut out,
1451 "thread '{name}' panicked at {location}:\n\
1452 {msg}\n\
1453 stack backtrace:\n\
1454 {:#}",
1455 std::backtrace::Backtrace::force_capture()
1456 );
1457 }
1458 }
1459
1460 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1462 },
1463 ));
1464}
1465
1466fn report_ice(
1473 info: &panic::PanicHookInfo<'_>,
1474 bug_report_url: &str,
1475 extra_info: fn(&DiagCtxt),
1476 using_internal_features: &AtomicBool,
1477) {
1478 let translator = default_translator();
1479 let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1480 stderr_destination(rustc_errors::ColorConfig::Auto),
1481 translator,
1482 ));
1483 let dcx = rustc_errors::DiagCtxt::new(emitter);
1484 let dcx = dcx.handle();
1485
1486 if !info.payload().is::<rustc_errors::ExplicitBug>()
1489 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1490 {
1491 dcx.emit_err(session_diagnostics::Ice);
1492 }
1493
1494 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1495 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1496 } else {
1497 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1498
1499 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1501 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1502 }
1503 }
1504
1505 let version = util::version_str!().unwrap_or("unknown_version");
1506 let tuple = config::host_tuple();
1507
1508 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1509
1510 let file = if let Some(path) = ice_path() {
1511 match crate::fs::File::options().create(true).append(true).open(path) {
1513 Ok(mut file) => {
1514 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1515 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1516 let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1517 }
1518 Some(file)
1519 }
1520 Err(err) => {
1521 dcx.emit_warn(session_diagnostics::IcePathError {
1523 path: path.clone(),
1524 error: err.to_string(),
1525 env_var: std::env::var_os("RUSTC_ICE")
1526 .map(PathBuf::from)
1527 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1528 });
1529 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1530 None
1531 }
1532 }
1533 } else {
1534 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1535 None
1536 };
1537
1538 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1539 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1540 if excluded_cargo_defaults {
1541 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1542 }
1543 }
1544
1545 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1547
1548 let limit_frames = if backtrace { None } else { Some(2) };
1549
1550 interface::try_print_query_stack(dcx, limit_frames, file);
1551
1552 extra_info(&dcx);
1555
1556 #[cfg(windows)]
1557 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1558 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1560 }
1561}
1562
1563pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1566 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1567}
1568
1569pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1573 if let Err(error) = rustc_log::init_logger(cfg) {
1574 early_dcx.early_fatal(error.to_string());
1575 }
1576}
1577
1578pub fn init_logger_with_additional_layer<F, T>(
1584 early_dcx: &EarlyDiagCtxt,
1585 cfg: rustc_log::LoggerConfig,
1586 build_subscriber: F,
1587) where
1588 F: FnOnce() -> T,
1589 T: rustc_log::BuildSubscriberRet,
1590{
1591 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1592 early_dcx.early_fatal(error.to_string());
1593 }
1594}
1595
1596pub fn install_ctrlc_handler() {
1599 #[cfg(all(not(miri), not(target_family = "wasm")))]
1600 ctrlc::set_handler(move || {
1601 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1606 std::thread::sleep(std::time::Duration::from_millis(100));
1607 std::process::exit(1);
1608 })
1609 .expect("Unable to install ctrlc handler");
1610}
1611
1612pub fn main() -> ! {
1613 let start_time = Instant::now();
1614 let start_rss = get_resident_set_size();
1615
1616 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1617
1618 init_rustc_env_logger(&early_dcx);
1619 signal_handler::install();
1620 let mut callbacks = TimePassesCallbacks::default();
1621 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1622 install_ctrlc_handler();
1623
1624 let exit_code =
1625 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1626
1627 if let Some(format) = callbacks.time_passes {
1628 let end_rss = get_resident_set_size();
1629 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1630 }
1631
1632 process::exit(exit_code)
1633}