Rename EarlyDiagCtxt methods to match DiagCtxt.

- `early_error_no_abort` -> `early_err`
- `early_error` -> `early_fatal`
- `early_struct_error` -> `early_struct_fatal`
This commit is contained in:
Nicholas Nethercote 2023-12-20 14:53:50 +11:00
parent 1f08bfa383
commit 3a1b8e643a
11 changed files with 92 additions and 93 deletions

View file

@ -179,7 +179,7 @@ pub(crate) fn compile_fn(
let early_dcx = rustc_session::EarlyDiagCtxt::new( let early_dcx = rustc_session::EarlyDiagCtxt::new(
rustc_session::config::ErrorOutputType::default(), rustc_session::config::ErrorOutputType::default(),
); );
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"backend implementation limit exceeded while compiling {name}", "backend implementation limit exceeded while compiling {name}",
name = codegened_func.symbol_name name = codegened_func.symbol_name
)); ));

View file

@ -28,7 +28,7 @@ pub fn arg_expand_all(early_dcx: &EarlyDiagCtxt, at_args: &[String]) -> Vec<Stri
for arg in at_args { for arg in at_args {
match arg_expand(arg.clone()) { match arg_expand(arg.clone()) {
Ok(arg) => args.extend(arg), Ok(arg) => args.extend(arg),
Err(err) => early_dcx.early_error(format!("Failed to load argument file: {err}")), Err(err) => early_dcx.early_fatal(format!("Failed to load argument file: {err}")),
} }
} }
args args

View file

@ -345,7 +345,7 @@ fn run_compiler(
Ok(None) => match matches.free.len() { Ok(None) => match matches.free.len() {
0 => false, // no input: we will exit early 0 => false, // no input: we will exit early
1 => panic!("make_input should have provided valid inputs"), 1 => panic!("make_input should have provided valid inputs"),
_ => default_early_dcx.early_error(format!( _ => default_early_dcx.early_fatal(format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)", "multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1], matches.free[0], matches.free[1],
)), )),
@ -376,7 +376,7 @@ fn run_compiler(
} }
if !has_input { if !has_input {
early_dcx.early_error("no input filename given"); // this is fatal early_dcx.early_fatal("no input filename given"); // this is fatal
} }
if !sess.opts.unstable_opts.ls.is_empty() { if !sess.opts.unstable_opts.ls.is_empty() {
@ -505,9 +505,8 @@ fn make_input(
if io::stdin().read_to_string(&mut src).is_err() { if io::stdin().read_to_string(&mut src).is_err() {
// Immediately stop compilation if there was an issue reading // Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8). // the input (for example if the input stream is not UTF-8).
let reported = early_dcx.early_error_no_abort( let reported = early_dcx
"couldn't read from stdin, as it did not contain valid UTF-8", .early_err("couldn't read from stdin, as it did not contain valid UTF-8");
);
return Err(reported); return Err(reported);
} }
if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") { if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
@ -567,7 +566,7 @@ fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, col
} }
} }
Err(InvalidErrorCode) => { Err(InvalidErrorCode) => {
early_dcx.early_error(format!("{code} is not a valid error code")); early_dcx.early_fatal(format!("{code} is not a valid error code"));
} }
} }
} }
@ -685,7 +684,7 @@ fn list_metadata(early_dcx: &EarlyDiagCtxt, sess: &Session, metadata_loader: &dy
safe_println!("{}", String::from_utf8(v).unwrap()); safe_println!("{}", String::from_utf8(v).unwrap());
} }
Input::Str { .. } => { Input::Str { .. } => {
early_dcx.early_error("cannot list metadata for stdin"); early_dcx.early_fatal("cannot list metadata for stdin");
} }
} }
} }
@ -839,7 +838,7 @@ fn print_crate_info(
println_info!("deployment_target={}", format!("{major}.{minor}")) println_info!("deployment_target={}", format!("{major}.{minor}"))
} else { } else {
early_dcx early_dcx
.early_error("only Apple targets currently support deployment version info") .early_fatal("only Apple targets currently support deployment version info")
} }
} }
} }
@ -1182,7 +1181,7 @@ pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<geto
.map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")), .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
_ => None, _ => None,
}; };
early_dcx.early_error(msg.unwrap_or_else(|| e.to_string())); early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
}); });
// For all options we just parsed, we check a few aspects: // For all options we just parsed, we check a few aspects:
@ -1333,7 +1332,7 @@ pub fn install_ice_hook(
{ {
// the error code is already going to be reported when the panic unwinds up the stack // the error code is already going to be reported when the panic unwinds up the stack
let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
let _ = early_dcx.early_error_no_abort(msg.clone()); let _ = early_dcx.early_err(msg.clone());
return; return;
} }
}; };
@ -1481,7 +1480,7 @@ pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
/// the values directly rather than having to set an environment variable. /// the values directly rather than having to set an environment variable.
pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) { pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
if let Err(error) = rustc_log::init_logger(cfg) { if let Err(error) = rustc_log::init_logger(cfg) {
early_dcx.early_error(error.to_string()); early_dcx.early_fatal(error.to_string());
} }
} }
@ -1500,7 +1499,7 @@ pub fn main() -> ! {
.enumerate() .enumerate()
.map(|(i, arg)| { .map(|(i, arg)| {
arg.into_string().unwrap_or_else(|arg| { arg.into_string().unwrap_or_else(|arg| {
early_dcx.early_error(format!("argument {i} is not valid Unicode: {arg:?}")) early_dcx.early_fatal(format!("argument {i} is not valid Unicode: {arg:?}"))
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View file

@ -347,7 +347,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
) { ) {
Ok(bundle) => bundle, Ok(bundle) => bundle,
Err(e) => { Err(e) => {
early_dcx.early_error(format!("failed to load fluent bundle: {e}")); early_dcx.early_fatal(format!("failed to load fluent bundle: {e}"));
} }
}; };

View file

@ -164,13 +164,13 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn { fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| { let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| {
let err = format!("couldn't load codegen backend {path:?}: {err}"); let err = format!("couldn't load codegen backend {path:?}: {err}");
early_dcx.early_error(err); early_dcx.early_fatal(err);
}); });
let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") } let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") }
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
let err = format!("couldn't load codegen backend: {e}"); let err = format!("couldn't load codegen backend: {e}");
early_dcx.early_error(err); early_dcx.early_fatal(err);
}); });
// Intentionally leak the dynamic library. We can't ever unload it // Intentionally leak the dynamic library. We can't ever unload it
@ -271,7 +271,7 @@ fn get_codegen_sysroot(
"failed to find a `codegen-backends` folder \ "failed to find a `codegen-backends` folder \
in the sysroot candidates:\n* {candidates}" in the sysroot candidates:\n* {candidates}"
); );
early_dcx.early_error(err); early_dcx.early_fatal(err);
}); });
info!("probing {} for a codegen backend", sysroot.display()); info!("probing {} for a codegen backend", sysroot.display());
@ -282,7 +282,7 @@ fn get_codegen_sysroot(
sysroot.display(), sysroot.display(),
e e
); );
early_dcx.early_error(err); early_dcx.early_fatal(err);
}); });
let mut file: Option<PathBuf> = None; let mut file: Option<PathBuf> = None;
@ -310,7 +310,7 @@ fn get_codegen_sysroot(
prev.display(), prev.display(),
path.display() path.display()
); );
early_dcx.early_error(err); early_dcx.early_fatal(err);
} }
file = Some(path.clone()); file = Some(path.clone());
} }
@ -319,7 +319,7 @@ fn get_codegen_sysroot(
Some(ref s) => load_backend_from_dylib(early_dcx, s), Some(ref s) => load_backend_from_dylib(early_dcx, s),
None => { None => {
let err = format!("unsupported builtin codegen backend `{backend_name}`"); let err = format!("unsupported builtin codegen backend `{backend_name}`");
early_dcx.early_error(err); early_dcx.early_fatal(err);
} }
} }
} }

