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