//! This API is completely unstable and subject to change.
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
-#![feature(nll)]
+#![feature(is_terminal)]
#![feature(once_cell)]
+#![feature(decl_macro)]
#![recursion_limit = "256"]
+#![allow(rustc::potential_query_instability)]
+#![deny(rustc::untranslatable_diagnostic)]
+#![deny(rustc::diagnostic_outside_of_impl)]
#[macro_use]
extern crate tracing;
pub extern crate rustc_plugin_impl as plugin;
use rustc_ast as ast;
-use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults};
-use rustc_data_structures::profiling::print_time_passes_entry;
+use rustc_codegen_ssa::{traits::CodegenBackend, CodegenErrors, CodegenResults};
+use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
use rustc_data_structures::sync::SeqCst;
use rustc_errors::registry::{InvalidErrorCode, Registry};
-use rustc_errors::{ErrorReported, PResult};
-use rustc_feature::{find_gated_cfg, UnstableFeatures};
+use rustc_errors::{ErrorGuaranteed, PResult};
+use rustc_feature::find_gated_cfg;
use rustc_hir::def_id::LOCAL_CRATE;
-use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend};
+use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
use rustc_interface::{interface, Queries};
use rustc_lint::LintStore;
use rustc_metadata::locator;
-use rustc_middle::middle::cstore::MetadataLoader;
-use rustc_middle::ty::TyCtxt;
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
-use rustc_serialize::json::{self, ToJson};
-use rustc_session::config::nightly_options;
+use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS};
use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
+use rustc_session::cstore::MetadataLoader;
use rustc_session::getopts;
use rustc_session::lint::{Lint, LintId};
-use rustc_session::{config, DiagnosticOutput, Session};
-use rustc_session::{early_error, early_warn};
+use rustc_session::{config, Session};
+use rustc_session::{early_error, early_error_no_abort, early_warn};
use rustc_span::source_map::{FileLoader, FileName};
use rustc_span::symbol::sym;
+use rustc_target::json::ToJson;
use std::borrow::Cow;
use std::cmp::max;
-use std::default::Default;
use std::env;
use std::ffi::OsString;
use std::fs;
-use std::io::{self, Read, Write};
-use std::lazy::SyncLazy;
-use std::mem;
+use std::io::{self, IsTerminal, Read, Write};
use std::panic::{self, catch_unwind};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
use std::str;
+use std::sync::LazyLock;
use std::time::Instant;
-mod args;
+pub mod args;
pub mod pretty;
+mod session_diagnostics;
+
+use crate::session_diagnostics::{
+ RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
+ RLinkWrongFileType, RlinkNotAFile, RlinkUnableToRead,
+};
/// Exit status code used for successful compilation and help output.
pub const EXIT_SUCCESS: i32 = 0;
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
-const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
+const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
-pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T {
+pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
match result {
Err(..) => {
sess.abort_if_errors();
}
impl Callbacks for TimePassesCallbacks {
+ // JUSTIFICATION: the session doesn't exist at this point.
+ #[allow(rustc::bad_opt_access)]
fn config(&mut self, config: &mut interface::Config) {
- // If a --prints=... option has been given, we don't print the "total"
- // time because it will mess up the --prints output. See #64339.
- self.time_passes = config.opts.prints.is_empty()
- && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time);
+ // If a --print=... option has been given, we don't print the "total"
+ // time because it will mess up the --print output. See #64339.
+ //
+ self.time_passes = config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes;
config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
}
}
pub fn diagnostics_registry() -> Registry {
- Registry::new(&rustc_error_codes::DIAGNOSTICS)
+ Registry::new(rustc_error_codes::DIAGNOSTICS)
+}
+
+/// This is the primary entry point for rustc.
+pub struct RunCompiler<'a, 'b> {
+ at_args: &'a [String],
+ callbacks: &'b 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>>,
}
-// Parse args and run the compiler. This is the primary entry point for rustc.
-// The FileLoader provides a way to load files from sources other than the file system.
-pub fn run_compiler(
+impl<'a, 'b> RunCompiler<'a, 'b> {
+ pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
+ Self { at_args, callbacks, file_loader: None, make_codegen_backend: None }
+ }
+
+ /// Set a custom codegen backend.
+ ///
+ /// Has no uses within this repository, but is used by bjorn3 for "the
+ /// hotswapping branch of cg_clif" for "setting the codegen backend from a
+ /// custom driver where the custom codegen backend has arbitrary data."
+ /// (See #102759.)
+ pub fn set_make_codegen_backend(
+ &mut self,
+ make_codegen_backend: Option<
+ Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
+ >,
+ ) -> &mut Self {
+ self.make_codegen_backend = make_codegen_backend;
+ self
+ }
+
+ /// Load files from sources other than the file system.
+ ///
+ /// Has no uses within this repository, but may be used in the future by
+ /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
+ /// running rustc without having to save". (See #102759.)
+ pub fn set_file_loader(
+ &mut self,
+ file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
+ ) -> &mut Self {
+ self.file_loader = file_loader;
+ self
+ }
+
+ /// Parse args and run the compiler.
+ pub fn run(self) -> interface::Result<()> {
+ run_compiler(self.at_args, self.callbacks, self.file_loader, self.make_codegen_backend)
+ }
+}
+
+fn run_compiler(
at_args: &[String],
callbacks: &mut (dyn Callbacks + Send),
file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
- emitter: Option<Box<dyn Write + Send>>,
make_codegen_backend: Option<
Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
>,
) -> interface::Result<()> {
- let mut args = Vec::new();
- for arg in at_args {
- match args::arg_expand(arg.clone()) {
- Ok(arg) => args.extend(arg),
- Err(err) => early_error(
- ErrorOutputType::default(),
- &format!("Failed to load argument file: {}", err),
- ),
- }
- }
- let diagnostic_output =
- emitter.map(|emitter| DiagnosticOutput::Raw(emitter)).unwrap_or(DiagnosticOutput::Default);
- let matches = match handle_options(&args) {
- Some(matches) => matches,
- None => return Ok(()),
- };
+ let args = args::arg_expand_all(at_args);
- let sopts = config::build_session_options(&matches);
- let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
+ let Some(matches) = handle_options(&args) else { return Ok(()) };
- // We wrap `make_codegen_backend` in another `Option` such that `dummy_config` can take
- // ownership of it when necessary, while also allowing the non-dummy config to take ownership
- // when `dummy_config` is not used.
- let mut make_codegen_backend = Some(make_codegen_backend);
-
- let mut dummy_config = |sopts, cfg, diagnostic_output| {
- let mut config = interface::Config {
- opts: sopts,
- crate_cfg: cfg,
- input: Input::File(PathBuf::new()),
- input_path: None,
- output_file: None,
- output_dir: None,
- file_loader: None,
- diagnostic_output,
- stderr: None,
- crate_name: None,
- lint_caps: Default::default(),
- register_lints: None,
- override_queries: None,
- make_codegen_backend: make_codegen_backend.take().unwrap(),
- registry: diagnostics_registry(),
- };
- callbacks.config(&mut config);
- config
- };
+ let sopts = config::build_session_options(&matches);
if let Some(ref code) = matches.opt_str("explain") {
handle_explain(diagnostics_registry(), code, sopts.error_format);
return Ok(());
}
+ let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
+ let check_cfg = interface::parse_check_cfg(matches.opt_strs("check-cfg"));
let (odir, ofile) = make_output(&matches);
- let (input, input_file_path, input_err) = match make_input(&matches.free) {
- Some(v) => v,
- None => match matches.free.len() {
+ let mut config = interface::Config {
+ opts: sopts,
+ crate_cfg: cfg,
+ crate_check_cfg: check_cfg,
+ input: Input::File(PathBuf::new()),
+ output_file: ofile,
+ output_dir: odir,
+ file_loader,
+ lint_caps: Default::default(),
+ parse_sess_created: None,
+ register_lints: None,
+ override_queries: None,
+ make_codegen_backend,
+ registry: diagnostics_registry(),
+ };
+
+ if !tracing::dispatcher::has_been_set() {
+ init_rustc_env_logger_with_backtrace_option(&config.opts.unstable_opts.log_backtrace);
+ }
+
+ match make_input(config.opts.error_format, &matches.free) {
+ Err(reported) => return Err(reported),
+ Ok(Some(input)) => {
+ config.input = input;
+
+ callbacks.config(&mut config);
+ }
+ Ok(None) => match matches.free.len() {
0 => {
- let config = dummy_config(sopts, cfg, diagnostic_output);
+ callbacks.config(&mut config);
interface::run_compiler(config, |compiler| {
let sopts = &compiler.session().opts;
if sopts.describe_lints {
- let lint_store = rustc_lint::new_lint_store(
- sopts.debugging_opts.no_interleave_lints,
- compiler.session().unstable_options(),
- );
- describe_lints(compiler.session(), &lint_store, false);
+ let mut lint_store =
+ rustc_lint::new_lint_store(compiler.session().enable_internal_lints());
+ let registered_lints =
+ if let Some(register_lints) = compiler.register_lints() {
+ register_lints(compiler.session(), &mut lint_store);
+ true
+ } else {
+ false
+ };
+ describe_lints(compiler.session(), &lint_store, registered_lints);
return;
}
- let should_stop = RustcDefaultCalls::print_crate_info(
- &***compiler.codegen_backend(),
- compiler.session(),
- None,
- &odir,
- &ofile,
- );
+ let should_stop =
+ print_crate_info(&***compiler.codegen_backend(), compiler.session(), false);
if should_stop == Compilation::Stop {
return;
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error(
- sopts.error_format,
+ config.opts.error_format,
&format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1],
},
};
- if let Some(err) = input_err {
- // Immediately stop compilation if there was an issue reading
- // the input (for example if the input stream is not UTF-8).
- interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| {
- compiler.session().err(&err.to_string());
- });
- return Err(ErrorReported);
- }
-
- let mut config = interface::Config {
- opts: sopts,
- crate_cfg: cfg,
- input,
- input_path: input_file_path,
- output_file: ofile,
- output_dir: odir,
- file_loader,
- diagnostic_output,
- stderr: None,
- crate_name: None,
- lint_caps: Default::default(),
- register_lints: None,
- override_queries: None,
- make_codegen_backend: make_codegen_backend.unwrap(),
- registry: diagnostics_registry(),
- };
-
- callbacks.config(&mut config);
-
interface::run_compiler(config, |compiler| {
let sess = compiler.session();
- let should_stop = RustcDefaultCalls::print_crate_info(
- &***compiler.codegen_backend(),
- sess,
- Some(compiler.input()),
- compiler.output_dir(),
- compiler.output_file(),
- )
- .and_then(|| {
- RustcDefaultCalls::list_metadata(
- sess,
- &*compiler.codegen_backend().metadata_loader(),
- &matches,
- compiler.input(),
- )
- })
- .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
+ let should_stop = print_crate_info(&***compiler.codegen_backend(), sess, true)
+ .and_then(|| list_metadata(sess, &*compiler.codegen_backend().metadata_loader()))
+ .and_then(|| try_process_rlink(sess, compiler));
if should_stop == Compilation::Stop {
return sess.compile_status();
if let Some(ppm) = &sess.opts.pretty {
if ppm.needs_ast_map() {
- queries.global_ctxt()?.peek_mut().enter(|tcx| {
- let expanded_crate = queries.expansion()?.take().0;
- pretty::print_after_hir_lowering(
- tcx,
- compiler.input(),
- &expanded_crate,
- *ppm,
- compiler.output_file().as_ref().map(|p| &**p),
- );
+ let expanded_crate = queries.expansion()?.borrow().0.clone();
+ queries.global_ctxt()?.enter(|tcx| {
+ pretty::print_after_hir_lowering(tcx, &*expanded_crate, *ppm);
Ok(())
})?;
} else {
- let krate = queries.parse()?.take();
- pretty::print_after_parsing(
- sess,
- &compiler.input(),
- &krate,
- *ppm,
- compiler.output_file().as_ref().map(|p| &**p),
- );
+ let krate = queries.parse()?.steal();
+ pretty::print_after_parsing(sess, &krate, *ppm);
}
trace!("finished pretty-printing");
return early_exit();
return early_exit();
}
- if sess.opts.debugging_opts.parse_only
- || sess.opts.debugging_opts.show_span.is_some()
- || sess.opts.debugging_opts.ast_json_noexpand
- {
+ if sess.opts.unstable_opts.parse_only || sess.opts.unstable_opts.show_span.is_some() {
return early_exit();
}
{
- let (_, lint_store) = &*queries.register_plugins()?.peek();
+ let plugins = queries.register_plugins()?;
+ let (_, lint_store) = &*plugins.borrow();
// Lint plugins are registered; now we can process command line flags.
if sess.opts.describe_lints {
- describe_lints(&sess, &lint_store, true);
+ describe_lints(sess, lint_store, true);
return early_exit();
}
}
- queries.expansion()?;
+ queries.global_ctxt()?;
if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
return early_exit();
}
- queries.prepare_outputs()?;
-
if sess.opts.output_types.contains_key(&OutputType::DepInfo)
&& sess.opts.output_types.len() == 1
{
return early_exit();
}
- queries.global_ctxt()?;
-
- // Drop AST after creating GlobalCtxt to free memory
- {
- let _timer = sess.prof.generic_activity("drop_ast");
- mem::drop(queries.expansion()?.take());
- }
-
- if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json {
+ if sess.opts.unstable_opts.no_analysis {
return early_exit();
}
- if sess.opts.debugging_opts.save_analysis {
- let crate_name = queries.crate_name()?.peek().clone();
- queries.global_ctxt()?.peek_mut().enter(|tcx| {
- let result = tcx.analysis(LOCAL_CRATE);
-
+ queries.global_ctxt()?.enter(|tcx| {
+ let result = tcx.analysis(());
+ if sess.opts.unstable_opts.save_analysis {
+ let crate_name = tcx.crate_name(LOCAL_CRATE);
sess.time("save_analysis", || {
save::process_crate(
tcx,
- &crate_name,
- &compiler.input(),
+ crate_name,
+ &sess.io.input,
None,
- DumpHandler::new(
- compiler.output_dir().as_ref().map(|p| &**p),
- &crate_name,
- ),
+ DumpHandler::new(sess.io.output_dir.as_deref(), crate_name),
)
});
-
- result
- })?;
- }
-
- queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
+ }
+ result
+ })?;
if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
return early_exit();
queries.ongoing_codegen()?;
- if sess.opts.debugging_opts.print_type_sizes {
+ if sess.opts.unstable_opts.print_type_sizes {
sess.code_stats.print_type_sizes();
}
linker.link()?
}
- if sess.opts.debugging_opts.perf_stats {
+ if sess.opts.unstable_opts.perf_stats {
sess.print_perf_stats();
}
- if sess.print_fuel_crate.is_some() {
+ if sess.opts.unstable_opts.print_fuel.is_some() {
eprintln!(
"Fuel used by {}: {}",
- sess.print_fuel_crate.as_ref().unwrap(),
+ sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
sess.print_fuel.load(SeqCst)
);
}
})
}
-#[cfg(unix)]
-pub fn set_sigpipe_handler() {
- unsafe {
- // Set the SIGPIPE signal handler, so that an EPIPE
- // will cause rustc to terminate, as expected.
- assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
- }
-}
-
-#[cfg(windows)]
-pub fn set_sigpipe_handler() {}
-
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
}
// Extract input (string or file and optional path) from matches.
-fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> {
+fn make_input(
+ error_format: ErrorOutputType,
+ free_matches: &[String],
+) -> Result<Option<Input>, ErrorGuaranteed> {
if free_matches.len() == 1 {
let ifile = &free_matches[0];
if ifile == "-" {
let mut src = String::new();
- let err = if io::stdin().read_to_string(&mut src).is_err() {
- Some(io::Error::new(
- io::ErrorKind::InvalidData,
+ if io::stdin().read_to_string(&mut src).is_err() {
+ // Immediately stop compilation if there was an issue reading
+ // the input (for example if the input stream is not UTF-8).
+ let reported = early_error_no_abort(
+ error_format,
"couldn't read from stdin, as it did not contain valid UTF-8",
- ))
- } else {
- None
- };
+ );
+ return Err(reported);
+ }
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
"when UNSTABLE_RUSTDOC_TEST_PATH is set \
let line = isize::from_str_radix(&line, 10)
.expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
- return Some((Input::Str { name: file_name, input: src }, None, err));
+ Ok(Some(Input::Str { name: file_name, input: src }))
+ } else {
+ Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src }))
}
- Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err))
} else {
- Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None))
+ Ok(Some(Input::File(PathBuf::from(ifile))))
}
} else {
- None
+ Ok(None)
}
}
-// Whether to stop or continue compilation.
+/// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
}
}
-/// CompilerCalls instance for a regular rustc build.
-#[derive(Copy, Clone)]
-pub struct RustcDefaultCalls;
-
-// FIXME remove these and use winapi 0.3 instead
-// Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
-#[cfg(unix)]
-fn stdout_isatty() -> bool {
- unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
-}
-
-#[cfg(windows)]
-fn stdout_isatty() -> bool {
- use winapi::um::consoleapi::GetConsoleMode;
- use winapi::um::processenv::GetStdHandle;
- use winapi::um::winbase::STD_OUTPUT_HANDLE;
-
- unsafe {
- let handle = GetStdHandle(STD_OUTPUT_HANDLE);
- let mut out = 0;
- GetConsoleMode(handle, &mut out) != 0
- }
-}
-
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
+ let upper_cased_code = code.to_ascii_uppercase();
let normalised =
- if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) };
+ if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") };
match registry.try_find_description(&normalised) {
Ok(Some(description)) => {
let mut is_in_code_block = false;
}
text.push('\n');
}
- if stdout_isatty() {
+ if io::stdout().is_terminal() {
show_content_with_pager(&text);
} else {
- print!("{}", text);
+ print!("{text}");
}
}
Ok(None) => {
- early_error(output, &format!("no extended information for {}", code));
+ early_error(output, &format!("no extended information for {code}"));
}
Err(InvalidErrorCode) => {
- early_error(output, &format!("{} is not a valid error code", code));
+ early_error(output, &format!("{code} is not a valid error code"));
}
}
}
-fn show_content_with_pager(content: &String) {
+fn show_content_with_pager(content: &str) {
let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
});
// If pager fails for whatever reason, we should still print the content
// to standard output
if fallback_to_println {
- print!("{}", content);
+ print!("{content}");
}
}
-impl RustcDefaultCalls {
- fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> {
- if let Input::File(file) = compiler.input() {
+pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
+ if sess.opts.unstable_opts.link_only {
+ if let Input::File(file) = &sess.io.input {
// FIXME: #![crate_type] and #![crate_name] support not implemented yet
- let attrs = vec![];
- sess.init_crate_types(collect_crate_types(sess, &attrs));
- let outputs = compiler.build_output_filenames(&sess, &attrs);
- let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| {
- sess.fatal(&format!("failed to read rlink file: {}", err));
- });
- let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| {
- sess.fatal(&format!("failed to decode rlink: {}", err));
+ sess.init_crate_types(collect_crate_types(sess, &[]));
+ let outputs = compiler.build_output_filenames(sess, &[]);
+ let rlink_data = fs::read(file).unwrap_or_else(|err| {
+ sess.emit_fatal(RlinkUnableToRead { err });
});
- compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs)
- } else {
- sess.fatal("rlink must be a file")
- }
- }
-
- pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
- if sess.opts.debugging_opts.link_only {
- let result = RustcDefaultCalls::process_rlink(sess, compiler);
+ let codegen_results = match CodegenResults::deserialize_rlink(rlink_data) {
+ Ok(codegen) => codegen,
+ Err(err) => {
+ match err {
+ CodegenErrors::WrongFileType => sess.emit_fatal(RLinkWrongFileType),
+ CodegenErrors::EmptyVersionNumber => {
+ sess.emit_fatal(RLinkEmptyVersionNumber)
+ }
+ CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
+ sess.emit_fatal(RLinkEncodingVersionMismatch {
+ version_array,
+ rlink_version,
+ })
+ }
+ CodegenErrors::RustcVersionMismatch { rustc_version, current_version } => {
+ sess.emit_fatal(RLinkRustcVersionMismatch {
+ rustc_version,
+ current_version,
+ })
+ }
+ };
+ }
+ };
+ let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
abort_on_err(result, sess);
- Compilation::Stop
} else {
- Compilation::Continue
+ sess.emit_fatal(RlinkNotAFile {})
}
+ Compilation::Stop
+ } else {
+ Compilation::Continue
}
+}
- pub fn list_metadata(
- sess: &Session,
- metadata_loader: &dyn MetadataLoader,
- matches: &getopts::Matches,
- input: &Input,
- ) -> Compilation {
- let r = matches.opt_strs("Z");
- if r.iter().any(|s| *s == "ls") {
- match *input {
- Input::File(ref ifile) => {
- let path = &(*ifile);
- let mut v = Vec::new();
- locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v)
- .unwrap();
- println!("{}", String::from_utf8(v).unwrap());
- }
- Input::Str { .. } => {
- early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
- }
+pub fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) -> Compilation {
+ if sess.opts.unstable_opts.ls {
+ match sess.io.input {
+ Input::File(ref ifile) => {
+ let path = &(*ifile);
+ let mut v = Vec::new();
+ locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
+ println!("{}", String::from_utf8(v).unwrap());
+ }
+ Input::Str { .. } => {
+ early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
}
- return Compilation::Stop;
}
+ return Compilation::Stop;
+ }
- Compilation::Continue
+ Compilation::Continue
+}
+
+fn print_crate_info(
+ codegen_backend: &dyn CodegenBackend,
+ sess: &Session,
+ parse_attrs: bool,
+) -> Compilation {
+ use rustc_session::config::PrintRequest::*;
+ // NativeStaticLibs and LinkArgs are special - printed during linking
+ // (empty iterator returns true)
+ if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
+ return Compilation::Continue;
}
- fn print_crate_info(
- codegen_backend: &dyn CodegenBackend,
- sess: &Session,
- input: Option<&Input>,
- odir: &Option<PathBuf>,
- ofile: &Option<PathBuf>,
- ) -> Compilation {
- use rustc_session::config::PrintRequest::*;
- // PrintRequest::NativeStaticLibs is special - printed during linking
- // (empty iterator returns true)
- if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
- return Compilation::Continue;
+ let attrs = if parse_attrs {
+ let result = parse_crate_attrs(sess);
+ match result {
+ Ok(attrs) => Some(attrs),
+ Err(mut parse_error) => {
+ parse_error.emit();
+ return Compilation::Stop;
+ }
}
-
- let attrs = match input {
- None => None,
- Some(input) => {
- let result = parse_crate_attrs(sess, input);
- match result {
- Ok(attrs) => Some(attrs),
- Err(mut parse_error) => {
- parse_error.emit();
- return Compilation::Stop;
- }
- }
+ } else {
+ None
+ };
+ for req in &sess.opts.prints {
+ match *req {
+ TargetList => {
+ let mut targets = rustc_target::spec::TARGETS.to_vec();
+ targets.sort_unstable();
+ println!("{}", targets.join("\n"));
}
- };
- for req in &sess.opts.prints {
- match *req {
- TargetList => {
- let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
- targets.sort();
- println!("{}", targets.join("\n"));
+ Sysroot => println!("{}", sess.sysroot.display()),
+ TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
+ TargetSpec => {
+ println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
+ }
+ FileNames | CrateName => {
+ let attrs = attrs.as_ref().unwrap();
+ let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
+ let id = rustc_session::output::find_crate_name(sess, attrs);
+ if *req == PrintRequest::CrateName {
+ println!("{id}");
+ continue;
}
- Sysroot => println!("{}", sess.sysroot.display()),
- TargetLibdir => println!(
- "{}",
- sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display()
- ),
- TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
- FileNames | CrateName => {
- let input = input.unwrap_or_else(|| {
- early_error(ErrorOutputType::default(), "no input file provided")
- });
- let attrs = attrs.as_ref().unwrap();
- let t_outputs = rustc_interface::util::build_output_filenames(
- input, odir, ofile, attrs, sess,
- );
- let id = rustc_session::output::find_crate_name(sess, attrs, input);
- if *req == PrintRequest::CrateName {
- println!("{}", id);
- continue;
- }
- let crate_types = collect_crate_types(sess, attrs);
- for &style in &crate_types {
- let fname =
- rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
- println!("{}", fname.file_name().unwrap().to_string_lossy());
- }
+ let crate_types = collect_crate_types(sess, attrs);
+ for &style in &crate_types {
+ let fname =
+ rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
+ println!("{}", fname.file_name().unwrap().to_string_lossy());
}
- Cfg => {
- let allow_unstable_cfg =
- UnstableFeatures::from_environment().is_nightly_build();
-
- let mut cfgs = sess
- .parse_sess
- .config
- .iter()
- .filter_map(|&(name, value)| {
- // Note that crt-static is a specially recognized cfg
- // directive that's printed out here as part of
- // rust-lang/rust#37406, but in general the
- // `target_feature` cfg is gated under
- // rust-lang/rust#29717. For now this is just
- // specifically allowing the crt-static cfg and that's
- // it, this is intended to get into Cargo and then go
- // through to build scripts.
- if (name != sym::target_feature || value != Some(sym::crt_dash_static))
- && !allow_unstable_cfg
- && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
- {
- return None;
- }
-
- if let Some(value) = value {
- Some(format!("{}=\"{}\"", name, value))
- } else {
- Some(name.to_string())
- }
- })
- .collect::<Vec<String>>();
-
- cfgs.sort();
- for cfg in cfgs {
- println!("{}", cfg);
- }
+ }
+ Cfg => {
+ let mut cfgs = sess
+ .parse_sess
+ .config
+ .iter()
+ .filter_map(|&(name, value)| {
+ // Note that crt-static is a specially recognized cfg
+ // directive that's printed out here as part of
+ // rust-lang/rust#37406, but in general the
+ // `target_feature` cfg is gated under
+ // rust-lang/rust#29717. For now this is just
+ // specifically allowing the crt-static cfg and that's
+ // it, this is intended to get into Cargo and then go
+ // through to build scripts.
+ if (name != sym::target_feature || value != Some(sym::crt_dash_static))
+ && !sess.is_nightly_build()
+ && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
+ {
+ return None;
+ }
+
+ if let Some(value) = value {
+ Some(format!("{name}=\"{value}\""))
+ } else {
+ Some(name.to_string())
+ }
+ })
+ .collect::<Vec<String>>();
+
+ cfgs.sort();
+ for cfg in cfgs {
+ println!("{cfg}");
}
- RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
- codegen_backend.print(*req, sess);
+ }
+ CallingConventions => {
+ let mut calling_conventions = rustc_target::spec::abi::all_names();
+ calling_conventions.sort_unstable();
+ println!("{}", calling_conventions.join("\n"));
+ }
+ RelocationModels
+ | CodeModels
+ | TlsModels
+ | TargetCPUs
+ | StackProtectorStrategies
+ | TargetFeatures => {
+ codegen_backend.print(*req, sess);
+ }
+ // Any output here interferes with Cargo's parsing of other printed output
+ NativeStaticLibs => {}
+ LinkArgs => {}
+ SplitDebuginfo => {
+ use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
+
+ for split in &[Off, Packed, Unpacked] {
+ let stable = sess.target.options.supported_split_debuginfo.contains(split);
+ let unstable_ok = sess.unstable_options();
+ if stable || unstable_ok {
+ println!("{split}");
+ }
}
- // Any output here interferes with Cargo's parsing of other printed output
- PrintRequest::NativeStaticLibs => {}
}
}
- Compilation::Stop
}
+ Compilation::Stop
}
-/// Returns a version string such as "0.12.0-dev".
-fn release_str() -> Option<&'static str> {
- option_env!("CFG_RELEASE")
-}
-
-/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
-fn commit_hash_str() -> Option<&'static str> {
- option_env!("CFG_VER_HASH")
-}
-
-/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
-fn commit_date_str() -> Option<&'static str> {
- option_env!("CFG_VER_DATE")
+/// Prints version information
+///
+/// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
+pub macro version($binary: literal, $matches: expr) {
+ fn unw(x: Option<&str>) -> &str {
+ x.unwrap_or("unknown")
+ }
+ $crate::version_at_macro_invocation(
+ $binary,
+ $matches,
+ unw(option_env!("CFG_VERSION")),
+ unw(option_env!("CFG_VER_HASH")),
+ unw(option_env!("CFG_VER_DATE")),
+ unw(option_env!("CFG_RELEASE")),
+ )
}
-/// Prints version information
-pub fn version(binary: &str, matches: &getopts::Matches) {
+#[doc(hidden)] // use the macro instead
+pub fn version_at_macro_invocation(
+ binary: &str,
+ matches: &getopts::Matches,
+ version: &str,
+ commit_hash: &str,
+ commit_date: &str,
+ release: &str,
+) {
let verbose = matches.opt_present("verbose");
- println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
+ println!("{binary} {version}");
if verbose {
- fn unw(x: Option<&str>) -> &str {
- x.unwrap_or("unknown")
- }
- println!("binary: {}", binary);
- println!("commit-hash: {}", unw(commit_hash_str()));
- println!("commit-date: {}", unw(commit_date_str()));
+ println!("binary: {binary}");
+ println!("commit-hash: {commit_hash}");
+ println!("commit-date: {commit_date}");
println!("host: {}", config::host_triple());
- println!("release: {}", unw(release_str()));
- get_builtin_codegen_backend("llvm")().print_version();
+ println!("release: {release}");
+
+ let debug_flags = matches.opt_strs("Z");
+ let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
+ get_codegen_backend(&None, backend_name).print_version();
}
}
-fn usage(verbose: bool, include_unstable_options: bool) {
+fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
let mut options = getopts::Options::new();
for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
(option.apply)(&mut options);
}
let message = "Usage: rustc [OPTIONS] INPUT";
- let nightly_help = if nightly_options::is_nightly_build() {
+ let nightly_help = if nightly_build {
"\n -Z help Print unstable compiler options"
} else {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
- let at_path = if verbose && nightly_options::is_nightly_build() {
+ let at_path = if verbose {
" @path Read newline separated options from `path`\n"
} else {
""
);
}
-fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
+/// Write to stdout lint command options, together with a list of all available lints
+pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
println!(
"
Available lint options:
let builtin = sort_lints(sess, builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) =
- lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p);
+ lint_store.get_lint_groups().partition(|&(.., p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
};
println!("Lint checks provided by rustc:\n");
- println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
- println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
+ println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
+ println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
for lint in lints {
- let name = lint.name_lower().replace("_", "-");
- println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc);
+ let name = lint.name_lower().replace('_', "-");
+ println!(
+ " {} {:7.7} {}",
+ padded(&name),
+ lint.default_level(sess.edition()).as_str(),
+ lint.desc
+ );
}
println!("\n");
};
};
println!("Lint groups provided by rustc:\n");
- println!(" {} {}", padded("name"), "sub-lints");
- println!(" {} {}", padded("----"), "---------");
- println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings");
- let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
+ let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
+ println!(" {} sub-lints", padded("name"));
+ println!(" {} ---------", padded("----"));
+
+ if all_warnings {
+ println!(" {} all lints that are set to issue warnings", padded("warnings"));
+ }
+
for (name, to) in lints {
- let name = name.to_lowercase().replace("_", "-");
+ let name = name.to_lowercase().replace('_', "-");
let desc = to
.into_iter()
- .map(|x| x.to_string().replace("_", "-"))
+ .map(|x| x.to_string().replace('_', "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded(&name), desc);
println!("\n");
};
- print_lint_groups(builtin_groups);
+ print_lint_groups(builtin_groups, true);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
- println!(
- "Compiler plugins can provide additional lints and lint groups. To see a \
- listing of these, re-run `rustc -W help` with a crate filename."
- );
+ println!("Lint tools like Clippy can provide additional lints and lint groups.");
}
(false, ..) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
- print_lint_groups(plugin_groups);
+ print_lint_groups(plugin_groups, false);
}
}
}
fn describe_debug_flags() {
println!("\nAvailable options:\n");
- print_flag_list("-Z", config::DB_OPTIONS);
+ print_flag_list("-Z", config::Z_OPTIONS);
}
fn describe_codegen_flags() {
print_flag_list("-C", config::CG_OPTIONS);
}
-fn print_flag_list<T>(
+pub fn print_flag_list<T>(
cmdline_opt: &str,
flag_list: &[(&'static str, T, &'static str, &'static str)],
) {
println!(
" {} {:>width$}=val -- {}",
cmdline_opt,
- name.replace("_", "-"),
+ name.replace('_', "-"),
desc,
width = max_len
);
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
- usage(false, false);
+ let nightly_build =
+ rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
+ usage(false, false, nightly_build);
return None;
}
for option in config::rustc_optgroups() {
(option.apply)(&mut options);
}
- let matches = options
- .parse(args)
- .unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string()));
+ let matches = options.parse(args).unwrap_or_else(|e| {
+ let msg = match e {
+ getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
+ .iter()
+ .map(|&(name, ..)| ('C', name))
+ .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
+ .find(|&(_, name)| *opt == name.replace('_', "-"))
+ .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
+ _ => None,
+ };
+ early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
+ });
// For all options we just parsed, we check a few aspects:
//
if matches.opt_present("h") || matches.opt_present("help") {
// Only show unstable options in --help if we accept unstable options.
- usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches));
+ let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
+ let nightly_build = nightly_options::match_is_nightly_build(&matches);
+ usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
return None;
}
let wall = matches.opt_strs("W");
if wall.iter().any(|x| *x == "all") {
print_wall_help();
- return None;
+ rustc_errors::FatalError.raise();
}
// Don't handle -W help here, because we might first load plugins.
- let r = matches.opt_strs("Z");
- if r.iter().any(|x| *x == "help") {
+ let debug_flags = matches.opt_strs("Z");
+ if debug_flags.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
}
if cg_flags.iter().any(|x| *x == "passes=list") {
- get_builtin_codegen_backend("llvm")().print_passes();
+ let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
+ get_codegen_backend(&None, backend_name).print_passes();
return None;
}
if matches.opt_present("version") {
- version("rustc", &matches);
+ version!("rustc", &matches);
return None;
}
Some(matches)
}
-fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
- match input {
+fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
+ match &sess.io.input {
Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
name.clone(),
/// debugging, since some ICEs only happens with non-default compiler flags
/// (and the users don't always report them).
fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
- let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>();
-
- // Avoid printing help because of empty args. This can suggest the compiler
- // itself is not the program root (consider RLS).
- if args.len() < 2 {
- return None;
- }
+ let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
- let matches = handle_options(&args)?;
let mut result = Vec::new();
let mut excluded_cargo_defaults = false;
- for flag in ICE_REPORT_COMPILER_FLAGS {
- let prefix = if flag.len() == 1 { "-" } else { "--" };
-
- for content in &matches.opt_strs(flag) {
- // Split always returns the first element
- let name = if let Some(first) = content.split('=').next() { first } else { &content };
-
- let content =
- if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content };
-
- if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) {
- result.push(format!("{}{} {}", prefix, flag, content));
+ while let Some(arg) = args.next() {
+ if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
+ let content = if arg.len() == a.len() {
+ // A space-separated option, like `-C incremental=foo` or `--crate-type rlib`
+ match args.next() {
+ Some(arg) => arg.to_string(),
+ None => continue,
+ }
+ } else if arg.get(a.len()..a.len() + 1) == Some("=") {
+ // An equals option, like `--crate-type=rlib`
+ arg[a.len() + 1..].to_string()
} else {
+ // A non-space option, like `-Cincremental=foo`
+ arg[a.len()..].to_string()
+ };
+ let option = content.split_once('=').map(|s| s.0).unwrap_or(&content);
+ if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| option == *exc) {
excluded_cargo_defaults = true;
+ } else {
+ result.push(a.to_string());
+ match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) {
+ Some(s) => result.push(format!("{s}=[REDACTED]")),
+ None => result.push(content),
+ }
}
}
}
/// The compiler currently unwinds with a special sentinel value to abort
/// compilation on fatal errors. This function catches that sentinel and turns
/// the panic into a `Result` instead.
-pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> {
+pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed> {
catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
if value.is::<rustc_errors::FatalErrorMarker>() {
- ErrorReported
+ ErrorGuaranteed::unchecked_claim_error_was_emitted()
} else {
panic::resume_unwind(value);
}
}
}
-static DEFAULT_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
- SyncLazy::new(|| {
+static DEFAULT_HOOK: LazyLock<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
+ LazyLock::new(|| {
let hook = panic::take_hook();
- panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL)));
+ panic::set_hook(Box::new(|info| {
+ // If the error was caused by a broken pipe then this is not a bug.
+ // Write the error and return immediately. See #98700.
+ #[cfg(windows)]
+ if let Some(msg) = info.payload().downcast_ref::<String>() {
+ if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
+ {
+ early_error_no_abort(ErrorOutputType::default(), &msg);
+ return;
+ }
+ };
+
+ // Invoke the default handler, which prints the actual panic message and optionally a backtrace
+ // Don't do this for delayed bugs, which already emit their own more useful backtrace.
+ if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
+ (*DEFAULT_HOOK)(info);
+
+ // Separate the output with an empty line
+ eprintln!();
+ }
+
+ // Print the ICE message
+ report_ice(info, BUG_REPORT_URL);
+ }));
hook
});
-/// Prints the ICE message, including backtrace and query stack.
+/// Prints the ICE message, including query stack, but without backtrace.
///
/// The message will point the user at `bug_report_url` to report the ICE.
///
/// When `install_ice_hook` is called, this function will be called as the panic
/// hook.
pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
- // Invoke the default handler, which prints the actual panic message and optionally a backtrace
- (*DEFAULT_HOOK)(info);
-
- // Separate the output with an empty line
- eprintln!();
-
+ let fallback_bundle =
+ rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
+ None,
+ fallback_bundle,
false,
false,
None,
false,
+ false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a .span_bug or .bug call has already printed what
// it wants to print.
- if !info.payload().is::<rustc_errors::ExplicitBug>() {
- let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
- handler.emit_diagnostic(&d);
+ if !info.payload().is::<rustc_errors::ExplicitBug>()
+ && !info.payload().is::<rustc_errors::DelayedBugPanic>()
+ {
+ let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
+ handler.emit_diagnostic(&mut d);
}
let mut xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
- format!("we would appreciate a bug report: {}", bug_report_url).into(),
+ format!("we would appreciate a bug report: {bug_report_url}").into(),
format!(
"rustc {} running on {}",
- option_env!("CFG_VERSION").unwrap_or("unknown_version"),
+ util::version_str!().unwrap_or("unknown_version"),
config::host_triple()
)
.into(),
}
for note in &xs {
- handler.note_without_error(¬e);
+ handler.note_without_error(note.as_ref());
}
// If backtraces are enabled, also print the query stack
- let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
+ let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
- if backtrace {
- TyCtxt::try_print_query_stack(&handler);
- }
+ let num_frames = if backtrace { None } else { Some(2) };
+
+ interface::try_print_query_stack(&handler, num_frames);
#[cfg(windows)]
unsafe {
///
/// A custom rustc driver can skip calling this to set up a custom ICE hook.
pub fn install_ice_hook() {
- SyncLazy::force(&DEFAULT_HOOK);
+ // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
+ // full backtraces. When a compiler ICE happens, we want to gather
+ // as much information as possible to present in the issue opened
+ // by the user. Compiler developers and other rustc users can
+ // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
+ // (e.g. `RUST_BACKTRACE=1`)
+ if std::env::var("RUST_BACKTRACE").is_err() {
+ std::env::set_var("RUST_BACKTRACE", "full");
+ }
+ LazyLock::force(&DEFAULT_HOOK);
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version.
pub fn init_rustc_env_logger() {
- init_env_logger("RUSTC_LOG")
+ init_rustc_env_logger_with_backtrace_option(&None);
+}
+
+/// This allows tools to enable rust logging without having to magically match rustc's
+/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to
+/// choose a target module you wish to show backtraces along with its logging.
+pub fn init_rustc_env_logger_with_backtrace_option(backtrace_target: &Option<String>) {
+ if let Err(error) = rustc_log::init_rustc_env_logger_with_backtrace_option(backtrace_target) {
+ early_error(ErrorOutputType::default(), &error.to_string());
+ }
}
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) {
- // Don't register a dispatcher if there's no filter to print anything
- match std::env::var(env) {
- Err(_) => return,
- Ok(s) if s.is_empty() => return,
- Ok(_) => {}
+ if let Err(error) = rustc_log::init_env_logger(env) {
+ early_error(ErrorOutputType::default(), &error.to_string());
+ }
+}
+
+#[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
+mod signal_handler {
+ extern "C" {
+ fn backtrace_symbols_fd(
+ buffer: *const *mut libc::c_void,
+ size: libc::c_int,
+ fd: libc::c_int,
+ );
+ }
+
+ extern "C" fn print_stack_trace(_: libc::c_int) {
+ const MAX_FRAMES: usize = 256;
+ static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
+ [std::ptr::null_mut(); MAX_FRAMES];
+ unsafe {
+ let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
+ if depth == 0 {
+ return;
+ }
+ backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
+ }
}
- let builder = tracing_subscriber::FmtSubscriber::builder();
- let builder = builder.with_env_filter(tracing_subscriber::EnvFilter::from_env(env));
+ /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
+ /// process, print a stack trace and then exit.
+ pub(super) fn install() {
+ unsafe {
+ const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
+ let mut alt_stack: libc::stack_t = std::mem::zeroed();
+ alt_stack.ss_sp =
+ std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
+ as *mut libc::c_void;
+ alt_stack.ss_size = ALT_STACK_SIZE;
+ libc::sigaltstack(&alt_stack, std::ptr::null_mut());
+
+ let mut sa: libc::sigaction = std::mem::zeroed();
+ sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
+ sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
+ libc::sigemptyset(&mut sa.sa_mask);
+ libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
+ }
+ }
+}
- builder.init()
+#[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
+mod signal_handler {
+ pub(super) fn install() {}
}
pub fn main() -> ! {
- let start = Instant::now();
- init_rustc_env_logger();
+ let start_time = Instant::now();
+ let start_rss = get_resident_set_size();
+ signal_handler::install();
let mut callbacks = TimePassesCallbacks::default();
install_ice_hook();
let exit_code = catch_with_exit_code(|| {
arg.into_string().unwrap_or_else(|arg| {
early_error(
ErrorOutputType::default(),
- &format!("Argument {} is not valid Unicode: {:?}", i, arg),
+ &format!("argument {i} is not valid Unicode: {arg:?}"),
)
})
})
.collect::<Vec<_>>();
- run_compiler(&args, &mut callbacks, None, None, None)
+ RunCompiler::new(&args, &mut callbacks).run()
});
- // The extra `\t` is necessary to align this label with the others.
- print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed());
+
+ if callbacks.time_passes {
+ let end_rss = get_resident_set_size();
+ print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
+ }
+
process::exit(exit_code)
}