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