1#![feature(decl_macro)]
9#![feature(file_buffered)]
10#![feature(panic_backtrace_config)]
11#![feature(panic_update_hook)]
12#![feature(try_blocks)]
13use std::cmp::max;
16use std::collections::{BTreeMap, BTreeSet};
17use std::ffi::OsString;
18use std::fmt::Write as _;
19use std::fs::{self, File};
20use std::io::{self, IsTerminal, Read, Write};
21use std::panic::{self, PanicHookInfo};
22use std::path::{Path, PathBuf};
23use std::process::{Command, ExitCode, Stdio, Termination};
24use std::sync::OnceLock;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::time::Instant;
27use std::{env, str};
28
29use rustc_ast as ast;
30use rustc_codegen_ssa::traits::CodegenBackend;
31use rustc_codegen_ssa::{CodegenError, CompiledModules};
32use rustc_data_structures::profiling::{
33 TimePassesFormat, get_resident_set_size, print_time_passes_entry,
34};
35pub use rustc_errors::catch_fatal_errors;
36use rustc_errors::emitter::stderr_destination;
37use rustc_errors::{ColorConfig, DiagCtxt, DiagCtxtHandle, ErrCode, PResult, markdown};
38use rustc_feature::find_gated_cfg;
39use rustc_index as _;
43use rustc_interface::passes::collect_crate_types;
44use rustc_interface::util::{self, get_codegen_backend};
45use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
46use rustc_lint::unerased_lint_store;
47use rustc_lint_defs::{Lint, LintId};
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, 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::output::invalid_output_for_target;
59use rustc_session::{EarlyDiagCtxt, Session, config};
60use rustc_span::def_id::LOCAL_CRATE;
61use rustc_span::{DUMMY_SP, FileName};
62use rustc_structures::CrateType;
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
85mod allocator;
86pub mod args;
87pub mod pretty;
88#[macro_use]
89mod print;
90mod diagnostics;
91pub mod highlighter;
92
93#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
97mod signal_handler;
98
99#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
100mod signal_handler {
101 pub(super) fn install() {}
104}
105
106use crate::diagnostics::{
107 CantEmitMIR, RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
108 RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
109};
110
111pub const EXIT_SUCCESS: i32 = 0;
113
114pub const EXIT_FAILURE: i32 = 1;
116
117pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
118 ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
119
120pub trait Callbacks {
121 fn config(&mut self, _config: &mut interface::Config) {}
123 fn after_crate_root_parsing(
127 &mut self,
128 _compiler: &interface::Compiler,
129 _krate: &mut ast::Crate,
130 ) -> Compilation {
131 Compilation::Continue
132 }
133 fn after_expansion<'tcx>(
136 &mut self,
137 _compiler: &interface::Compiler,
138 _tcx: TyCtxt<'tcx>,
139 ) -> Compilation {
140 Compilation::Continue
141 }
142 fn after_analysis<'tcx>(
145 &mut self,
146 _compiler: &interface::Compiler,
147 _tcx: TyCtxt<'tcx>,
148 ) -> Compilation {
149 Compilation::Continue
150 }
151}
152
153#[derive(#[automatically_derived]
impl ::core::default::Default for TimePassesCallbacks {
#[inline]
fn default() -> Self {
TimePassesCallbacks {
time_passes: ::core::default::Default::default(),
}
}
}Default)]
154pub struct TimePassesCallbacks {
155 time_passes: Option<TimePassesFormat>,
156}
157
158impl Callbacks for TimePassesCallbacks {
159 #[allow(rustc::bad_opt_access)]
161 fn config(&mut self, config: &mut interface::Config) {
162 self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
166 .then_some(config.opts.unstable_opts.time_passes_format);
167 config.opts.trimmed_def_paths = true;
168 }
169}
170
171pub fn compiler_entrypoint(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
173 let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
174
175 let at_args = at_args.get(1..).unwrap_or_default();
184
185 let args = args::arg_expand_all(&default_early_dcx, at_args);
186
187 let warn_unspecified_edition = match &args[..] {
190 [] => false,
191 [name] if name.starts_with("-") => false,
194 [_] => true,
195 _ => false,
196 };
197 let (matches, help_only) = match handle_options(&default_early_dcx, &args) {
198 HandledOptions::None => return,
199 HandledOptions::Normal(matches) => (matches, false),
200 HandledOptions::HelpOnly(matches) => (matches, true),
201 };
202
203 let sopts =
204 config::build_session_options(&mut default_early_dcx, &matches, warn_unspecified_edition);
205 let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
206 let _ = ICE_COLOR.set(sopts.color);
207
208 if let Some(ref code) = matches.opt_str("explain") {
209 handle_explain(&default_early_dcx, code, sopts.color);
210 return;
211 }
212
213 let input = make_input(&default_early_dcx, &matches.free);
214 let has_input = input.is_some();
215 let (odir, ofile) = make_output(&matches);
216
217 drop(default_early_dcx);
218
219 let mut config = interface::Config {
220 opts: sopts,
221 crate_cfg: matches.opt_strs("cfg"),
222 crate_check_cfg: matches.opt_strs("check-cfg"),
223 input: input.unwrap_or(Input::File(PathBuf::new())),
224 output_file: ofile,
225 output_dir: odir,
226 ice_file,
227 file_loader: None,
228 lint_caps: Default::default(),
229 psess_created: None,
230 track_state: None,
231 register_lints: None,
232 override_queries: None,
233 extra_symbols: Vec::new(),
234 make_codegen_backend: None,
235 using_internal_features: &USING_INTERNAL_FEATURES,
236 };
237
238 callbacks.config(&mut config);
239
240 let registered_lints = config.register_lints.is_some();
241
242 interface::run_compiler(config, |compiler| {
243 let sess = &compiler.sess;
244 let codegen_backend = &*compiler.codegen_backend;
245
246 if sess.opts.describe_lints {
250 describe_lints(sess, registered_lints);
251 return;
252 }
253
254 if help_only {
256 return;
257 }
258
259 if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
260 return;
261 }
262
263 if !has_input {
264 sess.dcx().fatal("no input filename given"); }
266
267 if !sess.opts.unstable_opts.ls.is_empty() {
268 list_metadata(sess, &*codegen_backend.metadata_loader());
269 return;
270 }
271
272 if sess.opts.unstable_opts.link_only {
273 process_rlink(sess, compiler);
274 return;
275 }
276
277 let mut krate = passes::parse(sess);
280
281 if let Some(pp_mode) = sess.opts.pretty {
283 if pp_mode.needs_ast_map() {
284 create_and_enter_global_ctxt(compiler, krate, |tcx| {
285 tcx.ensure_ok().early_lint_checks(());
286 pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
287 passes::write_dep_info(tcx);
288 });
289 } else {
290 pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
291 }
292 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs:292",
"rustc_driver_impl", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(292u32),
::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");
293 return;
294 }
295
296 if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
297 return;
298 }
299
300 if sess.opts.unstable_opts.parse_crate_root_only {
301 return;
302 }
303
304 let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
305 let _ = tcx.resolver_for_lowering();
307
308 if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
309 return None;
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 None;
320 }
321
322 if sess.opts.unstable_opts.no_analysis {
323 return None;
324 }
325
326 tcx.ensure_ok().analysis(());
327
328 if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
329 return None;
330 }
331
332 if sess.opts.output_types.contains_key(&OutputType::Mir) {
333 if let Err(error) = pretty::emit_mir(tcx) {
334 tcx.dcx().emit_fatal(CantEmitMIR { error });
335 }
336 }
337
338 let linker = Linker::codegen_and_build_linker(tcx, codegen_backend);
339
340 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
341 dump_feature_usage_metrics(tcx, metrics_dir);
342 }
343
344 tcx.report_unused_features();
345
346 Some(linker)
347 });
348
349 if let (Some(linker), incr_comp_session) = linker {
352 linker.link(sess, incr_comp_session, 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 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 Some(Input::DocTestStr { file: PathBuf::from(path), line, input })
405 }
406 Err(_) => {
407 let name = FileName::anon_source_code(&input);
408 Some(Input::Str { name, input })
409 }
410 }
411 }
412 [ifile] => Some(Input::File(PathBuf::from(ifile))),
413 [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!(
414 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
415 ifile1, ifile2
416 )),
417 }
418}
419
420#[derive(#[automatically_derived]
impl ::core::marker::Copy for Compilation { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Compilation { }
#[automatically_derived]
impl ::core::clone::Clone for Compilation {
#[inline]
fn clone(&self) -> Self { *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 { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Compilation { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Compilation {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
422pub enum Compilation {
423 Stop,
424 Continue,
425}
426
427fn handle_explain(early_dcx: &EarlyDiagCtxt, code: &str, color: ColorConfig) {
428 let upper_cased_code = code.to_ascii_uppercase();
430 if let Ok(code) = upper_cased_code.trim_prefix('E').parse::<u32>()
431 && code <= ErrCode::MAX_AS_U32
432 && let Ok(description) = rustc_errors::codes::try_find_description(ErrCode::from_u32(code))
433 {
434 let mut is_in_code_block = false;
435 let mut text = String::new();
436 for line in description.lines() {
438 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
439 let dedented_line = &line[indent_level..];
440 if dedented_line.starts_with("```") {
441 is_in_code_block = !is_in_code_block;
442 text.push_str(&line[..(indent_level + 3)]);
443 } else if is_in_code_block && dedented_line.starts_with("# ") {
444 continue;
445 } else {
446 text.push_str(line);
447 }
448 text.push('\n');
449 }
450
451 if io::stdout().is_terminal() {
453 show_md_content_with_pager(&text, color);
454 } else {
455 if color == ColorConfig::Always {
458 show_colored_md_content(&text);
459 } else {
460 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
461 }
462 }
463 } else {
464 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"));
465 }
466}
467
468fn show_md_content_with_pager(content: &str, color: ColorConfig) {
473 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
474 if falsecfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
475 });
476
477 let mut cmd = Command::new(&pager_name);
478 if pager_name == "less" {
479 cmd.arg("-R"); }
481
482 let pretty_on_pager = match color {
483 ColorConfig::Auto => {
484 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
486 }
487 ColorConfig::Always => true,
488 ColorConfig::Never => false,
489 };
490
491 let mut pretty_data = {
493 let mdstream = markdown::MdStream::parse_str(content);
494 let bufwtr = markdown::create_stdout_bufwtr();
495 let mut mdbuf = Vec::new();
496 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
497 Some((bufwtr, mdbuf))
498 } else {
499 None
500 }
501 };
502
503 let pager_res = try {
505 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
506
507 let pager_stdin = pager.stdin.as_mut()?;
508 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
509 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
510 } else {
511 pager_stdin.write_all(content.as_bytes()).ok()?;
512 };
513
514 pager.wait().ok()?;
515 };
516 if pager_res.is_some() {
517 return;
518 }
519
520 if let Some((bufwtr, mdbuf)) = &mut pretty_data
522 && bufwtr.write_all(&mdbuf).is_ok()
523 {
524 return;
525 }
526
527 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
529}
530
531fn show_colored_md_content(content: &str) {
536 let mut pretty_data = {
538 let mdstream = markdown::MdStream::parse_str(content);
539 let bufwtr = markdown::create_stdout_bufwtr();
540 let mut mdbuf = Vec::new();
541 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
542 Some((bufwtr, mdbuf))
543 } else {
544 None
545 }
546 };
547
548 if let Some((bufwtr, mdbuf)) = &mut pretty_data
549 && bufwtr.write_all(&mdbuf).is_ok()
550 {
551 return;
552 }
553
554 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
556}
557
558fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
559 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);
560 let dcx = sess.dcx();
561 if let Input::File(file) = &sess.io.input {
562 let rlink_data = fs::read(file).unwrap_or_else(|err| {
563 dcx.emit_fatal(RlinkUnableToRead { err });
564 });
565 let (compiled_modules, crate_info, metadata, outputs) =
566 match CompiledModules::deserialize_rlink(sess, rlink_data) {
567 Ok((codegen, crate_info, metadata, outputs)) => {
568 (codegen, crate_info, metadata, outputs)
569 }
570 Err(err) => {
571 match err {
572 CodegenError::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
573 CodegenError::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
574 CodegenError::EncodingVersionMismatch { version_array, rlink_version } => {
575 dcx.emit_fatal(RLinkEncodingVersionMismatch {
576 version_array,
577 rlink_version,
578 })
579 }
580 CodegenError::RustcVersionMismatch { rustc_version } => {
581 dcx.emit_fatal(RLinkRustcVersionMismatch {
582 rustc_version,
583 current_version: sess.cfg_version,
584 })
585 }
586 CodegenError::CorruptFile => {
587 dcx.emit_fatal(RlinkCorruptFile { file });
588 }
589 };
590 }
591 };
592 compiler.codegen_backend.link(sess, compiled_modules, crate_info, metadata, &outputs);
593 } else {
594 dcx.emit_fatal(RlinkNotAFile {});
595 }
596}
597
598fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
599 match sess.io.input {
600 Input::File(ref path) => {
601 let mut v = Vec::new();
602 if let Err(error) = locator::list_file_metadata(
603 &sess.target,
604 path,
605 metadata_loader,
606 &mut v,
607 &sess.opts.unstable_opts.ls,
608 sess.cfg_version,
609 ) {
610 if path.extension().is_some_and(|extension| extension == "rs") {
611 let mut err = sess
612 .dcx()
613 .struct_fatal("`-Zls` takes a `.rmeta` file as input, not a source file");
614 if rustc_session::utils::was_invoked_from_cargo() {
615 err.note("use `rustc +nightly -Zls=... path/to/file.rmeta` directly, instead of going through Cargo");
617 }
618 err.emit();
619 }
620 sess.dcx().fatal(error.to_string());
621 }
622 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
623 }
624 Input::Str { .. } | Input::DocTestStr { .. } => {
625 sess.dcx().fatal("cannot list metadata for stdin");
626 }
627 }
628}
629
630pub fn print_crate_info(
631 codegen_backend: &dyn CodegenBackend,
632 sess: &Session,
633 parse_attrs: bool,
634) -> Compilation {
635 use rustc_session::config::PrintKind::*;
636 #[allow(unused_imports)]
640 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
641
642 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
645 return Compilation::Continue;
646 }
647
648 let attrs = if parse_attrs {
649 let result = parse_crate_attrs(sess);
650 match result {
651 Ok(attrs) => Some(attrs),
652 Err(parse_error) => {
653 parse_error.emit();
654 return Compilation::Stop;
655 }
656 }
657 } else {
658 None
659 };
660
661 for req in &sess.opts.prints {
662 let mut crate_info = String::new();
663 macro println_info($($arg:tt)*) {
664 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
665 }
666
667 match req.kind {
668 TargetList => {
669 let mut targets = rustc_target::spec::TARGETS.to_vec();
670 targets.sort_unstable();
671 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
672 }
673 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()),
674 WasmProcMacroTuple => crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", sess.wasm_proc_macro_tuple))).unwrap()println_info!("{}", sess.wasm_proc_macro_tuple),
675 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()),
676 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()),
677 TargetSpecJson => {
678 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());
679 }
680 TargetSpecJsonSchema => {
681 let schema = rustc_target::spec::json_schema();
682 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());
683 }
684 AllTargetSpecsJson => {
685 let mut targets = BTreeMap::new();
686 for name in rustc_target::spec::TARGETS {
687 let triple = TargetTuple::from_tuple(name);
688 let target = Target::expect_builtin(&triple);
689 targets.insert(name, target.to_json());
690 }
691 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());
692 }
693 FileNames => {
694 let Some(attrs) = attrs.as_ref() else {
695 return Compilation::Continue;
697 };
698 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
699 let crate_name = passes::get_crate_name(sess, attrs);
700 let crate_types = collect_crate_types(
701 sess,
702 &codegen_backend.supported_crate_types(sess),
703 codegen_backend.name(),
704 attrs,
705 DUMMY_SP,
706 );
707 for &style in &crate_types {
708 let fname = rustc_session::output::filename_for_input(
709 sess, style, crate_name, &t_outputs,
710 );
711 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());
712 }
713 }
714 CrateName => {
715 let Some(attrs) = attrs.as_ref() else {
716 return Compilation::Continue;
718 };
719 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));
720 }
721 CrateRootLintLevels => {
722 let Some(attrs) = attrs.as_ref() else {
723 return Compilation::Continue;
725 };
726 let crate_name = passes::get_crate_name(sess, attrs);
727 let lint_store = crate::unerased_lint_store(sess);
728 let features = rustc_expand::config::features(sess, attrs, crate_name);
729 let registered_lint_tools = rustc_resolve::registered_lint_tools_ast(sess, attrs);
730 let builder = rustc_lint::LintLevelsBuilder::crate_root(
731 sess,
732 &features,
733 true,
734 lint_store,
735 ®istered_lint_tools,
736 attrs,
737 );
738 for lint in lint_store.get_lints() {
739 if let Some(feature_symbol) = lint.feature_gate
740 && !features.enabled(feature_symbol)
741 {
742 continue;
744 }
745 let level = builder.lint_level_spec(lint).level();
746 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());
747 }
748 }
749 Cfg => {
750 let mut cfgs = sess
751 .config
752 .iter()
753 .filter_map(|&(name, value)| {
754 if !sess.is_nightly_build() && find_gated_cfg(name).is_some() {
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.101.0-nightly (b6eeb93c9 2026-10-18)")),
unw(::core::option::Option::Some("b6eeb93c992027a03e1fd120b6652546396b142c")),
unw(::core::option::Option::Some("2026-10-18")),
unw(::core::option::Option::Some("1.101.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
1359 .early_struct_warn(
1360 "option `-o` has no space between flag name and value, which can be confusing",
1361 )
1362 .with_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!(
1363 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1364 ))
1365 .with_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!(
1366 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1367 ))
1368 .emit();
1369 }
1370 }
1371}
1372
1373fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1374 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1375 Input::File(file) => {
1376 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1377 }
1378 instr @ (Input::Str { input, .. } | Input::DocTestStr { input, .. }) => {
1379 new_parser_from_source_str(
1380 &sess.psess,
1381 instr.file_name(sess),
1382 input.clone(),
1383 StripTokens::ShebangAndFrontmatter,
1384 )
1385 }
1386 });
1387 parser.parse_inner_attributes()
1388}
1389
1390pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1393 match catch_fatal_errors(f) {
1394 Ok(status) => status.report(),
1395 _ => ExitCode::FAILURE,
1396 }
1397}
1398
1399static ICE_COLOR: OnceLock<ColorConfig> = OnceLock::new();
1400static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1401
1402fn ice_path() -> &'static Option<PathBuf> {
1410 ice_path_with_config(None)
1411}
1412
1413fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1414 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1415 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs:1415",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1415u32),
::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!(
1416 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1417 )
1418 }
1419
1420 ICE_PATH.get_or_init(|| {
1421 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1422 return None;
1423 }
1424 let mut path = match std::env::var_os("RUSTC_ICE") {
1425 Some(s) => {
1426 if s == "0" {
1427 return None;
1429 }
1430 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1431 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs:1431",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1431u32),
::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");
1432 }
1433 PathBuf::from(s)
1434 }
1435 None => config
1436 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1437 .or_else(|| std::env::current_dir().ok())
1438 .unwrap_or_default(),
1439 };
1440 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1442 let pid = std::process::id();
1443 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"));
1444 Some(path)
1445 })
1446}
1447
1448pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1449
1450pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(DiagCtxtHandle<'_>)) {
1462 if env::var_os("RUST_BACKTRACE").is_none() {
1469 let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1471 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1472 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1473 } else {
1474 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1475 }
1476 }
1477
1478 panic::update_hook(Box::new(
1479 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1480 info: &PanicHookInfo<'_>| {
1481 let _guard = io::stderr().lock();
1483 #[cfg(windows)]
1486 if let Some(msg) = info.payload().downcast_ref::<String>() {
1487 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1488 {
1489 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1491 let _ = early_dcx.early_err(msg.clone());
1492 return;
1493 }
1494 };
1495
1496 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1499 default_hook(info);
1500 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1502
1503 if let Some(ice_path) = ice_path()
1504 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1505 {
1506 let location = info.location().unwrap();
1508 let msg = match info.payload().downcast_ref::<&'static str>() {
1509 Some(s) => *s,
1510 None => match info.payload().downcast_ref::<String>() {
1511 Some(s) => &s[..],
1512 None => "Box<dyn Any>",
1513 },
1514 };
1515 let thread = std::thread::current();
1516 let name = thread.name().unwrap_or("<unnamed>");
1517 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!(
1518 &mut out,
1519 "thread '{name}' panicked at {location}:\n\
1520 {msg}\n\
1521 stack backtrace:\n\
1522 {:#}",
1523 std::backtrace::Backtrace::force_capture()
1524 );
1525 }
1526 }
1527
1528 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1530 },
1531 ));
1532}
1533
1534fn report_ice(
1541 info: &panic::PanicHookInfo<'_>,
1542 bug_report_url: &str,
1543 extra_info: fn(DiagCtxtHandle<'_>),
1544 using_internal_features: &AtomicBool,
1545) {
1546 let color = ICE_COLOR.get().copied().unwrap_or(ColorConfig::Auto);
1547 let emitter =
1548 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1549 stderr_destination(color),
1550 ));
1551 let dcx = DiagCtxt::new(emitter);
1552 let dcx = dcx.handle();
1553
1554 if !info.payload().is::<rustc_errors::ExplicitBug>()
1557 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1558 {
1559 dcx.emit_err(diagnostics::Ice);
1560 }
1561
1562 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1563 dcx.emit_note(diagnostics::IceBugReportInternalFeature);
1564 } else {
1565 dcx.emit_note(diagnostics::IceBugReport { bug_report_url });
1566
1567 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1569 dcx.emit_note(diagnostics::UpdateNightlyNote);
1570 }
1571 }
1572
1573 let version = ::core::option::Option::Some("1.101.0-nightly (b6eeb93c9 2026-10-18)")util::version_str!().unwrap_or("unknown_version");
1574 let tuple = config::host_tuple();
1575
1576 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1577
1578 let file = if let Some(path) = ice_path() {
1579 match crate::fs::File::options().create(true).append(true).open(path) {
1581 Ok(mut file) => {
1582 dcx.emit_note(diagnostics::IcePath { path: path.clone() });
1583 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1584 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1585 }
1586 Some(file)
1587 }
1588 Err(err) => {
1589 dcx.emit_warn(diagnostics::IcePathError {
1591 path: path.clone(),
1592 error: err.to_string(),
1593 env_var: std::env::var_os("RUSTC_ICE")
1594 .map(PathBuf::from)
1595 .map(|env_var| diagnostics::IcePathErrorEnv { env_var }),
1596 });
1597 None
1598 }
1599 }
1600 } else {
1601 None
1602 };
1603
1604 dcx.emit_note(diagnostics::IceVersion { version, triple: tuple });
1605
1606 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1607 dcx.emit_note(diagnostics::IceFlags { flags: flags.join(" ") });
1608 if excluded_cargo_defaults {
1609 dcx.emit_note(diagnostics::IceExcludeCargoDefaults);
1610 }
1611 }
1612
1613 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1615
1616 let limit_frames = if backtrace { None } else { Some(2) };
1617
1618 interface::try_print_query_stack(limit_frames, file);
1619
1620 extra_info(dcx);
1623
1624 #[cfg(windows)]
1625 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1626 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1628 }
1629}
1630
1631pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1634 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1635}
1636
1637pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1641 if let Err(error) = rustc_log::init_logger(cfg) {
1642 early_dcx.early_fatal(error.to_string());
1643 }
1644}
1645
1646pub fn init_logger_with_additional_layer<F, T>(
1652 early_dcx: &EarlyDiagCtxt,
1653 cfg: rustc_log::LoggerConfig,
1654 build_subscriber: F,
1655) where
1656 F: FnOnce() -> T,
1657 T: rustc_log::BuildSubscriberRet,
1658{
1659 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1660 early_dcx.early_fatal(error.to_string());
1661 }
1662}
1663
1664pub fn install_ctrlc_handler() {
1667 #[cfg(all(not(miri), not(target_family = "wasm")))]
1668 ctrlc::set_handler(move || {
1669 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1674 std::thread::sleep(std::time::Duration::from_millis(100));
1675 std::process::exit(1);
1676 })
1677 .expect("Unable to install ctrlc handler");
1678}
1679
1680pub fn main() -> ExitCode {
1681 let start_time = Instant::now();
1682 let start_rss = get_resident_set_size();
1683
1684 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1685
1686 init_rustc_env_logger(&early_dcx);
1687 signal_handler::install();
1688 let mut callbacks = TimePassesCallbacks::default();
1689 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1690 install_ctrlc_handler();
1691
1692 let exit_code =
1693 catch_with_exit_code(|| compiler_entrypoint(&args::raw_args(&early_dcx), &mut callbacks));
1694
1695 if let Some(format) = callbacks.time_passes {
1696 let end_rss = get_resident_set_size();
1697 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1698 }
1699
1700 exit_code
1701}