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::{CodegenError, CompiledModules};
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 track_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 let linker = Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend);
342
343 tcx.report_unused_features();
344
345 Some(linker)
346 });
347
348 if let Some(linker) = linker {
351 linker.link(sess, codegen_backend);
352 }
353 })
354}
355
356fn dump_feature_usage_metrics(tcx: TyCtxt<'_>, metrics_dir: &Path) {
357 let hash = tcx.crate_hash(LOCAL_CRATE);
358 let crate_name = tcx.crate_name(LOCAL_CRATE);
359 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");
360 let metrics_path = metrics_dir.join(metrics_file_name);
361 if let Err(error) = tcx.features().dump_feature_usage_metrics(metrics_path) {
362 tcx.dcx().emit_err(UnstableFeatureUsage { error });
366 }
367}
368
369fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
371 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
372 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
373 "-" => OutFileName::Stdout,
374 path => OutFileName::Real(PathBuf::from(path)),
375 });
376 (odir, ofile)
377}
378
379fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
382 match free_matches {
383 [] => None, [ifile] if ifile == "-" => {
385 let mut input = String::new();
387 if io::stdin().read_to_string(&mut input).is_err() {
388 early_dcx
391 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
392 }
393
394 let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
395 Ok(path) => {
396 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
397 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
398 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
399 );
400 let line = line
401 .parse::<isize>()
402 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be a number");
403 FileName::doc_test_source_code(PathBuf::from(path), line)
404 }
405 Err(_) => FileName::anon_source_code(&input),
406 };
407
408 Some(Input::Str { name, input })
409 }
410 [ifile] => Some(Input::File(PathBuf::from(ifile))),
411 [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!(
412 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
413 ifile1, ifile2
414 )),
415 }
416}
417
418#[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_fields_are_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)]
420pub enum Compilation {
421 Stop,
422 Continue,
423}
424
425fn handle_explain(early_dcx: &EarlyDiagCtxt, code: &str, color: ColorConfig) {
426 let upper_cased_code = code.to_ascii_uppercase();
428 if let Ok(code) = upper_cased_code.trim_prefix('E').parse::<u32>()
429 && code <= ErrCode::MAX_AS_U32
430 && let Ok(description) = rustc_errors::codes::try_find_description(ErrCode::from_u32(code))
431 {
432 let mut is_in_code_block = false;
433 let mut text = String::new();
434 for line in description.lines() {
436 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
437 let dedented_line = &line[indent_level..];
438 if dedented_line.starts_with("```") {
439 is_in_code_block = !is_in_code_block;
440 text.push_str(&line[..(indent_level + 3)]);
441 } else if is_in_code_block && dedented_line.starts_with("# ") {
442 continue;
443 } else {
444 text.push_str(line);
445 }
446 text.push('\n');
447 }
448
449 if io::stdout().is_terminal() {
451 show_md_content_with_pager(&text, color);
452 } else {
453 if color == ColorConfig::Always {
456 show_colored_md_content(&text);
457 } else {
458 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
459 }
460 }
461 } else {
462 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"));
463 }
464}
465
466fn show_md_content_with_pager(content: &str, color: ColorConfig) {
471 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
472 if falsecfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
473 });
474
475 let mut cmd = Command::new(&pager_name);
476 if pager_name == "less" {
477 cmd.arg("-R"); }
479
480 let pretty_on_pager = match color {
481 ColorConfig::Auto => {
482 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
484 }
485 ColorConfig::Always => true,
486 ColorConfig::Never => false,
487 };
488
489 let mut pretty_data = {
491 let mdstream = markdown::MdStream::parse_str(content);
492 let bufwtr = markdown::create_stdout_bufwtr();
493 let mut mdbuf = Vec::new();
494 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
495 Some((bufwtr, mdbuf))
496 } else {
497 None
498 }
499 };
500
501 let pager_res = try {
503 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
504
505 let pager_stdin = pager.stdin.as_mut()?;
506 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
507 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
508 } else {
509 pager_stdin.write_all(content.as_bytes()).ok()?;
510 };
511
512 pager.wait().ok()?;
513 };
514 if pager_res.is_some() {
515 return;
516 }
517
518 if let Some((bufwtr, mdbuf)) = &mut pretty_data
520 && bufwtr.write_all(&mdbuf).is_ok()
521 {
522 return;
523 }
524
525 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
527}
528
529fn show_colored_md_content(content: &str) {
534 let mut pretty_data = {
536 let mdstream = markdown::MdStream::parse_str(content);
537 let bufwtr = markdown::create_stdout_bufwtr();
538 let mut mdbuf = Vec::new();
539 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
540 Some((bufwtr, mdbuf))
541 } else {
542 None
543 }
544 };
545
546 if let Some((bufwtr, mdbuf)) = &mut pretty_data
547 && bufwtr.write_all(&mdbuf).is_ok()
548 {
549 return;
550 }
551
552 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
554}
555
556fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
557 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);
558 let dcx = sess.dcx();
559 if let Input::File(file) = &sess.io.input {
560 let rlink_data = fs::read(file).unwrap_or_else(|err| {
561 dcx.emit_fatal(RlinkUnableToRead { err });
562 });
563 let (compiled_modules, crate_info, metadata, outputs) =
564 match CompiledModules::deserialize_rlink(sess, rlink_data) {
565 Ok((codegen, crate_info, metadata, outputs)) => {
566 (codegen, crate_info, metadata, outputs)
567 }
568 Err(err) => {
569 match err {
570 CodegenError::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
571 CodegenError::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
572 CodegenError::EncodingVersionMismatch { version_array, rlink_version } => {
573 dcx.emit_fatal(RLinkEncodingVersionMismatch {
574 version_array,
575 rlink_version,
576 })
577 }
578 CodegenError::RustcVersionMismatch { rustc_version } => {
579 dcx.emit_fatal(RLinkRustcVersionMismatch {
580 rustc_version,
581 current_version: sess.cfg_version,
582 })
583 }
584 CodegenError::CorruptFile => {
585 dcx.emit_fatal(RlinkCorruptFile { file });
586 }
587 };
588 }
589 };
590 compiler.codegen_backend.link(sess, compiled_modules, crate_info, metadata, &outputs);
591 } else {
592 dcx.emit_fatal(RlinkNotAFile {});
593 }
594}
595
596fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
597 match sess.io.input {
598 Input::File(ref path) => {
599 let mut v = Vec::new();
600 locator::list_file_metadata(
601 &sess.target,
602 path,
603 metadata_loader,
604 &mut v,
605 &sess.opts.unstable_opts.ls,
606 sess.cfg_version,
607 )
608 .unwrap();
609 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
610 }
611 Input::Str { .. } => {
612 sess.dcx().fatal("cannot list metadata for stdin");
613 }
614 }
615}
616
617fn print_crate_info(
618 codegen_backend: &dyn CodegenBackend,
619 sess: &Session,
620 parse_attrs: bool,
621) -> Compilation {
622 use rustc_session::config::PrintKind::*;
623 #[allow(unused_imports)]
627 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
628
629 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
632 return Compilation::Continue;
633 }
634
635 let attrs = if parse_attrs {
636 let result = parse_crate_attrs(sess);
637 match result {
638 Ok(attrs) => Some(attrs),
639 Err(parse_error) => {
640 parse_error.emit();
641 return Compilation::Stop;
642 }
643 }
644 } else {
645 None
646 };
647
648 for req in &sess.opts.prints {
649 let mut crate_info = String::new();
650 macro println_info($($arg:tt)*) {
651 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
652 }
653
654 match req.kind {
655 TargetList => {
656 let mut targets = rustc_target::spec::TARGETS.to_vec();
657 targets.sort_unstable();
658 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
659 }
660 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()),
661 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()),
662 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()),
663 TargetSpecJson => {
664 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());
665 }
666 TargetSpecJsonSchema => {
667 let schema = rustc_target::spec::json_schema();
668 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());
669 }
670 AllTargetSpecsJson => {
671 let mut targets = BTreeMap::new();
672 for name in rustc_target::spec::TARGETS {
673 let triple = TargetTuple::from_tuple(name);
674 let target = Target::expect_builtin(&triple);
675 targets.insert(name, target.to_json());
676 }
677 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());
678 }
679 FileNames => {
680 let Some(attrs) = attrs.as_ref() else {
681 return Compilation::Continue;
683 };
684 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
685 let crate_name = passes::get_crate_name(sess, attrs);
686 let crate_types = collect_crate_types(
687 sess,
688 &codegen_backend.supported_crate_types(sess),
689 codegen_backend.name(),
690 attrs,
691 DUMMY_SP,
692 );
693 for &style in &crate_types {
694 let fname = rustc_session::output::filename_for_input(
695 sess, style, crate_name, &t_outputs,
696 );
697 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());
698 }
699 }
700 CrateName => {
701 let Some(attrs) = attrs.as_ref() else {
702 return Compilation::Continue;
704 };
705 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));
706 }
707 CrateRootLintLevels => {
708 let Some(attrs) = attrs.as_ref() else {
709 return Compilation::Continue;
711 };
712 let crate_name = passes::get_crate_name(sess, attrs);
713 let lint_store = crate::unerased_lint_store(sess);
714 let features = rustc_expand::config::features(sess, attrs, crate_name);
715 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs, sess);
716 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
717 sess,
718 &features,
719 true,
720 lint_store,
721 ®istered_tools,
722 attrs,
723 );
724 for lint in lint_store.get_lints() {
725 if let Some(feature_symbol) = lint.feature_gate
726 && !features.enabled(feature_symbol)
727 {
728 continue;
730 }
731 let level = lint_levels.lint_level(lint).level;
732 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());
733 }
734 }
735 Cfg => {
736 let mut cfgs = sess
737 .config
738 .iter()
739 .filter_map(|&(name, value)| {
740 if !sess.is_nightly_build()
742 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
743 {
744 return None;
745 }
746
747 if let Some(value) = value {
748 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
749 } else {
750 Some(name.to_string())
751 }
752 })
753 .collect::<Vec<String>>();
754
755 cfgs.sort();
756 for cfg in cfgs {
757 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
758 }
759 }
760 CheckCfg => {
761 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
762
763 #[allow(rustc::potential_query_instability)]
765 for (name, expected_values) in &sess.check_config.expecteds {
766 use crate::config::ExpectedValues;
767 match expected_values {
768 ExpectedValues::Any => {
769 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
770 }
771 ExpectedValues::Some(values) => {
772 let mut values: Vec<_> = values
773 .iter()
774 .map(|value| {
775 if let Some(value) = value {
776 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
777 } else {
778 "none()".to_string()
779 }
780 })
781 .collect();
782
783 values.sort_unstable();
784
785 let values = values.join(", ");
786
787 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
788 }
789 }
790 }
791
792 check_cfgs.sort_unstable();
793 if !sess.check_config.exhaustive_names && sess.check_config.exhaustive_values {
794 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
795 }
796 for check_cfg in check_cfgs {
797 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
798 }
799 }
800 CallingConventions => {
801 let calling_conventions = rustc_abi::all_names();
802 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
803 }
804 BackendHasMnemonic => {
805 codegen_backend.print(req, &mut crate_info, sess);
806 }
807 BackendHasZstd => {
808 let has_zstd: bool = codegen_backend.has_zstd();
809 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
810 }
811 RelocationModels
812 | CodeModels
813 | TlsModels
814 | TargetCPUs
815 | StackProtectorStrategies
816 | TargetFeatures => {
817 codegen_backend.print(req, &mut crate_info, sess);
818 }
819 NativeStaticLibs => {}
821 LinkArgs => {}
822 SplitDebuginfo => {
823 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
824
825 for split in &[Off, Packed, Unpacked] {
826 if sess.target.options.supported_split_debuginfo.contains(split) {
827 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
828 }
829 }
830 }
831 DeploymentTarget => {
832 if sess.target.is_like_darwin {
833 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!(
834 "{}={}",
835 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
836 sess.apple_deployment_target().fmt_pretty(),
837 )
838 } else {
839 sess.dcx().fatal("only Apple targets currently support deployment version info")
840 }
841 }
842 SupportedCrateTypes => {
843 let supported_crate_types = CrateType::all()
844 .iter()
845 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
846 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
847 .map(|(crate_type_sym, _)| *crate_type_sym)
848 .collect::<BTreeSet<_>>();
849 for supported_crate_type in supported_crate_types {
850 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
851 }
852 }
853 }
854
855 req.out.overwrite(&crate_info, sess);
856 }
857 Compilation::Stop
858}
859
860pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
864 fn unw(x: Option<&str>) -> &str {
865 x.unwrap_or("unknown")
866 }
867 $crate::version_at_macro_invocation(
868 $early_dcx,
869 $binary,
870 $matches,
871 unw(option_env!("CFG_VERSION")),
872 unw(option_env!("CFG_VER_HASH")),
873 unw(option_env!("CFG_VER_DATE")),
874 unw(option_env!("CFG_RELEASE")),
875 )
876}
877
878#[doc(hidden)] pub fn version_at_macro_invocation(
880 early_dcx: &EarlyDiagCtxt,
881 binary: &str,
882 matches: &getopts::Matches,
883 version: &str,
884 commit_hash: &str,
885 commit_date: &str,
886 release: &str,
887) {
888 let verbose = matches.opt_present("verbose");
889
890 let mut version = version;
891 let mut release = release;
892 let tmp;
893 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
894 tmp = force_version;
895 version = &tmp;
896 release = &tmp;
897 }
898
899 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
900
901 if verbose {
902 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
903 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
904 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
905 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
906 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
907
908 get_backend_from_raw_matches(early_dcx, matches).print_version();
909 }
910}
911
912fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
913 let mut options = getopts::Options::new();
914 for option in config::rustc_optgroups()
915 .iter()
916 .filter(|x| verbose || !x.is_verbose_help_only)
917 .filter(|x| include_unstable_options || x.is_stable())
918 {
919 option.apply(&mut options);
920 }
921 let message = "Usage: rustc [OPTIONS] INPUT";
922 let nightly_help = if nightly_build {
923 "\n -Z help Print unstable compiler options"
924 } else {
925 ""
926 };
927 let verbose_help = if verbose {
928 ""
929 } else {
930 "\n --help -v Print the full set of options rustc accepts"
931 };
932 let at_path = if verbose {
933 " @path Read newline separated options from `path`\n"
934 } else {
935 ""
936 };
937 {
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!(
938 "{options}{at_path}\nAdditional help:
939 -C help Print codegen options
940 -W help \
941 Print 'lint' options and default settings{nightly}{verbose}\n",
942 options = options.usage(message),
943 at_path = at_path,
944 nightly = nightly_help,
945 verbose = verbose_help
946 );
947}
948
949fn print_wall_help() {
950 {
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!(
951 "
952The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
953default. Use `rustc -W help` to see all available lints. It's more common to put
954warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
955the command line flag directly.
956"
957 );
958}
959
960pub fn describe_lints(sess: &Session, registered_lints: bool) {
962 {
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!(
963 "
964Available lint options:
965 -W <foo> Warn about <foo>
966 -A <foo> Allow <foo>
967 -D <foo> Deny <foo>
968 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
969
970"
971 );
972
973 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
974 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
976 lints
977 }
978
979 fn sort_lint_groups(
980 lints: Vec<(&'static str, Vec<LintId>, bool)>,
981 ) -> Vec<(&'static str, Vec<LintId>)> {
982 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
983 lints.sort_by_key(|l| l.0);
984 lints
985 }
986
987 let lint_store = unerased_lint_store(sess);
988 let (loaded, builtin): (Vec<_>, _) =
989 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
990 let loaded = sort_lints(sess, loaded);
991 let builtin = sort_lints(sess, builtin);
992
993 let (loaded_groups, builtin_groups): (Vec<_>, _) =
994 lint_store.get_lint_groups().partition(|&(.., p)| p);
995 let loaded_groups = sort_lint_groups(loaded_groups);
996 let builtin_groups = sort_lint_groups(builtin_groups);
997
998 let max_name_len =
999 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
1000 let padded = |x: &str| {
1001 let mut s = " ".repeat(max_name_len - x.chars().count());
1002 s.push_str(x);
1003 s
1004 };
1005
1006 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1007
1008 let print_lints = |lints: Vec<&Lint>| {
1009 {
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");
1010 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1011 for lint in lints {
1012 let name = lint.name_lower().replace('_', "-");
1013 {
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!(
1014 " {} {:7.7} {}",
1015 padded(&name),
1016 lint.default_level(sess.edition()).as_str(),
1017 lint.desc
1018 );
1019 }
1020 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1021 };
1022
1023 print_lints(builtin);
1024
1025 let max_name_len = max(
1026 "warnings".len(),
1027 loaded_groups
1028 .iter()
1029 .chain(&builtin_groups)
1030 .map(|&(s, _)| s.chars().count())
1031 .max()
1032 .unwrap_or(0),
1033 );
1034
1035 let padded = |x: &str| {
1036 let mut s = " ".repeat(max_name_len - x.chars().count());
1037 s.push_str(x);
1038 s
1039 };
1040
1041 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1042
1043 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1044 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1045 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1046
1047 if all_warnings {
1048 {
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"));
1049 }
1050
1051 for (name, to) in lints {
1052 let name = name.to_lowercase().replace('_', "-");
1053 let desc = to
1054 .into_iter()
1055 .map(|x| x.to_string().replace('_', "-"))
1056 .collect::<Vec<String>>()
1057 .join(", ");
1058 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1059 }
1060 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1061 };
1062
1063 print_lint_groups(builtin_groups, true);
1064
1065 match (registered_lints, loaded.len(), loaded_groups.len()) {
1066 (false, 0, _) | (false, _, 0) => {
1067 {
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.");
1068 }
1069 (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!"),
1070 (true, 0, 0) => {
1071 {
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.")
1072 }
1073 (true, l, g) => {
1074 if l > 0 {
1075 {
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");
1076 print_lints(loaded);
1077 }
1078 if g > 0 {
1079 {
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");
1080 print_lint_groups(loaded_groups, false);
1081 }
1082 }
1083 }
1084}
1085
1086pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1090 let wall = matches.opt_strs("W");
1092 if wall.iter().any(|x| *x == "all") {
1093 print_wall_help();
1094 return true;
1095 }
1096
1097 let debug_flags = matches.opt_strs("Z");
1099 if debug_flags.iter().any(|x| *x == "help") {
1100 describe_unstable_flags();
1101 return true;
1102 }
1103
1104 let cg_flags = matches.opt_strs("C");
1105 if cg_flags.iter().any(|x| *x == "help") {
1106 describe_codegen_flags();
1107 return true;
1108 }
1109
1110 if cg_flags.iter().any(|x| *x == "passes=list") {
1111 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1112 return true;
1113 }
1114
1115 false
1116}
1117
1118fn get_backend_from_raw_matches(
1125 early_dcx: &EarlyDiagCtxt,
1126 matches: &Matches,
1127) -> Box<dyn CodegenBackend> {
1128 let debug_flags = matches.opt_strs("Z");
1129 let backend_name = debug_flags
1130 .iter()
1131 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1132 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1133 let target = parse_target_triple(early_dcx, matches);
1134 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1135 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1136
1137 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1138}
1139
1140fn describe_unstable_flags() {
1141 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1142 print_flag_list("-Z", config::Z_OPTIONS);
1143}
1144
1145fn describe_codegen_flags() {
1146 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1147 print_flag_list("-C", config::CG_OPTIONS);
1148}
1149
1150fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1151 let max_len =
1152 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1153
1154 for opt_desc in flag_list {
1155 {
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!(
1156 " {} {:>width$}=val -- {}",
1157 cmdline_opt,
1158 opt_desc.name().replace('_', "-"),
1159 opt_desc.desc(),
1160 width = max_len
1161 );
1162 }
1163}
1164
1165pub enum HandledOptions {
1166 None,
1168 Normal(getopts::Matches),
1170 HelpOnly(getopts::Matches),
1173}
1174
1175pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1203 let mut options = getopts::Options::new();
1206 let optgroups = config::rustc_optgroups();
1207 for option in &optgroups {
1208 option.apply(&mut options);
1209 }
1210 let matches = options.parse(args).unwrap_or_else(|e| {
1211 let msg: Option<String> = match e {
1212 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1213 .iter()
1214 .map(|opt_desc| ('C', opt_desc.name()))
1215 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1216 .find(|&(_, name)| *opt == name.replace('_', "-"))
1217 .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}`?")),
1218 getopts::Fail::ArgumentMissing(ref opt) => {
1219 optgroups.iter().find(|option| option.name == opt).map(|option| {
1220 let mut options = getopts::Options::new();
1222 option.apply(&mut options);
1223 options.usage_with_format(|it| {
1226 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1227 })
1228 })
1229 }
1230 _ => None,
1231 };
1232 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1233 });
1234
1235 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1247
1248 let wall = matches.opt_strs("W");
1250 if wall.iter().any(|x| *x == "all") {
1251 print_wall_help();
1252 return HandledOptions::None;
1253 }
1254
1255 if handle_help(&matches, args) {
1256 return HandledOptions::HelpOnly(matches);
1257 }
1258
1259 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1260 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1261 return HandledOptions::None;
1262 }
1263
1264 if matches.opt_present("version") {
1265 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.97.0-nightly (f53b654a8 2026-04-30)")),
unw(::core::option::Option::Some("f53b654a8882fd5fc036c4ca7a4ff41ce32497a6")),
unw(::core::option::Option::Some("2026-04-30")),
unw(::core::option::Option::Some("1.97.0-nightly")));version!(early_dcx, "rustc", &matches);
1266 return HandledOptions::None;
1267 }
1268
1269 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1270
1271 HandledOptions::Normal(matches)
1272}
1273
1274pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1281 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1282 let opt_help_pos = |opt| {
1283 matches
1284 .opt_strs_pos(opt)
1285 .iter()
1286 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1287 .next()
1288 };
1289 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1290 let zhelp_pos = opt_help_pos("Z");
1291 let chelp_pos = opt_help_pos("C");
1292 let print_help = || {
1293 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1295 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1296 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1297 };
1298
1299 let mut helps = [
1300 (help_pos, &print_help as &dyn Fn()),
1301 (zhelp_pos, &describe_unstable_flags),
1302 (chelp_pos, &describe_codegen_flags),
1303 ];
1304 helps.sort_by_key(|(pos, _)| pos.clone());
1305 let mut printed_any = false;
1306 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1307 printer();
1308 printed_any = true;
1309 }
1310 printed_any
1311}
1312
1313fn warn_on_confusing_output_filename_flag(
1317 early_dcx: &EarlyDiagCtxt,
1318 matches: &getopts::Matches,
1319 args: &[String],
1320) {
1321 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1322 let s1 = s1.replace('-', "_");
1323 let s2 = s2.replace('-', "_");
1324 s1 == s2
1325 }
1326
1327 if let Some(name) = matches.opt_str("o")
1328 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1329 {
1330 let filename = suspect.trim_prefix("-");
1331 let optgroups = config::rustc_optgroups();
1332 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1333
1334 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1341 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1342 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1343 {
1344 early_dcx.early_warn(
1345 "option `-o` has no space between flag name and value, which can be confusing",
1346 );
1347 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!(
1348 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1349 ));
1350 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!(
1351 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1352 ));
1353 }
1354 }
1355}
1356
1357fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1358 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1359 Input::File(file) => {
1360 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1361 }
1362 Input::Str { name, input } => new_parser_from_source_str(
1363 &sess.psess,
1364 name.clone(),
1365 input.clone(),
1366 StripTokens::ShebangAndFrontmatter,
1367 ),
1368 });
1369 parser.parse_inner_attributes()
1370}
1371
1372pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1375 match catch_fatal_errors(f) {
1376 Ok(status) => status.report(),
1377 _ => ExitCode::FAILURE,
1378 }
1379}
1380
1381static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1382
1383fn ice_path() -> &'static Option<PathBuf> {
1391 ice_path_with_config(None)
1392}
1393
1394fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1395 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1396 {
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:1396",
"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(1396u32),
::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!(
1397 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1398 )
1399 }
1400
1401 ICE_PATH.get_or_init(|| {
1402 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1403 return None;
1404 }
1405 let mut path = match std::env::var_os("RUSTC_ICE") {
1406 Some(s) => {
1407 if s == "0" {
1408 return None;
1410 }
1411 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1412 {
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:1412",
"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(1412u32),
::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");
1413 }
1414 PathBuf::from(s)
1415 }
1416 None => config
1417 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1418 .or_else(|| std::env::current_dir().ok())
1419 .unwrap_or_default(),
1420 };
1421 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1423 let pid = std::process::id();
1424 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"));
1425 Some(path)
1426 })
1427}
1428
1429pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1430
1431pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1443 if env::var_os("RUST_BACKTRACE").is_none() {
1450 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1452 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1453 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1454 } else {
1455 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1456 }
1457 }
1458
1459 panic::update_hook(Box::new(
1460 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1461 info: &PanicHookInfo<'_>| {
1462 let _guard = io::stderr().lock();
1464 #[cfg(windows)]
1467 if let Some(msg) = info.payload().downcast_ref::<String>() {
1468 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1469 {
1470 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1472 let _ = early_dcx.early_err(msg.clone());
1473 return;
1474 }
1475 };
1476
1477 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1480 default_hook(info);
1481 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1483
1484 if let Some(ice_path) = ice_path()
1485 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1486 {
1487 let location = info.location().unwrap();
1489 let msg = match info.payload().downcast_ref::<&'static str>() {
1490 Some(s) => *s,
1491 None => match info.payload().downcast_ref::<String>() {
1492 Some(s) => &s[..],
1493 None => "Box<dyn Any>",
1494 },
1495 };
1496 let thread = std::thread::current();
1497 let name = thread.name().unwrap_or("<unnamed>");
1498 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!(
1499 &mut out,
1500 "thread '{name}' panicked at {location}:\n\
1501 {msg}\n\
1502 stack backtrace:\n\
1503 {:#}",
1504 std::backtrace::Backtrace::force_capture()
1505 );
1506 }
1507 }
1508
1509 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1511 },
1512 ));
1513}
1514
1515fn report_ice(
1522 info: &panic::PanicHookInfo<'_>,
1523 bug_report_url: &str,
1524 extra_info: fn(&DiagCtxt),
1525 using_internal_features: &AtomicBool,
1526) {
1527 let emitter =
1528 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1529 stderr_destination(rustc_errors::ColorConfig::Auto),
1530 ));
1531 let dcx = rustc_errors::DiagCtxt::new(emitter);
1532 let dcx = dcx.handle();
1533
1534 if !info.payload().is::<rustc_errors::ExplicitBug>()
1537 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1538 {
1539 dcx.emit_err(session_diagnostics::Ice);
1540 }
1541
1542 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1543 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1544 } else {
1545 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1546
1547 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1549 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1550 }
1551 }
1552
1553 let version = ::core::option::Option::Some("1.97.0-nightly (f53b654a8 2026-04-30)")util::version_str!().unwrap_or("unknown_version");
1554 let tuple = config::host_tuple();
1555
1556 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1557
1558 let file = if let Some(path) = ice_path() {
1559 match crate::fs::File::options().create(true).append(true).open(path) {
1561 Ok(mut file) => {
1562 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1563 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1564 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1565 }
1566 Some(file)
1567 }
1568 Err(err) => {
1569 dcx.emit_warn(session_diagnostics::IcePathError {
1571 path: path.clone(),
1572 error: err.to_string(),
1573 env_var: std::env::var_os("RUSTC_ICE")
1574 .map(PathBuf::from)
1575 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1576 });
1577 None
1578 }
1579 }
1580 } else {
1581 None
1582 };
1583
1584 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1585
1586 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1587 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1588 if excluded_cargo_defaults {
1589 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1590 }
1591 }
1592
1593 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1595
1596 let limit_frames = if backtrace { None } else { Some(2) };
1597
1598 interface::try_print_query_stack(dcx, limit_frames, file);
1599
1600 extra_info(&dcx);
1603
1604 #[cfg(windows)]
1605 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1606 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1608 }
1609}
1610
1611pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1614 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1615}
1616
1617pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1621 if let Err(error) = rustc_log::init_logger(cfg) {
1622 early_dcx.early_fatal(error.to_string());
1623 }
1624}
1625
1626pub fn init_logger_with_additional_layer<F, T>(
1632 early_dcx: &EarlyDiagCtxt,
1633 cfg: rustc_log::LoggerConfig,
1634 build_subscriber: F,
1635) where
1636 F: FnOnce() -> T,
1637 T: rustc_log::BuildSubscriberRet,
1638{
1639 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1640 early_dcx.early_fatal(error.to_string());
1641 }
1642}
1643
1644pub fn install_ctrlc_handler() {
1647 #[cfg(all(not(miri), not(target_family = "wasm")))]
1648 ctrlc::set_handler(move || {
1649 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1654 std::thread::sleep(std::time::Duration::from_millis(100));
1655 std::process::exit(1);
1656 })
1657 .expect("Unable to install ctrlc handler");
1658}
1659
1660pub fn main() -> ExitCode {
1661 let start_time = Instant::now();
1662 let start_rss = get_resident_set_size();
1663
1664 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1665
1666 init_rustc_env_logger(&early_dcx);
1667 signal_handler::install();
1668 let mut callbacks = TimePassesCallbacks::default();
1669 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1670 install_ctrlc_handler();
1671
1672 let exit_code =
1673 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1674
1675 if let Some(format) = callbacks.time_passes {
1676 let end_rss = get_resident_set_size();
1677 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1678 }
1679
1680 exit_code
1681}