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, LintName};
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, Input, OptionDesc, OutFileName, Sysroot, UnstableOptions, Z_OPTIONS,
55 nightly_options, parse_target_triple,
56};
57use rustc_session::getopts::{self, Matches};
58use rustc_session::output::{ErrorOutputType, OutputType, 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/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_driver_impl/src/lib.rs:292",
"rustc_driver_impl", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/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 rustc_interface::passes::full_analysis(tcx);
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 metadata = passes::finish_and_emit_metadata(tcx);
339 let linker = Linker::codegen_and_build_linker(tcx, codegen_backend, metadata);
340
341 if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
342 dump_feature_usage_metrics(tcx, metrics_dir);
343 }
344
345 tcx.report_unused_features();
346
347 Some(linker)
348 });
349
350 if let (Some(linker), incr_comp_session) = linker {
353 linker.link(sess, incr_comp_session, codegen_backend);
354 }
355 })
356}
357
358fn dump_feature_usage_metrics(tcx: TyCtxt<'_>, metrics_dir: &Path) {
359 let hash = tcx.crate_hash(LOCAL_CRATE);
360 let crate_name = tcx.crate_name(LOCAL_CRATE);
361 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");
362 let metrics_path = metrics_dir.join(metrics_file_name);
363 if let Err(error) = tcx.features().dump_feature_usage_metrics(metrics_path) {
364 tcx.dcx().emit_err(UnstableFeatureUsage { error });
368 }
369}
370
371fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
373 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
374 let ofile = matches.opt_str("o").map(|o| match o.as_str() {
375 "-" => OutFileName::Stdout,
376 path => OutFileName::Real(PathBuf::from(path)),
377 });
378 (odir, ofile)
379}
380
381fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
384 match free_matches {
385 [] => None, [ifile] if ifile == "-" => {
387 let mut input = String::new();
389 if io::stdin().read_to_string(&mut input).is_err() {
390 early_dcx
393 .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
394 }
395
396 match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
397 Ok(path) => {
398 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
399 "when UNSTABLE_RUSTDOC_TEST_PATH is set \
400 UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
401 );
402 let line = line
403 .parse::<isize>()
404 .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be a number");
405 Some(Input::DocTestStr { file: PathBuf::from(path), line, input })
406 }
407 Err(_) => {
408 let name = FileName::anon_source_code(&input);
409 Some(Input::Str { name, input })
410 }
411 }
412 }
413 [ifile] => Some(Input::File(PathBuf::from(ifile))),
414 [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!(
415 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
416 ifile1, ifile2
417 )),
418 }
419}
420
421#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Compilation {
#[inline]
#[rustc_trivial_field_reads]
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)]
423pub enum Compilation {
424 Stop,
425 Continue,
426}
427
428fn handle_explain(early_dcx: &EarlyDiagCtxt, code: &str, color: ColorConfig) {
429 let upper_cased_code = code.to_ascii_uppercase();
431 if let Ok(code) = upper_cased_code.trim_prefix('E').parse::<u32>()
432 && code <= ErrCode::MAX_AS_U32
433 && let Ok(description) = rustc_errors::codes::try_find_description(ErrCode::from_u32(code))
434 {
435 let mut is_in_code_block = false;
436 let mut text = String::new();
437 for line in description.lines() {
439 let indent_level = line.find(|c: char| !c.is_whitespace()).unwrap_or(line.len());
440 let dedented_line = &line[indent_level..];
441 if dedented_line.starts_with("```") {
442 is_in_code_block = !is_in_code_block;
443 text.push_str(&line[..(indent_level + 3)]);
444 } else if is_in_code_block && dedented_line.starts_with("# ") {
445 continue;
446 } else {
447 text.push_str(line);
448 }
449 text.push('\n');
450 }
451
452 if io::stdout().is_terminal() {
454 show_md_content_with_pager(&text, color);
455 } else {
456 if color == ColorConfig::Always {
459 show_colored_md_content(&text);
460 } else {
461 { crate::print::print(format_args!("{0}", text)); };safe_print!("{text}");
462 }
463 }
464 } else {
465 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"));
466 }
467}
468
469fn show_md_content_with_pager(content: &str, color: ColorConfig) {
474 let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
475 if falsecfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
476 });
477
478 let mut cmd = Command::new(&pager_name);
479 if pager_name == "less" {
480 cmd.arg("-R"); }
482
483 let pretty_on_pager = match color {
484 ColorConfig::Auto => {
485 ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
487 }
488 ColorConfig::Always => true,
489 ColorConfig::Never => false,
490 };
491
492 let mut pretty_data = {
494 let mdstream = markdown::MdStream::parse_str(content);
495 let bufwtr = markdown::create_stdout_bufwtr();
496 let mut mdbuf = Vec::new();
497 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
498 Some((bufwtr, mdbuf))
499 } else {
500 None
501 }
502 };
503
504 let pager_res = try {
506 let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
507
508 let pager_stdin = pager.stdin.as_mut()?;
509 if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
510 pager_stdin.write_all(mdbuf.as_slice()).ok()?;
511 } else {
512 pager_stdin.write_all(content.as_bytes()).ok()?;
513 };
514
515 pager.wait().ok()?;
516 };
517 if pager_res.is_some() {
518 return;
519 }
520
521 if #[allow(non_exhaustive_omitted_patterns)] match color {
ColorConfig::Auto | ColorConfig::Always => true,
_ => false,
}matches!(color, ColorConfig::Auto | ColorConfig::Always)
523 && let Some((bufwtr, mdbuf)) = &mut pretty_data
524 && bufwtr.write_all(&mdbuf).is_ok()
525 {
526 return;
528 }
529
530 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
532}
533
534fn show_colored_md_content(content: &str) {
539 let mut pretty_data = {
541 let mdstream = markdown::MdStream::parse_str(content);
542 let bufwtr = markdown::create_stdout_bufwtr();
543 let mut mdbuf = Vec::new();
544 if mdstream.write_anstream_buf(&mut mdbuf, Some(&highlighter::highlight)).is_ok() {
545 Some((bufwtr, mdbuf))
546 } else {
547 None
548 }
549 };
550
551 if let Some((bufwtr, mdbuf)) = &mut pretty_data
552 && bufwtr.write_all(&mdbuf).is_ok()
553 {
554 return;
555 }
556
557 { crate::print::print(format_args!("{0}", content)); };safe_print!("{content}");
559}
560
561fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
562 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);
563 let dcx = sess.dcx();
564 if let Input::File(file) = &sess.io.input {
565 let rlink_data = fs::read(file).unwrap_or_else(|err| {
566 dcx.emit_fatal(RlinkUnableToRead { err });
567 });
568 let (compiled_modules, crate_info, metadata, outputs) =
569 match CompiledModules::deserialize_rlink(sess, rlink_data) {
570 Ok((codegen, crate_info, metadata, outputs)) => {
571 (codegen, crate_info, metadata, outputs)
572 }
573 Err(err) => {
574 match err {
575 CodegenError::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
576 CodegenError::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
577 CodegenError::EncodingVersionMismatch { version_array, rlink_version } => {
578 dcx.emit_fatal(RLinkEncodingVersionMismatch {
579 version_array,
580 rlink_version,
581 })
582 }
583 CodegenError::RustcVersionMismatch { rustc_version } => {
584 dcx.emit_fatal(RLinkRustcVersionMismatch {
585 rustc_version,
586 current_version: sess.cfg_version,
587 })
588 }
589 CodegenError::CorruptFile => {
590 dcx.emit_fatal(RlinkCorruptFile { file });
591 }
592 };
593 }
594 };
595 compiler.codegen_backend.link(sess, compiled_modules, crate_info, metadata, &outputs);
596 } else {
597 dcx.emit_fatal(RlinkNotAFile {});
598 }
599}
600
601fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
602 match sess.io.input {
603 Input::File(ref path) => {
604 let mut v = Vec::new();
605 if let Err(error) = locator::list_file_metadata(
606 &sess.target,
607 path,
608 metadata_loader,
609 &mut v,
610 &sess.opts.unstable_opts.ls,
611 sess.cfg_version,
612 ) {
613 if path.extension().is_some_and(|extension| extension == "rs") {
614 let mut err = sess
615 .dcx()
616 .struct_fatal("`-Zls` takes a `.rmeta` file as input, not a source file");
617 if rustc_session::utils::was_invoked_from_cargo() {
618 err.note("use `rustc +nightly -Zls=... path/to/file.rmeta` directly, instead of going through Cargo");
620 }
621 err.emit();
622 }
623 sess.dcx().fatal(error.to_string());
624 }
625 {
crate::print::print(format_args!("{0}\n",
format_args!("{0}", String::from_utf8(v).unwrap())));
};safe_println!("{}", String::from_utf8(v).unwrap());
626 }
627 Input::Str { .. } | Input::DocTestStr { .. } => {
628 sess.dcx().fatal("cannot list metadata for stdin");
629 }
630 }
631}
632
633pub fn print_crate_info(
634 codegen_backend: &dyn CodegenBackend,
635 sess: &Session,
636 parse_attrs: bool,
637) -> Compilation {
638 use rustc_session::config::PrintKind::*;
639 #[allow(unused_imports)]
643 use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
644
645 if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
648 return Compilation::Continue;
649 }
650
651 let attrs = if parse_attrs {
652 let result = parse_crate_attrs(sess);
653 match result {
654 Ok(attrs) => Some(attrs),
655 Err(parse_error) => {
656 parse_error.emit();
657 return Compilation::Stop;
658 }
659 }
660 } else {
661 None
662 };
663
664 for req in &sess.opts.prints {
665 let mut crate_info = String::new();
666 macro println_info($($arg:tt)*) {
667 crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
668 }
669
670 match req.kind {
671 TargetList => {
672 let mut targets = rustc_target::spec::TARGETS.to_vec();
673 targets.sort_unstable();
674 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", targets.join("\n")))).unwrap();println_info!("{}", targets.join("\n"));
675 }
676 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()),
677 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),
678 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()),
679 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()),
680 TargetSpecJson => {
681 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());
682 }
683 TargetSpecJsonSchema => {
684 let schema = rustc_target::spec::json_schema();
685 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());
686 }
687 AllTargetSpecsJson => {
688 let mut targets = BTreeMap::new();
689 for name in rustc_target::spec::TARGETS {
690 let triple = TargetTuple::from_tuple(name);
691 let target = Target::expect_builtin(&triple);
692 targets.insert(name, target.to_json());
693 }
694 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());
695 }
696 TargetStandardLibrarySupport => {
697 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}",
serde_json::to_string_pretty(&sess.target.metadata.standard_library_support.to_json()).unwrap()))).unwrap();println_info!(
698 "{}",
699 serde_json::to_string_pretty(
700 &sess.target.metadata.standard_library_support.to_json()
701 )
702 .unwrap()
703 );
704 }
705 FileNames => {
706 let Some(attrs) = attrs.as_ref() else {
707 return Compilation::Continue;
709 };
710 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
711 let crate_name = passes::get_crate_name(sess, attrs);
712 let crate_types = collect_crate_types(
713 sess,
714 &codegen_backend.supported_crate_types(sess),
715 codegen_backend.name(),
716 attrs,
717 DUMMY_SP,
718 );
719 for &style in &crate_types {
720 let fname = rustc_session::output::filename_for_input(
721 sess, style, crate_name, &t_outputs,
722 );
723 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());
724 }
725 }
726 CrateName => {
727 let Some(attrs) = attrs.as_ref() else {
728 return Compilation::Continue;
730 };
731 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));
732 }
733 CrateRootLintLevels => {
734 let Some(attrs) = attrs.as_ref() else {
735 return Compilation::Continue;
737 };
738 let crate_name = passes::get_crate_name(sess, attrs);
739 let lint_store = crate::unerased_lint_store(sess);
740 let features = rustc_expand::config::features(sess, attrs, crate_name);
741 let registered_lint_tools = rustc_resolve::registered_lint_tools_ast(sess, attrs);
742 let builder = rustc_lint::LintLevelsBuilder::crate_root(
743 sess,
744 &features,
745 true,
746 lint_store,
747 ®istered_lint_tools,
748 attrs,
749 );
750 for lint in lint_store.get_lints() {
751 if let Some(feature_symbol) = lint.feature_gate
752 && !features.enabled(feature_symbol)
753 {
754 continue;
756 }
757 let level = builder.lint_level_spec(lint).level();
758 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());
759 }
760 }
761 Cfg => {
762 let mut cfgs = sess
763 .config
764 .iter()
765 .filter_map(|&(name, value)| {
766 if !sess.is_nightly_build() && find_gated_cfg(name).is_some() {
768 return None;
769 }
770
771 if let Some(value) = value {
772 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}=\"{1}\"", name, value))
})format!("{name}=\"{value}\""))
773 } else {
774 Some(name.to_string())
775 }
776 })
777 .collect::<Vec<String>>();
778
779 cfgs.sort();
780 for cfg in cfgs {
781 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", cfg))).unwrap();println_info!("{cfg}");
782 }
783 }
784 CheckCfg => {
785 let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
786
787 #[allow(rustc::potential_query_instability)]
789 for (name, expected_values) in &sess.check_config.expecteds {
790 use crate::config::ExpectedValues;
791 match expected_values {
792 ExpectedValues::Any => {
793 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values(any()))", name))
})format!("cfg({name}, values(any()))"))
794 }
795 ExpectedValues::Some(values) => {
796 let mut values: Vec<_> = values
797 .iter()
798 .map(|value| {
799 if let Some(value) = value {
800 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", value))
})format!("\"{value}\"")
801 } else {
802 "none()".to_string()
803 }
804 })
805 .collect();
806
807 values.sort_unstable();
808
809 let values = values.join(", ");
810
811 check_cfgs.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cfg({0}, values({1}))", name,
values))
})format!("cfg({name}, values({values}))"))
812 }
813 }
814 }
815
816 check_cfgs.sort_unstable();
817 if !sess.check_config.exhaustive_names && sess.check_config.exhaustive_values {
818 crate_info.write_fmt(format_args!("{0}\n",
format_args!("cfg(any())"))).unwrap();println_info!("cfg(any())");
819 }
820 for check_cfg in check_cfgs {
821 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", check_cfg))).unwrap();println_info!("{check_cfg}");
822 }
823 }
824 CallingConventions => {
825 let calling_conventions = rustc_abi::all_names();
826 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", calling_conventions.join("\n")))).unwrap();println_info!("{}", calling_conventions.join("\n"));
827 }
828 BackendHasMnemonic => {
829 let has_mnemonic: bool =
830 codegen_backend.has_mnemonic(sess, req.arg.as_ref().unwrap());
831 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_mnemonic))).unwrap();println_info!("{has_mnemonic}");
832 }
833 BackendHasZstd => {
834 let has_zstd: bool = codegen_backend.has_zstd();
835 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", has_zstd))).unwrap();println_info!("{has_zstd}");
836 }
837 RelocationModels
838 | CodeModels
839 | TlsModels
840 | TargetCPUs
841 | StackProtectorStrategies
842 | TargetFeatures => {
843 codegen_backend.print(req, &mut crate_info, sess);
844 }
845 NativeStaticLibs => {}
847 LinkArgs => {}
848 SplitDebuginfo => {
849 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
850
851 for split in &[Off, Packed, Unpacked] {
852 if sess.target.options.supported_split_debuginfo.contains(split) {
853 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", split))).unwrap();println_info!("{split}");
854 }
855 }
856 }
857 DeploymentTarget => {
858 if sess.target.is_like_darwin {
859 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!(
860 "{}={}",
861 rustc_target::spec::apple::deployment_target_env_var(&sess.target.os),
862 sess.apple_deployment_target().fmt_pretty(),
863 )
864 } else {
865 sess.dcx().fatal("only Apple targets currently support deployment version info")
866 }
867 }
868 SupportedCrateTypes => {
869 let supported_crate_types = CrateType::all()
870 .iter()
871 .filter(|(_, crate_type)| !invalid_output_for_target(sess, *crate_type))
872 .filter(|(_, crate_type)| *crate_type != CrateType::Sdylib)
873 .map(|(crate_type_sym, _)| *crate_type_sym)
874 .collect::<BTreeSet<_>>();
875 for supported_crate_type in supported_crate_types {
876 crate_info.write_fmt(format_args!("{0}\n",
format_args!("{0}", supported_crate_type.as_str()))).unwrap();println_info!("{}", supported_crate_type.as_str());
877 }
878 }
879 }
880
881 req.out.overwrite(&crate_info, sess);
882 }
883 Compilation::Stop
884}
885
886pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
890 fn unw(x: Option<&str>) -> &str {
891 x.unwrap_or("unknown")
892 }
893 $crate::version_at_macro_invocation(
894 $early_dcx,
895 $binary,
896 $matches,
897 unw(option_env!("CFG_VERSION")),
898 unw(option_env!("CFG_VER_HASH")),
899 unw(option_env!("CFG_VER_DATE")),
900 unw(option_env!("CFG_RELEASE")),
901 )
902}
903
904#[doc(hidden)] pub fn version_at_macro_invocation(
906 early_dcx: &EarlyDiagCtxt,
907 binary: &str,
908 matches: &getopts::Matches,
909 version: &str,
910 commit_hash: &str,
911 commit_date: &str,
912 release: &str,
913) {
914 let verbose = matches.opt_present("verbose");
915
916 let mut version = version;
917 let mut release = release;
918 let tmp;
919 if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
920 tmp = force_version;
921 version = &tmp;
922 release = &tmp;
923 }
924
925 {
crate::print::print(format_args!("{0}\n",
format_args!("{0} {1}", binary, version)));
};safe_println!("{binary} {version}");
926
927 if verbose {
928 {
crate::print::print(format_args!("{0}\n",
format_args!("binary: {0}", binary)));
};safe_println!("binary: {binary}");
929 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-hash: {0}", commit_hash)));
};safe_println!("commit-hash: {commit_hash}");
930 {
crate::print::print(format_args!("{0}\n",
format_args!("commit-date: {0}", commit_date)));
};safe_println!("commit-date: {commit_date}");
931 {
crate::print::print(format_args!("{0}\n",
format_args!("host: {0}", config::host_tuple())));
};safe_println!("host: {}", config::host_tuple());
932 {
crate::print::print(format_args!("{0}\n",
format_args!("release: {0}", release)));
};safe_println!("release: {release}");
933
934 get_backend_from_raw_matches(early_dcx, matches).print_version();
935 }
936}
937
938fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
939 let mut options = getopts::Options::new();
940 for option in config::rustc_optgroups()
941 .iter()
942 .filter(|x| verbose || !x.is_verbose_help_only)
943 .filter(|x| include_unstable_options || x.is_stable())
944 {
945 option.apply(&mut options);
946 }
947 let message = "Usage: rustc [OPTIONS] INPUT";
948 let nightly_help = if nightly_build {
949 "\n -Z help Print unstable compiler options"
950 } else {
951 ""
952 };
953 let verbose_help = if verbose {
954 ""
955 } else {
956 "\n --help -v Print the full set of options rustc accepts"
957 };
958 let at_path = if verbose {
959 " @path Read newline separated options from `path`\n"
960 } else {
961 ""
962 };
963 {
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!(
964 "{options}{at_path}\nAdditional help:
965 -C help Print codegen options
966 -W help \
967 Print 'lint' options and default settings{nightly}{verbose}\n",
968 options = options.usage(message),
969 at_path = at_path,
970 nightly = nightly_help,
971 verbose = verbose_help
972 );
973}
974
975fn print_wall_help() {
976 {
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!(
977 "
978The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
979default. Use `rustc -W help` to see all available lints. It's more common to put
980warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
981the command line flag directly.
982"
983 );
984}
985
986pub fn describe_lints(sess: &Session, registered_lints: bool) {
988 {
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!(
989 "
990Available lint options:
991 -W <foo> Warn about <foo>
992 -A <foo> Allow <foo>
993 -D <foo> Deny <foo>
994 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
995
996"
997 );
998
999 fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
1000 lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
1002 lints
1003 }
1004
1005 fn sort_lint_groups(lints: Vec<(LintName, Vec<LintId>, bool)>) -> Vec<(LintName, Vec<LintId>)> {
1006 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
1007 lints.sort_by(|left, right| Ord::cmp(&left.0, &right.0));
1008 lints
1009 }
1010
1011 let lint_store = unerased_lint_store(sess);
1012 let (loaded, builtin): (Vec<_>, _) =
1013 lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
1014 let loaded = sort_lints(sess, loaded);
1015 let builtin = sort_lints(sess, builtin);
1016
1017 let (loaded_groups, builtin_groups): (Vec<_>, _) =
1018 lint_store.get_lint_groups().partition(|&(.., p)| p);
1019 let loaded_groups = sort_lint_groups(loaded_groups);
1020 let builtin_groups = sort_lint_groups(builtin_groups);
1021
1022 let max_name_len =
1023 loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
1024 let padded = |x: &str| {
1025 let mut s = " ".repeat(max_name_len - x.chars().count());
1026 s.push_str(x);
1027 s
1028 };
1029
1030 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint checks provided by rustc:\n")));
};safe_println!("Lint checks provided by rustc:\n");
1031
1032 let print_lints = |lints: Vec<&Lint>| {
1033 {
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");
1034 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1:7.7} {2}", padded("----"), "-------",
"-------")));
};safe_println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1035 for lint in lints {
1036 let name = lint.name_lower().replace('_', "-");
1037 {
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!(
1038 " {} {:7.7} {}",
1039 padded(&name),
1040 lint.default_level(sess.edition()).as_str(),
1041 lint.desc
1042 );
1043 }
1044 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1045 };
1046
1047 print_lints(builtin);
1048
1049 let max_name_len = max(
1050 "warnings".len(),
1051 loaded_groups
1052 .iter()
1053 .chain(&builtin_groups)
1054 .map(|(s, _)| s.name.as_str().chars().count())
1055 .max()
1056 .unwrap_or(0),
1057 );
1058
1059 let padded = |x: &str| {
1060 let mut s = " ".repeat(max_name_len - x.chars().count());
1061 s.push_str(x);
1062 s
1063 };
1064
1065 {
crate::print::print(format_args!("{0}\n",
format_args!("Lint groups provided by rustc:\n")));
};safe_println!("Lint groups provided by rustc:\n");
1066
1067 let print_lint_groups = |lints: Vec<(LintName, Vec<LintId>)>, all_warnings| {
1068 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} sub-lints", padded("name"))));
};safe_println!(" {} sub-lints", padded("name"));
1069 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} ---------", padded("----"))));
};safe_println!(" {} ---------", padded("----"));
1070
1071 if all_warnings {
1072 {
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"));
1073 }
1074
1075 for (name, to) in lints {
1076 let name = name.to_string().to_lowercase().replace('_', "-");
1077 let desc = to
1078 .into_iter()
1079 .map(|x| x.to_string().replace('_', "-"))
1080 .collect::<Vec<String>>()
1081 .join(", ");
1082 {
crate::print::print(format_args!("{0}\n",
format_args!(" {0} {1}", padded(&name), desc)));
};safe_println!(" {} {}", padded(&name), desc);
1083 }
1084 { crate::print::print(format_args!("{0}\n", format_args!("\n"))); };safe_println!("\n");
1085 };
1086
1087 print_lint_groups(builtin_groups, true);
1088
1089 match (registered_lints, loaded.len(), loaded_groups.len()) {
1090 (false, 0, _) | (false, _, 0) => {
1091 {
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.");
1092 }
1093 (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!"),
1094 (true, 0, 0) => {
1095 {
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.")
1096 }
1097 (true, l, g) => {
1098 if l > 0 {
1099 {
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");
1100 print_lints(loaded);
1101 }
1102 if g > 0 {
1103 {
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");
1104 print_lint_groups(loaded_groups, false);
1105 }
1106 }
1107 }
1108}
1109
1110pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1114 let wall = matches.opt_strs("W");
1116 if wall.iter().any(|x| *x == "all") {
1117 print_wall_help();
1118 return true;
1119 }
1120
1121 let debug_flags = matches.opt_strs("Z");
1123 if debug_flags.iter().any(|x| *x == "help") {
1124 describe_unstable_flags();
1125 return true;
1126 }
1127
1128 let cg_flags = matches.opt_strs("C");
1129 if cg_flags.iter().any(|x| *x == "help") {
1130 describe_codegen_flags();
1131 return true;
1132 }
1133
1134 if cg_flags.iter().any(|x| *x == "passes=list") {
1135 get_backend_from_raw_matches(early_dcx, matches).print_passes();
1136 return true;
1137 }
1138
1139 false
1140}
1141
1142fn get_backend_from_raw_matches(
1149 early_dcx: &EarlyDiagCtxt,
1150 matches: &Matches,
1151) -> Box<dyn CodegenBackend> {
1152 let debug_flags = matches.opt_strs("Z");
1153 let backend_name = debug_flags
1154 .iter()
1155 .find_map(|x| x.strip_prefix("codegen-backend=").or(x.strip_prefix("codegen_backend=")));
1156 let unstable_options = debug_flags.iter().find(|x| *x == "unstable-options").is_some();
1157 let target = parse_target_triple(early_dcx, matches);
1158 let sysroot = Sysroot::new(matches.opt_str("sysroot").map(PathBuf::from));
1159 let target = config::build_target_config(early_dcx, &target, sysroot.path(), unstable_options);
1160
1161 get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1162}
1163
1164fn describe_unstable_flags() {
1165 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable unstable options:\n")));
};safe_println!("\nAvailable unstable options:\n");
1166 print_flag_list("-Z", config::Z_OPTIONS);
1167}
1168
1169fn describe_codegen_flags() {
1170 {
crate::print::print(format_args!("{0}\n",
format_args!("\nAvailable codegen options:\n")));
};safe_println!("\nAvailable codegen options:\n");
1171 print_flag_list("-C", config::CG_OPTIONS);
1172}
1173
1174fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1175 let max_len =
1176 flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1177
1178 for opt_desc in flag_list {
1179 {
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!(
1180 " {} {:>width$}=val -- {}",
1181 cmdline_opt,
1182 opt_desc.name().replace('_', "-"),
1183 opt_desc.desc(),
1184 width = max_len
1185 );
1186 }
1187}
1188
1189pub enum HandledOptions {
1190 None,
1192 Normal(getopts::Matches),
1194 HelpOnly(getopts::Matches),
1197}
1198
1199pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> HandledOptions {
1227 let mut options = getopts::Options::new();
1230 let optgroups = config::rustc_optgroups();
1231 for option in &optgroups {
1232 option.apply(&mut options);
1233 }
1234 let matches = options.parse(args).unwrap_or_else(|e| {
1235 let msg: Option<String> = match e {
1236 getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1237 .iter()
1238 .map(|opt_desc| ('C', opt_desc.name()))
1239 .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1240 .find(|&(_, name)| *opt == name.replace('_', "-"))
1241 .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}`?")),
1242 getopts::Fail::ArgumentMissing(ref opt) => {
1243 optgroups.iter().find(|option| option.name == opt).map(|option| {
1244 let mut options = getopts::Options::new();
1246 option.apply(&mut options);
1247 options.usage_with_format(|it| {
1250 it.fold(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}\nUsage:", e))
})format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1251 })
1252 })
1253 }
1254 _ => None,
1255 };
1256 early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1257 });
1258
1259 nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1271
1272 let wall = matches.opt_strs("W");
1274 if wall.iter().any(|x| *x == "all") {
1275 print_wall_help();
1276 return HandledOptions::None;
1277 }
1278
1279 if handle_help(&matches, args) {
1280 return HandledOptions::HelpOnly(matches);
1281 }
1282
1283 if matches.opt_strs("C").iter().any(|x| x == "passes=list") {
1284 get_backend_from_raw_matches(early_dcx, &matches).print_passes();
1285 return HandledOptions::None;
1286 }
1287
1288 if matches.opt_present("version") {
1289 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.102.0-nightly (064405c5f 2026-12-02)")),
unw(::core::option::Option::Some("064405c5f7fbc7d41aa30b45da1e45a85777bd58")),
unw(::core::option::Option::Some("2026-12-02")),
unw(::core::option::Option::Some("1.102.0-nightly")));version!(early_dcx, "rustc", &matches);
1290 return HandledOptions::None;
1291 }
1292
1293 warn_on_confusing_output_filename_flag(early_dcx, &matches, args);
1294
1295 HandledOptions::Normal(matches)
1296}
1297
1298pub fn handle_help(matches: &getopts::Matches, args: &[String]) -> bool {
1305 let opt_pos = |opt| matches.opt_positions(opt).first().copied();
1306 let opt_help_pos = |opt| {
1307 matches
1308 .opt_strs_pos(opt)
1309 .iter()
1310 .filter_map(|(pos, oval)| if oval == "help" { Some(*pos) } else { None })
1311 .next()
1312 };
1313 let help_pos = if args.is_empty() { Some(0) } else { opt_pos("h").or_else(|| opt_pos("help")) };
1314 let zhelp_pos = opt_help_pos("Z");
1315 let chelp_pos = opt_help_pos("C");
1316 let print_help = || {
1317 let unstable_enabled = nightly_options::unstable_options_enabled(&matches);
1319 let nightly_build = nightly_options::match_is_nightly_build(&matches);
1320 usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1321 };
1322
1323 let mut helps = [
1324 (help_pos, &print_help as &dyn Fn()),
1325 (zhelp_pos, &describe_unstable_flags),
1326 (chelp_pos, &describe_codegen_flags),
1327 ];
1328 helps.sort_by_key(|(pos, _)| pos.clone());
1329 let mut printed_any = false;
1330 for printer in helps.iter().filter_map(|(pos, func)| pos.is_some().then_some(func)) {
1331 printer();
1332 printed_any = true;
1333 }
1334 printed_any
1335}
1336
1337fn warn_on_confusing_output_filename_flag(
1341 early_dcx: &EarlyDiagCtxt,
1342 matches: &getopts::Matches,
1343 args: &[String],
1344) {
1345 fn eq_ignore_separators(s1: &str, s2: &str) -> bool {
1346 let s1 = s1.replace('-', "_");
1347 let s2 = s2.replace('-', "_");
1348 s1 == s2
1349 }
1350
1351 if let Some(name) = matches.opt_str("o")
1352 && let Some(suspect) = args.iter().find(|arg| arg.starts_with("-o") && *arg != "-o")
1353 {
1354 let filename = suspect.trim_prefix("-");
1355 let optgroups = config::rustc_optgroups();
1356 let fake_args = ["optimize", "o0", "o1", "o2", "o3", "ofast", "og", "os", "oz"];
1357
1358 if optgroups.iter().any(|option| eq_ignore_separators(option.long_name(), filename))
1365 || config::CG_OPTIONS.iter().any(|option| eq_ignore_separators(option.name(), filename))
1366 || fake_args.iter().any(|arg| eq_ignore_separators(arg, filename))
1367 {
1368 early_dcx
1369 .early_struct_warn(
1370 "option `-o` has no space between flag name and value, which can be confusing",
1371 )
1372 .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!(
1373 "output filename `-o {name}` is applied instead of a flag named `o{name}`"
1374 ))
1375 .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!(
1376 "insert a space between `-o` and `{name}` if this is intentional: `-o {name}`"
1377 ))
1378 .emit();
1379 }
1380 }
1381}
1382
1383fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1384 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1385 Input::File(file) => {
1386 new_parser_from_file(&sess.psess, file, StripTokens::ShebangAndFrontmatter, None)
1387 }
1388 instr @ (Input::Str { input, .. } | Input::DocTestStr { input, .. }) => {
1389 new_parser_from_source_str(
1390 &sess.psess,
1391 instr.file_name(sess),
1392 input.clone(),
1393 StripTokens::ShebangAndFrontmatter,
1394 )
1395 }
1396 });
1397 parser.parse_inner_attributes()
1398}
1399
1400pub fn catch_with_exit_code<T: Termination>(f: impl FnOnce() -> T) -> ExitCode {
1403 match catch_fatal_errors(f) {
1404 Ok(status) => status.report(),
1405 _ => ExitCode::FAILURE,
1406 }
1407}
1408
1409static ICE_COLOR: OnceLock<ColorConfig> = OnceLock::new();
1410static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1411
1412fn ice_path() -> &'static Option<PathBuf> {
1420 ice_path_with_config(None)
1421}
1422
1423fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1424 if ICE_PATH.get().is_some() && config.is_some() && truecfg!(debug_assertions) {
1425 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_driver_impl/src/lib.rs:1425",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1425u32),
::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!(
1426 "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1427 )
1428 }
1429
1430 ICE_PATH.get_or_init(|| {
1431 if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1432 return None;
1433 }
1434 let mut path = match std::env::var_os("RUSTC_ICE") {
1435 Some(s) => {
1436 if s == "0" {
1437 return None;
1439 }
1440 if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1441 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_driver_impl/src/lib.rs:1441",
"rustc_driver_impl", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_driver_impl/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1441u32),
::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");
1442 }
1443 PathBuf::from(s)
1444 }
1445 None => config
1446 .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1447 .or_else(|| std::env::current_dir().ok())
1448 .unwrap_or_default(),
1449 };
1450 let file_now = jiff::Zoned::now().strftime("%Y-%m-%dT%H_%M_%S");
1452 let pid = std::process::id();
1453 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"));
1454 Some(path)
1455 })
1456}
1457
1458pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1459
1460pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(DiagCtxtHandle<'_>)) {
1472 if env::var_os("RUST_BACKTRACE").is_none() {
1479 let ui_testing = env::args_os().any(|arg| arg == "-Zui-testing");
1481 if "nightly"env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1482 panic::set_backtrace_style(panic::BacktraceStyle::Short);
1483 } else {
1484 panic::set_backtrace_style(panic::BacktraceStyle::Full);
1485 }
1486 }
1487
1488 panic::update_hook(Box::new(
1489 move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1490 info: &PanicHookInfo<'_>| {
1491 let _guard = io::stderr().lock();
1493 #[cfg(windows)]
1496 if let Some(msg) = info.payload().downcast_ref::<String>() {
1497 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1498 {
1499 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1501 let _ = early_dcx.early_err(msg.clone());
1502 return;
1503 }
1504 };
1505
1506 if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1509 default_hook(info);
1510 { ::std::io::_eprint(format_args!("\n")); };eprintln!();
1512
1513 if let Some(ice_path) = ice_path()
1514 && let Ok(mut out) = File::options().create(true).append(true).open(ice_path)
1515 {
1516 let location = info.location().unwrap();
1518 let msg = match info.payload().downcast_ref::<&'static str>() {
1519 Some(s) => *s,
1520 None => match info.payload().downcast_ref::<String>() {
1521 Some(s) => &s[..],
1522 None => "Box<dyn Any>",
1523 },
1524 };
1525 let thread = std::thread::current();
1526 let name = thread.name().unwrap_or("<unnamed>");
1527 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!(
1528 &mut out,
1529 "thread '{name}' panicked at {location}:\n\
1530 {msg}\n\
1531 stack backtrace:\n\
1532 {:#}",
1533 std::backtrace::Backtrace::force_capture()
1534 );
1535 }
1536 }
1537
1538 report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1540 },
1541 ));
1542}
1543
1544fn report_ice(
1551 info: &panic::PanicHookInfo<'_>,
1552 bug_report_url: &str,
1553 extra_info: fn(DiagCtxtHandle<'_>),
1554 using_internal_features: &AtomicBool,
1555) {
1556 let color = ICE_COLOR.get().copied().unwrap_or(ColorConfig::Auto);
1557 let emitter =
1558 Box::new(rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter::new(
1559 stderr_destination(color),
1560 ));
1561 let dcx = DiagCtxt::new(emitter);
1562 let dcx = dcx.handle();
1563
1564 if !info.payload().is::<rustc_errors::ExplicitBug>()
1567 && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1568 {
1569 dcx.emit_err(diagnostics::Ice);
1570 }
1571
1572 if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1573 dcx.emit_note(diagnostics::IceBugReportInternalFeature);
1574 } else {
1575 dcx.emit_note(diagnostics::IceBugReport { bug_report_url });
1576
1577 if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1579 dcx.emit_note(diagnostics::UpdateNightlyNote);
1580 }
1581 }
1582
1583 let version = ::core::option::Option::Some("1.102.0-nightly (064405c5f 2026-12-02)")util::version_str!().unwrap_or("unknown_version");
1584 let tuple = config::host_tuple();
1585
1586 static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1587
1588 let file = if let Some(path) = ice_path() {
1589 match crate::fs::File::options().create(true).append(true).open(path) {
1591 Ok(mut file) => {
1592 dcx.emit_note(diagnostics::IcePath { path: path.clone() });
1593 if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1594 let _ = file.write_fmt(format_args!("\n\nrustc version: {0}\nplatform: {1}", version,
tuple))write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1595 }
1596 Some(file)
1597 }
1598 Err(err) => {
1599 dcx.emit_warn(diagnostics::IcePathError {
1601 path: path.clone(),
1602 error: err.to_string(),
1603 env_var: std::env::var_os("RUSTC_ICE")
1604 .map(PathBuf::from)
1605 .map(|env_var| diagnostics::IcePathErrorEnv { env_var }),
1606 });
1607 None
1608 }
1609 }
1610 } else {
1611 None
1612 };
1613
1614 dcx.emit_note(diagnostics::IceVersion { version, triple: tuple });
1615
1616 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1617 dcx.emit_note(diagnostics::IceFlags { flags: flags.join(" ") });
1618 if excluded_cargo_defaults {
1619 dcx.emit_note(diagnostics::IceExcludeCargoDefaults);
1620 }
1621 }
1622
1623 let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1625
1626 let limit_frames = if backtrace { None } else { Some(2) };
1627
1628 interface::try_print_query_stack(limit_frames, file);
1629
1630 extra_info(dcx);
1633
1634 #[cfg(windows)]
1635 if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1636 unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1638 }
1639}
1640
1641pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1644 init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1645}
1646
1647pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1651 if let Err(error) = rustc_log::init_logger(cfg) {
1652 early_dcx.early_fatal(error.to_string());
1653 }
1654}
1655
1656pub fn init_logger_with_additional_layer<F, T>(
1662 early_dcx: &EarlyDiagCtxt,
1663 cfg: rustc_log::LoggerConfig,
1664 build_subscriber: F,
1665) where
1666 F: FnOnce() -> T,
1667 T: rustc_log::BuildSubscriberRet,
1668{
1669 if let Err(error) = rustc_log::init_logger_with_additional_layer(cfg, build_subscriber) {
1670 early_dcx.early_fatal(error.to_string());
1671 }
1672}
1673
1674pub fn install_ctrlc_handler() {
1677 #[cfg(all(not(miri), not(target_family = "wasm")))]
1678 ctrlc::set_handler(move || {
1679 rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1684 std::thread::sleep(std::time::Duration::from_millis(100));
1685 std::process::exit(1);
1686 })
1687 .expect("Unable to install ctrlc handler");
1688}
1689
1690pub fn main() -> ExitCode {
1691 let start_time = Instant::now();
1692 let start_rss = get_resident_set_size();
1693
1694 let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1695
1696 init_rustc_env_logger(&early_dcx);
1697 signal_handler::install();
1698 let mut callbacks = TimePassesCallbacks::default();
1699 install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1700 install_ctrlc_handler();
1701
1702 let exit_code =
1703 catch_with_exit_code(|| compiler_entrypoint(&args::raw_args(&early_dcx), &mut callbacks));
1704
1705 if let Some(format) = callbacks.time_passes {
1706 let end_rss = get_resident_set_size();
1707 print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1708 }
1709
1710 exit_code
1711}