1#![feature(decl_macro)]
9#![feature(file_buffered)]
10#![feature(panic_backtrace_config)]
11#![feature(panic_update_hook)]
12#![feature(trim_prefix_suffix)]
13#![feature(try_blocks)]
14use std::cmp::max;
17use std::collections::{BTreeMap, BTreeSet};
18use std::ffi::OsString;
19use std::fmt::Write as _;
20use std::fs::{self, File};
21use std::io::{self, IsTerminal, Read, Write};
22use std::panic::{self, PanicHookInfo};
23use std::path::{Path, PathBuf};
24use std::process::{Command, ExitCode, Stdio, Termination};
25use std::sync::OnceLock;
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::time::Instant;
28use std::{env, str};
29
30use rustc_ast as ast;
31use rustc_codegen_ssa::traits::CodegenBackend;
32use rustc_codegen_ssa::{CodegenError, CompiledModules};
33use rustc_data_structures::profiling::{
34 TimePassesFormat, get_resident_set_size, print_time_passes_entry,
35};
36pub use rustc_errors::catch_fatal_errors;
37use rustc_errors::emitter::stderr_destination;
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 const EXIT_SUCCESS: i32 = 0;
112
113pub const EXIT_FAILURE: i32 = 1;
115
116pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
117 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
118
119pub trait Callbacks {
120 fn config(&mut self, _config: &mut interface::Config) {}
122 fn after_crate_root_parsing(
126 &mut self,
127 _compiler: &interface::Compiler,
128 _krate: &mut ast::Crate,
129 ) -> Compilation {
130 Compilation::Continue
131 }
132 fn after_expansion<'tcx>(
135 &mut self,
136 _compiler: &interface::Compiler,
137 _tcx: TyCtxt<'tcx>,
138 ) -> Compilation {
139 Compilation::Continue
140 }
141 fn after_analysis<'tcx>(
144 &mut self,
145 _compiler: &interface::Compiler,
146 _tcx: TyCtxt<'tcx>,
147 ) -> Compilation {
148 Compilation::Continue
149 }
150}
151
152#[derive(#[automatically_derived]
impl ::core::default::Default for TimePassesCallbacks {
#[inline]
fn default() -> TimePassesCallbacks {
TimePassesCallbacks {
time_passes: ::core::default::Default::default(),
}
}
}Default)]
153pub struct TimePassesCallbacks {
154 time_passes: Option<TimePassesFormat>,
155}
156
157impl Callbacks for TimePassesCallbacks {
158 #[allow(rustc::bad_opt_access)]
160 fn config(&mut self, config: &mut interface::Config) {
161 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
165 .then_some(config.opts.unstable_opts.time_passes_format);
166 config.opts.trimmed_def_paths = true;
167 }
168}
169
170pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
172 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
173
174 let at_args = at_args.get(1..).unwrap_or_default();
183
184 let args = args::arg_expand_all(&default_early_dcx, at_args);
185
186 let (matches, help_only) = match handle_options(&default_early_dcx, &args) {
187 HandledOptions::None => return,
188 HandledOptions::Normal(matches) => (matches, false),
189 HandledOptions::HelpOnly(matches) => (matches, true),
190 };
191
192 let sopts = config::build_session_options(&mut default_early_dcx, &matches);
193 let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
195
196 if let Some(ref code) = matches.opt_str("explain") {
197 handle_explain(&default_early_dcx, code, sopts.color);
198 return;
199 }
200
201 let input = make_input(&default_early_dcx, &matches.free);
202 let has_input = input.is_some();
203 let (odir, ofile) = make_output(&matches);
204
205 drop(default_early_dcx);
206
207 let mut config = interface::Config {
208 opts: sopts,
209 crate_cfg: matches.opt_strs("cfg"),
210 crate_check_cfg: matches.opt_strs("check-cfg"),
211 input: input.unwrap_or(Input::File(PathBuf::new())),
212 output_file: ofile,
213 output_dir: odir,
214 ice_file,
215 file_loader: None,
216 lint_caps: Default::default(),
217 psess_created: None,
218 track_state: None,
219 register_lints: None,
220 override_queries: None,
221 extra_symbols: Vec::new(),
222 make_codegen_backend: None,
223 using_internal_features: &USING_INTERNAL_FEATURES,
224 };
225
226 callbacks.config(&mut config);
227
228 let registered_lints = config.register_lints.is_some();
229
230 interface::run_compiler(config, |compiler| {
231 let sess = &compiler.sess;
232 let codegen_backend = &*compiler.codegen_backend;
233
234 let early_exit = || {
238 sess.dcx().abort_if_errors();
239 };
240
241 if sess.opts.describe_lints {
245 describe_lints(sess, registered_lints);
246 return early_exit();
247 }
248
249 if help_only {
251 return early_exit();
252 }
253
254 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
255 return early_exit();
256 }
257
258 if !has_input {
259 sess.dcx().fatal("no input filename given"); }
261
262 if !sess.opts.unstable_opts.ls.is_empty() {
263 list_metadata(sess, &*codegen_backend.metadata_loader());
264 return early_exit();
265 }
266
267 if sess.opts.unstable_opts.link_only {
268 process_rlink(sess, compiler);
269 return early_exit();
270 }
271
272 let mut krate = passes::parse(sess);
275
276 if let Some(pp_mode) = sess.opts.pretty {
278 if pp_mode.needs_ast_map() {
279 create_and_enter_global_ctxt(compiler, krate, |tcx| {
280 tcx.ensure_ok().early_lint_checks(());
281 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
282 passes::write_dep_info(tcx);
283 });
284 } else {
285 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
286 }
287 {
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:287",
"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(287u32),
::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");
288 return early_exit();
289 }
290
291 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
292 return early_exit();
293 }
294
295 if sess.opts.unstable_opts.parse_crate_root_only {
296 return early_exit();
297 }
298
299 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
300 let early_exit = || {
301 sess.dcx().abort_if_errors();
302 None
303 };
304
305 let _ = tcx.resolver_for_lowering();
307
308 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
309 return early_exit();
310 }
311
312 passes::write_dep_info(tcx);
313
314 passes::write_interface(tcx);
315
316 if sess.opts.output_types.contains_key(&OutputType::DepInfo)
317 && sess.opts.output_types.len() == 1
318 {
319 return early_exit();
320 }
321
322 if sess.opts.unstable_opts.no_analysis {
323 return early_exit();
324 }
325
326 tcx.ensure_ok().analysis(());
327
328 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
329 dump_feature_usage_metrics(tcx, metrics_dir);
330 }
331
332 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
333 return early_exit();
334 }
335
336 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
337 if let Err(error) = pretty::emit_mir(tcx) {
338 tcx.dcx().emit_fatal(CantEmitMIR { error });
339 }
340 }
341
342 let linker = Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend);
343
344 tcx.report_unused_features();
345
346 Some(linker)
347 });
348
349 if let Some(linker) = linker {
352 linker.link(sess, codegen_backend);
353 }
354 })
355}
356
357fn dump_feature_usage_metrics(tcx: TyCtxt<'_>, metrics_dir: &Path) {
358 let hash = tcx.crate_hash(LOCAL_CRATE);
359 let crate_name = tcx.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) = tcx.features().dump_feature_usage_metrics(metrics_path) {
363 tcx.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_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)]
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 (compiled_modules, crate_info, metadata, outputs) =
565 match CompiledModules::deserialize_rlink(sess, rlink_data) {
566 Ok((codegen, crate_info, metadata, outputs)) => {
567 (codegen, crate_info, metadata, outputs)
568 }
569 Err(err) => {
570 match err {
571 CodegenError::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
572 CodegenError::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
573 CodegenError::EncodingVersionMismatch { version_array, rlink_version } => {
574 dcx.emit_fatal(RLinkEncodingVersionMismatch {
575 version_array,
576 rlink_version,
577 })
578 }
579 CodegenError::RustcVersionMismatch { rustc_version } => {
580 dcx.emit_fatal(RLinkRustcVersionMismatch {
581 rustc_version,
582 current_version: sess.cfg_version,
583 })
584 }
585 CodegenError::CorruptFile => {
586 dcx.emit_fatal(RlinkCorruptFile { file });
587 }
588 };
589 }
590 };
591 compiler.codegen_backend.link(sess, compiled_modules, crate_info, 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 if let Err(error) = 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 if path.extension().is_some_and(|extension| extension == "rs") {
610 let mut err = sess
611 .dcx()
612 .struct_fatal("`-Zls` takes a `.rmeta` file as input, not a source file");
613 if rustc_session::utils::was_invoked_from_cargo() {
614 err.note("use `rustc +nightly -Zls=... path/to/file.rmeta` directly, instead of going through Cargo");
616 }
617 err.emit();
618 }
619 sess.dcx().fatal(error.to_string());
620 }
621 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
622 }
623 Input::Str { .. } => {
624 sess.dcx().fatal("cannot list metadata for stdin");
625 }
626 }
627}
628
629fn print_crate_info(
630 codegen_backend: &dyn CodegenBackend,
631 sess: &Session,
632 parse_attrs: bool,
633) -> Compilation {
634 use rustc_session::config::PrintKind::*;
635 #[allow(unused_imports)]
639 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
640
641 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
644 return Compilation::Continue;
645 }
646
647 let attrs = if parse_attrs {
648 let result = parse_crate_attrs(sess);
649 match result {
650 Ok(attrs) => Some(attrs),
651 Err(parse_error) => {
652 parse_error.emit();
653 return Compilation::Stop;
654 }
655 }
656 } else {
657 None
658 };
659
660 for req in &sess.opts.prints {
661 let mut crate_info = String::new();
662 macro println_info($($arg:tt)*) {
663 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
664 }
665
666 match req.kind {
667 TargetList => {
668 let mut targets = rustc_target::spec::TARGETS.to_vec();
669 targets.sort_unstable();
670 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
671 }
672 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()),
673 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()),
674 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()),
675 TargetSpecJson => {
676 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());
677 }
678 TargetSpecJsonSchema => {
679 let schema = rustc_target::spec::json_schema();
680 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());
681 }
682 AllTargetSpecsJson => {
683 let mut targets = BTreeMap::new();
684 for name in rustc_target::spec::TARGETS {
685 let triple = TargetTuple::from_tuple(name);
686 let target = Target::expect_builtin(&triple);
687 targets.insert(name, target.to_json());
688 }
689 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());
690 }
691 FileNames => {
692 let Some(attrs) = attrs.as_ref() else {
693 return Compilation::Continue;
695 };
696 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
697 let crate_name = passes::get_crate_name(sess, attrs);
698 let crate_types = collect_crate_types(
699 sess,
700 &codegen_backend.supported_crate_types(sess),
701 codegen_backend.name(),
702 attrs,
703 DUMMY_SP,
704 );
705 for &style in &crate_types {
706 let fname = rustc_session::output::filename_for_input(
707 sess, style, crate_name, &t_outputs,
708 );
709 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());
710 }
711 }
712 CrateName => {
713 let Some(attrs) = attrs.as_ref() else {
714 return Compilation::Continue;
716 };
717 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));
718 }
719 CrateRootLintLevels => {
720 let Some(attrs) = attrs.as_ref() else {
721 return Compilation::Continue;
723 };
724 let crate_name = passes::get_crate_name(sess, attrs);
725 let lint_store = crate::unerased_lint_store(sess);
726 let features = rustc_expand::config::features(sess, attrs, crate_name);
727 let registered_tools = rustc_resolve::registered_tools_ast(sess.dcx(), attrs, sess);
728 let builder = rustc_lint::LintLevelsBuilder::crate_root(
729 sess,
730 &features,
731 true,
732 lint_store,
733 ®istered_tools,
734 attrs,
735 );
736 for lint in lint_store.get_lints() {
737 if let Some(feature_symbol) = lint.feature_gate
738 && !features.enabled(feature_symbol)
739 {
740 continue;
742 }
743 let level = builder.lint_level_spec(lint).level();
744 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());
745 }
746 }
747 Cfg => {
748 let mut cfgs = sess
749 .config
750 .iter()
751 .filter_map(|&(name, value)| {
752 if !sess.is_nightly_build()
754 && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
755 {
756 return None;
757 }
758
759 if let Some(value) = value {
760 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
761 } else {
762 Some(name.to_string())
763 }
764 })
765 .collect::<Vec<String>>();
766
767 cfgs.sort();
768 for cfg in cfgs {
769 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
770 }
771 }
772 CheckCfg => {
773 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
774
775 #[allow(rustc::potential_query_instability)]
777 for (name, expected_values) in &sess.check_config.expecteds {
778 use crate::config::ExpectedValues;
779 match expected_values {
780 ExpectedValues::Any => {
781 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
782 }
783 ExpectedValues::Some(values) => {
784 let mut values: Vec<_> = values
785 .iter()
786 .map(|value| {
787 if let Some(value) = value {
788 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
789 } else {
790 "none()".to_string()
791 }
792 })
793 .collect();
794
795 values.sort_unstable();
796
797 let values = values.join(", ");
798
799 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
800 }
801 }
802 }
803
804 check_cfgs.sort_unstable();
805 if !sess.check_config.exhaustive_names && sess.check_config.exhaustive_values {
806 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
807 }
808 for check_cfg in check_cfgs {
809 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
810 }
811 }
812 CallingConventions => {
813 let calling_conventions = rustc_abi::all_names();
814 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
815 }
816 BackendHasMnemonic => {
817 let has_mnemonic: bool =
818 codegen_backend.has_mnemonic(sess, req.arg.as_ref().unwrap());
819 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_mnemonic))).unwrap();println_info!("{has_mnemonic}");
820 }
821 BackendHasZstd => {
822 let has_zstd: bool = codegen_backend.has_zstd();
823 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
824 }
825 RelocationModels
826 | CodeModels
827 | TlsModels
828 | TargetCPUs
829 | StackProtectorStrategies
830 | TargetFeatures => {
831 codegen_backend.print(req, &mut crate_info, sess);
832 }
833 NativeStaticLibs => {}
835 LinkArgs => {}
836 SplitDebuginfo => {
837 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
838
839 for split in &[Off, Packed, Unpacked] {
840 if sess.target.options.supported_split_debuginfo.contains(split) {
841 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
842 }
843 }
844 }
845 DeploymentTarget => {
846 if sess.target.is_like_darwin {
847 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!(
848 "{}={}",
849 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
850 sess.apple_deployment_target().fmt_pretty(),
851 )
852 } else {
853 sess.dcx().fatal("only Apple targets currently support deployment version info")
854 }
855 }
856 SupportedCrateTypes => {
857 let supported_crate_types = CrateType::all()
858 .iter()
859 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
860 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
861 .map(|(crate_type_sym, _)| *crate_type_sym)
862 .collect::<BTreeSet<_>>();
863 for supported_crate_type in supported_crate_types {
864 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
865 }
866 }
867 }
868
869 req.out.overwrite(&crate_info, sess);
870 }
871 Compilation::Stop
872}
873
874pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
878 fn unw(x: Option<&str>) -> &str {
879 x.unwrap_or("unknown")
880 }
881 $crate::version_at_macro_invocation(
882 $early_dcx,
883 $binary,
884 $matches,
885 unw(option_env!("CFG_VERSION")),
886 unw(option_env!("CFG_VER_HASH")),
887 unw(option_env!("CFG_VER_DATE")),
888 unw(option_env!("CFG_RELEASE")),
889 )
890}
891
892#[doc(hidden)] pub fn version_at_macro_invocation(
894 early_dcx: &EarlyDiagCtxt,
895 binary: &str,
896 matches: &getopts::Matches,
897 version: &str,
898 commit_hash: &str,
899 commit_date: &str,
900 release: &str,
901) {
902 let verbose = matches.opt_present("verbose");
903
904 let mut version = version;
905 let mut release = release;
906 let tmp;
907 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
908 tmp = force_version;
909 version = &tmp;
910 release = &tmp;
911 }
912
913 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
914
915 if verbose {
916 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
917 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
918 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
919 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
920 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
921
922 get_backend_from_raw_matches(early_dcx, matches).print_version();
923 }
924}
925
926fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
927 let mut options = getopts::Options::new();
928 for option in config::rustc_optgroups()
929 .iter()
930 .filter(|x| verbose || !x.is_verbose_help_only)
931 .filter(|x| include_unstable_options || x.is_stable())
932 {
933 option.apply(&mut options);
934 }
935 let message = "Usage: rustc [OPTIONS] INPUT";
936 let nightly_help = if nightly_build {
937 "\n -Z help Print unstable compiler options"
938 } else {
939 ""
940 };
941 let verbose_help = if verbose {
942 ""
943 } else {
944 "\n --help -v Print the full set of options rustc accepts"
945 };
946 let at_path = if verbose {
947 " @path Read newline separated options from `path`\n"
948 } else {
949 ""
950 };
951 {
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!(
952 "{options}{at_path}\nAdditional help:
953 -C help Print codegen options
954 -W help \
955 Print 'lint' options and default settings{nightly}{verbose}\n",
956 options = options.usage(message),
957 at_path = at_path,
958 nightly = nightly_help,
959 verbose = verbose_help
960 );
961}
962
963fn print_wall_help() {
964 {
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!(
965 "
966The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
967default. Use `rustc -W help` to see all available lints. It's more common to put
968warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
969the command line flag directly.
970"
971 );
972}
973
974pub fn describe_lints(sess: &Session, registered_lints: bool) {
976 {
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!(
977 "
978Available lint options:
979 -W <foo> Warn about <foo>
980 -A <foo> Allow <foo>
981 -D <foo> Deny <foo>
982 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
983
984"
985 );
986
987 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
988 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
990 lints
991 }
992
993 fn sort_lint_groups(
994 lints: Vec<(&'static str, Vec<LintId>, bool)>,
995 ) -> Vec<(&'static str, Vec<LintId>)> {
996 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
997 lints.sort_by_key(|l| l.0);
998 lints
999 }
1000
1001 let lint_store = unerased_lint_store(sess);
1002 let (loaded, builtin): (Vec<_>, _) =
1003 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
1004 let loaded = sort_lints(sess, loaded);
1005 let builtin = sort_lints(sess, builtin);
1006
1007 let (loaded_groups, builtin_groups): (Vec<_>, _) =
1008 lint_store.get_lint_groups().partition(|&(.., p)| p);
1009 let loaded_groups = sort_lint_groups(loaded_groups);
1010 let builtin_groups = sort_lint_groups(builtin_groups);
1011
1012 let max_name_len =
1013 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
1014 let padded = |x: &str| {
1015 let mut s = " ".repeat(max_name_len - x.chars().count());
1016 s.push_str(x);
1017 s
1018 };
1019
1020 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1021
1022 let print_lints = |lints: Vec<&Lint>| {
1023 {
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");
1024 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1025 for lint in lints {
1026 let name = lint.name_lower().replace('_', "-");
1027 {
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!(
1028 " {} {:7.7} {}",
1029 padded(&name),
1030 lint.default_level(sess.edition()).as_str(),
1031 lint.desc
1032 );
1033 }
1034 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1035 };
1036
1037 print_lints(builtin);
1038
1039 let max_name_len = max(
1040 "warnings".len(),
1041 loaded_groups
1042 .iter()
1043 .chain(&builtin_groups)
1044 .map(|&(s, _)| s.chars().count())
1045 .max()
1046 .unwrap_or(0),
1047 );
1048
1049 let padded = |x: &str| {
1050 let mut s = " ".repeat(max_name_len - x.chars().count());
1051 s.push_str(x);
1052 s
1053 };
1054
1055 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1056
1057 let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1058 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1059 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1060
1061 if all_warnings {
1062 {
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"));
1063 }
1064
1065 for (name, to) in lints {
1066 let name = name.to_lowercase().replace('_', "-");
1067 let desc = to
1068 .into_iter()
1069 .map(|x| x.to_string().replace('_', "-"))
1070 .collect::<Vec<String>>()
1071 .join(", ");
1072 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1073 }
1074 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1075 };
1076
1077 print_lint_groups(builtin_groups, true);
1078
1079 match (registered_lints, loaded.len(), loaded_groups.len()) {
1080 (false, 0, _) | (false, _, 0) => {
1081 {
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.");
1082 }
1083 (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!"),
1084 (true, 0, 0) => {
1085 {
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.")
1086 }
1087 (true, l, g) => {
1088 if l > 0 {
1089 {
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");
1090 print_lints(loaded);
1091 }
1092 if g > 0 {
1093 {
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");
1094 print_lint_groups(loaded_groups, false);
1095 }
1096 }
1097 }
1098}
1099
1100pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1104 let wall = matches.opt_strs("W");
1106 if wall.iter().any(|x| *x == "all") {
1107 print_wall_help();
1108 return true;
1109 }
1110
1111 let debug_flags = matches.opt_strs("Z");
1113 if debug_flags.iter().any(|x| *x == "help") {
1114 describe_unstable_flags();
1115 return true;
1116 }
1117
1118 let cg_flags = matches.opt_strs("C");
1119 if cg_flags.iter().any(|x| *x == "help") {
1120 describe_codegen_flags();
1121 return true;
1122 }
1123
1124 if cg_flags.iter().any(|x| *x == "passes=list") {
1125 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1126 return true;
1127 }
1128
1129 false
1130}
1131
1132fn get_backend_from_raw_matches(
1139 early_dcx: &EarlyDiagCtxt,
1140 matches: &Matches,
1141) -> Box<dyn CodegenBackend> {
1142 let debug_flags = matches.opt_strs("Z");
1143 let backend_name = debug_flags
1144 .iter()
1145 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1146 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1147 let target = parse_target_triple(early_dcx, matches);
1148 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1149 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1150
1151 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1152}
1153
1154fn describe_unstable_flags() {
1155 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1156 print_flag_list("-Z", config::Z_OPTIONS);
1157}
1158
1159fn describe_codegen_flags() {
1160 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1161 print_flag_list("-C", config::CG_OPTIONS);
1162}
1163
1164fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1165 let max_len =
1166 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1167
1168 for opt_desc in flag_list {
1169 {
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!(
1170 " {} {:>width$}=val -- {}",
1171 cmdline_opt,
1172 opt_desc.name().replace('_', "-"),
1173 opt_desc.desc(),
1174 width = max_len
1175 );
1176 }
1177}
1178
1179pub enum HandledOptions {
1180 None,
1182 Normal(getopts::Matches),
1184 HelpOnly(getopts::Matches),
1187}
1188
1189pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1217 let mut options = getopts::Options::new();
1220 let optgroups = config::rustc_optgroups();
1221 for option in &optgroups {
1222 option.apply(&mut options);
1223 }
1224 let matches = options.parse(args).unwrap_or_else(|e| {
1225 let msg: Option<String> = match e {
1226 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1227 .iter()
1228 .map(|opt_desc| ('C', opt_desc.name()))
1229 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1230 .find(|&(_, name)| *opt == name.replace('_', "-"))
1231 .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}`?")),
1232 getopts::Fail::ArgumentMissing(ref opt) => {
1233 optgroups.iter().find(|option| option.name == opt).map(|option| {
1234 let mut options = getopts::Options::new();
1236 option.apply(&mut options);
1237 options.usage_with_format(|it| {
1240 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1241 })
1242 })
1243 }
1244 _ => None,
1245 };
1246 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1247 });
1248
1249 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1261
1262 let wall = matches.opt_strs("W");
1264 if wall.iter().any(|x| *x == "all") {
1265 print_wall_help();
1266 return HandledOptions::None;
1267 }
1268
1269 if handle_help(&matches, args) {
1270 return HandledOptions::HelpOnly(matches);
1271 }
1272
1273 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1274 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1275 return HandledOptions::None;
1276 }
1277
1278 if matches.opt_present("version") {
1279 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.99.0-nightly (77cf889bc 2026-07-12)")),
unw(::core::option::Option::Some("77cf889bc178ddb44d6a1c78e5a820b5abb31d8d")),
unw(::core::option::Option::Some("2026-07-12")),
unw(::core::option::Option::Some("1.99.0-nightly")));version!(early_dcx, "rustc", &matches);
1280 return HandledOptions::None;
1281 }
1282
1283 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1284
1285 HandledOptions::Normal(matches)
1286}
1287
1288pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1295 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1296 let opt_help_pos = |opt| {
1297 matches
1298 .opt_strs_pos(opt)
1299 .iter()
1300 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1301 .next()
1302 };
1303 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1304 let zhelp_pos = opt_help_pos("Z");
1305 let chelp_pos = opt_help_pos("C");
1306 let print_help = || {
1307 let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1309 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1310 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1311 };
1312
1313 let mut helps = [
1314 (help_pos, &print_help as &dyn Fn()),
1315 (zhelp_pos, &describe_unstable_flags),
1316 (chelp_pos, &describe_codegen_flags),
1317 ];
1318 helps.sort_by_key(|(pos, _)| pos.clone());
1319 let mut printed_any = false;
1320 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1321 printer();
1322 printed_any = true;
1323 }
1324 printed_any
1325}
1326
1327fn warn_on_confusing_output_filename_flag(
1331 early_dcx: &EarlyDiagCtxt,
1332 matches: &getopts::Matches,
1333 args: &[String],
1334) {
1335 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1336 let s1 = s1.replace('-', "_");
1337 let s2 = s2.replace('-', "_");
1338 s1 == s2
1339 }
1340
1341 if let Some(name) = matches.opt_str("o")
1342 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1343 {
1344 let filename = suspect.trim_prefix("-");
1345 let optgroups = config::rustc_optgroups();
1346 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1347
1348 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1355 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1356 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1357 {
1358 early_dcx.early_warn(
1359 "option `-o` has no space between flag name and value, which can be confusing",
1360 );
1361 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!(
1362 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1363 ));
1364 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!(
1365 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1366 ));
1367 }
1368 }
1369}
1370
1371fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1372 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1373 Input::File(file) => {
1374 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1375 }
1376 Input::Str { name, input } => new_parser_from_source_str(
1377 &sess.psess,
1378 name.clone(),
1379 input.clone(),
1380 StripTokens::ShebangAndFrontmatter,
1381 ),
1382 });
1383 parser.parse_inner_attributes()
1384}
1385
1386pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1389 match catch_fatal_errors(f) {
1390 Ok(status) => status.report(),
1391 _ => ExitCode::FAILURE,
1392 }
1393}
1394
1395static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1396
1397fn ice_path() -> &'static Option<PathBuf> {
1405 ice_path_with_config(None)
1406}
1407
1408fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1409 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1410 {
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:1410",
"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(1410u32),
::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!(
1411 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1412 )
1413 }
1414
1415 ICE_PATH.get_or_init(|| {
1416 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1417 return None;
1418 }
1419 let mut path = match std::env::var_os("RUSTC_ICE") {
1420 Some(s) => {
1421 if s == "0" {
1422 return None;
1424 }
1425 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1426 {
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:1426",
"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(1426u32),
::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");
1427 }
1428 PathBuf::from(s)
1429 }
1430 None => config
1431 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1432 .or_else(|| std::env::current_dir().ok())
1433 .unwrap_or_default(),
1434 };
1435 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1437 let pid = std::process::id();
1438 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"));
1439 Some(path)
1440 })
1441}
1442
1443pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1444
1445pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1457 if env::var_os("RUST_BACKTRACE").is_none() {
1464 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1466 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1467 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1468 } else {
1469 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1470 }
1471 }
1472
1473 panic::update_hook(Box::new(
1474 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1475 info: &PanicHookInfo<'_>| {
1476 let _guard = io::stderr().lock();
1478 #[cfg(windows)]
1481 if let Some(msg) = info.payload().downcast_ref::<String>() {
1482 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1483 {
1484 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1486 let _ = early_dcx.early_err(msg.clone());
1487 return;
1488 }
1489 };
1490
1491 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1494 default_hook(info);
1495 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1497
1498 if let Some(ice_path) = ice_path()
1499 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1500 {
1501 let location = info.location().unwrap();
1503 let msg = match info.payload().downcast_ref::<&'static str>() {
1504 Some(s) => *s,
1505 None => match info.payload().downcast_ref::<String>() {
1506 Some(s) => &s[..],
1507 None => "Box<dyn Any>",
1508 },
1509 };
1510 let thread = std::thread::current();
1511 let name = thread.name().unwrap_or("<unnamed>");
1512 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!(
1513 &mut out,
1514 "thread '{name}' panicked at {location}:\n\
1515 {msg}\n\
1516 stack backtrace:\n\
1517 {:#}",
1518 std::backtrace::Backtrace::force_capture()
1519 );
1520 }
1521 }
1522
1523 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1525 },
1526 ));
1527}
1528
1529fn report_ice(
1536 info: &panic::PanicHookInfo<'_>,
1537 bug_report_url: &str,
1538 extra_info: fn(&DiagCtxt),
1539 using_internal_features: &AtomicBool,
1540) {
1541 let emitter =
1542 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1543 stderr_destination(rustc_errors::ColorConfig::Auto),
1544 ));
1545 let dcx = rustc_errors::DiagCtxt::new(emitter);
1546 let dcx = dcx.handle();
1547
1548 if !info.payload().is::<rustc_errors::ExplicitBug>()
1551 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1552 {
1553 dcx.emit_err(session_diagnostics::Ice);
1554 }
1555
1556 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1557 dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1558 } else {
1559 dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1560
1561 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1563 dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1564 }
1565 }
1566
1567 let version = ::core::option::Option::Some("1.99.0-nightly (77cf889bc 2026-07-12)")util::version_str!().unwrap_or("unknown_version");
1568 let tuple = config::host_tuple();
1569
1570 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1571
1572 let file = if let Some(path) = ice_path() {
1573 match crate::fs::File::options().create(true).append(true).open(path) {
1575 Ok(mut file) => {
1576 dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1577 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1578 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1579 }
1580 Some(file)
1581 }
1582 Err(err) => {
1583 dcx.emit_warn(session_diagnostics::IcePathError {
1585 path: path.clone(),
1586 error: err.to_string(),
1587 env_var: std::env::var_os("RUSTC_ICE")
1588 .map(PathBuf::from)
1589 .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1590 });
1591 None
1592 }
1593 }
1594 } else {
1595 None
1596 };
1597
1598 dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1599
1600 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1601 dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1602 if excluded_cargo_defaults {
1603 dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1604 }
1605 }
1606
1607 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1609
1610 let limit_frames = if backtrace { None } else { Some(2) };
1611
1612 interface::try_print_query_stack(dcx, limit_frames, file);
1613
1614 extra_info(&dcx);
1617
1618 #[cfg(windows)]
1619 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1620 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1622 }
1623}
1624
1625pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1628 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1629}
1630
1631pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1635 if let Err(error) = rustc_log::init_logger(cfg) {
1636 early_dcx.early_fatal(error.to_string());
1637 }
1638}
1639
1640pub fn init_logger_with_additional_layer<F, T>(
1646 early_dcx: &EarlyDiagCtxt,
1647 cfg: rustc_log::LoggerConfig,
1648 build_subscriber: F,
1649) where
1650 F: FnOnce() -> T,
1651 T: rustc_log::BuildSubscriberRet,
1652{
1653 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1654 early_dcx.early_fatal(error.to_string());
1655 }
1656}
1657
1658pub fn install_ctrlc_handler() {
1661 #[cfg(all(not(miri), not(target_family = "wasm")))]
1662 ctrlc::set_handler(move || {
1663 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1668 std::thread::sleep(std::time::Duration::from_millis(100));
1669 std::process::exit(1);
1670 })
1671 .expect("Unable to install ctrlc handler");
1672}
1673
1674pub fn main() -> ExitCode {
1675 let start_time = Instant::now();
1676 let start_rss = get_resident_set_size();
1677
1678 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1679
1680 init_rustc_env_logger(&early_dcx);
1681 signal_handler::install();
1682 let mut callbacks = TimePassesCallbacks::default();
1683 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1684 install_ctrlc_handler();
1685
1686 let exit_code =
1687 catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1688
1689 if let Some(format) = callbacks.time_passes {
1690 let end_rss = get_resident_set_size();
1691 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1692 }
1693
1694 exit_code
1695}