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 {
#[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)]
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 features = rustc_expand::config::features(sess, attrs, crate_name);
711 let registered_tools =
712 rustc_resolve::registered_tools_ast(sess.dcx(), attrs, sess, &features);
713 let lint_levels = rustc_lint::LintLevelsBuilder::crate_root(
714 sess,
715 &features,
716 true,
717 lint_store,
718 ®istered_tools,
719 attrs,
720 );
721 for lint in lint_store.get_lints() {
722 if let Some(feature_symbol) = lint.feature_gate
723 && !features.enabled(feature_symbol)
724 {
725 continue;
727 }
728 let level = lint_levels.lint_level(lint).level;
729 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());
730 }
731 }
732 Cfg => {
733 let mut cfgs = sess
734 .psess
735 .config
736 .iter()
737 .filter_map(|&(name, value)| {
738 if !sess.is_nightly_build()
740 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
741 {
742 return None;
743 }
744
745 if let Some(value) = value {
746 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
747 } else {
748 Some(name.to_string())
749 }
750 })
751 .collect::<Vec<String>>();
752
753 cfgs.sort();
754 for cfg in cfgs {
755 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
756 }
757 }
758 CheckCfg => {
759 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
760
761 #[allow(rustc::potential_query_instability)]
763 for (name, expected_values) in &sess.psess.check_config.expecteds {
764 use crate::config::ExpectedValues;
765 match expected_values {
766 ExpectedValues::Any => {
767 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
768 }
769 ExpectedValues::Some(values) => {
770 let mut values: Vec<_> = values
771 .iter()
772 .map(|value| {
773 if let Some(value) = value {
774 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
775 } else {
776 "none()".to_string()
777 }
778 })
779 .collect();
780
781 values.sort_unstable();
782
783 let values = values.join(", ");
784
785 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
786 }
787 }
788 }
789
790 check_cfgs.sort_unstable();
791 if !sess.psess.check_config.exhaustive_names
792 && sess.psess.check_config.exhaustive_values
793 {
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 BackendHasZstd => {
805 let has_zstd: bool = codegen_backend.has_zstd();
806 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
807 }
808 RelocationModels
809 | CodeModels
810 | TlsModels
811 | TargetCPUs
812 | StackProtectorStrategies
813 | TargetFeatures => {
814 codegen_backend.print(req, &mut crate_info, sess);
815 }
816 NativeStaticLibs => {}
818 LinkArgs => {}
819 SplitDebuginfo => {
820 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
821
822 for split in &[Off, Packed, Unpacked] {
823 if sess.target.options.supported_split_debuginfo.contains(split) {
824 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
825 }
826 }
827 }
828 DeploymentTarget => {
829 if sess.target.is_like_darwin {
830 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!(
831 "{}={}",
832 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
833 sess.apple_deployment_target().fmt_pretty(),
834 )
835 } else {
836 sess.dcx().fatal("only Apple targets currently support deployment version info")
837 }
838 }
839 SupportedCrateTypes => {
840 let supported_crate_types = CrateType::all()
841 .iter()
842 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
843 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
844 .map(|(crate_type_sym, _)| *crate_type_sym)
845 .collect::<BTreeSet<_>>();
846 for supported_crate_type in supported_crate_types {
847 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
848 }
849 }
850 }
851
852 req.out.overwrite(&crate_info, sess);
853 }
854 Compilation::Stop
855}
856
857pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
861 fn unw(x: Option<&str>) -> &str {
862 x.unwrap_or("unknown")
863 }
864 $crate::version_at_macro_invocation(
865 $early_dcx,
866 $binary,
867 $matches,
868 unw(option_env!("CFG_VERSION")),
869 unw(option_env!("CFG_VER_HASH")),
870 unw(option_env!("CFG_VER_DATE")),
871 unw(option_env!("CFG_RELEASE")),
872 )
873}
874
875#[doc(hidden)] pub fn version_at_macro_invocation(
877 early_dcx: &EarlyDiagCtxt,
878 binary: &str,
879 matches: &getopts::Matches,
880 version: &str,
881 commit_hash: &str,
882 commit_date: &str,
883 release: &str,
884) {
885 let verbose = matches.opt_present("verbose");
886
887 let mut version = version;
888 let mut release = release;
889 let tmp;
890 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
891 tmp = force_version;
892 version = &tmp;
893 release = &tmp;
894 }
895
896 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
897
898 if verbose {
899 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
900 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
901 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
902 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
903 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
904
905 get_backend_from_raw_matches(early_dcx, matches).print_version();
906 }
907}
908
909fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
910 let mut options = getopts::Options::new();
911 for option in config::rustc_optgroups()
912 .iter()
913 .filter(|x| verbose || !x.is_verbose_help_only)
914 .filter(|x| include_unstable_options || x.is_stable())
915 {
916 option.apply(&mut options);
917 }
918 let message = "Usage: rustc [OPTIONS] INPUT";
919 let nightly_help = if nightly_build {
920 "\n -Z help Print unstable compiler options"
921 } else {
922 ""
923 };
924 let verbose_help = if verbose {
925 ""
926 } else {
927 "\n --help -v Print the full set of options rustc accepts"
928 };
929 let at_path = if verbose {
930 " @path Read newline separated options from `path`\n"
931 } else {
932 ""
933 };
934 {
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!(
935 "{options}{at_path}\nAdditional help:
936 -C help Print codegen options
937 -W help \
938 Print 'lint' options and default settings{nightly}{verbose}\n",
939 options = options.usage(message),
940 at_path = at_path,
941 nightly = nightly_help,
942 verbose = verbose_help
943 );
944}
945
946fn print_wall_help() {
947 {
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!(
948 "
949The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
950default. Use `rustc -W help` to see all available lints. It's more common to put
951warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
952the command line flag directly.
953"
954 );
955}
956
957pub fn describe_lints(sess: &Session, registered_lints: bool) {
959 {
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!(
960 "
961Available lint options:
962 -W <foo> Warn about <foo>
963 -A <foo> Allow <foo>
964 -D <foo> Deny <foo>
965 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
966
967"
968 );
969
970 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
971 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
973 lints
974 }
975
976 fn sort_lint_groups(
977 lints: Vec<(&'static str, Vec<LintId>, bool)>,
978 ) -> Vec<(&'static str, Vec<LintId>)> {
979 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
980 lints.sort_by_key(|l| l.0);
981 lints
982 }
983
984 let lint_store = unerased_lint_store(sess);
985 let (loaded, builtin): (Vec<_>, _) =
986 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
987 let loaded = sort_lints(sess, loaded);
988 let builtin = sort_lints(sess, builtin);
989
990 let (loaded_groups, builtin_groups): (Vec<_>, _) =
991 lint_store.get_lint_groups().partition(|&(.., p)| p);
992 let loaded_groups = sort_lint_groups(loaded_groups);
993 let builtin_groups = sort_lint_groups(builtin_groups);
994
995 let max_name_len =
996 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
997 let padded = |x: &str| {
998 let mut s = " ".repeat(max_name_len - x.chars().count());
999 s.push_str(x);
1000 s
1001 };
1002
1003 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1004
1005 let print_lints = |lints: Vec<&Lint>| {
1006 {
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");
1007 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1008 for lint in lints {
1009 let name = lint.name_lower().replace('_', "-");
1010 {
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!(
1011 " {} {:7.7} {}",
1012 padded(&name),
1013 lint.default_level(sess.edition()).as_str(),
1014 lint.desc
1015 );
1016 }
1017 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1018 };
1019
1020 print_lints(builtin);
1021
1022 let max_name_len = max(
1023 "warnings".len(),
1024 loaded_groups
1025 .iter()
1026 .chain(&builtin_groups)
1027 .map(|&(s, _)| s.chars().count())
1028 .max()
1029 .unwrap_or(0),
1030 );
1031
1032 let padded = |x: &str| {
1033 let mut s = " ".repeat(max_name_len - x.chars().count());
1034 s.push_str(x);
1035 s
1036 };
1037
1038 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1039
1040 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1041 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1042 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1043
1044 if all_warnings {
1045 {
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"));
1046 }
1047
1048 for (name, to) in lints {
1049 let name = name.to_lowercase().replace('_', "-");
1050 let desc = to
1051 .into_iter()
1052 .map(|x| x.to_string().replace('_', "-"))
1053 .collect::<Vec<String>>()
1054 .join(", ");
1055 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1056 }
1057 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1058 };
1059
1060 print_lint_groups(builtin_groups, true);
1061
1062 match (registered_lints, loaded.len(), loaded_groups.len()) {
1063 (false, 0, _) | (false, _, 0) => {
1064 {
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.");
1065 }
1066 (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!"),
1067 (true, 0, 0) => {
1068 {
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.")
1069 }
1070 (true, l, g) => {
1071 if l > 0 {
1072 {
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");
1073 print_lints(loaded);
1074 }
1075 if g > 0 {
1076 {
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");
1077 print_lint_groups(loaded_groups, false);
1078 }
1079 }
1080 }
1081}
1082
1083pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1087 let wall = matches.opt_strs("W");
1089 if wall.iter().any(|x| *x == "all") {
1090 print_wall_help();
1091 return true;
1092 }
1093
1094 let debug_flags = matches.opt_strs("Z");
1096 if debug_flags.iter().any(|x| *x == "help") {
1097 describe_unstable_flags();
1098 return true;
1099 }
1100
1101 let cg_flags = matches.opt_strs("C");
1102 if cg_flags.iter().any(|x| *x == "help") {
1103 describe_codegen_flags();
1104 return true;
1105 }
1106
1107 if cg_flags.iter().any(|x| *x == "passes=list") {
1108 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1109 return true;
1110 }
1111
1112 false
1113}
1114
1115fn get_backend_from_raw_matches(
1122 early_dcx: &EarlyDiagCtxt,
1123 matches: &Matches,
1124) -> Box<dyn CodegenBackend> {
1125 let debug_flags = matches.opt_strs("Z");
1126 let backend_name = debug_flags
1127 .iter()
1128 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1129 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1130 let target = parse_target_triple(early_dcx, matches);
1131 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1132 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1133
1134 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1135}
1136
1137fn describe_unstable_flags() {
1138 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1139 print_flag_list("-Z", config::Z_OPTIONS);
1140}
1141
1142fn describe_codegen_flags() {
1143 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1144 print_flag_list("-C", config::CG_OPTIONS);
1145}
1146
1147fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1148 let max_len =
1149 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1150
1151 for opt_desc in flag_list {
1152 {
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!(
1153 " {} {:>width$}=val -- {}",
1154 cmdline_opt,
1155 opt_desc.name().replace('_', "-"),
1156 opt_desc.desc(),
1157 width = max_len
1158 );
1159 }
1160}
1161
1162pub enum HandledOptions {
1163 None,
1165 Normal(getopts::Matches),
1167 HelpOnly(getopts::Matches),
1170}
1171
1172pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1200 let mut options = getopts::Options::new();
1203 let optgroups = config::rustc_optgroups();
1204 for option in &optgroups {
1205 option.apply(&mut options);
1206 }
1207 let matches = options.parse(args).unwrap_or_else(|e| {
1208 let msg: Option<String> = match e {
1209 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1210 .iter()
1211 .map(|opt_desc| ('C', opt_desc.name()))
1212 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1213 .find(|&(_, name)| *opt == name.replace('_', "-"))
1214 .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}`?")),
1215 getopts::Fail::ArgumentMissing(ref opt) => {
1216 optgroups.iter().find(|option| option.name == opt).map(|option| {
1217 let mut options = getopts::Options::new();
1219 option.apply(&mut options);
1220 options.usage_with_format(|it| {
1223 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1224 })
1225 })
1226 }
1227 _ => None,
1228 };
1229 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1230 });
1231
1232 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1244
1245 let wall = matches.opt_strs("W");
1247 if wall.iter().any(|x| *x == "all") {
1248 print_wall_help();
1249 return HandledOptions::None;
1250 }
1251
1252 if handle_help(&matches, args) {
1253 return HandledOptions::HelpOnly(matches);
1254 }
1255
1256 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1257 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1258 return HandledOptions::None;
1259 }
1260
1261 if matches.opt_present("version") {
1262 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-beta.1 (ad726b506 2026-03-05)")),
unw(::core::option::Option::Some("ad726b5063362ec9897ef3d67452fc5606ee70fa")),
unw(::core::option::Option::Some("2026-03-05")),
unw(::core::option::Option::Some("1.95.0-beta.1")));version!(early_dcx, "rustc", &matches);
1263 return HandledOptions::None;
1264 }
1265
1266 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1267
1268 HandledOptions::Normal(matches)
1269}
1270
1271pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1278 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1279 let opt_help_pos = |opt| {
1280 matches
1281 .opt_strs_pos(opt)
1282 .iter()
1283 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1284 .next()
1285 };
1286 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1287 let zhelp_pos = opt_help_pos("Z");
1288 let chelp_pos = opt_help_pos("C");
1289 let print_help = || {
1290 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1292 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1293 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1294 };
1295
1296 let mut helps = [
1297 (help_pos, &print_help as &dyn Fn()),
1298 (zhelp_pos, &describe_unstable_flags),
1299 (chelp_pos, &describe_codegen_flags),
1300 ];
1301 helps.sort_by_key(|(pos, _)| pos.clone());
1302 let mut printed_any = false;
1303 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1304 printer();
1305 printed_any = true;
1306 }
1307 printed_any
1308}
1309
1310fn warn_on_confusing_output_filename_flag(
1314 early_dcx: &EarlyDiagCtxt,
1315 matches: &getopts::Matches,
1316 args: &[String],
1317) {
1318 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1319 let s1 = s1.replace('-', "_");
1320 let s2 = s2.replace('-', "_");
1321 s1 == s2
1322 }
1323
1324 if let Some(name) = matches.opt_str("o")
1325 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1326 {
1327 let filename = suspect.trim_prefix("-");
1328 let optgroups = config::rustc_optgroups();
1329 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1330
1331 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1338 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1339 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1340 {
1341 early_dcx.early_warn(
1342 "option `-o` has no space between flag name and value, which can be confusing",
1343 );
1344 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!(
1345 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1346 ));
1347 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!(
1348 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1349 ));
1350 }
1351 }
1352}
1353
1354fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1355 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1356 Input::File(file) => {
1357 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1358 }
1359 Input::Str { name, input } => new_parser_from_source_str(
1360 &sess.psess,
1361 name.clone(),
1362 input.clone(),
1363 StripTokens::ShebangAndFrontmatter,
1364 ),
1365 });
1366 parser.parse_inner_attributes()
1367}
1368
1369pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1372 match catch_fatal_errors(f) {
1373 Ok(status) => status.report(),
1374 _ => ExitCode::FAILURE,
1375 }
1376}
1377
1378static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1379
1380fn ice_path() -> &'static Option<PathBuf> {
1388 ice_path_with_config(None)
1389}
1390
1391fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1392 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1393 {
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:1393",
"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(1393u32),
::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!(
1394 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1395 )
1396 }
1397
1398 ICE_PATH.get_or_init(|| {
1399 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1400 return None;
1401 }
1402 let mut path = match std::env::var_os("RUSTC_ICE") {
1403 Some(s) => {
1404 if s == "0" {
1405 return None;
1407 }
1408 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1409 {
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:1409",
"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(1409u32),
::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");
1410 }
1411 PathBuf::from(s)
1412 }
1413 None => config
1414 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1415 .or_else(|| std::env::current_dir().ok())
1416 .unwrap_or_default(),
1417 };
1418 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1420 let pid = std::process::id();
1421 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"));
1422 Some(path)
1423 })
1424}
1425
1426pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1427
1428pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1440 if env::var_os("RUST_BACKTRACE").is_none() {
1447 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1449 if "beta"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1450 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1451 } else {
1452 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1453 }
1454 }
1455
1456 panic::update_hook(Box::new(
1457 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1458 info: &PanicHookInfo<'_>| {
1459 let _guard = io::stderr().lock();
1461 #[cfg(windows)]
1464 if let Some(msg) = info.payload().downcast_ref::<String>() {
1465 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1466 {
1467 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1469 let _ = early_dcx.early_err(msg.clone());
1470 return;
1471 }
1472 };
1473
1474 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1477 default_hook(info);
1478 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1480
1481 if let Some(ice_path) = ice_path()
1482 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1483 {
1484 let location = info.location().unwrap();
1486 let msg = match info.payload().downcast_ref::<&'static str>() {
1487 Some(s) => *s,
1488 None => match info.payload().downcast_ref::<String>() {
1489 Some(s) => &s[..],
1490 None => "Box<dyn Any>",
1491 },
1492 };
1493 let thread = std::thread::current();
1494 let name = thread.name().unwrap_or("<unnamed>");
1495 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!(
1496 &mut out,
1497 "thread '{name}' panicked at {location}:\n\
1498 {msg}\n\
1499 stack backtrace:\n\
1500 {:#}",
1501 std::backtrace::Backtrace::force_capture()
1502 );
1503 }
1504 }
1505
1506 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1508 },
1509 ));
1510}
1511
1512fn report_ice(
1519 info: &panic::PanicHookInfo<'_>,
1520 bug_report_url: &str,
1521 extra_info: fn(&DiagCtxt),
1522 using_internal_features: &AtomicBool,
1523) {
1524 let emitter =
1525 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1526 stderr_destination(rustc_errors::ColorConfig::Auto),
1527 ));
1528 let dcx = rustc_errors::DiagCtxt::new(emitter);
1529 let dcx = dcx.handle();
1530
1531 if !info.payload().is::<rustc_errors::ExplicitBug>()
1534 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1535 {
1536 dcx.emit_err(session_diagnostics::Ice);
1537 }
1538
1539 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1540 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1541 } else {
1542 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1543
1544 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1546 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1547 }
1548 }
1549
1550 let version = ::core::option::Option::Some("1.95.0-beta.1 (ad726b506 2026-03-05)")util::version_str!().unwrap_or("unknown_version");
1551 let tuple = config::host_tuple();
1552
1553 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1554
1555 let file = if let Some(path) = ice_path() {
1556 match crate::fs::File::options().create(true).append(true).open(path) {
1558 Ok(mut file) => {
1559 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1560 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1561 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1562 }
1563 Some(file)
1564 }
1565 Err(err) => {
1566 dcx.emit_warn(session_diagnostics::IcePathError {
1568 path: path.clone(),
1569 error: err.to_string(),
1570 env_var: std::env::var_os("RUSTC_ICE")
1571 .map(PathBuf::from)
1572 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1573 });
1574 None
1575 }
1576 }
1577 } else {
1578 None
1579 };
1580
1581 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1582
1583 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1584 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1585 if excluded_cargo_defaults {
1586 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1587 }
1588 }
1589
1590 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1592
1593 let limit_frames = if backtrace { None } else { Some(2) };
1594
1595 interface::try_print_query_stack(dcx, limit_frames, file);
1596
1597 extra_info(&dcx);
1600
1601 #[cfg(windows)]
1602 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1603 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1605 }
1606}
1607
1608pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1611 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1612}
1613
1614pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1618 if let Err(error) = rustc_log::init_logger(cfg) {
1619 early_dcx.early_fatal(error.to_string());
1620 }
1621}
1622
1623pub fn init_logger_with_additional_layer<F, T>(
1629 early_dcx: &EarlyDiagCtxt,
1630 cfg: rustc_log::LoggerConfig,
1631 build_subscriber: F,
1632) where
1633 F: FnOnce() -> T,
1634 T: rustc_log::BuildSubscriberRet,
1635{
1636 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1637 early_dcx.early_fatal(error.to_string());
1638 }
1639}
1640
1641pub fn install_ctrlc_handler() {
1644 #[cfg(all(not(miri), not(target_family = "wasm")))]
1645 ctrlc::set_handler(move || {
1646 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1651 std::thread::sleep(std::time::Duration::from_millis(100));
1652 std::process::exit(1);
1653 })
1654 .expect("Unable to install ctrlc handler");
1655}
1656
1657pub fn main() -> ExitCode {
1658 let start_time = Instant::now();
1659 let start_rss = get_resident_set_size();
1660
1661 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1662
1663 init_rustc_env_logger(&early_dcx);
1664 signal_handler::install();
1665 let mut callbacks = TimePassesCallbacks::default();
1666 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1667 install_ctrlc_handler();
1668
1669 let exit_code =
1670 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1671
1672 if let Some(format) = callbacks.time_passes {
1673 let end_rss = get_resident_set_size();
1674 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1675 }
1676
1677 exit_code
1678}