• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6 
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(lazy_cell)]
9 #![feature(decl_macro)]
10 #![recursion_limit = "256"]
11 #![allow(rustc::potential_query_instability)]
12 #![deny(rustc::untranslatable_diagnostic)]
13 #![deny(rustc::diagnostic_outside_of_impl)]
14 
15 #[macro_use]
16 extern crate tracing;
17 
18 pub extern crate rustc_plugin_impl as plugin;
19 
20 use rustc_ast as ast;
21 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenErrors, CodegenResults};
22 use rustc_data_structures::profiling::{
23     get_resident_set_size, print_time_passes_entry, TimePassesFormat,
24 };
25 use rustc_data_structures::sync::SeqCst;
26 use rustc_errors::registry::{InvalidErrorCode, Registry};
27 use rustc_errors::{markdown, ColorConfig};
28 use rustc_errors::{
29     DiagnosticMessage, ErrorGuaranteed, Handler, PResult, SubdiagnosticMessage, TerminalUrl,
30 };
31 use rustc_feature::find_gated_cfg;
32 use rustc_fluent_macro::fluent_messages;
33 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
34 use rustc_interface::{interface, Queries};
35 use rustc_lint::LintStore;
36 use rustc_metadata::locator;
37 use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS};
38 use rustc_session::config::{
39     ErrorOutputType, Input, OutFileName, OutputType, PrintRequest, TrimmedDefPaths,
40 };
41 use rustc_session::cstore::MetadataLoader;
42 use rustc_session::getopts::{self, Matches};
43 use rustc_session::lint::{Lint, LintId};
44 use rustc_session::{config, EarlyErrorHandler, Session};
45 use rustc_span::source_map::{FileLoader, FileName};
46 use rustc_span::symbol::sym;
47 use rustc_target::json::ToJson;
48 use rustc_target::spec::{Target, TargetTriple};
49 
50 use std::cmp::max;
51 use std::collections::BTreeMap;
52 use std::env;
53 use std::ffi::OsString;
54 use std::fs;
55 use std::io::{self, IsTerminal, Read, Write};
56 use std::panic::{self, catch_unwind};
57 use std::path::PathBuf;
58 use std::process::{self, Command, Stdio};
59 use std::str;
60 use std::sync::OnceLock;
61 use std::time::Instant;
62 
63 #[allow(unused_macros)]
64 macro do_not_use_print($($t:tt)*) {
65     std::compile_error!(
66         "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
67     )
68 }
69 
70 // This import blocks the use of panicking `print` and `println` in all the code
71 // below. Please use `safe_print` and `safe_println` to avoid ICE when
72 // encountering an I/O error during print.
73 #[allow(unused_imports)]
74 use {do_not_use_print as print, do_not_use_print as println};
75 
76 pub mod args;
77 pub mod pretty;
78 #[macro_use]
79 mod print;
80 mod session_diagnostics;
81 
82 use crate::session_diagnostics::{
83     RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
84     RLinkWrongFileType, RlinkNotAFile, RlinkUnableToRead,
85 };
86 
87 fluent_messages! { "../messages.ftl" }
88 
89 pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
90     // tidy-alphabetical-start
91     crate::DEFAULT_LOCALE_RESOURCE,
92     rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
93     rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
94     rustc_attr::DEFAULT_LOCALE_RESOURCE,
95     rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
96     rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
97     rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
98     rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
99     rustc_error_messages::DEFAULT_LOCALE_RESOURCE,
100     rustc_errors::DEFAULT_LOCALE_RESOURCE,
101     rustc_expand::DEFAULT_LOCALE_RESOURCE,
102     rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
103     rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
104     rustc_incremental::DEFAULT_LOCALE_RESOURCE,
105     rustc_infer::DEFAULT_LOCALE_RESOURCE,
106     rustc_interface::DEFAULT_LOCALE_RESOURCE,
107     rustc_lint::DEFAULT_LOCALE_RESOURCE,
108     rustc_metadata::DEFAULT_LOCALE_RESOURCE,
109     rustc_middle::DEFAULT_LOCALE_RESOURCE,
110     rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
111     rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
112     rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
113     rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
114     rustc_parse::DEFAULT_LOCALE_RESOURCE,
115     rustc_passes::DEFAULT_LOCALE_RESOURCE,
116     rustc_plugin_impl::DEFAULT_LOCALE_RESOURCE,
117     rustc_privacy::DEFAULT_LOCALE_RESOURCE,
118     rustc_query_system::DEFAULT_LOCALE_RESOURCE,
119     rustc_resolve::DEFAULT_LOCALE_RESOURCE,
120     rustc_session::DEFAULT_LOCALE_RESOURCE,
121     rustc_symbol_mangling::DEFAULT_LOCALE_RESOURCE,
122     rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
123     rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
124     // tidy-alphabetical-end
125 ];
126 
127 /// Exit status code used for successful compilation and help output.
128 pub const EXIT_SUCCESS: i32 = 0;
129 
130 /// Exit status code used for compilation failures and invalid flags.
131 pub const EXIT_FAILURE: i32 = 1;
132 
133 pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
134     ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
135 
136 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
137 
138 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
139 
140 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
141 
abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T142 pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
143     match result {
144         Err(..) => {
145             sess.abort_if_errors();
146             panic!("error reported but abort_if_errors didn't abort???");
147         }
148         Ok(x) => x,
149     }
150 }
151 
152 pub trait Callbacks {
153     /// Called before creating the compiler instance
config(&mut self, _config: &mut interface::Config)154     fn config(&mut self, _config: &mut interface::Config) {}
155     /// Called after parsing. Return value instructs the compiler whether to
156     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
after_parsing<'tcx>( &mut self, _compiler: &interface::Compiler, _queries: &'tcx Queries<'tcx>, ) -> Compilation157     fn after_parsing<'tcx>(
158         &mut self,
159         _compiler: &interface::Compiler,
160         _queries: &'tcx Queries<'tcx>,
161     ) -> Compilation {
162         Compilation::Continue
163     }
164     /// Called after expansion. Return value instructs the compiler whether to
165     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
after_expansion<'tcx>( &mut self, _compiler: &interface::Compiler, _queries: &'tcx Queries<'tcx>, ) -> Compilation166     fn after_expansion<'tcx>(
167         &mut self,
168         _compiler: &interface::Compiler,
169         _queries: &'tcx Queries<'tcx>,
170     ) -> Compilation {
171         Compilation::Continue
172     }
173     /// Called after analysis. Return value instructs the compiler whether to
174     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
after_analysis<'tcx>( &mut self, _handler: &EarlyErrorHandler, _compiler: &interface::Compiler, _queries: &'tcx Queries<'tcx>, ) -> Compilation175     fn after_analysis<'tcx>(
176         &mut self,
177         _handler: &EarlyErrorHandler,
178         _compiler: &interface::Compiler,
179         _queries: &'tcx Queries<'tcx>,
180     ) -> Compilation {
181         Compilation::Continue
182     }
183 }
184 
185 #[derive(Default)]
186 pub struct TimePassesCallbacks {
187     time_passes: Option<TimePassesFormat>,
188 }
189 
190 impl Callbacks for TimePassesCallbacks {
191     // JUSTIFICATION: the session doesn't exist at this point.
192     #[allow(rustc::bad_opt_access)]
config(&mut self, config: &mut interface::Config)193     fn config(&mut self, config: &mut interface::Config) {
194         // If a --print=... option has been given, we don't print the "total"
195         // time because it will mess up the --print output. See #64339.
196         //
197         self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
198             .then(|| config.opts.unstable_opts.time_passes_format);
199         config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
200     }
201 }
202 
diagnostics_registry() -> Registry203 pub fn diagnostics_registry() -> Registry {
204     Registry::new(rustc_error_codes::DIAGNOSTICS)
205 }
206 
207 /// This is the primary entry point for rustc.
208 pub struct RunCompiler<'a, 'b> {
209     at_args: &'a [String],
210     callbacks: &'b mut (dyn Callbacks + Send),
211     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
212     make_codegen_backend:
213         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
214 }
215 
216 impl<'a, 'b> RunCompiler<'a, 'b> {
new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self217     pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
218         Self { at_args, callbacks, file_loader: None, make_codegen_backend: None }
219     }
220 
221     /// Set a custom codegen backend.
222     ///
223     /// Has no uses within this repository, but is used by bjorn3 for "the
224     /// hotswapping branch of cg_clif" for "setting the codegen backend from a
225     /// custom driver where the custom codegen backend has arbitrary data."
226     /// (See #102759.)
set_make_codegen_backend( &mut self, make_codegen_backend: Option< Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>, >, ) -> &mut Self227     pub fn set_make_codegen_backend(
228         &mut self,
229         make_codegen_backend: Option<
230             Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
231         >,
232     ) -> &mut Self {
233         self.make_codegen_backend = make_codegen_backend;
234         self
235     }
236 
237     /// Load files from sources other than the file system.
238     ///
239     /// Has no uses within this repository, but may be used in the future by
240     /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
241     /// running rustc without having to save". (See #102759.)
set_file_loader( &mut self, file_loader: Option<Box<dyn FileLoader + Send + Sync>>, ) -> &mut Self242     pub fn set_file_loader(
243         &mut self,
244         file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
245     ) -> &mut Self {
246         self.file_loader = file_loader;
247         self
248     }
249 
250     /// Parse args and run the compiler.
run(self) -> interface::Result<()>251     pub fn run(self) -> interface::Result<()> {
252         run_compiler(self.at_args, self.callbacks, self.file_loader, self.make_codegen_backend)
253     }
254 }
255 
run_compiler( at_args: &[String], callbacks: &mut (dyn Callbacks + Send), file_loader: Option<Box<dyn FileLoader + Send + Sync>>, make_codegen_backend: Option< Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>, >, ) -> interface::Result<()>256 fn run_compiler(
257     at_args: &[String],
258     callbacks: &mut (dyn Callbacks + Send),
259     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
260     make_codegen_backend: Option<
261         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
262     >,
263 ) -> interface::Result<()> {
264     let mut early_error_handler = EarlyErrorHandler::new(ErrorOutputType::default());
265 
266     // Throw away the first argument, the name of the binary.
267     // In case of at_args being empty, as might be the case by
268     // passing empty argument array to execve under some platforms,
269     // just use an empty slice.
270     //
271     // This situation was possible before due to arg_expand_all being
272     // called before removing the argument, enabling a crash by calling
273     // the compiler with @empty_file as argv[0] and no more arguments.
274     let at_args = at_args.get(1..).unwrap_or_default();
275 
276     let args = args::arg_expand_all(&early_error_handler, at_args);
277 
278     let Some(matches) = handle_options(&early_error_handler, &args) else { return Ok(()) };
279 
280     let sopts = config::build_session_options(&mut early_error_handler, &matches);
281 
282     // Set parallel mode before thread pool creation, which will create `Lock`s.
283     interface::set_thread_safe_mode(&sopts.unstable_opts);
284 
285     if let Some(ref code) = matches.opt_str("explain") {
286         handle_explain(&early_error_handler, diagnostics_registry(), code, sopts.color);
287         return Ok(());
288     }
289 
290     let cfg = interface::parse_cfgspecs(&early_error_handler, matches.opt_strs("cfg"));
291     let check_cfg = interface::parse_check_cfg(&early_error_handler, matches.opt_strs("check-cfg"));
292     let (odir, ofile) = make_output(&matches);
293     let mut config = interface::Config {
294         opts: sopts,
295         crate_cfg: cfg,
296         crate_check_cfg: check_cfg,
297         input: Input::File(PathBuf::new()),
298         output_file: ofile,
299         output_dir: odir,
300         file_loader,
301         locale_resources: DEFAULT_LOCALE_RESOURCES,
302         lint_caps: Default::default(),
303         parse_sess_created: None,
304         register_lints: None,
305         override_queries: None,
306         make_codegen_backend,
307         registry: diagnostics_registry(),
308     };
309 
310     match make_input(&early_error_handler, &matches.free) {
311         Err(reported) => return Err(reported),
312         Ok(Some(input)) => {
313             config.input = input;
314 
315             callbacks.config(&mut config);
316         }
317         Ok(None) => match matches.free.len() {
318             0 => {
319                 callbacks.config(&mut config);
320 
321                 early_error_handler.abort_if_errors();
322 
323                 interface::run_compiler(config, |compiler| {
324                     let sopts = &compiler.session().opts;
325                     let handler = EarlyErrorHandler::new(sopts.error_format);
326 
327                     if sopts.describe_lints {
328                         let mut lint_store =
329                             rustc_lint::new_lint_store(compiler.session().enable_internal_lints());
330                         let registered_lints =
331                             if let Some(register_lints) = compiler.register_lints() {
332                                 register_lints(compiler.session(), &mut lint_store);
333                                 true
334                             } else {
335                                 false
336                             };
337                         describe_lints(compiler.session(), &lint_store, registered_lints);
338                         return;
339                     }
340                     let should_stop = print_crate_info(
341                         &handler,
342                         &**compiler.codegen_backend(),
343                         compiler.session(),
344                         false,
345                     );
346 
347                     if should_stop == Compilation::Stop {
348                         return;
349                     }
350                     handler.early_error("no input filename given")
351                 });
352                 return Ok(());
353             }
354             1 => panic!("make_input should have provided valid inputs"),
355             _ => early_error_handler.early_error(format!(
356                 "multiple input filenames provided (first two filenames are `{}` and `{}`)",
357                 matches.free[0], matches.free[1],
358             )),
359         },
360     };
361 
362     early_error_handler.abort_if_errors();
363 
364     interface::run_compiler(config, |compiler| {
365         let sess = compiler.session();
366         let handler = EarlyErrorHandler::new(sess.opts.error_format);
367 
368         let should_stop = print_crate_info(&handler, &**compiler.codegen_backend(), sess, true)
369             .and_then(|| {
370                 list_metadata(&handler, sess, &*compiler.codegen_backend().metadata_loader())
371             })
372             .and_then(|| try_process_rlink(sess, compiler));
373 
374         if should_stop == Compilation::Stop {
375             return sess.compile_status();
376         }
377 
378         let linker = compiler.enter(|queries| {
379             let early_exit = || sess.compile_status().map(|_| None);
380             queries.parse()?;
381 
382             if let Some(ppm) = &sess.opts.pretty {
383                 if ppm.needs_ast_map() {
384                     queries.global_ctxt()?.enter(|tcx| {
385                         tcx.ensure().early_lint_checks(());
386                         pretty::print_after_hir_lowering(tcx, *ppm);
387                         Ok(())
388                     })?;
389                 } else {
390                     let krate = queries.parse()?.steal();
391                     pretty::print_after_parsing(sess, &krate, *ppm);
392                 }
393                 trace!("finished pretty-printing");
394                 return early_exit();
395             }
396 
397             if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
398                 return early_exit();
399             }
400 
401             if sess.opts.unstable_opts.parse_only || sess.opts.unstable_opts.show_span.is_some() {
402                 return early_exit();
403             }
404 
405             {
406                 let plugins = queries.register_plugins()?;
407                 let (.., lint_store) = &*plugins.borrow();
408 
409                 // Lint plugins are registered; now we can process command line flags.
410                 if sess.opts.describe_lints {
411                     describe_lints(sess, lint_store, true);
412                     return early_exit();
413                 }
414             }
415 
416             // Make sure name resolution and macro expansion is run.
417             queries.global_ctxt()?.enter(|tcx| tcx.resolver_for_lowering(()));
418 
419             if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
420                 return early_exit();
421             }
422 
423             // Make sure the `output_filenames` query is run for its side
424             // effects of writing the dep-info and reporting errors.
425             queries.global_ctxt()?.enter(|tcx| tcx.output_filenames(()));
426 
427             if sess.opts.output_types.contains_key(&OutputType::DepInfo)
428                 && sess.opts.output_types.len() == 1
429             {
430                 return early_exit();
431             }
432 
433             if sess.opts.unstable_opts.no_analysis {
434                 return early_exit();
435             }
436 
437             queries.global_ctxt()?.enter(|tcx| tcx.analysis(()))?;
438 
439             if callbacks.after_analysis(&handler, compiler, queries) == Compilation::Stop {
440                 return early_exit();
441             }
442 
443             let ongoing_codegen = queries.ongoing_codegen()?;
444 
445             if sess.opts.unstable_opts.print_type_sizes {
446                 sess.code_stats.print_type_sizes();
447             }
448 
449             if sess.opts.unstable_opts.print_vtable_sizes {
450                 let crate_name =
451                     compiler.session().opts.crate_name.as_deref().unwrap_or("<UNKNOWN_CRATE>");
452 
453                 sess.code_stats.print_vtable_sizes(crate_name);
454             }
455 
456             let linker = queries.linker(ongoing_codegen)?;
457             Ok(Some(linker))
458         })?;
459 
460         if let Some(linker) = linker {
461             let _timer = sess.timer("link");
462             linker.link()?
463         }
464 
465         if sess.opts.unstable_opts.perf_stats {
466             sess.print_perf_stats();
467         }
468 
469         if sess.opts.unstable_opts.print_fuel.is_some() {
470             eprintln!(
471                 "Fuel used by {}: {}",
472                 sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
473                 sess.print_fuel.load(SeqCst)
474             );
475         }
476 
477         Ok(())
478     })
479 }
480 
481 // Extract output directory and file from matches.
make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>)482 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
483     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
484     let ofile = matches.opt_str("o").map(|o| match o.as_str() {
485         "-" => OutFileName::Stdout,
486         path => OutFileName::Real(PathBuf::from(path)),
487     });
488     (odir, ofile)
489 }
490 
491 // Extract input (string or file and optional path) from matches.
make_input( handler: &EarlyErrorHandler, free_matches: &[String], ) -> Result<Option<Input>, ErrorGuaranteed>492 fn make_input(
493     handler: &EarlyErrorHandler,
494     free_matches: &[String],
495 ) -> Result<Option<Input>, ErrorGuaranteed> {
496     if free_matches.len() == 1 {
497         let ifile = &free_matches[0];
498         if ifile == "-" {
499             let mut src = String::new();
500             if io::stdin().read_to_string(&mut src).is_err() {
501                 // Immediately stop compilation if there was an issue reading
502                 // the input (for example if the input stream is not UTF-8).
503                 let reported = handler.early_error_no_abort(
504                     "couldn't read from stdin, as it did not contain valid UTF-8",
505                 );
506                 return Err(reported);
507             }
508             if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
509                 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
510                     "when UNSTABLE_RUSTDOC_TEST_PATH is set \
511                                     UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
512                 );
513                 let line = isize::from_str_radix(&line, 10)
514                     .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
515                 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
516                 Ok(Some(Input::Str { name: file_name, input: src }))
517             } else {
518                 Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src }))
519             }
520         } else {
521             Ok(Some(Input::File(PathBuf::from(ifile))))
522         }
523     } else {
524         Ok(None)
525     }
526 }
527 
528 /// Whether to stop or continue compilation.
529 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
530 pub enum Compilation {
531     Stop,
532     Continue,
533 }
534 
535 impl Compilation {
and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation536     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
537         match self {
538             Compilation::Stop => Compilation::Stop,
539             Compilation::Continue => next(),
540         }
541     }
542 }
543 
handle_explain(handler: &EarlyErrorHandler, registry: Registry, code: &str, color: ColorConfig)544 fn handle_explain(handler: &EarlyErrorHandler, registry: Registry, code: &str, color: ColorConfig) {
545     let upper_cased_code = code.to_ascii_uppercase();
546     let normalised =
547         if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") };
548     match registry.try_find_description(&normalised) {
549         Ok(description) => {
550             let mut is_in_code_block = false;
551             let mut text = String::new();
552             // Slice off the leading newline and print.
553             for line in description.lines() {
554                 let indent_level =
555                     line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
556                 let dedented_line = &line[indent_level..];
557                 if dedented_line.starts_with("```") {
558                     is_in_code_block = !is_in_code_block;
559                     text.push_str(&line[..(indent_level + 3)]);
560                 } else if is_in_code_block && dedented_line.starts_with("# ") {
561                     continue;
562                 } else {
563                     text.push_str(line);
564                 }
565                 text.push('\n');
566             }
567             if io::stdout().is_terminal() {
568                 show_md_content_with_pager(&text, color);
569             } else {
570                 safe_print!("{text}");
571             }
572         }
573         Err(InvalidErrorCode) => {
574             handler.early_error(format!("{code} is not a valid error code"));
575         }
576     }
577 }
578 
579 /// If color is always or auto, print formatted & colorized markdown. If color is never or
580 /// if formatted printing fails, print the raw text.
581 ///
582 /// Prefers a pager, falls back standard print
show_md_content_with_pager(content: &str, color: ColorConfig)583 fn show_md_content_with_pager(content: &str, color: ColorConfig) {
584     let mut fallback_to_println = false;
585     let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
586         if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
587     });
588 
589     let mut cmd = Command::new(&pager_name);
590     // FIXME: find if other pagers accept color options
591     let mut print_formatted = if pager_name == "less" {
592         cmd.arg("-r");
593         true
594     } else if ["bat", "catbat", "delta"].iter().any(|v| *v == pager_name) {
595         true
596     } else {
597         false
598     };
599 
600     if color == ColorConfig::Never {
601         print_formatted = false;
602     } else if color == ColorConfig::Always {
603         print_formatted = true;
604     }
605 
606     let mdstream = markdown::MdStream::parse_str(content);
607     let bufwtr = markdown::create_stdout_bufwtr();
608     let mut mdbuf = bufwtr.buffer();
609     if mdstream.write_termcolor_buf(&mut mdbuf).is_err() {
610         print_formatted = false;
611     }
612 
613     if let Ok(mut pager) = cmd.stdin(Stdio::piped()).spawn() {
614         if let Some(pipe) = pager.stdin.as_mut() {
615             let res = if print_formatted {
616                 pipe.write_all(mdbuf.as_slice())
617             } else {
618                 pipe.write_all(content.as_bytes())
619             };
620 
621             if res.is_err() {
622                 fallback_to_println = true;
623             }
624         }
625 
626         if pager.wait().is_err() {
627             fallback_to_println = true;
628         }
629     } else {
630         fallback_to_println = true;
631     }
632 
633     // If pager fails for whatever reason, we should still print the content
634     // to standard output
635     if fallback_to_println {
636         let fmt_success = match color {
637             ColorConfig::Auto => io::stdout().is_terminal() && bufwtr.print(&mdbuf).is_ok(),
638             ColorConfig::Always => bufwtr.print(&mdbuf).is_ok(),
639             ColorConfig::Never => false,
640         };
641 
642         if !fmt_success {
643             safe_print!("{content}");
644         }
645     }
646 }
647 
try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation648 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
649     if sess.opts.unstable_opts.link_only {
650         if let Input::File(file) = &sess.io.input {
651             // FIXME: #![crate_type] and #![crate_name] support not implemented yet
652             sess.init_crate_types(collect_crate_types(sess, &[]));
653             let outputs = compiler.build_output_filenames(sess, &[]);
654             let rlink_data = fs::read(file).unwrap_or_else(|err| {
655                 sess.emit_fatal(RlinkUnableToRead { err });
656             });
657             let codegen_results = match CodegenResults::deserialize_rlink(sess, rlink_data) {
658                 Ok(codegen) => codegen,
659                 Err(err) => {
660                     match err {
661                         CodegenErrors::WrongFileType => sess.emit_fatal(RLinkWrongFileType),
662                         CodegenErrors::EmptyVersionNumber => {
663                             sess.emit_fatal(RLinkEmptyVersionNumber)
664                         }
665                         CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
666                             sess.emit_fatal(RLinkEncodingVersionMismatch {
667                                 version_array,
668                                 rlink_version,
669                             })
670                         }
671                         CodegenErrors::RustcVersionMismatch { rustc_version } => {
672                             sess.emit_fatal(RLinkRustcVersionMismatch {
673                                 rustc_version,
674                                 current_version: sess.cfg_version,
675                             })
676                         }
677                     };
678                 }
679             };
680             let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
681             abort_on_err(result, sess);
682         } else {
683             sess.emit_fatal(RlinkNotAFile {})
684         }
685         Compilation::Stop
686     } else {
687         Compilation::Continue
688     }
689 }
690 
list_metadata( handler: &EarlyErrorHandler, sess: &Session, metadata_loader: &dyn MetadataLoader, ) -> Compilation691 pub fn list_metadata(
692     handler: &EarlyErrorHandler,
693     sess: &Session,
694     metadata_loader: &dyn MetadataLoader,
695 ) -> Compilation {
696     if sess.opts.unstable_opts.ls {
697         match sess.io.input {
698             Input::File(ref ifile) => {
699                 let path = &(*ifile);
700                 let mut v = Vec::new();
701                 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
702                 safe_println!("{}", String::from_utf8(v).unwrap());
703             }
704             Input::Str { .. } => {
705                 handler.early_error("cannot list metadata for stdin");
706             }
707         }
708         return Compilation::Stop;
709     }
710 
711     Compilation::Continue
712 }
713 
print_crate_info( handler: &EarlyErrorHandler, codegen_backend: &dyn CodegenBackend, sess: &Session, parse_attrs: bool, ) -> Compilation714 fn print_crate_info(
715     handler: &EarlyErrorHandler,
716     codegen_backend: &dyn CodegenBackend,
717     sess: &Session,
718     parse_attrs: bool,
719 ) -> Compilation {
720     use rustc_session::config::PrintRequest::*;
721     // NativeStaticLibs and LinkArgs are special - printed during linking
722     // (empty iterator returns true)
723     if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
724         return Compilation::Continue;
725     }
726 
727     let attrs = if parse_attrs {
728         let result = parse_crate_attrs(sess);
729         match result {
730             Ok(attrs) => Some(attrs),
731             Err(mut parse_error) => {
732                 parse_error.emit();
733                 return Compilation::Stop;
734             }
735         }
736     } else {
737         None
738     };
739     for req in &sess.opts.prints {
740         match *req {
741             TargetList => {
742                 let mut targets = rustc_target::spec::TARGETS.to_vec();
743                 targets.sort_unstable();
744                 safe_println!("{}", targets.join("\n"));
745             }
746             Sysroot => safe_println!("{}", sess.sysroot.display()),
747             TargetLibdir => safe_println!("{}", sess.target_tlib_path.dir.display()),
748             TargetSpec => {
749                 safe_println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
750             }
751             AllTargetSpecs => {
752                 let mut targets = BTreeMap::new();
753                 for name in rustc_target::spec::TARGETS {
754                     let triple = TargetTriple::from_triple(name);
755                     let target = Target::expect_builtin(&triple);
756                     targets.insert(name, target.to_json());
757                 }
758                 safe_println!("{}", serde_json::to_string_pretty(&targets).unwrap());
759             }
760             FileNames | CrateName => {
761                 let Some(attrs) = attrs.as_ref() else {
762                     // no crate attributes, print out an error and exit
763                     return Compilation::Continue;
764                 };
765                 let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
766                 let id = rustc_session::output::find_crate_name(sess, attrs);
767                 if *req == PrintRequest::CrateName {
768                     safe_println!("{id}");
769                     continue;
770                 }
771                 let crate_types = collect_crate_types(sess, attrs);
772                 for &style in &crate_types {
773                     let fname =
774                         rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
775                     safe_println!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
776                 }
777             }
778             Cfg => {
779                 let mut cfgs = sess
780                     .parse_sess
781                     .config
782                     .iter()
783                     .filter_map(|&(name, value)| {
784                         // Note that crt-static is a specially recognized cfg
785                         // directive that's printed out here as part of
786                         // rust-lang/rust#37406, but in general the
787                         // `target_feature` cfg is gated under
788                         // rust-lang/rust#29717. For now this is just
789                         // specifically allowing the crt-static cfg and that's
790                         // it, this is intended to get into Cargo and then go
791                         // through to build scripts.
792                         if (name != sym::target_feature || value != Some(sym::crt_dash_static))
793                             && !sess.is_nightly_build()
794                             && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
795                         {
796                             return None;
797                         }
798 
799                         if let Some(value) = value {
800                             Some(format!("{name}=\"{value}\""))
801                         } else {
802                             Some(name.to_string())
803                         }
804                     })
805                     .collect::<Vec<String>>();
806 
807                 cfgs.sort();
808                 for cfg in cfgs {
809                     safe_println!("{cfg}");
810                 }
811             }
812             CallingConventions => {
813                 let mut calling_conventions = rustc_target::spec::abi::all_names();
814                 calling_conventions.sort_unstable();
815                 safe_println!("{}", calling_conventions.join("\n"));
816             }
817             RelocationModels
818             | CodeModels
819             | TlsModels
820             | TargetCPUs
821             | StackProtectorStrategies
822             | TargetFeatures => {
823                 codegen_backend.print(*req, sess);
824             }
825             // Any output here interferes with Cargo's parsing of other printed output
826             NativeStaticLibs => {}
827             LinkArgs => {}
828             SplitDebuginfo => {
829                 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
830 
831                 for split in &[Off, Packed, Unpacked] {
832                     if sess.target.options.supported_split_debuginfo.contains(split) {
833                         safe_println!("{split}");
834                     }
835                 }
836             }
837             DeploymentTarget => {
838                 use rustc_target::spec::current_apple_deployment_target;
839 
840                 if sess.target.is_like_osx {
841                     safe_println!(
842                         "deployment_target={}",
843                         current_apple_deployment_target(&sess.target)
844                             .expect("unknown Apple target OS")
845                     )
846                 } else {
847                     handler
848                         .early_error("only Apple targets currently support deployment version info")
849                 }
850             }
851         }
852     }
853     Compilation::Stop
854 }
855 
856 /// Prints version information
857 ///
858 /// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
859 pub macro version($handler: expr, $binary: literal, $matches: expr) {
unw(x: Option<&str>) -> &str860     fn unw(x: Option<&str>) -> &str {
861         x.unwrap_or("unknown")
862     }
863     $crate::version_at_macro_invocation(
864         $handler,
865         $binary,
866         $matches,
867         unw(option_env!("CFG_VERSION")),
868         unw(option_env!("CFG_VER_HASH")),
869         unw(option_env!("CFG_VER_DATE")),
870         unw(option_env!("CFG_RELEASE")),
871     )
872 }
873 
874 #[doc(hidden)] // use the macro instead
version_at_macro_invocation( handler: &EarlyErrorHandler, binary: &str, matches: &getopts::Matches, version: &str, commit_hash: &str, commit_date: &str, release: &str, )875 pub fn version_at_macro_invocation(
876     handler: &EarlyErrorHandler,
877     binary: &str,
878     matches: &getopts::Matches,
879     version: &str,
880     commit_hash: &str,
881     commit_date: &str,
882     release: &str,
883 ) {
884     let verbose = matches.opt_present("verbose");
885 
886     safe_println!("{binary} {version}");
887 
888     if verbose {
889         safe_println!("binary: {binary}");
890         safe_println!("commit-hash: {commit_hash}");
891         safe_println!("commit-date: {commit_date}");
892         safe_println!("host: {}", config::host_triple());
893         safe_println!("release: {release}");
894 
895         let debug_flags = matches.opt_strs("Z");
896         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
897         get_codegen_backend(handler, &None, backend_name).print_version();
898     }
899 }
900 
usage(verbose: bool, include_unstable_options: bool, nightly_build: bool)901 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
902     let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
903     let mut options = getopts::Options::new();
904     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
905         (option.apply)(&mut options);
906     }
907     let message = "Usage: rustc [OPTIONS] INPUT";
908     let nightly_help = if nightly_build {
909         "\n    -Z help             Print unstable compiler options"
910     } else {
911         ""
912     };
913     let verbose_help = if verbose {
914         ""
915     } else {
916         "\n    --help -v           Print the full set of options rustc accepts"
917     };
918     let at_path = if verbose {
919         "    @path               Read newline separated options from `path`\n"
920     } else {
921         ""
922     };
923     safe_println!(
924         "{options}{at_path}\nAdditional help:
925     -C help             Print codegen options
926     -W help             \
927               Print 'lint' options and default settings{nightly}{verbose}\n",
928         options = options.usage(message),
929         at_path = at_path,
930         nightly = nightly_help,
931         verbose = verbose_help
932     );
933 }
934 
print_wall_help()935 fn print_wall_help() {
936     safe_println!(
937         "
938 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
939 default. Use `rustc -W help` to see all available lints. It's more common to put
940 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
941 the command line flag directly.
942 "
943     );
944 }
945 
946 /// Write to stdout lint command options, together with a list of all available lints
describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool)947 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
948     safe_println!(
949         "
950 Available lint options:
951     -W <foo>           Warn about <foo>
952     -A <foo>           \
953               Allow <foo>
954     -D <foo>           Deny <foo>
955     -F <foo>           Forbid <foo> \
956               (deny <foo> and all attempts to override)
957 
958 "
959     );
960 
961     fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
962         // The sort doesn't case-fold but it's doubtful we care.
963         lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
964         lints
965     }
966 
967     fn sort_lint_groups(
968         lints: Vec<(&'static str, Vec<LintId>, bool)>,
969     ) -> Vec<(&'static str, Vec<LintId>)> {
970         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
971         lints.sort_by_key(|l| l.0);
972         lints
973     }
974 
975     let (plugin, builtin): (Vec<_>, _) =
976         lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
977     let plugin = sort_lints(sess, plugin);
978     let builtin = sort_lints(sess, builtin);
979 
980     let (plugin_groups, builtin_groups): (Vec<_>, _) =
981         lint_store.get_lint_groups().partition(|&(.., p)| p);
982     let plugin_groups = sort_lint_groups(plugin_groups);
983     let builtin_groups = sort_lint_groups(builtin_groups);
984 
985     let max_name_len =
986         plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
987     let padded = |x: &str| {
988         let mut s = " ".repeat(max_name_len - x.chars().count());
989         s.push_str(x);
990         s
991     };
992 
993     safe_println!("Lint checks provided by rustc:\n");
994 
995     let print_lints = |lints: Vec<&Lint>| {
996         safe_println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
997         safe_println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
998         for lint in lints {
999             let name = lint.name_lower().replace('_', "-");
1000             safe_println!(
1001                 "    {}  {:7.7}  {}",
1002                 padded(&name),
1003                 lint.default_level(sess.edition()).as_str(),
1004                 lint.desc
1005             );
1006         }
1007         safe_println!("\n");
1008     };
1009 
1010     print_lints(builtin);
1011 
1012     let max_name_len = max(
1013         "warnings".len(),
1014         plugin_groups
1015             .iter()
1016             .chain(&builtin_groups)
1017             .map(|&(s, _)| s.chars().count())
1018             .max()
1019             .unwrap_or(0),
1020     );
1021 
1022     let padded = |x: &str| {
1023         let mut s = " ".repeat(max_name_len - x.chars().count());
1024         s.push_str(x);
1025         s
1026     };
1027 
1028     safe_println!("Lint groups provided by rustc:\n");
1029 
1030     let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
1031         safe_println!("    {}  sub-lints", padded("name"));
1032         safe_println!("    {}  ---------", padded("----"));
1033 
1034         if all_warnings {
1035             safe_println!("    {}  all lints that are set to issue warnings", padded("warnings"));
1036         }
1037 
1038         for (name, to) in lints {
1039             let name = name.to_lowercase().replace('_', "-");
1040             let desc = to
1041                 .into_iter()
1042                 .map(|x| x.to_string().replace('_', "-"))
1043                 .collect::<Vec<String>>()
1044                 .join(", ");
1045             safe_println!("    {}  {}", padded(&name), desc);
1046         }
1047         safe_println!("\n");
1048     };
1049 
1050     print_lint_groups(builtin_groups, true);
1051 
1052     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1053         (false, 0, _) | (false, _, 0) => {
1054             safe_println!("Lint tools like Clippy can provide additional lints and lint groups.");
1055         }
1056         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1057         (true, 0, 0) => safe_println!("This crate does not load any lint plugins or lint groups."),
1058         (true, l, g) => {
1059             if l > 0 {
1060                 safe_println!("Lint checks provided by plugins loaded by this crate:\n");
1061                 print_lints(plugin);
1062             }
1063             if g > 0 {
1064                 safe_println!("Lint groups provided by plugins loaded by this crate:\n");
1065                 print_lint_groups(plugin_groups, false);
1066             }
1067         }
1068     }
1069 }
1070 
1071 /// Show help for flag categories shared between rustdoc and rustc.
1072 ///
1073 /// Returns whether a help option was printed.
describe_flag_categories(handler: &EarlyErrorHandler, matches: &Matches) -> bool1074 pub fn describe_flag_categories(handler: &EarlyErrorHandler, matches: &Matches) -> bool {
1075     // Handle the special case of -Wall.
1076     let wall = matches.opt_strs("W");
1077     if wall.iter().any(|x| *x == "all") {
1078         print_wall_help();
1079         rustc_errors::FatalError.raise();
1080     }
1081 
1082     // Don't handle -W help here, because we might first load plugins.
1083     let debug_flags = matches.opt_strs("Z");
1084     if debug_flags.iter().any(|x| *x == "help") {
1085         describe_debug_flags();
1086         return true;
1087     }
1088 
1089     let cg_flags = matches.opt_strs("C");
1090     if cg_flags.iter().any(|x| *x == "help") {
1091         describe_codegen_flags();
1092         return true;
1093     }
1094 
1095     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1096         handler.early_warn("the --no-stack-check flag is deprecated and does nothing");
1097     }
1098 
1099     if cg_flags.iter().any(|x| *x == "passes=list") {
1100         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1101         get_codegen_backend(handler, &None, backend_name).print_passes();
1102         return true;
1103     }
1104 
1105     false
1106 }
1107 
describe_debug_flags()1108 fn describe_debug_flags() {
1109     safe_println!("\nAvailable options:\n");
1110     print_flag_list("-Z", config::Z_OPTIONS);
1111 }
1112 
describe_codegen_flags()1113 fn describe_codegen_flags() {
1114     safe_println!("\nAvailable codegen options:\n");
1115     print_flag_list("-C", config::CG_OPTIONS);
1116 }
1117 
print_flag_list<T>( cmdline_opt: &str, flag_list: &[(&'static str, T, &'static str, &'static str)], )1118 fn print_flag_list<T>(
1119     cmdline_opt: &str,
1120     flag_list: &[(&'static str, T, &'static str, &'static str)],
1121 ) {
1122     let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
1123 
1124     for &(name, _, _, desc) in flag_list {
1125         safe_println!(
1126             "    {} {:>width$}=val -- {}",
1127             cmdline_opt,
1128             name.replace('_', "-"),
1129             desc,
1130             width = max_len
1131         );
1132     }
1133 }
1134 
1135 /// Process command line options. Emits messages as appropriate. If compilation
1136 /// should continue, returns a getopts::Matches object parsed from args,
1137 /// otherwise returns `None`.
1138 ///
1139 /// The compiler's handling of options is a little complicated as it ties into
1140 /// our stability story. The current intention of each compiler option is to
1141 /// have one of two modes:
1142 ///
1143 /// 1. An option is stable and can be used everywhere.
1144 /// 2. An option is unstable, and can only be used on nightly.
1145 ///
1146 /// Like unstable library and language features, however, unstable options have
1147 /// always required a form of "opt in" to indicate that you're using them. This
1148 /// provides the easy ability to scan a code base to check to see if anything
1149 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1150 ///
1151 /// All options behind `-Z` are considered unstable by default. Other top-level
1152 /// options can also be considered unstable, and they were unlocked through the
1153 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1154 /// instability in both cases, though.
1155 ///
1156 /// So with all that in mind, the comments below have some more detail about the
1157 /// contortions done here to get things to work out correctly.
handle_options(handler: &EarlyErrorHandler, args: &[String]) -> Option<getopts::Matches>1158 pub fn handle_options(handler: &EarlyErrorHandler, args: &[String]) -> Option<getopts::Matches> {
1159     if args.is_empty() {
1160         // user did not write `-v` nor `-Z unstable-options`, so do not
1161         // include that extra information.
1162         let nightly_build =
1163             rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
1164         usage(false, false, nightly_build);
1165         return None;
1166     }
1167 
1168     // Parse with *all* options defined in the compiler, we don't worry about
1169     // option stability here we just want to parse as much as possible.
1170     let mut options = getopts::Options::new();
1171     for option in config::rustc_optgroups() {
1172         (option.apply)(&mut options);
1173     }
1174     let matches = options.parse(args).unwrap_or_else(|e| {
1175         let msg = match e {
1176             getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1177                 .iter()
1178                 .map(|&(name, ..)| ('C', name))
1179                 .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1180                 .find(|&(_, name)| *opt == name.replace('_', "-"))
1181                 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1182             _ => None,
1183         };
1184         handler.early_error(msg.unwrap_or_else(|| e.to_string()));
1185     });
1186 
1187     // For all options we just parsed, we check a few aspects:
1188     //
1189     // * If the option is stable, we're all good
1190     // * If the option wasn't passed, we're all good
1191     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1192     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1193     //   this option that was passed.
1194     // * If we're a nightly compiler, then unstable options are now unlocked, so
1195     //   we're good to go.
1196     // * Otherwise, if we're an unstable option then we generate an error
1197     //   (unstable option being used on stable)
1198     nightly_options::check_nightly_options(handler, &matches, &config::rustc_optgroups());
1199 
1200     if matches.opt_present("h") || matches.opt_present("help") {
1201         // Only show unstable options in --help if we accept unstable options.
1202         let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1203         let nightly_build = nightly_options::match_is_nightly_build(&matches);
1204         usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1205         return None;
1206     }
1207 
1208     if describe_flag_categories(handler, &matches) {
1209         return None;
1210     }
1211 
1212     if matches.opt_present("version") {
1213         version!(handler, "rustc", &matches);
1214         return None;
1215     }
1216 
1217     Some(matches)
1218 }
1219 
parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec>1220 fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1221     match &sess.io.input {
1222         Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1223         Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1224             name.clone(),
1225             input.clone(),
1226             &sess.parse_sess,
1227         ),
1228     }
1229 }
1230 
1231 /// Gets a list of extra command-line flags provided by the user, as strings.
1232 ///
1233 /// This function is used during ICEs to show more information useful for
1234 /// debugging, since some ICEs only happens with non-default compiler flags
1235 /// (and the users don't always report them).
extra_compiler_flags() -> Option<(Vec<String>, bool)>1236 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1237     let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
1238 
1239     let mut result = Vec::new();
1240     let mut excluded_cargo_defaults = false;
1241     while let Some(arg) = args.next() {
1242         if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
1243             let content = if arg.len() == a.len() {
1244                 // A space-separated option, like `-C incremental=foo` or `--crate-type rlib`
1245                 match args.next() {
1246                     Some(arg) => arg.to_string(),
1247                     None => continue,
1248                 }
1249             } else if arg.get(a.len()..a.len() + 1) == Some("=") {
1250                 // An equals option, like `--crate-type=rlib`
1251                 arg[a.len() + 1..].to_string()
1252             } else {
1253                 // A non-space option, like `-Cincremental=foo`
1254                 arg[a.len()..].to_string()
1255             };
1256             let option = content.split_once('=').map(|s| s.0).unwrap_or(&content);
1257             if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| option == *exc) {
1258                 excluded_cargo_defaults = true;
1259             } else {
1260                 result.push(a.to_string());
1261                 match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) {
1262                     Some(s) => result.push(format!("{s}=[REDACTED]")),
1263                     None => result.push(content),
1264                 }
1265             }
1266         }
1267     }
1268 
1269     if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1270 }
1271 
1272 /// Runs a closure and catches unwinds triggered by fatal errors.
1273 ///
1274 /// The compiler currently unwinds with a special sentinel value to abort
1275 /// compilation on fatal errors. This function catches that sentinel and turns
1276 /// the panic into a `Result` instead.
catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed>1277 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed> {
1278     catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1279         if value.is::<rustc_errors::FatalErrorMarker>() {
1280             #[allow(deprecated)]
1281             ErrorGuaranteed::unchecked_claim_error_was_emitted()
1282         } else {
1283             panic::resume_unwind(value);
1284         }
1285     })
1286 }
1287 
1288 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1289 /// that also computes the exit code.
catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i321290 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1291     let result = catch_fatal_errors(f).and_then(|result| result);
1292     match result {
1293         Ok(()) => EXIT_SUCCESS,
1294         Err(_) => EXIT_FAILURE,
1295     }
1296 }
1297 
1298 /// Stores the default panic hook, from before [`install_ice_hook`] was called.
1299 static DEFAULT_HOOK: OnceLock<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1300     OnceLock::new();
1301 
1302 /// Installs a panic hook that will print the ICE message on unexpected panics.
1303 ///
1304 /// The hook is intended to be useable even by external tools. You can pass a custom
1305 /// `bug_report_url`, or report arbitrary info in `extra_info`. Note that `extra_info` is called in
1306 /// a context where *the thread is currently panicking*, so it must not panic or the process will
1307 /// abort.
1308 ///
1309 /// If you have no extra info to report, pass the empty closure `|_| ()` as the argument to
1310 /// extra_info.
1311 ///
1312 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
install_ice_hook(bug_report_url: &'static str, extra_info: fn(&Handler))1313 pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&Handler)) {
1314     // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1315     // full backtraces. When a compiler ICE happens, we want to gather
1316     // as much information as possible to present in the issue opened
1317     // by the user. Compiler developers and other rustc users can
1318     // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1319     // (e.g. `RUST_BACKTRACE=1`)
1320     if std::env::var("RUST_BACKTRACE").is_err() {
1321         std::env::set_var("RUST_BACKTRACE", "full");
1322     }
1323 
1324     let default_hook = DEFAULT_HOOK.get_or_init(panic::take_hook);
1325 
1326     panic::set_hook(Box::new(move |info| {
1327         // If the error was caused by a broken pipe then this is not a bug.
1328         // Write the error and return immediately. See #98700.
1329         #[cfg(windows)]
1330         if let Some(msg) = info.payload().downcast_ref::<String>() {
1331             if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)") {
1332                 // the error code is already going to be reported when the panic unwinds up the stack
1333                 let handler = EarlyErrorHandler::new(ErrorOutputType::default());
1334                 let _ = handler.early_error_no_abort(msg.clone());
1335                 return;
1336             }
1337         };
1338 
1339         // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1340         // Don't do this for delayed bugs, which already emit their own more useful backtrace.
1341         if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1342             (*default_hook)(info);
1343 
1344             // Separate the output with an empty line
1345             eprintln!();
1346         }
1347 
1348         // Print the ICE message
1349         report_ice(info, bug_report_url, extra_info);
1350     }));
1351 }
1352 
1353 /// Prints the ICE message, including query stack, but without backtrace.
1354 ///
1355 /// The message will point the user at `bug_report_url` to report the ICE.
1356 ///
1357 /// When `install_ice_hook` is called, this function will be called as the panic
1358 /// hook.
report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str, extra_info: fn(&Handler))1359 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str, extra_info: fn(&Handler)) {
1360     let fallback_bundle =
1361         rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1362     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1363         rustc_errors::ColorConfig::Auto,
1364         None,
1365         None,
1366         fallback_bundle,
1367         false,
1368         false,
1369         None,
1370         false,
1371         false,
1372         TerminalUrl::No,
1373     ));
1374     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1375 
1376     // a .span_bug or .bug call has already printed what
1377     // it wants to print.
1378     if !info.payload().is::<rustc_errors::ExplicitBug>()
1379         && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1380     {
1381         handler.emit_err(session_diagnostics::Ice);
1382     }
1383 
1384     handler.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1385     handler.emit_note(session_diagnostics::IceVersion {
1386         version: util::version_str!().unwrap_or("unknown_version"),
1387         triple: config::host_triple(),
1388     });
1389 
1390     if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1391         handler.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1392         if excluded_cargo_defaults {
1393             handler.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1394         }
1395     }
1396 
1397     // If backtraces are enabled, also print the query stack
1398     let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1399 
1400     let num_frames = if backtrace { None } else { Some(2) };
1401 
1402     interface::try_print_query_stack(&handler, num_frames);
1403 
1404     // We don't trust this callback not to panic itself, so run it at the end after we're sure we've
1405     // printed all the relevant info.
1406     extra_info(&handler);
1407 
1408     #[cfg(windows)]
1409     if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1410         // Trigger a debugger if we crashed during bootstrap
1411         unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1412     }
1413 }
1414 
1415 /// This allows tools to enable rust logging without having to magically match rustc's
1416 /// tracing crate version.
init_rustc_env_logger(handler: &EarlyErrorHandler)1417 pub fn init_rustc_env_logger(handler: &EarlyErrorHandler) {
1418     init_env_logger(handler, "RUSTC_LOG");
1419 }
1420 
1421 /// This allows tools to enable rust logging without having to magically match rustc's
1422 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1423 /// other than `RUSTC_LOG`.
init_env_logger(handler: &EarlyErrorHandler, env: &str)1424 pub fn init_env_logger(handler: &EarlyErrorHandler, env: &str) {
1425     if let Err(error) = rustc_log::init_env_logger(env) {
1426         handler.early_error(error.to_string());
1427     }
1428 }
1429 
1430 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1431 mod signal_handler {
1432     extern "C" {
backtrace_symbols_fd( buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int, )1433         fn backtrace_symbols_fd(
1434             buffer: *const *mut libc::c_void,
1435             size: libc::c_int,
1436             fd: libc::c_int,
1437         );
1438     }
1439 
print_stack_trace(_: libc::c_int)1440     extern "C" fn print_stack_trace(_: libc::c_int) {
1441         const MAX_FRAMES: usize = 256;
1442         static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1443             [std::ptr::null_mut(); MAX_FRAMES];
1444         unsafe {
1445             let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1446             if depth == 0 {
1447                 return;
1448             }
1449             backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1450         }
1451     }
1452 
1453     /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1454     /// process, print a stack trace and then exit.
install()1455     pub(super) fn install() {
1456         unsafe {
1457             const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1458             let mut alt_stack: libc::stack_t = std::mem::zeroed();
1459             alt_stack.ss_sp =
1460                 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1461                     as *mut libc::c_void;
1462             alt_stack.ss_size = ALT_STACK_SIZE;
1463             libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1464 
1465             let mut sa: libc::sigaction = std::mem::zeroed();
1466             sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1467             sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1468             libc::sigemptyset(&mut sa.sa_mask);
1469             libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1470         }
1471     }
1472 }
1473 
1474 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1475 mod signal_handler {
install()1476     pub(super) fn install() {}
1477 }
1478 
main() -> !1479 pub fn main() -> ! {
1480     let start_time = Instant::now();
1481     let start_rss = get_resident_set_size();
1482 
1483     let handler = EarlyErrorHandler::new(ErrorOutputType::default());
1484 
1485     init_rustc_env_logger(&handler);
1486     signal_handler::install();
1487     let mut callbacks = TimePassesCallbacks::default();
1488     install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1489     let exit_code = catch_with_exit_code(|| {
1490         let args = env::args_os()
1491             .enumerate()
1492             .map(|(i, arg)| {
1493                 arg.into_string().unwrap_or_else(|arg| {
1494                     handler.early_error(format!("argument {i} is not valid Unicode: {arg:?}"))
1495                 })
1496             })
1497             .collect::<Vec<_>>();
1498         RunCompiler::new(&args, &mut callbacks).run()
1499     });
1500 
1501     if let Some(format) = callbacks.time_passes {
1502         let end_rss = get_resident_set_size();
1503         print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1504     }
1505 
1506     process::exit(exit_code)
1507 }
1508