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