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