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::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
42use rustc_feature::find_gated_cfg;
43use rustc_index as _;
47use rustc_interface::util::{self, get_codegen_backend};
48use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
49use rustc_lint::unerased_lint_store;
50use rustc_metadata::creader::MetadataLoader;
51use rustc_metadata::locator;
52use rustc_middle::ty::TyCtxt;
53use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
54use rustc_session::config::{
55 CG_OPTIONS, CrateType, ErrorOutputType, Input, OptionDesc, OutFileName, OutputType,
56 UnstableOptions, Z_OPTIONS, nightly_options, parse_target_triple,
57};
58use rustc_session::getopts::{self, Matches};
59use rustc_session::lint::{Lint, LintId};
60use rustc_session::output::{CRATE_TYPES, collect_crate_types, invalid_output_for_target};
61use rustc_session::{EarlyDiagCtxt, Session, config, filesearch};
62use rustc_span::FileName;
63use rustc_span::def_id::LOCAL_CRATE;
64use rustc_target::json::ToJson;
65use rustc_target::spec::{Target, TargetTuple};
66use tracing::trace;
67
68#[allow(unused_macros)]
69macro do_not_use_print($($t:tt)*) {
70 std::compile_error!(
71 "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
72 )
73}
74
75#[allow(unused_macros)]
76macro do_not_use_safe_print($($t:tt)*) {
77 std::compile_error!("Don't use `safe_print` or `safe_println` here, use `println_info` instead")
78}
79
80#[allow(unused_imports)]
84use {do_not_use_print as print, do_not_use_print as println};
85
86pub mod args;
87pub mod pretty;
88#[macro_use]
89mod print;
90mod session_diagnostics;
91
92#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
96mod signal_handler;
97
98#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
99mod signal_handler {
100 pub(super) fn install() {}
103}
104
105use crate::session_diagnostics::{
106 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
107 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
108};
109
110rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
111
112pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
113 crate::DEFAULT_LOCALE_RESOURCE,
115 rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
116 rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
117 rustc_attr_parsing::DEFAULT_LOCALE_RESOURCE,
118 rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
119 rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
120 rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
121 rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
122 rustc_errors::DEFAULT_LOCALE_RESOURCE,
123 rustc_expand::DEFAULT_LOCALE_RESOURCE,
124 rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
125 rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
126 rustc_incremental::DEFAULT_LOCALE_RESOURCE,
127 rustc_infer::DEFAULT_LOCALE_RESOURCE,
128 rustc_interface::DEFAULT_LOCALE_RESOURCE,
129 rustc_lint::DEFAULT_LOCALE_RESOURCE,
130 rustc_metadata::DEFAULT_LOCALE_RESOURCE,
131 rustc_middle::DEFAULT_LOCALE_RESOURCE,
132 rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
133 rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
134 rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
135 rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
136 rustc_parse::DEFAULT_LOCALE_RESOURCE,
137 rustc_passes::DEFAULT_LOCALE_RESOURCE,
138 rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE,
139 rustc_privacy::DEFAULT_LOCALE_RESOURCE,
140 rustc_query_system::DEFAULT_LOCALE_RESOURCE,
141 rustc_resolve::DEFAULT_LOCALE_RESOURCE,
142 rustc_session::DEFAULT_LOCALE_RESOURCE,
143 rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
144 rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
145 ];
147
148pub const EXIT_SUCCESS: i32 = 0;
150
151pub const EXIT_FAILURE: i32 = 1;
153
154pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
155 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
156
157pub trait Callbacks {
158 fn config(&mut self, _config: &mut interface::Config) {}
160 fn after_crate_root_parsing(
164 &mut self,
165 _compiler: &interface::Compiler,
166 _krate: &mut ast::Crate,
167 ) -> Compilation {
168 Compilation::Continue
169 }
170 fn after_expansion<'tcx>(
173 &mut self,
174 _compiler: &interface::Compiler,
175 _tcx: TyCtxt<'tcx>,
176 ) -> Compilation {
177 Compilation::Continue
178 }
179 fn after_analysis<'tcx>(
182 &mut self,
183 _compiler: &interface::Compiler,
184 _tcx: TyCtxt<'tcx>,
185 ) -> Compilation {
186 Compilation::Continue
187 }
188}
189
190#[derive(Default)]
191pub struct TimePassesCallbacks {
192 time_passes: Option<TimePassesFormat>,
193}
194
195impl Callbacks for TimePassesCallbacks {
196 #[allow(rustc::bad_opt_access)]
198 fn config(&mut self, config: &mut interface::Config) {
199 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
203 .then(|| config.opts.unstable_opts.time_passes_format);
204 config.opts.trimmed_def_paths = true;
205 }
206}
207
208pub fn diagnostics_registry() -> Registry {
209 Registry::new(rustc_errors::codes::DIAGNOSTICS)
210}
211
212pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
214 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
215
216 let at_args = at_args.get(1..).unwrap_or_default();
225
226 let args = args::arg_expand_all(&default_early_dcx, at_args);
227
228 let Some(matches) = handle_options(&default_early_dcx, &args) else {
229 return;
230 };
231
232 let sopts = config::build_session_options(&mut default_early_dcx, &matches);
233 let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
235
236 if let Some(ref code) = matches.opt_str("explain") {
237 handle_explain(&default_early_dcx, diagnostics_registry(), code, sopts.color);
238 return;
239 }
240
241 let input = make_input(&default_early_dcx, &matches.free);
242 let has_input = input.is_some();
243 let (odir, ofile) = make_output(&matches);
244
245 drop(default_early_dcx);
246
247 let mut config = interface::Config {
248 opts: sopts,
249 crate_cfg: matches.opt_strs("cfg"),
250 crate_check_cfg: matches.opt_strs("check-cfg"),
251 input: input.unwrap_or(Input::File(PathBuf::new())),
252 output_file: ofile,
253 output_dir: odir,
254 ice_file,
255 file_loader: None,
256 locale_resources: DEFAULT_LOCALE_RESOURCES.to_vec(),
257 lint_caps: Default::default(),
258 psess_created: None,
259 hash_untracked_state: None,
260 register_lints: None,
261 override_queries: None,
262 extra_symbols: Vec::new(),
263 make_codegen_backend: None,
264 registry: diagnostics_registry(),
265 using_internal_features: &USING_INTERNAL_FEATURES,
266 expanded_args: args,
267 };
268
269 callbacks.config(&mut config);
270
271 let registered_lints = config.register_lints.is_some();
272
273 interface::run_compiler(config, |compiler| {
274 let sess = &compiler.sess;
275 let codegen_backend = &*compiler.codegen_backend;
276
277 let early_exit = || {
281 sess.dcx().abort_if_errors();
282 };
283
284 if sess.opts.describe_lints {
288 describe_lints(sess, registered_lints);
289 return early_exit();
290 }
291
292 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
293 return early_exit();
294 }
295
296 if !has_input {
297 #[allow(rustc::diagnostic_outside_of_impl)]
298 sess.dcx().fatal("no input filename given"); }
300
301 if !sess.opts.unstable_opts.ls.is_empty() {
302 list_metadata(sess, &*codegen_backend.metadata_loader());
303 return early_exit();
304 }
305
306 if sess.opts.unstable_opts.link_only {
307 process_rlink(sess, compiler);
308 return early_exit();
309 }
310
311 let mut krate = passes::parse(sess);
314
315 if let Some(pp_mode) = sess.opts.pretty {
317 if pp_mode.needs_ast_map() {
318 create_and_enter_global_ctxt(compiler, krate, |tcx| {
319 tcx.ensure_ok().early_lint_checks(());
320 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
321 passes::write_dep_info(tcx);
322 });
323 } else {
324 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
325 }
326 trace!("finished pretty-printing");
327 return early_exit();
328 }
329
330 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
331 return early_exit();
332 }
333
334 if sess.opts.unstable_opts.parse_crate_root_only {
335 return early_exit();
336 }
337
338 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
339 let early_exit = || {
340 sess.dcx().abort_if_errors();
341 None
342 };
343
344 let _ = tcx.resolver_for_lowering();
346
347 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
348 return early_exit();
349 }
350
351 passes::write_dep_info(tcx);
352
353 passes::write_interface(tcx);
354
355 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
356 && sess.opts.output_types.len() == 1
357 {
358 return early_exit();
359 }
360
361 if sess.opts.unstable_opts.no_analysis {
362 return early_exit();
363 }
364
365 tcx.ensure_ok().analysis(());
366
367 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
368 dump_feature_usage_metrics(tcx, metrics_dir);
369 }
370
371 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
372 return early_exit();
373 }
374
375 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
376 if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
377 tcx.dcx().emit_fatal(CantEmitMIR { error });
378 }
379 }
380
381 Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
382 });
383
384 if let Some(linker) = linker {
387 linker.link(sess, codegen_backend);
388 }
389 })
390}
391
392fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
393 let hash = tcxt.crate_hash(LOCAL_CRATE);
394 let crate_name = tcxt.crate_name(LOCAL_CRATE);
395 let metrics_file_name = format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
396 let metrics_path = metrics_dir.join(metrics_file_name);
397 if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
398 tcxt.dcx().emit_err(UnstableFeatureUsage { error });
402 }
403}
404
405fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
407 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
408 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
409 "-" => OutFileName::Stdout,
410 path => OutFileName::Real(PathBuf::from(path)),
411 });
412 (odir, ofile)
413}
414
415fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
418 match free_matches {
419 [] => None, [ifile] if ifile == "-" => {
421 let mut input = String::new();
423 if io::stdin().read_to_string(&mut input).is_err() {
424 early_dcx
427 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
428 }
429
430 let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
431 Ok(path) => {
432 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
433 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
434 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
435 );
436 let line = isize::from_str_radix(&line, 10)
437 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
438 FileName::doc_test_source_code(PathBuf::from(path), line)
439 }
440 Err(_) => FileName::anon_source_code(&input),
441 };
442
443 Some(Input::Str { name, input })
444 }
445 [ifile] => Some(Input::File(PathBuf::from(ifile))),
446 [ifile1, ifile2, ..] => early_dcx.early_fatal(format!(
447 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
448 ifile1, ifile2
449 )),
450 }
451}
452
453#[derive(Copy, Clone, Debug, Eq, PartialEq)]
455pub enum Compilation {
456 Stop,
457 Continue,
458}
459
460fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
461 let upper_cased_code = code.to_ascii_uppercase();
463 if let Ok(code) = upper_cased_code.strip_prefix('E').unwrap_or(&upper_cased_code).parse::<u32>()
464 && code <= ErrCode::MAX_AS_U32
465 && let Ok(description) = registry.try_find_description(ErrCode::from_u32(code))
466 {
467 let mut is_in_code_block = false;
468 let mut text = String::new();
469 for line in description.lines() {
471 let indent_level =
472 line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
473 let dedented_line = &line[indent_level..];
474 if dedented_line.starts_with("```") {
475 is_in_code_block = !is_in_code_block;
476 text.push_str(&line[..(indent_level + 3)]);
477 } else if is_in_code_block && dedented_line.starts_with("# ") {
478 continue;
479 } else {
480 text.push_str(line);
481 }
482 text.push('\n');
483 }
484 if io::stdout().is_terminal() {
485 show_md_content_with_pager(&text, color);
486 } else {
487 safe_print!("{text}");
488 }
489 } else {
490 early_dcx.early_fatal(format!("{code} is not a valid error code"));
491 }
492}
493
494fn show_md_content_with_pager(content: &str, color: ColorConfig) {
499 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
500 if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
501 });
502
503 let mut cmd = Command::new(&pager_name);
504 if pager_name == "less" {
505 cmd.arg("-R"); }
507
508 let pretty_on_pager = match color {
509 ColorConfig::Auto => {
510 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
512 }
513 ColorConfig::Always => true,
514 ColorConfig::Never => false,
515 };
516
517 let pretty_data = {
519 let mdstream = markdown::MdStream::parse_str(content);
520 let bufwtr = markdown::create_stdout_bufwtr();
521 let mut mdbuf = bufwtr.buffer();
522 if mdstream.write_termcolor_buf(&mut mdbuf).is_ok() { Some((bufwtr, mdbuf)) } else { None }
523 };
524
525 let pager_res: Option<()> = try {
527 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
528
529 let pager_stdin = pager.stdin.as_mut()?;
530 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
531 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
532 } else {
533 pager_stdin.write_all(content.as_bytes()).ok()?;
534 };
535
536 pager.wait().ok()?;
537 };
538 if pager_res.is_some() {
539 return;
540 }
541
542 if let Some((bufwtr, mdbuf)) = &pretty_data
544 && bufwtr.print(&mdbuf).is_ok()
545 {
546 return;
547 }
548
549 safe_print!("{content}");
551}
552
553fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
554 assert!(sess.opts.unstable_opts.link_only);
555 let dcx = sess.dcx();
556 if let Input::File(file) = &sess.io.input {
557 let rlink_data = fs::read(file).unwrap_or_else(|err| {
558 dcx.emit_fatal(RlinkUnableToRead { err });
559 });
560 let (codegen_results, outputs) = match CodegenResults::deserialize_rlink(sess, rlink_data) {
561 Ok((codegen, outputs)) => (codegen, outputs),
562 Err(err) => {
563 match err {
564 CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
565 CodegenErrors::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
566 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => dcx
567 .emit_fatal(RLinkEncodingVersionMismatch { version_array, rlink_version }),
568 CodegenErrors::RustcVersionMismatch { rustc_version } => {
569 dcx.emit_fatal(RLinkRustcVersionMismatch {
570 rustc_version,
571 current_version: sess.cfg_version,
572 })
573 }
574 CodegenErrors::CorruptFile => {
575 dcx.emit_fatal(RlinkCorruptFile { file });
576 }
577 };
578 }
579 };
580 compiler.codegen_backend.link(sess, codegen_results, &outputs);
581 } else {
582 dcx.emit_fatal(RlinkNotAFile {});
583 }
584}
585
586fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
587 match sess.io.input {
588 Input::File(ref ifile) => {
589 let path = &(*ifile);
590 let mut v = Vec::new();
591 locator::list_file_metadata(
592 &sess.target,
593 path,
594 metadata_loader,
595 &mut v,
596 &sess.opts.unstable_opts.ls,
597 sess.cfg_version,
598 )
599 .unwrap();
600 safe_println!("{}", String::from_utf8(v).unwrap());
601 }
602 Input::Str { .. } => {
603 #[allow(rustc::diagnostic_outside_of_impl)]
604 sess.dcx().fatal("cannot list metadata for stdin");
605 }
606 }
607}
608
609fn print_crate_info(
610 codegen_backend: &dyn CodegenBackend,
611 sess: &Session,
612 parse_attrs: bool,
613) -> Compilation {
614 use rustc_session::config::PrintKind::*;
615 #[allow(unused_imports)]
619 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
620
621 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
624 return Compilation::Continue;
625 }
626
627 let attrs = if parse_attrs {
628 let result = parse_crate_attrs(sess);
629 match result {
630 Ok(attrs) => Some(attrs),
631 Err(parse_error) => {
632 parse_error.emit();
633 return Compilation::Stop;
634 }
635 }
636 } else {
637 None
638 };
639
640 for req in &sess.opts.prints {
641 let mut crate_info = String::new();
642 macro println_info($($arg:tt)*) {
643 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
644 }
645
646 match req.kind {
647 TargetList => {
648 let mut targets = rustc_target::spec::TARGETS.to_vec();
649 targets.sort_unstable();
650 println_info!("{}", targets.join("\n"));
651 }
652 HostTuple => println_info!("{}", rustc_session::config::host_tuple()),
653 Sysroot => println_info!("{}", sess.sysroot.display()),
654 TargetLibdir => println_info!("{}", sess.target_tlib_path.dir.display()),
655 TargetSpecJson => {
656 println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
657 }
658 AllTargetSpecsJson => {
659 let mut targets = BTreeMap::new();
660 for name in rustc_target::spec::TARGETS {
661 let triple = TargetTuple::from_tuple(name);
662 let target = Target::expect_builtin(&triple);
663 targets.insert(name, target.to_json());
664 }
665 println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
666 }
667 FileNames => {
668 let Some(attrs) = attrs.as_ref() else {
669 return Compilation::Continue;
671 };
672 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
673 let crate_name = passes::get_crate_name(sess, attrs);
674 let crate_types = collect_crate_types(sess, attrs);
675 for &style in &crate_types {
676 let fname = rustc_session::output::filename_for_input(
677 sess, style, crate_name, &t_outputs,
678 );
679 println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
680 }
681 }
682 CrateName => {
683 let Some(attrs) = attrs.as_ref() else {
684 return Compilation::Continue;
686 };
687 println_info!("{}", passes::get_crate_name(sess, attrs));
688 }
689 CrateRootLintLevels => {
690 let Some(attrs) = attrs.as_ref() else {
691 return Compilation::Continue;
693 };
694 let crate_name = passes::get_crate_name(sess, attrs);
695 let lint_store = crate::unerased_lint_store(sess);
696 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
697 let features = rustc_expand::config::features(sess, attrs, crate_name);
698 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
699 sess,
700 &features,
701 true,
702 lint_store,
703 ®istered_tools,
704 attrs,
705 );
706 for lint in lint_store.get_lints() {
707 if let Some(feature_symbol) = lint.feature_gate
708 && !features.enabled(feature_symbol)
709 {
710 continue;
712 }
713 let level = lint_levels.lint_level(lint).level;
714 println_info!("{}={}", lint.name_lower(), level.as_str());
715 }
716 }
717 Cfg => {
718 let mut cfgs = sess
719 .psess
720 .config
721 .iter()
722 .filter_map(|&(name, value)| {
723 if !sess.is_nightly_build()
725 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
726 {
727 return None;
728 }
729
730 if let Some(value) = value {
731 Some(format!("{name}=\"{value}\""))
732 } else {
733 Some(name.to_string())
734 }
735 })
736 .collect::<Vec<String>>();
737
738 cfgs.sort();
739 for cfg in cfgs {
740 println_info!("{cfg}");
741 }
742 }
743 CheckCfg => {
744 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
745
746 #[allow(rustc::potential_query_instability)]
748 for (name, expected_values) in &sess.psess.check_config.expecteds {
749 use crate::config::ExpectedValues;
750 match expected_values {
751 ExpectedValues::Any => check_cfgs.push(format!("{name}=any()")),
752 ExpectedValues::Some(values) => {
753 if !values.is_empty() {
754 check_cfgs.extend(values.iter().map(|value| {
755 if let Some(value) = value {
756 format!("{name}=\"{value}\"")
757 } else {
758 name.to_string()
759 }
760 }))
761 } else {
762 check_cfgs.push(format!("{name}="))
763 }
764 }
765 }
766 }
767
768 check_cfgs.sort_unstable();
769 if !sess.psess.check_config.exhaustive_names {
770 if !sess.psess.check_config.exhaustive_values {
771 println_info!("any()=any()");
772 } else {
773 println_info!("any()");
774 }
775 }
776 for check_cfg in check_cfgs {
777 println_info!("{check_cfg}");
778 }
779 }
780 CallingConventions => {
781 let calling_conventions = rustc_abi::all_names();
782 println_info!("{}", calling_conventions.join("\n"));
783 }
784 RelocationModels
785 | CodeModels
786 | TlsModels
787 | TargetCPUs
788 | StackProtectorStrategies
789 | TargetFeatures => {
790 codegen_backend.print(req, &mut crate_info, sess);
791 }
792 NativeStaticLibs => {}
794 LinkArgs => {}
795 SplitDebuginfo => {
796 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
797
798 for split in &[Off, Packed, Unpacked] {
799 if sess.target.options.supported_split_debuginfo.contains(split) {
800 println_info!("{split}");
801 }
802 }
803 }
804 DeploymentTarget => {
805 if sess.target.is_like_darwin {
806 println_info!(
807 "{}={}",
808 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
809 sess.apple_deployment_target().fmt_pretty(),
810 )
811 } else {
812 #[allow(rustc::diagnostic_outside_of_impl)]
813 sess.dcx().fatal("only Apple targets currently support deployment version info")
814 }
815 }
816 SupportedCrateTypes => {
817 let supported_crate_types = CRATE_TYPES
818 .iter()
819 .filter(|(_, crate_type)| !invalid_output_for_target(&sess, *crate_type))
820 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
821 .map(|(crate_type_sym, _)| *crate_type_sym)
822 .collect::<BTreeSet<_>>();
823 for supported_crate_type in supported_crate_types {
824 println_info!("{}", supported_crate_type.as_str());
825 }
826 }
827 }
828
829 req.out.overwrite(&crate_info, sess);
830 }
831 Compilation::Stop
832}
833
834pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
838 fn unw(x: Option<&str>) -> &str {
839 x.unwrap_or("unknown")
840 }
841 $crate::version_at_macro_invocation(
842 $early_dcx,
843 $binary,
844 $matches,
845 unw(option_env!("CFG_VERSION")),
846 unw(option_env!("CFG_VER_HASH")),
847 unw(option_env!("CFG_VER_DATE")),
848 unw(option_env!("CFG_RELEASE")),
849 )
850}
851
852#[doc(hidden)] pub fn version_at_macro_invocation(
854 early_dcx: &EarlyDiagCtxt,
855 binary: &str,
856 matches: &getopts::Matches,
857 version: &str,
858 commit_hash: &str,
859 commit_date: &str,
860 release: &str,
861) {
862 let verbose = matches.opt_present("verbose");
863
864 let mut version = version;
865 let mut release = release;
866 let tmp;
867 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
868 tmp = force_version;
869 version = &tmp;
870 release = &tmp;
871 }
872
873 safe_println!("{binary} {version}");
874
875 if verbose {
876 safe_println!("binary: {binary}");
877 safe_println!("commit-hash: {commit_hash}");
878 safe_println!("commit-date: {commit_date}");
879 safe_println!("host: {}", config::host_tuple());
880 safe_println!("release: {release}");
881
882 get_backend_from_raw_matches(early_dcx, matches).print_version();
883 }
884}
885
886fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
887 let mut options = getopts::Options::new();
888 for option in config::rustc_optgroups()
889 .iter()
890 .filter(|x| verbose || !x.is_verbose_help_only)
891 .filter(|x| include_unstable_options || x.is_stable())
892 {
893 option.apply(&mut options);
894 }
895 let message = "Usage: rustc [OPTIONS] INPUT";
896 let nightly_help = if nightly_build {
897 "\n -Z help Print unstable compiler options"
898 } else {
899 ""
900 };
901 let verbose_help = if verbose {
902 ""
903 } else {
904 "\n --help -v Print the full set of options rustc accepts"
905 };
906 let at_path = if verbose {
907 " @path Read newline separated options from `path`\n"
908 } else {
909 ""
910 };
911 safe_println!(
912 "{options}{at_path}\nAdditional help:
913 -C help Print codegen options
914 -W help \
915 Print 'lint' options and default settings{nightly}{verbose}\n",
916 options = options.usage(message),
917 at_path = at_path,
918 nightly = nightly_help,
919 verbose = verbose_help
920 );
921}
922
923fn print_wall_help() {
924 safe_println!(
925 "
926The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
927default. Use `rustc -W help` to see all available lints. It's more common to put
928warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
929the command line flag directly.
930"
931 );
932}
933
934pub fn describe_lints(sess: &Session, registered_lints: bool) {
936 safe_println!(
937 "
938Available lint options:
939 -W <foo> Warn about <foo>
940 -A <foo> Allow <foo>
941 -D <foo> Deny <foo>
942 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
943
944"
945 );
946
947 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
948 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
950 lints
951 }
952
953 fn sort_lint_groups(
954 lints: Vec<(&'static str, Vec<LintId>, bool)>,
955 ) -> Vec<(&'static str, Vec<LintId>)> {
956 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
957 lints.sort_by_key(|l| l.0);
958 lints
959 }
960
961 let lint_store = unerased_lint_store(sess);
962 let (loaded, builtin): (Vec<_>, _) =
963 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
964 let loaded = sort_lints(sess, loaded);
965 let builtin = sort_lints(sess, builtin);
966
967 let (loaded_groups, builtin_groups): (Vec<_>, _) =
968 lint_store.get_lint_groups().partition(|&(.., p)| p);
969 let loaded_groups = sort_lint_groups(loaded_groups);
970 let builtin_groups = sort_lint_groups(builtin_groups);
971
972 let max_name_len =
973 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
974 let padded = |x: &str| {
975 let mut s = " ".repeat(max_name_len - x.chars().count());
976 s.push_str(x);
977 s
978 };
979
980 safe_println!("Lint checks provided by rustc:\n");
981
982 let print_lints = |lints: Vec<&Lint>| {
983 safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
984 safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
985 for lint in lints {
986 let name = lint.name_lower().replace('_', "-");
987 safe_println!(
988 " {} {:7.7} {}",
989 padded(&name),
990 lint.default_level(sess.edition()).as_str(),
991 lint.desc
992 );
993 }
994 safe_println!("\n");
995 };
996
997 print_lints(builtin);
998
999 let max_name_len = max(
1000 "warnings".len(),
1001 loaded_groups
1002 .iter()
1003 .chain(&builtin_groups)
1004 .map(|&(s, _)| s.chars().count())
1005 .max()
1006 .unwrap_or(0),
1007 );
1008
1009 let padded = |x: &str| {
1010 let mut s = " ".repeat(max_name_len - x.chars().count());
1011 s.push_str(x);
1012 s
1013 };
1014
1015 safe_println!("Lint groups provided by rustc:\n");
1016
1017 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1018 safe_println!(" {} sub-lints", padded("name"));
1019 safe_println!(" {} ---------", padded("----"));
1020
1021 if all_warnings {
1022 safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1023 }
1024
1025 for (name, to) in lints {
1026 let name = name.to_lowercase().replace('_', "-");
1027 let desc = to
1028 .into_iter()
1029 .map(|x| x.to_string().replace('_', "-"))
1030 .collect::<Vec<String>>()
1031 .join(", ");
1032 safe_println!(" {} {}", padded(&name), desc);
1033 }
1034 safe_println!("\n");
1035 };
1036
1037 print_lint_groups(builtin_groups, true);
1038
1039 match (registered_lints, loaded.len(), loaded_groups.len()) {
1040 (false, 0, _) | (false, _, 0) => {
1041 safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1042 }
1043 (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1044 (true, 0, 0) => {
1045 safe_println!("This crate does not load any additional lints or lint groups.")
1046 }
1047 (true, l, g) => {
1048 if l > 0 {
1049 safe_println!("Lint checks loaded by this crate:\n");
1050 print_lints(loaded);
1051 }
1052 if g > 0 {
1053 safe_println!("Lint groups loaded by this crate:\n");
1054 print_lint_groups(loaded_groups, false);
1055 }
1056 }
1057 }
1058}
1059
1060pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1064 let wall = matches.opt_strs("W");
1066 if wall.iter().any(|x| *x == "all") {
1067 print_wall_help();
1068 return true;
1069 }
1070
1071 let debug_flags = matches.opt_strs("Z");
1073 if debug_flags.iter().any(|x| *x == "help") {
1074 describe_debug_flags();
1075 return true;
1076 }
1077
1078 let cg_flags = matches.opt_strs("C");
1079 if cg_flags.iter().any(|x| *x == "help") {
1080 describe_codegen_flags();
1081 return true;
1082 }
1083
1084 if cg_flags.iter().any(|x| *x == "passes=list") {
1085 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1086 return true;
1087 }
1088
1089 false
1090}
1091
1092fn get_backend_from_raw_matches(
1099 early_dcx: &EarlyDiagCtxt,
1100 matches: &Matches,
1101) -> Box<dyn CodegenBackend> {
1102 let debug_flags = matches.opt_strs("Z");
1103 let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1104 let target = parse_target_triple(early_dcx, matches);
1105 let sysroot = filesearch::materialize_sysroot(matches.opt_str("sysroot").map(PathBuf::from));
1106 let target = config::build_target_config(early_dcx, &target, &sysroot);
1107
1108 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1109}
1110
1111fn describe_debug_flags() {
1112 safe_println!("\nAvailable options:\n");
1113 print_flag_list("-Z", config::Z_OPTIONS);
1114}
1115
1116fn describe_codegen_flags() {
1117 safe_println!("\nAvailable codegen options:\n");
1118 print_flag_list("-C", config::CG_OPTIONS);
1119}
1120
1121fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1122 let max_len =
1123 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1124
1125 for opt_desc in flag_list {
1126 safe_println!(
1127 " {} {:>width$}=val -- {}",
1128 cmdline_opt,
1129 opt_desc.name().replace('_', "-"),
1130 opt_desc.desc(),
1131 width = max_len
1132 );
1133 }
1134}
1135
1136pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1164 let mut options = getopts::Options::new();
1167 let optgroups = config::rustc_optgroups();
1168 for option in &optgroups {
1169 option.apply(&mut options);
1170 }
1171 let matches = options.parse(args).unwrap_or_else(|e| {
1172 let msg: Option<String> = match e {
1173 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1174 .iter()
1175 .map(|opt_desc| ('C', opt_desc.name()))
1176 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1177 .find(|&(_, name)| *opt == name.replace('_', "-"))
1178 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1179 getopts::Fail::ArgumentMissing(ref opt) => {
1180 optgroups.iter().find(|option| option.name == opt).map(|option| {
1181 let mut options = getopts::Options::new();
1183 option.apply(&mut options);
1184 options.usage_with_format(|it| {
1187 it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1188 })
1189 })
1190 }
1191 _ => None,
1192 };
1193 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1194 });
1195
1196 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1208
1209 if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1210 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1212 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1213 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1214 return None;
1215 }
1216
1217 if describe_flag_categories(early_dcx, &matches) {
1218 return None;
1219 }
1220
1221 if matches.opt_present("version") {
1222 version!(early_dcx, "rustc", &matches);
1223 return None;
1224 }
1225
1226 Some(matches)
1227}
1228
1229fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1230 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1231 Input::File(file) => new_parser_from_file(&sess.psess, file, None),
1232 Input::Str { name, input } => {
1233 new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
1234 }
1235 });
1236 parser.parse_inner_attributes()
1237}
1238
1239pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1245 catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1246 if value.is::<rustc_errors::FatalErrorMarker>() {
1247 FatalError
1248 } else {
1249 panic::resume_unwind(value);
1250 }
1251 })
1252}
1253
1254pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1257 match catch_fatal_errors(f) {
1258 Ok(()) => EXIT_SUCCESS,
1259 _ => EXIT_FAILURE,
1260 }
1261}
1262
1263static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1264
1265fn ice_path() -> &'static Option<PathBuf> {
1273 ice_path_with_config(None)
1274}
1275
1276fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1277 if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1278 tracing::warn!(
1279 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1280 )
1281 }
1282
1283 ICE_PATH.get_or_init(|| {
1284 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1285 return None;
1286 }
1287 let mut path = match std::env::var_os("RUSTC_ICE") {
1288 Some(s) => {
1289 if s == "0" {
1290 return None;
1292 }
1293 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1294 tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1295 }
1296 PathBuf::from(s)
1297 }
1298 None => config
1299 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1300 .or_else(|| std::env::current_dir().ok())
1301 .unwrap_or_default(),
1302 };
1303 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1305 let pid = std::process::id();
1306 path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1307 Some(path)
1308 })
1309}
1310
1311pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1312
1313pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1325 if env::var_os("RUST_BACKTRACE").is_none() {
1332 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1334 if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1335 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1336 } else {
1337 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1338 }
1339 }
1340
1341 panic::update_hook(Box::new(
1342 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1343 info: &PanicHookInfo<'_>| {
1344 let _guard = io::stderr().lock();
1346 #[cfg(windows)]
1349 if let Some(msg) = info.payload().downcast_ref::<String>() {
1350 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1351 {
1352 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1354 let _ = early_dcx.early_err(msg.clone());
1355 return;
1356 }
1357 };
1358
1359 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1362 default_hook(info);
1363 eprintln!();
1365
1366 if let Some(ice_path) = ice_path()
1367 && let Ok(mut out) = File::options().create(true).append(true).open(&ice_path)
1368 {
1369 let location = info.location().unwrap();
1371 let msg = match info.payload().downcast_ref::<&'static str>() {
1372 Some(s) => *s,
1373 None => match info.payload().downcast_ref::<String>() {
1374 Some(s) => &s[..],
1375 None => "Box<dyn Any>",
1376 },
1377 };
1378 let thread = std::thread::current();
1379 let name = thread.name().unwrap_or("<unnamed>");
1380 let _ = write!(
1381 &mut out,
1382 "thread '{name}' panicked at {location}:\n\
1383 {msg}\n\
1384 stack backtrace:\n\
1385 {:#}",
1386 std::backtrace::Backtrace::force_capture()
1387 );
1388 }
1389 }
1390
1391 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1393 },
1394 ));
1395}
1396
1397fn report_ice(
1404 info: &panic::PanicHookInfo<'_>,
1405 bug_report_url: &str,
1406 extra_info: fn(&DiagCtxt),
1407 using_internal_features: &AtomicBool,
1408) {
1409 let fallback_bundle =
1410 rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1411 let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1412 stderr_destination(rustc_errors::ColorConfig::Auto),
1413 fallback_bundle,
1414 ));
1415 let dcx = rustc_errors::DiagCtxt::new(emitter);
1416 let dcx = dcx.handle();
1417
1418 if !info.payload().is::<rustc_errors::ExplicitBug>()
1421 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1422 {
1423 dcx.emit_err(session_diagnostics::Ice);
1424 }
1425
1426 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1427 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1428 } else {
1429 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1430
1431 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1433 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1434 }
1435 }
1436
1437 let version = util::version_str!().unwrap_or("unknown_version");
1438 let tuple = config::host_tuple();
1439
1440 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1441
1442 let file = if let Some(path) = ice_path() {
1443 match crate::fs::File::options().create(true).append(true).open(&path) {
1445 Ok(mut file) => {
1446 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1447 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1448 let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1449 }
1450 Some(file)
1451 }
1452 Err(err) => {
1453 dcx.emit_warn(session_diagnostics::IcePathError {
1455 path: path.clone(),
1456 error: err.to_string(),
1457 env_var: std::env::var_os("RUSTC_ICE")
1458 .map(PathBuf::from)
1459 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1460 });
1461 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1462 None
1463 }
1464 }
1465 } else {
1466 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1467 None
1468 };
1469
1470 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1471 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1472 if excluded_cargo_defaults {
1473 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1474 }
1475 }
1476
1477 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1479
1480 let limit_frames = if backtrace { None } else { Some(2) };
1481
1482 interface::try_print_query_stack(dcx, limit_frames, file);
1483
1484 extra_info(&dcx);
1487
1488 #[cfg(windows)]
1489 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1490 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1492 }
1493}
1494
1495pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1498 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1499}
1500
1501pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1505 if let Err(error) = rustc_log::init_logger(cfg) {
1506 early_dcx.early_fatal(error.to_string());
1507 }
1508}
1509
1510pub fn install_ctrlc_handler() {
1513 #[cfg(all(not(miri), not(target_family = "wasm")))]
1514 ctrlc::set_handler(move || {
1515 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1520 std::thread::sleep(std::time::Duration::from_millis(100));
1521 std::process::exit(1);
1522 })
1523 .expect("Unable to install ctrlc handler");
1524}
1525
1526pub fn main() -> ! {
1527 let start_time = Instant::now();
1528 let start_rss = get_resident_set_size();
1529
1530 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1531
1532 init_rustc_env_logger(&early_dcx);
1533 signal_handler::install();
1534 let mut callbacks = TimePassesCallbacks::default();
1535 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1536 install_ctrlc_handler();
1537
1538 let exit_code =
1539 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1540
1541 if let Some(format) = callbacks.time_passes {
1542 let end_rss = get_resident_set_size();
1543 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1544 }
1545
1546 process::exit(exit_code)
1547}