View file

@ -1594,7 +1594,7 @@ pub(super) fn build_target_config(
|t| Ok((t, TargetWarnings::empty())), |t| Ok((t, TargetWarnings::empty())),
); );
let (target, target_warnings) = target_result.unwrap_or_else(|e| { let (target, target_warnings) = target_result.unwrap_or_else(|e| {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"Error loading target specification: {e}. \ "Error loading target specification: {e}. \
Run `rustc --print target-list` for a list of built-in targets" Run `rustc --print target-list` for a list of built-in targets"
)) ))
@ -1604,7 +1604,7 @@ pub(super) fn build_target_config(
} }
if !matches!(target.pointer_width, 16 | 32 | 64) { if !matches!(target.pointer_width, 16 | 32 | 64) {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"target specification was invalid: unrecognized target-pointer-width {}", "target specification was invalid: unrecognized target-pointer-width {}",
target.pointer_width target.pointer_width
)) ))
@ -1869,7 +1869,7 @@ pub fn get_cmd_lint_options(
let lint_cap = matches.opt_str("cap-lints").map(|cap| { let lint_cap = matches.opt_str("cap-lints").map(|cap| {
lint::Level::from_str(&cap) lint::Level::from_str(&cap)
.unwrap_or_else(|| early_dcx.early_error(format!("unknown lint level: `{cap}`"))) .unwrap_or_else(|| early_dcx.early_fatal(format!("unknown lint level: `{cap}`")))
}); });
(lint_opts, describe_lints, lint_cap) (lint_opts, describe_lints, lint_cap)
@ -1884,7 +1884,7 @@ pub fn parse_color(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Col
None => ColorConfig::Auto, None => ColorConfig::Auto,
Some(arg) => early_dcx.early_error(format!( Some(arg) => early_dcx.early_fatal(format!(
"argument for `--color` must be auto, \ "argument for `--color` must be auto, \
always or never (instead was `{arg}`)" always or never (instead was `{arg}`)"
)), )),
@ -1942,7 +1942,7 @@ pub fn parse_json(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Json
// won't actually be emitting any colors and anything colorized is // won't actually be emitting any colors and anything colorized is
// embedded in a diagnostic message anyway. // embedded in a diagnostic message anyway.
if matches.opt_str("color").is_some() { if matches.opt_str("color").is_some() {
early_dcx.early_error("cannot specify the `--color` option with `--json`"); early_dcx.early_fatal("cannot specify the `--color` option with `--json`");
} }
for sub_option in option.split(',') { for sub_option in option.split(',') {
@ -1953,7 +1953,7 @@ pub fn parse_json(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Json
"unused-externs" => json_unused_externs = JsonUnusedExterns::Loud, "unused-externs" => json_unused_externs = JsonUnusedExterns::Loud,
"unused-externs-silent" => json_unused_externs = JsonUnusedExterns::Silent, "unused-externs-silent" => json_unused_externs = JsonUnusedExterns::Silent,
"future-incompat" => json_future_incompat = true, "future-incompat" => json_future_incompat = true,
s => early_dcx.early_error(format!("unknown `--json` option `{s}`")), s => early_dcx.early_fatal(format!("unknown `--json` option `{s}`")),
} }
} }
} }
@ -1993,7 +1993,7 @@ pub fn parse_error_format(
early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::HumanReadable( early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::HumanReadable(
HumanReadableErrorType::Default(color), HumanReadableErrorType::Default(color),
)); ));
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"argument for `--error-format` must be `human`, `json` or \ "argument for `--error-format` must be `human`, `json` or \
`short` (instead was `{arg}`)" `short` (instead was `{arg}`)"
)) ))
@ -2010,7 +2010,7 @@ pub fn parse_error_format(
// `--error-format=json`. This means that `--json` is specified we // `--error-format=json`. This means that `--json` is specified we
// should actually be emitting JSON blobs. // should actually be emitting JSON blobs.
_ if !matches.opt_strs("json").is_empty() => { _ if !matches.opt_strs("json").is_empty() => {
early_dcx.early_error("using `--json` requires also using `--error-format=json`"); early_dcx.early_fatal("using `--json` requires also using `--error-format=json`");
} }
_ => {} _ => {}
@ -2022,7 +2022,7 @@ pub fn parse_error_format(
pub fn parse_crate_edition(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Edition { pub fn parse_crate_edition(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Edition {
let edition = match matches.opt_str("edition") { let edition = match matches.opt_str("edition") {
Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| { Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"argument for `--edition` must be one of: \ "argument for `--edition` must be one of: \
{EDITION_NAME_LIST}. (instead was `{arg}`)" {EDITION_NAME_LIST}. (instead was `{arg}`)"
)) ))
@ -2039,7 +2039,7 @@ pub fn parse_crate_edition(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches
} else { } else {
format!("edition {edition} is unstable and only available with -Z unstable-options") format!("edition {edition} is unstable and only available with -Z unstable-options")
}; };
early_dcx.early_error(msg) early_dcx.early_fatal(msg)
} }
edition edition
@ -2057,7 +2057,7 @@ fn check_error_format_stability(
pretty: false, pretty: false,
json_rendered, json_rendered,
}); });
early_dcx.early_error("`--error-format=pretty-json` is unstable"); early_dcx.early_fatal("`--error-format=pretty-json` is unstable");
} }
if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) = if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) =
error_format error_format
@ -2066,7 +2066,7 @@ fn check_error_format_stability(
pretty: false, pretty: false,
json_rendered, json_rendered,
}); });
early_dcx.early_error("`--error-format=human-annotate-rs` is unstable"); early_dcx.early_fatal("`--error-format=human-annotate-rs` is unstable");
} }
} }
} }
@ -2082,7 +2082,7 @@ fn parse_output_types(
for output_type in list.split(',') { for output_type in list.split(',') {
let (shorthand, path) = split_out_file_name(output_type); let (shorthand, path) = split_out_file_name(output_type);
let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| { let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"unknown emission type: `{shorthand}` - expected one of: {display}", "unknown emission type: `{shorthand}` - expected one of: {display}",
display = OutputType::shorthands_display(), display = OutputType::shorthands_display(),
)) ))
@ -2144,7 +2144,7 @@ fn should_override_cgus_and_disable_thinlto(
} }
if codegen_units == Some(0) { if codegen_units == Some(0) {
early_dcx.early_error("value for codegen units must be a positive non-zero integer"); early_dcx.early_fatal("value for codegen units must be a positive non-zero integer");
} }
(disable_local_thinlto, codegen_units) (disable_local_thinlto, codegen_units)
@ -2204,7 +2204,7 @@ fn collect_print_requests(
if unstable_opts.unstable_options { if unstable_opts.unstable_options {
PrintKind::TargetSpec PrintKind::TargetSpec
} else { } else {
early_dcx.early_error( early_dcx.early_fatal(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable the target-spec-json print option", enable the target-spec-json print option",
); );
@ -2214,7 +2214,7 @@ fn collect_print_requests(
if unstable_opts.unstable_options { if unstable_opts.unstable_options {
PrintKind::AllTargetSpecs PrintKind::AllTargetSpecs
} else { } else {
early_dcx.early_error( early_dcx.early_fatal(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable the all-target-specs-json print option", enable the all-target-specs-json print option",
); );
@ -2225,7 +2225,7 @@ fn collect_print_requests(
let prints = let prints =
PRINT_KINDS.iter().map(|(name, _)| format!("`{name}`")).collect::<Vec<_>>(); PRINT_KINDS.iter().map(|(name, _)| format!("`{name}`")).collect::<Vec<_>>();
let prints = prints.join(", "); let prints = prints.join(", ");
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"unknown print request `{req}`. Valid print requests are: {prints}" "unknown print request `{req}`. Valid print requests are: {prints}"
)); ));
} }
@ -2234,7 +2234,7 @@ fn collect_print_requests(
let out = out.unwrap_or(OutFileName::Stdout); let out = out.unwrap_or(OutFileName::Stdout);
if let OutFileName::Real(path) = &out { if let OutFileName::Real(path) = &out {
if !printed_paths.insert(path.clone()) { if !printed_paths.insert(path.clone()) {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"cannot print multiple outputs to the same path: {}", "cannot print multiple outputs to the same path: {}",
path.display(), path.display(),
)); ));
@ -2252,7 +2252,7 @@ pub fn parse_target_triple(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches
Some(target) if target.ends_with(".json") => { Some(target) if target.ends_with(".json") => {
let path = Path::new(&target); let path = Path::new(&target);
TargetTriple::from_path(path).unwrap_or_else(|_| { TargetTriple::from_path(path).unwrap_or_else(|_| {
early_dcx.early_error(format!("target file {path:?} does not exist")) early_dcx.early_fatal(format!("target file {path:?} does not exist"))
}) })
} }
Some(target) => TargetTriple::TargetTriple(target), Some(target) => TargetTriple::TargetTriple(target),
@ -2291,7 +2291,7 @@ fn parse_opt_level(
"s" => OptLevel::Size, "s" => OptLevel::Size,
"z" => OptLevel::SizeMin, "z" => OptLevel::SizeMin,
arg => { arg => {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"optimization level needs to be \ "optimization level needs to be \
between 0-3, s or z (instead was `{arg}`)" between 0-3, s or z (instead was `{arg}`)"
)); ));
@ -2321,7 +2321,7 @@ fn parse_assert_incr_state(
Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded), Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded),
Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded), Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded),
Some(s) => { Some(s) => {
early_dcx.early_error(format!("unexpected incremental state assertion value: {s}")) early_dcx.early_fatal(format!("unexpected incremental state assertion value: {s}"))
} }
None => None, None => None,
} }
@ -2348,11 +2348,11 @@ fn parse_native_lib_kind(
} else { } else {
", the `-Z unstable-options` flag must also be passed to use it" ", the `-Z unstable-options` flag must also be passed to use it"
}; };
early_dcx.early_error(format!("library kind `link-arg` is unstable{why}")) early_dcx.early_fatal(format!("library kind `link-arg` is unstable{why}"))
} }
NativeLibKind::LinkArg NativeLibKind::LinkArg
} }
_ => early_dcx.early_error(format!( _ => early_dcx.early_fatal(format!(
"unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg" "unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg"
)), )),
}; };
@ -2372,7 +2372,7 @@ fn parse_native_lib_modifiers(
for modifier in modifiers.split(',') { for modifier in modifiers.split(',') {
let (modifier, value) = match modifier.strip_prefix(['+', '-']) { let (modifier, value) = match modifier.strip_prefix(['+', '-']) {
Some(m) => (m, modifier.starts_with('+')), Some(m) => (m, modifier.starts_with('+')),
None => early_dcx.early_error( None => early_dcx.early_fatal(
"invalid linking modifier syntax, expected '+' or '-' prefix \ "invalid linking modifier syntax, expected '+' or '-' prefix \
before one of: bundle, verbatim, whole-archive, as-needed", before one of: bundle, verbatim, whole-archive, as-needed",
), ),
@ -2385,20 +2385,20 @@ fn parse_native_lib_modifiers(
} else { } else {
", the `-Z unstable-options` flag must also be passed to use it" ", the `-Z unstable-options` flag must also be passed to use it"
}; };
early_dcx.early_error(format!("linking modifier `{modifier}` is unstable{why}")) early_dcx.early_fatal(format!("linking modifier `{modifier}` is unstable{why}"))
} }
}; };
let assign_modifier = |dst: &mut Option<bool>| { let assign_modifier = |dst: &mut Option<bool>| {
if dst.is_some() { if dst.is_some() {
let msg = format!("multiple `{modifier}` modifiers in a single `-l` option"); let msg = format!("multiple `{modifier}` modifiers in a single `-l` option");
early_dcx.early_error(msg) early_dcx.early_fatal(msg)
} else { } else {
*dst = Some(value); *dst = Some(value);
} }
}; };
match (modifier, &mut kind) { match (modifier, &mut kind) {
("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle), ("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle),
("bundle", _) => early_dcx.early_error( ("bundle", _) => early_dcx.early_fatal(
"linking modifier `bundle` is only compatible with `static` linking kind", "linking modifier `bundle` is only compatible with `static` linking kind",
), ),
@ -2407,7 +2407,7 @@ fn parse_native_lib_modifiers(
("whole-archive", NativeLibKind::Static { whole_archive, .. }) => { ("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
assign_modifier(whole_archive) assign_modifier(whole_archive)
} }
("whole-archive", _) => early_dcx.early_error( ("whole-archive", _) => early_dcx.early_fatal(
"linking modifier `whole-archive` is only compatible with `static` linking kind", "linking modifier `whole-archive` is only compatible with `static` linking kind",
), ),
@ -2416,14 +2416,14 @@ fn parse_native_lib_modifiers(
report_unstable_modifier(); report_unstable_modifier();
assign_modifier(as_needed) assign_modifier(as_needed)
} }
("as-needed", _) => early_dcx.early_error( ("as-needed", _) => early_dcx.early_fatal(
"linking modifier `as-needed` is only compatible with \ "linking modifier `as-needed` is only compatible with \
`dylib` and `framework` linking kinds", `dylib` and `framework` linking kinds",
), ),
// Note: this error also excludes the case with empty modifier // Note: this error also excludes the case with empty modifier
// string, like `modifiers = ""`. // string, like `modifiers = ""`.
_ => early_dcx.early_error(format!( _ => early_dcx.early_fatal(format!(
"unknown linking modifier `{modifier}`, expected one \ "unknown linking modifier `{modifier}`, expected one \
of: bundle, verbatim, whole-archive, as-needed" of: bundle, verbatim, whole-archive, as-needed"
)), )),
@ -2457,7 +2457,7 @@ fn parse_libs(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<Nati
Some((name, new_name)) => (name.to_string(), Some(new_name.to_owned())), Some((name, new_name)) => (name.to_string(), Some(new_name.to_owned())),
}; };
if name.is_empty() { if name.is_empty() {
early_dcx.early_error("library name must not be empty"); early_dcx.early_fatal("library name must not be empty");
} }
NativeLib { name, new_name, kind, verbatim } NativeLib { name, new_name, kind, verbatim }
}) })
@ -2493,7 +2493,7 @@ pub fn parse_externs(
}; };
if !is_ascii_ident(&name) { if !is_ascii_ident(&name) {
let mut error = early_dcx.early_struct_error(format!( let mut error = early_dcx.early_struct_fatal(format!(
"crate name `{name}` passed to `--extern` is not a valid ASCII identifier" "crate name `{name}` passed to `--extern` is not a valid ASCII identifier"
)); ));
let adjusted_name = name.replace('-', "_"); let adjusted_name = name.replace('-', "_");
@ -2555,7 +2555,7 @@ pub fn parse_externs(
let mut force = false; let mut force = false;
if let Some(opts) = options { if let Some(opts) = options {
if !is_unstable_enabled { if !is_unstable_enabled {
early_dcx.early_error( early_dcx.early_fatal(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable `--extern` options", enable `--extern` options",
); );
@ -2567,14 +2567,14 @@ pub fn parse_externs(
if let ExternLocation::ExactPaths(_) = &entry.location { if let ExternLocation::ExactPaths(_) = &entry.location {
add_prelude = false; add_prelude = false;
} else { } else {
early_dcx.early_error( early_dcx.early_fatal(
"the `noprelude` --extern option requires a file path", "the `noprelude` --extern option requires a file path",
); );
} }
} }
"nounused" => nounused_dep = true, "nounused" => nounused_dep = true,
"force" => force = true, "force" => force = true,
_ => early_dcx.early_error(format!("unknown --extern option `{opt}`")), _ => early_dcx.early_fatal(format!("unknown --extern option `{opt}`")),
} }
} }
} }
@ -2602,7 +2602,7 @@ fn parse_remap_path_prefix(
.into_iter() .into_iter()
.map(|remap| match remap.rsplit_once('=') { .map(|remap| match remap.rsplit_once('=') {
None => { None => {
early_dcx.early_error("--remap-path-prefix must contain '=' between FROM and TO") early_dcx.early_fatal("--remap-path-prefix must contain '=' between FROM and TO")
} }
Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)), Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)),
}) })
@ -2627,7 +2627,7 @@ fn parse_logical_env(
if let Some((name, val)) = arg.split_once('=') { if let Some((name, val)) = arg.split_once('=') {
vars.insert(name.to_string(), val.to_string()); vars.insert(name.to_string(), val.to_string());
} else { } else {
early_dcx.early_error(format!("`--env`: specify value for variable `{arg}`")); early_dcx.early_fatal(format!("`--env`: specify value for variable `{arg}`"));
} }
} }
@ -2653,12 +2653,12 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
early_dcx.abort_if_error_and_set_error_format(error_format); early_dcx.abort_if_error_and_set_error_format(error_format);
let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_else(|_| { let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_else(|_| {
early_dcx.early_error("`--diagnostic-width` must be an positive integer"); early_dcx.early_fatal("`--diagnostic-width` must be an positive integer");
}); });
let unparsed_crate_types = matches.opt_strs("crate-type"); let unparsed_crate_types = matches.opt_strs("crate-type");
let crate_types = parse_crate_types_from_list(unparsed_crate_types) let crate_types = parse_crate_types_from_list(unparsed_crate_types)
.unwrap_or_else(|e| early_dcx.early_error(e)); .unwrap_or_else(|e| early_dcx.early_fatal(e));
let mut unstable_opts = UnstableOptions::build(early_dcx, matches); let mut unstable_opts = UnstableOptions::build(early_dcx, matches);
let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
@ -2666,7 +2666,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
check_error_format_stability(early_dcx, &unstable_opts, error_format, json_rendered); check_error_format_stability(early_dcx, &unstable_opts, error_format, json_rendered);
if !unstable_opts.unstable_options && json_unused_externs.is_enabled() { if !unstable_opts.unstable_options && json_unused_externs.is_enabled() {
early_dcx.early_error( early_dcx.early_fatal(
"the `-Z unstable-options` flag must also be passed to enable \ "the `-Z unstable-options` flag must also be passed to enable \
the flag `--json=unused-externs`", the flag `--json=unused-externs`",
); );
@ -2683,15 +2683,15 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
); );
if unstable_opts.threads == 0 { if unstable_opts.threads == 0 {
early_dcx.early_error("value for threads must be a positive non-zero integer"); early_dcx.early_fatal("value for threads must be a positive non-zero integer");
} }
let fuel = unstable_opts.fuel.is_some() || unstable_opts.print_fuel.is_some(); let fuel = unstable_opts.fuel.is_some() || unstable_opts.print_fuel.is_some();
if fuel && unstable_opts.threads > 1 { if fuel && unstable_opts.threads > 1 {
early_dcx.early_error("optimization fuel is incompatible with multiple threads"); early_dcx.early_fatal("optimization fuel is incompatible with multiple threads");
} }
if fuel && cg.incremental.is_some() { if fuel && cg.incremental.is_some() {
early_dcx.early_error("optimization fuel is incompatible with incremental compilation"); early_dcx.early_fatal("optimization fuel is incompatible with incremental compilation");
} }
let incremental = cg.incremental.as_ref().map(PathBuf::from); let incremental = cg.incremental.as_ref().map(PathBuf::from);
@ -2699,25 +2699,25 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
let assert_incr_state = parse_assert_incr_state(early_dcx, &unstable_opts.assert_incr_state); let assert_incr_state = parse_assert_incr_state(early_dcx, &unstable_opts.assert_incr_state);
if unstable_opts.profile && incremental.is_some() { if unstable_opts.profile && incremental.is_some() {
early_dcx.early_error("can't instrument with gcov profiling when compiling incrementally"); early_dcx.early_fatal("can't instrument with gcov profiling when compiling incrementally");
} }
if unstable_opts.profile { if unstable_opts.profile {
match codegen_units { match codegen_units {
Some(1) => {} Some(1) => {}
None => codegen_units = Some(1), None => codegen_units = Some(1),
Some(_) => early_dcx Some(_) => early_dcx
.early_error("can't instrument with gcov profiling with multiple codegen units"), .early_fatal("can't instrument with gcov profiling with multiple codegen units"),
} }
} }
if cg.profile_generate.enabled() && cg.profile_use.is_some() { if cg.profile_generate.enabled() && cg.profile_use.is_some() {
early_dcx.early_error("options `-C profile-generate` and `-C profile-use` are exclusive"); early_dcx.early_fatal("options `-C profile-generate` and `-C profile-use` are exclusive");
} }
if unstable_opts.profile_sample_use.is_some() if unstable_opts.profile_sample_use.is_some()
&& (cg.profile_generate.enabled() || cg.profile_use.is_some()) && (cg.profile_generate.enabled() || cg.profile_use.is_some())
{ {
early_dcx.early_error( early_dcx.early_fatal(
"option `-Z profile-sample-use` cannot be used with `-C profile-generate` or `-C profile-use`", "option `-Z profile-sample-use` cannot be used with `-C profile-generate` or `-C profile-use`",
); );
} }
@ -2730,7 +2730,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
// Unstable values: // Unstable values:
Some(SymbolManglingVersion::Legacy) => { Some(SymbolManglingVersion::Legacy) => {
if !unstable_opts.unstable_options { if !unstable_opts.unstable_options {
early_dcx.early_error( early_dcx.early_fatal(
"`-C symbol-mangling-version=legacy` requires `-Z unstable-options`", "`-C symbol-mangling-version=legacy` requires `-Z unstable-options`",
); );
} }
@ -2747,7 +2747,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
| InstrumentCoverage::ExceptUnusedFunctions | InstrumentCoverage::ExceptUnusedFunctions
| InstrumentCoverage::ExceptUnusedGenerics => { | InstrumentCoverage::ExceptUnusedGenerics => {
if !unstable_opts.unstable_options { if !unstable_opts.unstable_options {
early_dcx.early_error( early_dcx.early_fatal(
"`-C instrument-coverage=branch` and `-C instrument-coverage=except-*` \ "`-C instrument-coverage=branch` and `-C instrument-coverage=except-*` \
require `-Z unstable-options`", require `-Z unstable-options`",
); );
@ -2757,7 +2757,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
if cg.instrument_coverage != InstrumentCoverage::Off { if cg.instrument_coverage != InstrumentCoverage::Off {
if cg.profile_generate.enabled() || cg.profile_use.is_some() { if cg.profile_generate.enabled() || cg.profile_use.is_some() {
early_dcx.early_error( early_dcx.early_fatal(
"option `-C instrument-coverage` is not compatible with either `-C profile-use` \ "option `-C instrument-coverage` is not compatible with either `-C profile-use` \
or `-C profile-generate`", or `-C profile-generate`",
); );
@ -2787,7 +2787,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
match cg.lto { match cg.lto {
LtoCli::No | LtoCli::Unspecified => {} LtoCli::No | LtoCli::Unspecified => {}
LtoCli::Yes | LtoCli::NoParam | LtoCli::Thin | LtoCli::Fat => { LtoCli::Yes | LtoCli::NoParam | LtoCli::Thin | LtoCli::Fat => {
early_dcx.early_error("options `-C embed-bitcode=no` and `-C lto` are incompatible") early_dcx.early_fatal("options `-C embed-bitcode=no` and `-C lto` are incompatible")
} }
} }
} }
@ -2799,7 +2799,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
let uses_unstable_self_contained_option = let uses_unstable_self_contained_option =
cg.link_self_contained.are_unstable_variants_set(); cg.link_self_contained.are_unstable_variants_set();
if uses_unstable_self_contained_option { if uses_unstable_self_contained_option {
early_dcx.early_error( early_dcx.early_fatal(
"only `-C link-self-contained` values `y`/`yes`/`on`/`n`/`no`/`off` are stable, \ "only `-C link-self-contained` values `y`/`yes`/`on`/`n`/`no`/`off` are stable, \
the `-Z unstable-options` flag must also be passed to use the unstable values", the `-Z unstable-options` flag must also be passed to use the unstable values",
); );
@ -2807,7 +2807,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
if let Some(flavor) = cg.linker_flavor { if let Some(flavor) = cg.linker_flavor {
if flavor.is_unstable() { if flavor.is_unstable() {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"the linker flavor `{}` is unstable, the `-Z unstable-options` \ "the linker flavor `{}` is unstable, the `-Z unstable-options` \
flag must also be passed to use the unstable values", flag must also be passed to use the unstable values",
flavor.desc() flavor.desc()
@ -2824,7 +2824,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
.map(|c| c.as_str().unwrap()) .map(|c| c.as_str().unwrap())
.intersperse(", ") .intersperse(", ")
.collect(); .collect();
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"some `-C link-self-contained` components were both enabled and disabled: {names}" "some `-C link-self-contained` components were both enabled and disabled: {names}"
)); ));
} }
@ -2871,7 +2871,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
// query-dep-graph is required if dump-dep-graph is given #106736 // query-dep-graph is required if dump-dep-graph is given #106736
if unstable_opts.dump_dep_graph && !unstable_opts.query_dep_graph { if unstable_opts.dump_dep_graph && !unstable_opts.query_dep_graph {
early_dcx.early_error("can't dump dependency graph without `-Z query-dep-graph`"); early_dcx.early_fatal("can't dump dependency graph without `-Z query-dep-graph`");
} }
let logical_env = parse_logical_env(early_dcx, matches); let logical_env = parse_logical_env(early_dcx, matches);
@ -2905,7 +2905,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
}; };
let working_dir = std::env::current_dir().unwrap_or_else(|e| { let working_dir = std::env::current_dir().unwrap_or_else(|e| {
early_dcx.early_error(format!("Current directory is invalid: {e}")); early_dcx.early_fatal(format!("Current directory is invalid: {e}"));
}); });
let remap = file_path_mapping(remap_path_prefix.clone(), &unstable_opts); let remap = file_path_mapping(remap_path_prefix.clone(), &unstable_opts);
@ -2980,7 +2980,7 @@ fn parse_pretty(early_dcx: &EarlyDiagCtxt, unstable_opts: &UnstableOptions) -> O
"mir" => Mir, "mir" => Mir,
"stable-mir" => StableMir, "stable-mir" => StableMir,
"mir-cfg" => MirCFG, "mir-cfg" => MirCFG,
name => early_dcx.early_error(format!( name => early_dcx.early_fatal(format!(
"argument to `unpretty` must be one of `normal`, `identified`, \ "argument to `unpretty` must be one of `normal`, `identified`, \
`expanded`, `expanded,identified`, `expanded,hygiene`, \ `expanded`, `expanded,identified`, `expanded,hygiene`, \
`ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \ `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \
@ -3060,7 +3060,7 @@ pub mod nightly_options {
continue; continue;
} }
if opt.name != "Z" && !has_z_unstable_option { if opt.name != "Z" && !has_z_unstable_option {
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"the `-Z unstable-options` flag must also be passed to enable \ "the `-Z unstable-options` flag must also be passed to enable \
the flag `{}`", the flag `{}`",
opt.name opt.name
@ -3076,7 +3076,7 @@ pub mod nightly_options {
"the option `{}` is only accepted on the nightly compiler", "the option `{}` is only accepted on the nightly compiler",
opt.name opt.name
); );
let _ = early_dcx.early_error_no_abort(msg); let _ = early_dcx.early_err(msg);
} }
OptionStability::Stable => {} OptionStability::Stable => {}
} }
@ -3086,7 +3086,7 @@ pub mod nightly_options {
.early_help("consider switching to a nightly toolchain: `rustup default nightly`"); .early_help("consider switching to a nightly toolchain: `rustup default nightly`");
early_dcx.early_note("selecting a toolchain with `+toolchain` arguments require a rustup proxy; see <https://rust-lang.github.io/rustup/concepts/index.html>"); early_dcx.early_note("selecting a toolchain with `+toolchain` arguments require a rustup proxy; see <https://rust-lang.github.io/rustup/concepts/index.html>");
early_dcx.early_note("for more information about Rust's stability policy, see <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#unstable-features>"); early_dcx.early_note("for more information about Rust's stability policy, see <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#unstable-features>");
early_dcx.early_error(format!( early_dcx.early_fatal(format!(
"{} nightly option{} were parsed", "{} nightly option{} were parsed",
nightly_options_on_stable, nightly_options_on_stable,
if nightly_options_on_stable > 1 { "s" } else { "" } if nightly_options_on_stable > 1 { "s" } else { "" }

View file

@ -337,12 +337,12 @@ fn build_options<O: Default>(
Some((_, setter, type_desc, _)) => { Some((_, setter, type_desc, _)) => {
if !setter(&mut op, value) { if !setter(&mut op, value) {
match value { match value {
None => early_dcx.early_error( None => early_dcx.early_fatal(
format!( format!(
"{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)" "{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)"
), ),
), ),
Some(value) => early_dcx.early_error( Some(value) => early_dcx.early_fatal(
format!( format!(
"incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected" "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
), ),
@ -350,7 +350,7 @@ fn build_options<O: Default>(
} }
} }
} }
None => early_dcx.early_error(format!("unknown {outputname} option: `{key}`")), None => early_dcx.early_fatal(format!("unknown {outputname} option: `{key}`")),
} }
} }
return op; return op;

View file

@ -61,7 +61,7 @@ impl SearchPath {
(PathKind::All, path) (PathKind::All, path)
}; };
if path.is_empty() { if path.is_empty() {
early_dcx.early_error("empty search path given via `-L`"); early_dcx.early_fatal("empty search path given via `-L`");
} }
let dir = PathBuf::from(path); let dir = PathBuf::from(path);

View file

@ -1359,7 +1359,7 @@ pub fn build_session(
let target_cfg = config::build_target_config(&early_dcx, &sopts, target_override, &sysroot); let target_cfg = config::build_target_config(&early_dcx, &sopts, target_override, &sysroot);
let host_triple = TargetTriple::from_triple(config::host_triple()); let host_triple = TargetTriple::from_triple(config::host_triple());
let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| { let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
early_dcx.early_error(format!("Error loading host specification: {e}")) early_dcx.early_fatal(format!("Error loading host specification: {e}"))
}); });
for warning in target_warnings.warning_messages() { for warning in target_warnings.warning_messages() {
early_dcx.early_warn(warning) early_dcx.early_warn(warning)
@ -1734,19 +1734,19 @@ impl EarlyDiagCtxt {
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
#[must_use = "ErrorGuaranteed must be returned from `run_compiler` in order to exit with a non-zero status code"] #[must_use = "ErrorGuaranteed must be returned from `run_compiler` in order to exit with a non-zero status code"]
pub fn early_error_no_abort(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed { pub fn early_err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
self.dcx.struct_err(msg).emit() self.dcx.struct_err(msg).emit()
} }
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
pub fn early_error(&self, msg: impl Into<DiagnosticMessage>) -> ! { pub fn early_fatal(&self, msg: impl Into<DiagnosticMessage>) -> ! {
self.dcx.struct_fatal(msg).emit() self.dcx.struct_fatal(msg).emit()
} }
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
pub fn early_struct_error( pub fn early_struct_fatal(
&self, &self,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalAbort> { ) -> DiagnosticBuilder<'_, FatalAbort> {

View file

@ -403,7 +403,7 @@ impl Options {
&& !matches.opt_present("show-coverage") && !matches.opt_present("show-coverage")
&& !nightly_options::is_unstable_enabled(matches) && !nightly_options::is_unstable_enabled(matches)
{ {
early_dcx.early_error( early_dcx.early_fatal(
"the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)", "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
); );
} }

View file

@ -194,10 +194,10 @@ fn init_logging(early_dcx: &EarlyDiagCtxt) {
Ok("always") => true, Ok("always") => true,
Ok("never") => false, Ok("never") => false,
Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(), Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(),
Ok(value) => early_dcx.early_error(format!( Ok(value) => early_dcx.early_fatal(format!(
"invalid log color value '{value}': expected one of always, never, or auto", "invalid log color value '{value}': expected one of always, never, or auto",
)), )),
Err(VarError::NotUnicode(value)) => early_dcx.early_error(format!( Err(VarError::NotUnicode(value)) => early_dcx.early_fatal(format!(
"invalid log color value '{}': expected one of always, never, or auto", "invalid log color value '{}': expected one of always, never, or auto",
value.to_string_lossy() value.to_string_lossy()
)), )),
@ -727,7 +727,7 @@ fn main_args(
let matches = match options.parse(&args) { let matches = match options.parse(&args) {
Ok(m) => m, Ok(m) => m,
Err(err) => { Err(err) => {
early_dcx.early_error(err.to_string()); early_dcx.early_fatal(err.to_string());
} }
}; };