1#![feature(decl_macro)]
9#![feature(panic_backtrace_config)]
10#![feature(panic_update_hook)]
11#![feature(trim_prefix_suffix)]
12#![feature(try_blocks)]
13use std::cmp::max;
16use std::collections::{BTreeMap, BTreeSet};
17use std::ffi::OsString;
18use std::fmt::Write as _;
19use std::fs::{self, File};
20use std::io::{self, IsTerminal, Read, Write};
21use std::panic::{self, PanicHookInfo};
22use std::path::{Path, PathBuf};
23use std::process::{Command, ExitCode, Stdio, Termination};
24use std::sync::OnceLock;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::time::Instant;
27use std::{env, str};
28
29use rustc_ast as ast;
30use rustc_codegen_ssa::traits::CodegenBackend;
31use rustc_codegen_ssa::{CodegenErrors, CodegenResults};
32use rustc_data_structures::profiling::{
33 TimePassesFormat, get_resident_set_size, print_time_passes_entry,
34};
35pub use rustc_errors::catch_fatal_errors;
36use rustc_errors::emitter::stderr_destination;
37use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, PResult, markdown};
38use rustc_feature::find_gated_cfg;
39use rustc_index as _;
43use rustc_interface::passes::collect_crate_types;
44use rustc_interface::util::{self, get_codegen_backend};
45use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
46use rustc_lint::unerased_lint_store;
47use rustc_metadata::creader::MetadataLoader;
48use rustc_metadata::locator;
49use rustc_middle::ty::TyCtxt;
50use rustc_parse::lexer::StripTokens;
51use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
52use rustc_session::config::{
53 CG_OPTIONS, CrateType, ErrorOutputType, Input, OptionDesc, OutFileName, OutputType, Sysroot,
54 UnstableOptions, Z_OPTIONS, nightly_options, parse_target_triple,
55};
56use rustc_session::getopts::{self, Matches};
57use rustc_session::lint::{Lint, LintId};
58use rustc_session::output::invalid_output_for_target;
59use rustc_session::{EarlyDiagCtxt, Session, config};
60use rustc_span::def_id::LOCAL_CRATE;
61use rustc_span::{DUMMY_SP, FileName};
62use rustc_target::json::ToJson;
63use rustc_target::spec::{Target, TargetTuple};
64use tracing::trace;
65
66#[allow(unused_macros)]
67macro do_not_use_print($($t:tt)*) {
68 std::compile_error!(
69 "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
70 )
71}
72
73#[allow(unused_macros)]
74macro do_not_use_safe_print($($t:tt)*) {
75 std::compile_error!("Don't use `safe_print` or `safe_println` here, use `println_info` instead")
76}
77
78#[allow(unused_imports)]
82use {do_not_use_print as print, do_not_use_print as println};
83
84pub mod args;
85pub mod pretty;
86#[macro_use]
87mod print;
88pub mod highlighter;
89mod session_diagnostics;
90
91#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
95mod signal_handler;
96
97#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
98mod signal_handler {
99 pub(super) fn install() {}
102}
103
104use crate::session_diagnostics::{
105 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
106 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
107};
108
109pub const EXIT_SUCCESS: i32 = 0;
111
112pub const EXIT_FAILURE: i32 = 1;
114
115pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
116 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
117
118pub trait Callbacks {
119 fn config(&mut self, _config: &mut interface::Config) {}
121 fn after_crate_root_parsing(
125 &mut self,
126 _compiler: &interface::Compiler,
127 _krate: &mut ast::Crate,
128 ) -> Compilation {
129 Compilation::Continue
130 }
131 fn after_expansion<'tcx>(
134 &mut self,
135 _compiler: &interface::Compiler,
136 _tcx: TyCtxt<'tcx>,
137 ) -> Compilation {
138 Compilation::Continue
139 }
140 fn after_analysis<'tcx>(
143 &mut self,
144 _compiler: &interface::Compiler,
145 _tcx: TyCtxt<'tcx>,
146 ) -> Compilation {
147 Compilation::Continue
148 }
149}
150
151#[derive(#[automatically_derived]
impl ::core::default::Default for TimePassesCallbacks {
#[inline]
fn default() -> TimePassesCallbacks {
TimePassesCallbacks {
time_passes: ::core::default::Default::default(),
}
}
}Default)]
152pub struct TimePassesCallbacks {
153 time_passes: Option<TimePassesFormat>,
154}
155
156impl Callbacks for TimePassesCallbacks {
157 #[allow(rustc::bad_opt_access)]
159 fn config(&mut self, config: &mut interface::Config) {
160 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
164 .then_some(config.opts.unstable_opts.time_passes_format);
165 config.opts.trimmed_def_paths = true;
166 }
167}
168
169pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
171 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
172
173 let at_args = at_args.get(1..).unwrap_or_default();
182
183 let args = args::arg_expand_all(&default_early_dcx, at_args);
184
185 let (matches, help_only) = match handle_options(&default_early_dcx, &args) {
186 HandledOptions::None => return,
187 HandledOptions::Normal(matches) => (matches, false),
188 HandledOptions::HelpOnly(matches) => (matches, true),
189 };
190
191 let sopts = config::build_session_options(&mut default_early_dcx, &matches);
192 let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
194
195 if let Some(ref code) = matches.opt_str("explain") {
196 handle_explain(&default_early_dcx, code, sopts.color);
197 return;
198 }
199
200 let input = make_input(&default_early_dcx, &matches.free);
201 let has_input = input.is_some();
202 let (odir, ofile) = make_output(&matches);
203
204 drop(default_early_dcx);
205
206 let mut config = interface::Config {
207 opts: sopts,
208 crate_cfg: matches.opt_strs("cfg"),
209 crate_check_cfg: matches.opt_strs("check-cfg"),
210 input: input.unwrap_or(Input::File(PathBuf::new())),
211 output_file: ofile,
212 output_dir: odir,
213 ice_file,
214 file_loader: None,
215 lint_caps: Default::default(),
216 psess_created: None,
217 hash_untracked_state: None,
218 register_lints: None,
219 override_queries: None,
220 extra_symbols: Vec::new(),
221 make_codegen_backend: None,
222 using_internal_features: &USING_INTERNAL_FEATURES,
223 };
224
225 callbacks.config(&mut config);
226
227 let registered_lints = config.register_lints.is_some();
228
229 interface::run_compiler(config, |compiler| {
230 let sess = &compiler.sess;
231 let codegen_backend = &*compiler.codegen_backend;
232
233 let early_exit = || {
237 sess.dcx().abort_if_errors();
238 };
239
240 if sess.opts.describe_lints {
244 describe_lints(sess, registered_lints);
245 return early_exit();
246 }
247
248 if help_only {
250 return early_exit();
251 }
252
253 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
254 return early_exit();
255 }
256
257 if !has_input {
258 sess.dcx().fatal("no input filename given"); }
260
261 if !sess.opts.unstable_opts.ls.is_empty() {
262 list_metadata(sess, &*codegen_backend.metadata_loader());
263 return early_exit();
264 }
265
266 if sess.opts.unstable_opts.link_only {
267 process_rlink(sess, compiler);
268 return early_exit();
269 }
270
271 let mut krate = passes::parse(sess);
274
275 if let Some(pp_mode) = sess.opts.pretty {
277 if pp_mode.needs_ast_map() {
278 create_and_enter_global_ctxt(compiler, krate, |tcx| {
279 tcx.ensure_ok().early_lint_checks(());
280 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
281 passes::write_dep_info(tcx);
282 });
283 } else {
284 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
285 }
286 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:286",
"rustc_driver_impl", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(286u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("finished pretty-printing")
as &dyn Value))])
});
} else { ; }
};trace!("finished pretty-printing");
287 return early_exit();
288 }
289
290 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
291 return early_exit();
292 }
293
294 if sess.opts.unstable_opts.parse_crate_root_only {
295 return early_exit();
296 }
297
298 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
299 let early_exit = || {
300 sess.dcx().abort_if_errors();
301 None
302 };
303
304 let _ = tcx.resolver_for_lowering();
306
307 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
308 return early_exit();
309 }
310
311 passes::write_dep_info(tcx);
312
313 passes::write_interface(tcx);
314
315 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
316 && sess.opts.output_types.len() == 1
317 {
318 return early_exit();
319 }
320
321 if sess.opts.unstable_opts.no_analysis {
322 return early_exit();
323 }
324
325 tcx.ensure_ok().analysis(());
326
327 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
328 dump_feature_usage_metrics(tcx, metrics_dir);
329 }
330
331 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
332 return early_exit();
333 }
334
335 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
336 if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
337 tcx.dcx().emit_fatal(CantEmitMIR { error });
338 }
339 }
340
341 Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
342 });
343
344 if let Some(linker) = linker {
347 linker.link(sess, codegen_backend);
348 }
349 })
350}
351
352fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
353 let hash = tcxt.crate_hash(LOCAL_CRATE);
354 let crate_name = tcxt.crate_name(LOCAL_CRATE);
355 let metrics_file_name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unstable_feature_usage_metrics-{0}-{1}.json",
crate_name, hash))
})format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
356 let metrics_path = metrics_dir.join(metrics_file_name);
357 if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
358 tcxt.dcx().emit_err(UnstableFeatureUsage { error });
362 }
363}
364
365fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
367 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
368 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
369 "-" => OutFileName::Stdout,
370 path => OutFileName::Real(PathBuf::from(path)),
371 });
372 (odir, ofile)
373}
374
375fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
378 match free_matches {
379 [] => None, [ifile] if ifile == "-" => {
381 let mut input = String::new();
383 if io::stdin().read_to_string(&mut input).is_err() {
384 early_dcx
387 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
388 }
389
390 let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
391 Ok(path) => {
392 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
393 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
394 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
395 );
396 let line = line
397 .parse::<isize>()
398 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be a number");
399 FileName::doc_test_source_code(PathBuf::from(path), line)
400 }
401 Err(_) => FileName::anon_source_code(&input),
402 };
403
404 Some(Input::Str { name, input })
405 }
406 [ifile] => Some(Input::File(PathBuf::from(ifile))),
407 [ifile1, ifile2, ..] => early_dcx.early_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple input filenames provided (first two filenames are `{0}` and `{1}`)",
ifile1, ifile2))
})format!(
408 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
409 ifile1, ifile2
410 )),
411 }
412}
413
414#[derive(#[automatically_derived]
impl ::core::marker::Copy for Compilation { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Compilation {
#[inline]
fn clone(&self) -> Compilation { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Compilation {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Compilation::Stop => "Stop",
Compilation::Continue => "Continue",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Compilation {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Compilation {
#[inline]
fn eq(&self, other: &Compilation) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
416pub enum Compilation {
417 Stop,
418 Continue,
419}
420
421fn handle_explain(early_dcx: &EarlyDiagCtxt, code: &str, color: ColorConfig) {
422 let upper_cased_code = code.to_ascii_uppercase();
424 if let Ok(code) = upper_cased_code.trim_prefix('E').parse::<u32>()
425 && code <= ErrCode::MAX_AS_U32
426 && let Ok(description) = rustc_errors::codes::try_find_description(ErrCode::from_u32(code))
427 {
428 let mut is_in_code_block = false;
429 let mut text = String::new();
430 for line in description.lines() {
432 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
433 let dedented_line = &line[indent_level..];
434 if dedented_line.starts_with("```") {
435 is_in_code_block = !is_in_code_block;
436 text.push_str(&line[..(indent_level + 3)]);
437 } else if is_in_code_block && dedented_line.starts_with("# ") {
438 continue;
439 } else {
440 text.push_str(line);
441 }
442 text.push('\n');
443 }
444
445 if io::stdout().is_terminal() {
447 show_md_content_with_pager(&text, color);
448 } else {
449 if color == ColorConfig::Always {
452 show_colored_md_content(&text);
453 } else {
454 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
455 }
456 }
457 } else {
458 early_dcx.early_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a valid error code",
code))
})format!("{code} is not a valid error code"));
459 }
460}
461
462fn show_md_content_with_pager(content: &str, color: ColorConfig) {
467 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
468 if falsecfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
469 });
470
471 let mut cmd = Command::new(&pager_name);
472 if pager_name == "less" {
473 cmd.arg("-R"); }
475
476 let pretty_on_pager = match color {
477 ColorConfig::Auto => {
478 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
480 }
481 ColorConfig::Always => true,
482 ColorConfig::Never => false,
483 };
484
485 let mut pretty_data = {
487 let mdstream = markdown::MdStream::parse_str(content);
488 let bufwtr = markdown::create_stdout_bufwtr();
489 let mut mdbuf = Vec::new();
490 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
491 Some((bufwtr, mdbuf))
492 } else {
493 None
494 }
495 };
496
497 let pager_res = try {
499 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
500
501 let pager_stdin = pager.stdin.as_mut()?;
502 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
503 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
504 } else {
505 pager_stdin.write_all(content.as_bytes()).ok()?;
506 };
507
508 pager.wait().ok()?;
509 };
510 if pager_res.is_some() {
511 return;
512 }
513
514 if let Some((bufwtr, mdbuf)) = &mut pretty_data
516 && bufwtr.write_all(&mdbuf).is_ok()
517 {
518 return;
519 }
520
521 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
523}
524
525fn show_colored_md_content(content: &str) {
530 let mut pretty_data = {
532 let mdstream = markdown::MdStream::parse_str(content);
533 let bufwtr = markdown::create_stdout_bufwtr();
534 let mut mdbuf = Vec::new();
535 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
536 Some((bufwtr, mdbuf))
537 } else {
538 None
539 }
540 };
541
542 if let Some((bufwtr, mdbuf)) = &mut pretty_data
543 && bufwtr.write_all(&mdbuf).is_ok()
544 {
545 return;
546 }
547
548 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
550}
551
552fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
553 if !sess.opts.unstable_opts.link_only {
::core::panicking::panic("assertion failed: sess.opts.unstable_opts.link_only")
};assert!(sess.opts.unstable_opts.link_only);
554 let dcx = sess.dcx();
555 if let Input::File(file) = &sess.io.input {
556 let rlink_data = fs::read(file).unwrap_or_else(|err| {
557 dcx.emit_fatal(RlinkUnableToRead { err });
558 });
559 let (codegen_results, metadata, outputs) =
560 match CodegenResults::deserialize_rlink(sess, rlink_data) {
561 Ok((codegen, metadata, outputs)) => (codegen, metadata, outputs),
562 Err(err) => {
563 match err {
564 CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
565 CodegenErrors::EmptyVersionNumber => {
566 dcx.emit_fatal(RLinkEmptyVersionNumber)
567 }
568 CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
569 dcx.emit_fatal(RLinkEncodingVersionMismatch {
570 version_array,
571 rlink_version,
572 })
573 }
574 CodegenErrors::RustcVersionMismatch { rustc_version } => {
575 dcx.emit_fatal(RLinkRustcVersionMismatch {
576 rustc_version,
577 current_version: sess.cfg_version,
578 })
579 }
580 CodegenErrors::CorruptFile => {
581 dcx.emit_fatal(RlinkCorruptFile { file });
582 }
583 };
584 }
585 };
586 compiler.codegen_backend.link(sess, codegen_results, metadata, &outputs);
587 } else {
588 dcx.emit_fatal(RlinkNotAFile {});
589 }
590}
591
592fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
593 match sess.io.input {
594 Input::File(ref path) => {
595 let mut v = Vec::new();
596 locator::list_file_metadata(
597 &sess.target,
598 path,
599 metadata_loader,
600 &mut v,
601 &sess.opts.unstable_opts.ls,
602 sess.cfg_version,
603 )
604 .unwrap();
605 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
606 }
607 Input::Str { .. } => {
608 sess.dcx().fatal("cannot list metadata for stdin");
609 }
610 }
611}
612
613fn print_crate_info(
614 codegen_backend: &dyn CodegenBackend,
615 sess: &Session,
616 parse_attrs: bool,
617) -> Compilation {
618 use rustc_session::config::PrintKind::*;
619 #[allow(unused_imports)]
623 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
624
625 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
628 return Compilation::Continue;
629 }
630
631 let attrs = if parse_attrs {
632 let result = parse_crate_attrs(sess);
633 match result {
634 Ok(attrs) => Some(attrs),
635 Err(parse_error) => {
636 parse_error.emit();
637 return Compilation::Stop;
638 }
639 }
640 } else {
641 None
642 };
643
644 for req in &sess.opts.prints {
645 let mut crate_info = String::new();
646 macro println_info($($arg:tt)*) {
647 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
648 }
649
650 match req.kind {
651 TargetList => {
652 let mut targets = rustc_target::spec::TARGETS.to_vec();
653 targets.sort_unstable();
654 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
655 }
656 HostTuple => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
rustc_session::config::host_tuple()))).unwrap()println_info!("{}", rustc_session::config::host_tuple()),
657 Sysroot => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", sess.opts.sysroot.path().display()))).unwrap()println_info!("{}", sess.opts.sysroot.path().display()),
658 TargetLibdir => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
sess.target_tlib_path.dir.display()))).unwrap()println_info!("{}", sess.target_tlib_path.dir.display()),
659 TargetSpecJson => {
660 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&sess.target.to_json()).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
661 }
662 TargetSpecJsonSchema => {
663 let schema = rustc_target::spec::json_schema();
664 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&schema).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&schema).unwrap());
665 }
666 AllTargetSpecsJson => {
667 let mut targets = BTreeMap::new();
668 for name in rustc_target::spec::TARGETS {
669 let triple = TargetTuple::from_tuple(name);
670 let target = Target::expect_builtin(&triple);
671 targets.insert(name, target.to_json());
672 }
673 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&targets).unwrap()))).unwrap();println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
674 }
675 FileNames => {
676 let Some(attrs) = attrs.as_ref() else {
677 return Compilation::Continue;
679 };
680 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
681 let crate_name = passes::get_crate_name(sess, attrs);
682 let crate_types = collect_crate_types(
683 sess,
684 &codegen_backend.supported_crate_types(sess),
685 codegen_backend.name(),
686 attrs,
687 DUMMY_SP,
688 );
689 for &style in &crate_types {
690 let fname = rustc_session::output::filename_for_input(
691 sess, style, crate_name, &t_outputs,
692 );
693 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
fname.as_path().file_name().unwrap().to_string_lossy()))).unwrap();println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
694 }
695 }
696 CrateName => {
697 let Some(attrs) = attrs.as_ref() else {
698 return Compilation::Continue;
700 };
701 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
passes::get_crate_name(sess, attrs)))).unwrap();println_info!("{}", passes::get_crate_name(sess, attrs));
702 }
703 CrateRootLintLevels => {
704 let Some(attrs) = attrs.as_ref() else {
705 return Compilation::Continue;
707 };
708 let crate_name = passes::get_crate_name(sess, attrs);
709 let lint_store = crate::unerased_lint_store(sess);
710 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs);
711 let features = rustc_expand::config::features(sess, attrs, crate_name);
712 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
713 sess,
714 &features,
715 true,
716 lint_store,
717 ®istered_tools,
718 attrs,
719 );
720 for lint in lint_store.get_lints() {
721 if let Some(feature_symbol) = lint.feature_gate
722 && !features.enabled(feature_symbol)
723 {
724 continue;
726 }
727 let level = lint_levels.lint_level(lint).level;
728 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}", lint.name_lower(),
level.as_str()))).unwrap();println_info!("{}={}", lint.name_lower(), level.as_str());
729 }
730 }
731 Cfg => {
732 let mut cfgs = sess
733 .psess
734 .config
735 .iter()
736 .filter_map(|&(name, value)| {
737 if !sess.is_nightly_build()
739 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
740 {
741 return None;
742 }
743
744 if let Some(value) = value {
745 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
746 } else {
747 Some(name.to_string())
748 }
749 })
750 .collect::<Vec<String>>();
751
752 cfgs.sort();
753 for cfg in cfgs {
754 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
755 }
756 }
757 CheckCfg => {
758 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
759
760 #[allow(rustc::potential_query_instability)]
762 for (name, expected_values) in &sess.psess.check_config.expecteds {
763 use crate::config::ExpectedValues;
764 match expected_values {
765 ExpectedValues::Any => {
766 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
767 }
768 ExpectedValues::Some(values) => {
769 let mut values: Vec<_> = values
770 .iter()
771 .map(|value| {
772 if let Some(value) = value {
773 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
774 } else {
775 "none()".to_string()
776 }
777 })
778 .collect();
779
780 values.sort_unstable();
781
782 let values = values.join(", ");
783
784 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
785 }
786 }
787 }
788
789 check_cfgs.sort_unstable();
790 if !sess.psess.check_config.exhaustive_names
791 && sess.psess.check_config.exhaustive_values
792 {
793 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
794 }
795 for check_cfg in check_cfgs {
796 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
797 }
798 }
799 CallingConventions => {
800 let calling_conventions = rustc_abi::all_names();
801 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
802 }
803 BackendHasZstd => {
804 let has_zstd: bool = codegen_backend.has_zstd();
805 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
806 }
807 RelocationModels
808 | CodeModels
809 | TlsModels
810 | TargetCPUs
811 | StackProtectorStrategies
812 | TargetFeatures => {
813 codegen_backend.print(req, &mut crate_info, sess);
814 }
815 NativeStaticLibs => {}
817 LinkArgs => {}
818 SplitDebuginfo => {
819 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
820
821 for split in &[Off, Packed, Unpacked] {
822 if sess.target.options.supported_split_debuginfo.contains(split) {
823 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
824 }
825 }
826 }
827 DeploymentTarget => {
828 if sess.target.is_like_darwin {
829 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}={1}",
rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
sess.apple_deployment_target().fmt_pretty()))).unwrap()println_info!(
830 "{}={}",
831 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
832 sess.apple_deployment_target().fmt_pretty(),
833 )
834 } else {
835 sess.dcx().fatal("only Apple targets currently support deployment version info")
836 }
837 }
838 SupportedCrateTypes => {
839 let supported_crate_types = CrateType::all()
840 .iter()
841 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
842 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
843 .map(|(crate_type_sym, _)| *crate_type_sym)
844 .collect::<BTreeSet<_>>();
845 for supported_crate_type in supported_crate_types {
846 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
847 }
848 }
849 }
850
851 req.out.overwrite(&crate_info, sess);
852 }
853 Compilation::Stop
854}
855
856pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
860 fn unw(x: Option<&str>) -> &str {
861 x.unwrap_or("unknown")
862 }
863 $crate::version_at_macro_invocation(
864 $early_dcx,
865 $binary,
866 $matches,
867 unw(option_env!("CFG_VERSION")),
868 unw(option_env!("CFG_VER_HASH")),
869 unw(option_env!("CFG_VER_DATE")),
870 unw(option_env!("CFG_RELEASE")),
871 )
872}
873
874#[doc(hidden)] pub fn version_at_macro_invocation(
876 early_dcx: &EarlyDiagCtxt,
877 binary: &str,
878 matches: &getopts::Matches,
879 version: &str,
880 commit_hash: &str,
881 commit_date: &str,
882 release: &str,
883) {
884 let verbose = matches.opt_present("verbose");
885
886 let mut version = version;
887 let mut release = release;
888 let tmp;
889 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
890 tmp = force_version;
891 version = &tmp;
892 release = &tmp;
893 }
894
895 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
896
897 if verbose {
898 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
899 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
900 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
901 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
902 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
903
904 get_backend_from_raw_matches(early_dcx, matches).print_version();
905 }
906}
907
908fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
909 let mut options = getopts::Options::new();
910 for option in config::rustc_optgroups()
911 .iter()
912 .filter(|x| verbose || !x.is_verbose_help_only)
913 .filter(|x| include_unstable_options || x.is_stable())
914 {
915 option.apply(&mut options);
916 }
917 let message = "Usage: rustc [OPTIONS] INPUT";
918 let nightly_help = if nightly_build {
919 "\n -Z help Print unstable compiler options"
920 } else {
921 ""
922 };
923 let verbose_help = if verbose {
924 ""
925 } else {
926 "\n --help -v Print the full set of options rustc accepts"
927 };
928 let at_path = if verbose {
929 " @path Read newline separated options from `path`\n"
930 } else {
931 ""
932 };
933 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}{1}\nAdditional help:\n -C help Print codegen options\n -W help Print \'lint\' options and default settings{2}{3}\n",
options.usage(message), at_path, nightly_help,
verbose_help)));
};safe_println!(
934 "{options}{at_path}\nAdditional help:
935 -C help Print codegen options
936 -W help \
937 Print 'lint' options and default settings{nightly}{verbose}\n",
938 options = options.usage(message),
939 at_path = at_path,
940 nightly = nightly_help,
941 verbose = verbose_help
942 );
943}
944
945fn print_wall_help() {
946 {
crate::print::print(format_args!("{0}\n",
format_args!("\nThe flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by\ndefault. Use `rustc -W help` to see all available lints. It\'s more common to put\nwarning settings in the crate root using `#![warn(LINT_NAME)]` instead of using\nthe command line flag directly.\n")));
};safe_println!(
947 "
948The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
949default. Use `rustc -W help` to see all available lints. It's more common to put
950warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
951the command line flag directly.
952"
953 );
954}
955
956pub fn describe_lints(sess: &Session, registered_lints: bool) {
958 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable lint options:\n -W <foo> Warn about <foo>\n -A <foo> Allow <foo>\n -D <foo> Deny <foo>\n -F <foo> Forbid <foo> (deny <foo> and all attempts to override)\n\n")));
};safe_println!(
959 "
960Available lint options:
961 -W <foo> Warn about <foo>
962 -A <foo> Allow <foo>
963 -D <foo> Deny <foo>
964 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
965
966"
967 );
968
969 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
970 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
972 lints
973 }
974
975 fn sort_lint_groups(
976 lints: Vec<(&'static str, Vec<LintId>, bool)>,
977 ) -> Vec<(&'static str, Vec<LintId>)> {
978 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
979 lints.sort_by_key(|l| l.0);
980 lints
981 }
982
983 let lint_store = unerased_lint_store(sess);
984 let (loaded, builtin): (Vec<_>, _) =
985 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
986 let loaded = sort_lints(sess, loaded);
987 let builtin = sort_lints(sess, builtin);
988
989 let (loaded_groups, builtin_groups): (Vec<_>, _) =
990 lint_store.get_lint_groups().partition(|&(.., p)| p);
991 let loaded_groups = sort_lint_groups(loaded_groups);
992 let builtin_groups = sort_lint_groups(builtin_groups);
993
994 let max_name_len =
995 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
996 let padded = |x: &str| {
997 let mut s = " ".repeat(max_name_len - x.chars().count());
998 s.push_str(x);
999 s
1000 };
1001
1002 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1003
1004 let print_lints = |lints: Vec<&Lint>| {
1005 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("name"), "default",
"meaning")));
};safe_println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1006 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1007 for lint in lints {
1008 let name = lint.name_lower().replace('_', "-");
1009 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded(&name),
lint.default_level(sess.edition()).as_str(), lint.desc)));
};safe_println!(
1010 " {} {:7.7} {}",
1011 padded(&name),
1012 lint.default_level(sess.edition()).as_str(),
1013 lint.desc
1014 );
1015 }
1016 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1017 };
1018
1019 print_lints(builtin);
1020
1021 let max_name_len = max(
1022 "warnings".len(),
1023 loaded_groups
1024 .iter()
1025 .chain(&builtin_groups)
1026 .map(|&(s, _)| s.chars().count())
1027 .max()
1028 .unwrap_or(0),
1029 );
1030
1031 let padded = |x: &str| {
1032 let mut s = " ".repeat(max_name_len - x.chars().count());
1033 s.push_str(x);
1034 s
1035 };
1036
1037 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1038
1039 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1040 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1041 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1042
1043 if all_warnings {
1044 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} all lints that are set to issue warnings",
padded("warnings"))));
};safe_println!(" {} all lints that are set to issue warnings", padded("warnings"));
1045 }
1046
1047 for (name, to) in lints {
1048 let name = name.to_lowercase().replace('_', "-");
1049 let desc = to
1050 .into_iter()
1051 .map(|x| x.to_string().replace('_', "-"))
1052 .collect::<Vec<String>>()
1053 .join(", ");
1054 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1055 }
1056 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1057 };
1058
1059 print_lint_groups(builtin_groups, true);
1060
1061 match (registered_lints, loaded.len(), loaded_groups.len()) {
1062 (false, 0, _) | (false, _, 0) => {
1063 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint tools like Clippy can load additional lints and lint groups.")));
};safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1064 }
1065 (false, ..) => {
::core::panicking::panic_fmt(format_args!("didn\'t load additional lints but got them anyway!"));
}panic!("didn't load additional lints but got them anyway!"),
1066 (true, 0, 0) => {
1067 {
crate::print::print(format_args!("{0}\n",
format_args!("This crate does not load any additional lints or lint groups.")));
}safe_println!("This crate does not load any additional lints or lint groups.")
1068 }
1069 (true, l, g) => {
1070 if l > 0 {
1071 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks loaded by this crate:\n")));
};safe_println!("Lint checks loaded by this crate:\n");
1072 print_lints(loaded);
1073 }
1074 if g > 0 {
1075 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups loaded by this crate:\n")));
};safe_println!("Lint groups loaded by this crate:\n");
1076 print_lint_groups(loaded_groups, false);
1077 }
1078 }
1079 }
1080}
1081
1082pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1086 let wall = matches.opt_strs("W");
1088 if wall.iter().any(|x| *x == "all") {
1089 print_wall_help();
1090 return true;
1091 }
1092
1093 let debug_flags = matches.opt_strs("Z");
1095 if debug_flags.iter().any(|x| *x == "help") {
1096 describe_unstable_flags();
1097 return true;
1098 }
1099
1100 let cg_flags = matches.opt_strs("C");
1101 if cg_flags.iter().any(|x| *x == "help") {
1102 describe_codegen_flags();
1103 return true;
1104 }
1105
1106 if cg_flags.iter().any(|x| *x == "passes=list") {
1107 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1108 return true;
1109 }
1110
1111 false
1112}
1113
1114fn get_backend_from_raw_matches(
1121 early_dcx: &EarlyDiagCtxt,
1122 matches: &Matches,
1123) -> Box<dyn CodegenBackend> {
1124 let debug_flags = matches.opt_strs("Z");
1125 let backend_name = debug_flags
1126 .iter()
1127 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1128 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1129 let target = parse_target_triple(early_dcx, matches);
1130 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1131 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1132
1133 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1134}
1135
1136fn describe_unstable_flags() {
1137 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1138 print_flag_list("-Z", config::Z_OPTIONS);
1139}
1140
1141fn describe_codegen_flags() {
1142 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1143 print_flag_list("-C", config::CG_OPTIONS);
1144}
1145
1146fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1147 let max_len =
1148 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1149
1150 for opt_desc in flag_list {
1151 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:>3$}=val -- {2}", cmdline_opt,
opt_desc.name().replace('_', "-"), opt_desc.desc(),
max_len)));
};safe_println!(
1152 " {} {:>width$}=val -- {}",
1153 cmdline_opt,
1154 opt_desc.name().replace('_', "-"),
1155 opt_desc.desc(),
1156 width = max_len
1157 );
1158 }
1159}
1160
1161pub enum HandledOptions {
1162 None,
1164 Normal(getopts::Matches),
1166 HelpOnly(getopts::Matches),
1169}
1170
1171pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1199 let mut options = getopts::Options::new();
1202 let optgroups = config::rustc_optgroups();
1203 for option in &optgroups {
1204 option.apply(&mut options);
1205 }
1206 let matches = options.parse(args).unwrap_or_else(|e| {
1207 let msg: Option<String> = match e {
1208 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1209 .iter()
1210 .map(|opt_desc| ('C', opt_desc.name()))
1211 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1212 .find(|&(_, name)| *opt == name.replace('_', "-"))
1213 .map(|(flag, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}. Did you mean `-{1} {2}`?", e,
flag, opt))
})format!("{e}. Did you mean `-{flag} {opt}`?")),
1214 getopts::Fail::ArgumentMissing(ref opt) => {
1215 optgroups.iter().find(|option| option.name == opt).map(|option| {
1216 let mut options = getopts::Options::new();
1218 option.apply(&mut options);
1219 options.usage_with_format(|it| {
1222 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1223 })
1224 })
1225 }
1226 _ => None,
1227 };
1228 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1229 });
1230
1231 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1243
1244 let wall = matches.opt_strs("W");
1246 if wall.iter().any(|x| *x == "all") {
1247 print_wall_help();
1248 return HandledOptions::None;
1249 }
1250
1251 if handle_help(&matches, args) {
1252 return HandledOptions::HelpOnly(matches);
1253 }
1254
1255 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1256 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1257 return HandledOptions::None;
1258 }
1259
1260 if matches.opt_present("version") {
1261 fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
crate::version_at_macro_invocation(early_dcx, "rustc", &matches,
unw(::core::option::Option::Some("1.95.0-nightly (5fb2ff861 2026-02-21)")),
unw(::core::option::Option::Some("5fb2ff8611e5a4af4dc85977cfdecfbf3ffa6ade")),
unw(::core::option::Option::Some("2026-02-21")),
unw(::core::option::Option::Some("1.95.0-nightly")));version!(early_dcx, "rustc", &matches);
1262 return HandledOptions::None;
1263 }
1264
1265 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1266
1267 HandledOptions::Normal(matches)
1268}
1269
1270pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1277 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1278 let opt_help_pos = |opt| {
1279 matches
1280 .opt_strs_pos(opt)
1281 .iter()
1282 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1283 .next()
1284 };
1285 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1286 let zhelp_pos = opt_help_pos("Z");
1287 let chelp_pos = opt_help_pos("C");
1288 let print_help = || {
1289 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1291 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1292 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1293 };
1294
1295 let mut helps = [
1296 (help_pos, &print_help as &dyn Fn()),
1297 (zhelp_pos, &describe_unstable_flags),
1298 (chelp_pos, &describe_codegen_flags),
1299 ];
1300 helps.sort_by_key(|(pos, _)| pos.clone());
1301 let mut printed_any = false;
1302 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1303 printer();
1304 printed_any = true;
1305 }
1306 printed_any
1307}
1308
1309fn warn_on_confusing_output_filename_flag(
1313 early_dcx: &EarlyDiagCtxt,
1314 matches: &getopts::Matches,
1315 args: &[String],
1316) {
1317 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1318 let s1 = s1.replace('-', "_");
1319 let s2 = s2.replace('-', "_");
1320 s1 == s2
1321 }
1322
1323 if let Some(name) = matches.opt_str("o")
1324 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1325 {
1326 let filename = suspect.trim_prefix("-");
1327 let optgroups = config::rustc_optgroups();
1328 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1329
1330 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1337 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1338 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1339 {
1340 early_dcx.early_warn(
1341 "option `-o` has no space between flag name and value, which can be confusing",
1342 );
1343 early_dcx.early_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("output filename `-o {0}` is applied instead of a flag named `o{0}`",
name))
})format!(
1344 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1345 ));
1346 early_dcx.early_help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("insert a space between `-o` and `{0}` if this is intentional: `-o {0}`",
name))
})format!(
1347 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1348 ));
1349 }
1350 }
1351}
1352
1353fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1354 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1355 Input::File(file) => {
1356 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1357 }
1358 Input::Str { name, input } => new_parser_from_source_str(
1359 &sess.psess,
1360 name.clone(),
1361 input.clone(),
1362 StripTokens::ShebangAndFrontmatter,
1363 ),
1364 });
1365 parser.parse_inner_attributes()
1366}
1367
1368pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1371 match catch_fatal_errors(f) {
1372 Ok(status) => status.report(),
1373 _ => ExitCode::FAILURE,
1374 }
1375}
1376
1377static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1378
1379fn ice_path() -> &'static Option<PathBuf> {
1387 ice_path_with_config(None)
1388}
1389
1390fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1391 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1392 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1392",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1392u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ICE_PATH has already been initialized -- files may be emitted at unintended paths")
as &dyn Value))])
});
} else { ; }
}tracing::warn!(
1393 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1394 )
1395 }
1396
1397 ICE_PATH.get_or_init(|| {
1398 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1399 return None;
1400 }
1401 let mut path = match std::env::var_os("RUSTC_ICE") {
1402 Some(s) => {
1403 if s == "0" {
1404 return None;
1406 }
1407 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1408 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_driver_impl/src/lib.rs:1408",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1408u32),
::tracing_core::__macro_support::Option::Some("rustc_driver_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files")
as &dyn Value))])
});
} else { ; }
};tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1409 }
1410 PathBuf::from(s)
1411 }
1412 None => config
1413 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1414 .or_else(|| std::env::current_dir().ok())
1415 .unwrap_or_default(),
1416 };
1417 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1419 let pid = std::process::id();
1420 path.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc-ice-{0}-{1}.txt", file_now,
pid))
})format!("rustc-ice-{file_now}-{pid}.txt"));
1421 Some(path)
1422 })
1423}
1424
1425pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1426
1427pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1439 if env::var_os("RUST_BACKTRACE").is_none() {
1446 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1448 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1449 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1450 } else {
1451 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1452 }
1453 }
1454
1455 panic::update_hook(Box::new(
1456 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1457 info: &PanicHookInfo<'_>| {
1458 let _guard = io::stderr().lock();
1460 #[cfg(windows)]
1463 if let Some(msg) = info.payload().downcast_ref::<String>() {
1464 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1465 {
1466 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1468 let _ = early_dcx.early_err(msg.clone());
1469 return;
1470 }
1471 };
1472
1473 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1476 default_hook(info);
1477 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1479
1480 if let Some(ice_path) = ice_path()
1481 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1482 {
1483 let location = info.location().unwrap();
1485 let msg = match info.payload().downcast_ref::<&'static str>() {
1486 Some(s) => *s,
1487 None => match info.payload().downcast_ref::<String>() {
1488 Some(s) => &s[..],
1489 None => "Box<dyn Any>",
1490 },
1491 };
1492 let thread = std::thread::current();
1493 let name = thread.name().unwrap_or("<unnamed>");
1494 let _ = (&mut out).write_fmt(format_args!("thread \'{1}\' panicked at {2}:\n{3}\nstack backtrace:\n{0:#}",
std::backtrace::Backtrace::force_capture(), name, location, msg))write!(
1495 &mut out,
1496 "thread '{name}' panicked at {location}:\n\
1497 {msg}\n\
1498 stack backtrace:\n\
1499 {:#}",
1500 std::backtrace::Backtrace::force_capture()
1501 );
1502 }
1503 }
1504
1505 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1507 },
1508 ));
1509}
1510
1511fn report_ice(
1518 info: &panic::PanicHookInfo<'_>,
1519 bug_report_url: &str,
1520 extra_info: fn(&DiagCtxt),
1521 using_internal_features: &AtomicBool,
1522) {
1523 let emitter =
1524 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1525 stderr_destination(rustc_errors::ColorConfig::Auto),
1526 ));
1527 let dcx = rustc_errors::DiagCtxt::new(emitter);
1528 let dcx = dcx.handle();
1529
1530 if !info.payload().is::<rustc_errors::ExplicitBug>()
1533 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1534 {
1535 dcx.emit_err(session_diagnostics::Ice);
1536 }
1537
1538 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1539 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1540 } else {
1541 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1542
1543 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1545 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1546 }
1547 }
1548
1549 let version = ::core::option::Option::Some("1.95.0-nightly (5fb2ff861 2026-02-21)")util::version_str!().unwrap_or("unknown_version");
1550 let tuple = config::host_tuple();
1551
1552 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1553
1554 let file = if let Some(path) = ice_path() {
1555 match crate::fs::File::options().create(true).append(true).open(path) {
1557 Ok(mut file) => {
1558 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1559 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1560 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1561 }
1562 Some(file)
1563 }
1564 Err(err) => {
1565 dcx.emit_warn(session_diagnostics::IcePathError {
1567 path: path.clone(),
1568 error: err.to_string(),
1569 env_var: std::env::var_os("RUSTC_ICE")
1570 .map(PathBuf::from)
1571 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1572 });
1573 None
1574 }
1575 }
1576 } else {
1577 None
1578 };
1579
1580 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1581
1582 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1583 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1584 if excluded_cargo_defaults {
1585 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1586 }
1587 }
1588
1589 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1591
1592 let limit_frames = if backtrace { None } else { Some(2) };
1593
1594 interface::try_print_query_stack(dcx, limit_frames, file);
1595
1596 extra_info(&dcx);
1599
1600 #[cfg(windows)]
1601 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1602 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1604 }
1605}
1606
1607pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1610 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1611}
1612
1613pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1617 if let Err(error) = rustc_log::init_logger(cfg) {
1618 early_dcx.early_fatal(error.to_string());
1619 }
1620}
1621
1622pub fn init_logger_with_additional_layer<F, T>(
1628 early_dcx: &EarlyDiagCtxt,
1629 cfg: rustc_log::LoggerConfig,
1630 build_subscriber: F,
1631) where
1632 F: FnOnce() -> T,
1633 T: rustc_log::BuildSubscriberRet,
1634{
1635 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1636 early_dcx.early_fatal(error.to_string());
1637 }
1638}
1639
1640pub fn install_ctrlc_handler() {
1643 #[cfg(all(not(miri), not(target_family = "wasm")))]
1644 ctrlc::set_handler(move || {
1645 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1650 std::thread::sleep(std::time::Duration::from_millis(100));
1651 std::process::exit(1);
1652 })
1653 .expect("Unable to install ctrlc handler");
1654}
1655
1656pub fn main() -> ExitCode {
1657 let start_time = Instant::now();
1658 let start_rss = get_resident_set_size();
1659
1660 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1661
1662 init_rustc_env_logger(&early_dcx);
1663 signal_handler::install();
1664 let mut callbacks = TimePassesCallbacks::default();
1665 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1666 install_ctrlc_handler();
1667
1668 let exit_code =
1669 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1670
1671 if let Some(format) = callbacks.time_passes {
1672 let end_rss = get_resident_set_size();
1673 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1674 }
1675
1676 exit_code
1677}