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