Rollup merge of #119538 - nnethercote:cleanup-errors-5, r=compiler-errors

Cleanup error handlers: round 5

More rustc_errors cleanups. A sequel to https://github.com/rust-lang/rust/pull/119171.

r? ````@compiler-errors````
This commit is contained in:
Michael Goulet 2024-01-05 10:57:21 -05:00 committed by GitHub
commit f361b591ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 369 additions and 464 deletions

View File

@ -725,8 +725,8 @@ impl AddToDiagnostic for StableFeature {
rustc_errors::SubdiagnosticMessage, rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage, ) -> rustc_errors::SubdiagnosticMessage,
{ {
diag.set_arg("name", self.name); diag.arg("name", self.name);
diag.set_arg("since", self.since); diag.arg("since", self.since);
diag.help(fluent::ast_passes_stable_since); diag.help(fluent::ast_passes_stable_since);
} }
} }

View File

@ -55,10 +55,10 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnknownMetaItem<'_> {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>(); let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::attr_unknown_meta_item); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::attr_unknown_meta_item);
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0541)); diag.code(error_code!(E0541));
diag.set_arg("item", self.item); diag.arg("item", self.item);
diag.set_arg("expected", expected.join(", ")); diag.arg("expected", expected.join(", "));
diag.span_label(self.span, fluent::attr_label); diag.span_label(self.span, fluent::attr_label);
diag diag
} }
@ -215,7 +215,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnsupportedLiteral {
} }
}, },
); );
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0565)); diag.code(error_code!(E0565));
if self.is_bytestr { if self.is_bytestr {
diag.span_suggestion( diag.span_suggestion(

View File

@ -454,7 +454,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for EnvNotDefinedWithUserMe
reason = "cannot translate user-provided messages" reason = "cannot translate user-provided messages"
)] )]
let mut diag = DiagnosticBuilder::new(dcx, level, self.msg_from_user.to_string()); let mut diag = DiagnosticBuilder::new(dcx, level, self.msg_from_user.to_string());
diag.set_span(self.span); diag.span(self.span);
diag diag
} }
} }
@ -618,7 +618,7 @@ impl AddToDiagnostic for FormatUnusedArg {
rustc_errors::SubdiagnosticMessage, rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage, ) -> rustc_errors::SubdiagnosticMessage,
{ {
diag.set_arg("named", self.named); diag.arg("named", self.named);
let msg = f(diag, crate::fluent_generated::builtin_macros_format_unused_arg.into()); let msg = f(diag, crate::fluent_generated::builtin_macros_format_unused_arg.into());
diag.span_label(self.span, msg); diag.span_label(self.span, msg);
} }
@ -808,7 +808,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for AsmClobberNoReg {
level, level,
crate::fluent_generated::builtin_macros_asm_clobber_no_reg, crate::fluent_generated::builtin_macros_asm_clobber_no_reg,
); );
diag.set_span(self.spans.clone()); diag.span(self.spans.clone());
// eager translation as `span_labels` takes `AsRef<str>` // eager translation as `span_labels` takes `AsRef<str>`
let lbl1 = dcx.eagerly_translate_to_string( let lbl1 = dcx.eagerly_translate_to_string(
crate::fluent_generated::builtin_macros_asm_clobber_abi, crate::fluent_generated::builtin_macros_asm_clobber_abi,

View File

@ -395,10 +395,10 @@ fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>)
// These were a warning before #92959 and need to continue being that to avoid breaking // These were a warning before #92959 and need to continue being that to avoid breaking
// stable user code (#94508). // stable user code (#94508).
Some(ast::ItemKind::MacCall(_)) => Level::Warning(None), Some(ast::ItemKind::MacCall(_)) => Level::Warning(None),
_ => Level::Error { lint: false }, _ => Level::Error,
}; };
let mut err = DiagnosticBuilder::<()>::new(dcx, level, msg); let mut err = DiagnosticBuilder::<()>::new(dcx, level, msg);
err.set_span(attr_sp); err.span(attr_sp);
if let Some(item) = item { if let Some(item) = item {
err.span_label( err.span_label(
item.span, item.span,

View File

@ -119,12 +119,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnabl
fluent::codegen_gcc_target_feature_disable_or_enable fluent::codegen_gcc_target_feature_disable_or_enable
); );
if let Some(span) = self.span { if let Some(span) = self.span {
diag.set_span(span); diag.span(span);
}; };
if let Some(missing_features) = self.missing_features { if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(missing_features); diag.subdiagnostic(missing_features);
} }
diag.set_arg("features", self.features.join(", ")); diag.arg("features", self.features.join(", "));
diag diag
} }
} }

View File

@ -416,7 +416,7 @@ fn report_inline_asm(
cookie = 0; cookie = 0;
} }
let level = match level { let level = match level {
llvm::DiagnosticLevel::Error => Level::Error { lint: false }, llvm::DiagnosticLevel::Error => Level::Error,
llvm::DiagnosticLevel::Warning => Level::Warning(None), llvm::DiagnosticLevel::Warning => Level::Warning(None),
llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note, llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
}; };

View File

@ -107,7 +107,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ParseTargetMachineConfig<'_
let mut diag = let mut diag =
DiagnosticBuilder::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config); DiagnosticBuilder::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config);
diag.set_arg("error", message); diag.arg("error", message);
diag diag
} }
} }
@ -130,12 +130,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnabl
fluent::codegen_llvm_target_feature_disable_or_enable, fluent::codegen_llvm_target_feature_disable_or_enable,
); );
if let Some(span) = self.span { if let Some(span) = self.span {
diag.set_span(span); diag.span(span);
}; };
if let Some(missing_features) = self.missing_features { if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(missing_features); diag.subdiagnostic(missing_features);
} }
diag.set_arg("features", self.features.join(", ")); diag.arg("features", self.features.join(", "));
diag diag
} }
} }
@ -205,8 +205,8 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> {
ParseBitcode => fluent::codegen_llvm_parse_bitcode_with_llvm_err, ParseBitcode => fluent::codegen_llvm_parse_bitcode_with_llvm_err,
}; };
let mut diag = self.0.into_diagnostic(dcx, level); let mut diag = self.0.into_diagnostic(dcx, level);
diag.set_primary_message(msg_with_llvm_err); diag.primary_message(msg_with_llvm_err);
diag.set_arg("llvm_err", self.1); diag.arg("llvm_err", self.1);
diag diag
} }
} }

View File

@ -1848,9 +1848,9 @@ impl SharedEmitterMain {
} }
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => { Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
let err_level = match level { let err_level = match level {
Level::Error { lint: false } => rustc_errors::Level::Error { lint: false }, Level::Error => Level::Error,
Level::Warning(_) => rustc_errors::Level::Warning(None), Level::Warning(_) => Level::Warning(None),
Level::Note => rustc_errors::Level::Note, Level::Note => Level::Note,
_ => bug!("Invalid inline asm diagnostic level"), _ => bug!("Invalid inline asm diagnostic level"),
}; };
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string(); let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
@ -1860,7 +1860,7 @@ impl SharedEmitterMain {
if cookie != 0 { if cookie != 0 {
let pos = BytePos::from_u32(cookie); let pos = BytePos::from_u32(cookie);
let span = Span::with_root_ctxt(pos, pos); let span = Span::with_root_ctxt(pos, pos);
err.set_span(span); err.span(span);
}; };
// Point to the generated assembly if it is available. // Point to the generated assembly if it is available.

View File

@ -244,30 +244,30 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::NamelessSection(_, offset) => { thorin::Error::NamelessSection(_, offset) => {
diag = build(fluent::codegen_ssa_thorin_section_without_name); diag = build(fluent::codegen_ssa_thorin_section_without_name);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::RelocationWithInvalidSymbol(section, offset) => { thorin::Error::RelocationWithInvalidSymbol(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol); diag = build(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol);
diag.set_arg("section", section); diag.arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MultipleRelocations(section, offset) => { thorin::Error::MultipleRelocations(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_multiple_relocations); diag = build(fluent::codegen_ssa_thorin_multiple_relocations);
diag.set_arg("section", section); diag.arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::UnsupportedRelocation(section, offset) => { thorin::Error::UnsupportedRelocation(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_unsupported_relocation); diag = build(fluent::codegen_ssa_thorin_unsupported_relocation);
diag.set_arg("section", section); diag.arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MissingDwoName(id) => { thorin::Error::MissingDwoName(id) => {
diag = build(fluent::codegen_ssa_thorin_missing_dwo_name); diag = build(fluent::codegen_ssa_thorin_missing_dwo_name);
diag.set_arg("id", format!("0x{id:08x}")); diag.arg("id", format!("0x{id:08x}"));
diag diag
} }
thorin::Error::NoCompilationUnits => { thorin::Error::NoCompilationUnits => {
@ -284,7 +284,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::MissingRequiredSection(section) => { thorin::Error::MissingRequiredSection(section) => {
diag = build(fluent::codegen_ssa_thorin_missing_required_section); diag = build(fluent::codegen_ssa_thorin_missing_required_section);
diag.set_arg("section", section); diag.arg("section", section);
diag diag
} }
thorin::Error::ParseUnitAbbreviations(_) => { thorin::Error::ParseUnitAbbreviations(_) => {
@ -305,34 +305,34 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::IncompatibleIndexVersion(section, format, actual) => { thorin::Error::IncompatibleIndexVersion(section, format, actual) => {
diag = build(fluent::codegen_ssa_thorin_incompatible_index_version); diag = build(fluent::codegen_ssa_thorin_incompatible_index_version);
diag.set_arg("section", section); diag.arg("section", section);
diag.set_arg("actual", actual); diag.arg("actual", actual);
diag.set_arg("format", format); diag.arg("format", format);
diag diag
} }
thorin::Error::OffsetAtIndex(_, index) => { thorin::Error::OffsetAtIndex(_, index) => {
diag = build(fluent::codegen_ssa_thorin_offset_at_index); diag = build(fluent::codegen_ssa_thorin_offset_at_index);
diag.set_arg("index", index); diag.arg("index", index);
diag diag
} }
thorin::Error::StrAtOffset(_, offset) => { thorin::Error::StrAtOffset(_, offset) => {
diag = build(fluent::codegen_ssa_thorin_str_at_offset); diag = build(fluent::codegen_ssa_thorin_str_at_offset);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::ParseIndex(_, section) => { thorin::Error::ParseIndex(_, section) => {
diag = build(fluent::codegen_ssa_thorin_parse_index); diag = build(fluent::codegen_ssa_thorin_parse_index);
diag.set_arg("section", section); diag.arg("section", section);
diag diag
} }
thorin::Error::UnitNotInIndex(unit) => { thorin::Error::UnitNotInIndex(unit) => {
diag = build(fluent::codegen_ssa_thorin_unit_not_in_index); diag = build(fluent::codegen_ssa_thorin_unit_not_in_index);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::RowNotInIndex(_, row) => { thorin::Error::RowNotInIndex(_, row) => {
diag = build(fluent::codegen_ssa_thorin_row_not_in_index); diag = build(fluent::codegen_ssa_thorin_row_not_in_index);
diag.set_arg("row", row); diag.arg("row", row);
diag diag
} }
thorin::Error::SectionNotInRow => { thorin::Error::SectionNotInRow => {
@ -341,7 +341,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::EmptyUnit(unit) => { thorin::Error::EmptyUnit(unit) => {
diag = build(fluent::codegen_ssa_thorin_empty_unit); diag = build(fluent::codegen_ssa_thorin_empty_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MultipleDebugInfoSection => { thorin::Error::MultipleDebugInfoSection => {
@ -358,12 +358,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::DuplicateUnit(unit) => { thorin::Error::DuplicateUnit(unit) => {
diag = build(fluent::codegen_ssa_thorin_duplicate_unit); diag = build(fluent::codegen_ssa_thorin_duplicate_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MissingReferencedUnit(unit) => { thorin::Error::MissingReferencedUnit(unit) => {
diag = build(fluent::codegen_ssa_thorin_missing_referenced_unit); diag = build(fluent::codegen_ssa_thorin_missing_referenced_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::NoOutputObjectCreated => { thorin::Error::NoOutputObjectCreated => {
@ -376,27 +376,27 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
} }
thorin::Error::Io(e) => { thorin::Error::Io(e) => {
diag = build(fluent::codegen_ssa_thorin_io); diag = build(fluent::codegen_ssa_thorin_io);
diag.set_arg("error", format!("{e}")); diag.arg("error", format!("{e}"));
diag diag
} }
thorin::Error::ObjectRead(e) => { thorin::Error::ObjectRead(e) => {
diag = build(fluent::codegen_ssa_thorin_object_read); diag = build(fluent::codegen_ssa_thorin_object_read);
diag.set_arg("error", format!("{e}")); diag.arg("error", format!("{e}"));
diag diag
} }
thorin::Error::ObjectWrite(e) => { thorin::Error::ObjectWrite(e) => {
diag = build(fluent::codegen_ssa_thorin_object_write); diag = build(fluent::codegen_ssa_thorin_object_write);
diag.set_arg("error", format!("{e}")); diag.arg("error", format!("{e}"));
diag diag
} }
thorin::Error::GimliRead(e) => { thorin::Error::GimliRead(e) => {
diag = build(fluent::codegen_ssa_thorin_gimli_read); diag = build(fluent::codegen_ssa_thorin_gimli_read);
diag.set_arg("error", format!("{e}")); diag.arg("error", format!("{e}"));
diag diag
} }
thorin::Error::GimliWrite(e) => { thorin::Error::GimliWrite(e) => {
diag = build(fluent::codegen_ssa_thorin_gimli_write); diag = build(fluent::codegen_ssa_thorin_gimli_write);
diag.set_arg("error", format!("{e}")); diag.arg("error", format!("{e}"));
diag diag
} }
_ => unimplemented!("Untranslated thorin error"), _ => unimplemented!("Untranslated thorin error"),
@ -414,8 +414,8 @@ pub struct LinkingFailed<'a> {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for LinkingFailed<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for LinkingFailed<'_> {
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::codegen_ssa_linking_failed); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::codegen_ssa_linking_failed);
diag.set_arg("linker_path", format!("{}", self.linker_path.display())); diag.arg("linker_path", format!("{}", self.linker_path.display()));
diag.set_arg("exit_status", format!("{}", self.exit_status)); diag.arg("exit_status", format!("{}", self.exit_status));
let contains_undefined_ref = self.escaped_output.contains("undefined reference to"); let contains_undefined_ref = self.escaped_output.contains("undefined reference to");

View File

@ -518,7 +518,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
Ub(_) => {} Ub(_) => {}
Custom(custom) => { Custom(custom) => {
(custom.add_args)(&mut |name, value| { (custom.add_args)(&mut |name, value| {
builder.set_arg(name, value); builder.arg(name, value);
}); });
} }
ValidationError(e) => e.add_args(dcx, builder), ValidationError(e) => e.add_args(dcx, builder),
@ -536,65 +536,65 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
| UninhabitedEnumVariantWritten(_) | UninhabitedEnumVariantWritten(_)
| UninhabitedEnumVariantRead(_) => {} | UninhabitedEnumVariantRead(_) => {}
BoundsCheckFailed { len, index } => { BoundsCheckFailed { len, index } => {
builder.set_arg("len", len); builder.arg("len", len);
builder.set_arg("index", index); builder.arg("index", index);
} }
UnterminatedCString(ptr) | InvalidFunctionPointer(ptr) | InvalidVTablePointer(ptr) => { UnterminatedCString(ptr) | InvalidFunctionPointer(ptr) | InvalidVTablePointer(ptr) => {
builder.set_arg("pointer", ptr); builder.arg("pointer", ptr);
} }
PointerUseAfterFree(alloc_id, msg) => { PointerUseAfterFree(alloc_id, msg) => {
builder builder
.set_arg("alloc_id", alloc_id) .arg("alloc_id", alloc_id)
.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx)); .arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => { PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => {
builder builder
.set_arg("alloc_id", alloc_id) .arg("alloc_id", alloc_id)
.set_arg("alloc_size", alloc_size.bytes()) .arg("alloc_size", alloc_size.bytes())
.set_arg("ptr_offset", ptr_offset) .arg("ptr_offset", ptr_offset)
.set_arg("ptr_size", ptr_size.bytes()) .arg("ptr_size", ptr_size.bytes())
.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx)); .arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
DanglingIntPointer(ptr, msg) => { DanglingIntPointer(ptr, msg) => {
if ptr != 0 { if ptr != 0 {
builder.set_arg("pointer", format!("{ptr:#x}[noalloc]")); builder.arg("pointer", format!("{ptr:#x}[noalloc]"));
} }
builder.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx)); builder.arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
AlignmentCheckFailed(Misalignment { required, has }, msg) => { AlignmentCheckFailed(Misalignment { required, has }, msg) => {
builder.set_arg("required", required.bytes()); builder.arg("required", required.bytes());
builder.set_arg("has", has.bytes()); builder.arg("has", has.bytes());
builder.set_arg("msg", format!("{msg:?}")); builder.arg("msg", format!("{msg:?}"));
} }
WriteToReadOnly(alloc) | DerefFunctionPointer(alloc) | DerefVTablePointer(alloc) => { WriteToReadOnly(alloc) | DerefFunctionPointer(alloc) | DerefVTablePointer(alloc) => {
builder.set_arg("allocation", alloc); builder.arg("allocation", alloc);
} }
InvalidBool(b) => { InvalidBool(b) => {
builder.set_arg("value", format!("{b:02x}")); builder.arg("value", format!("{b:02x}"));
} }
InvalidChar(c) => { InvalidChar(c) => {
builder.set_arg("value", format!("{c:08x}")); builder.arg("value", format!("{c:08x}"));
} }
InvalidTag(tag) => { InvalidTag(tag) => {
builder.set_arg("tag", format!("{tag:x}")); builder.arg("tag", format!("{tag:x}"));
} }
InvalidStr(err) => { InvalidStr(err) => {
builder.set_arg("err", format!("{err}")); builder.arg("err", format!("{err}"));
} }
InvalidUninitBytes(Some((alloc, info))) => { InvalidUninitBytes(Some((alloc, info))) => {
builder.set_arg("alloc", alloc); builder.arg("alloc", alloc);
builder.set_arg("access", info.access); builder.arg("access", info.access);
builder.set_arg("uninit", info.bad); builder.arg("uninit", info.bad);
} }
ScalarSizeMismatch(info) => { ScalarSizeMismatch(info) => {
builder.set_arg("target_size", info.target_size); builder.arg("target_size", info.target_size);
builder.set_arg("data_size", info.data_size); builder.arg("data_size", info.data_size);
} }
AbiMismatchArgument { caller_ty, callee_ty } AbiMismatchArgument { caller_ty, callee_ty }
| AbiMismatchReturn { caller_ty, callee_ty } => { | AbiMismatchReturn { caller_ty, callee_ty } => {
builder.set_arg("caller_ty", caller_ty.to_string()); builder.arg("caller_ty", caller_ty.to_string());
builder.set_arg("callee_ty", callee_ty.to_string()); builder.arg("callee_ty", callee_ty.to_string());
} }
} }
} }
@ -695,7 +695,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
) )
}; };
err.set_arg("front_matter", message); err.arg("front_matter", message);
fn add_range_arg<G: EmissionGuarantee>( fn add_range_arg<G: EmissionGuarantee>(
r: WrappingRange, r: WrappingRange,
@ -725,12 +725,12 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
]; ];
let args = args.iter().map(|(a, b)| (a, b)); let args = args.iter().map(|(a, b)| (a, b));
let message = dcx.eagerly_translate_to_string(msg, args); let message = dcx.eagerly_translate_to_string(msg, args);
err.set_arg("in_range", message); err.arg("in_range", message);
} }
match self.kind { match self.kind {
PtrToUninhabited { ty, .. } | UninhabitedVal { ty } => { PtrToUninhabited { ty, .. } | UninhabitedVal { ty } => {
err.set_arg("ty", ty); err.arg("ty", ty);
} }
PointerAsInt { expected } | Uninit { expected } => { PointerAsInt { expected } | Uninit { expected } => {
let msg = match expected { let msg = match expected {
@ -747,28 +747,28 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
ExpectedKind::Str => fluent::const_eval_validation_expected_str, ExpectedKind::Str => fluent::const_eval_validation_expected_str,
}; };
let msg = dcx.eagerly_translate_to_string(msg, [].into_iter()); let msg = dcx.eagerly_translate_to_string(msg, [].into_iter());
err.set_arg("expected", msg); err.arg("expected", msg);
} }
InvalidEnumTag { value } InvalidEnumTag { value }
| InvalidVTablePtr { value } | InvalidVTablePtr { value }
| InvalidBool { value } | InvalidBool { value }
| InvalidChar { value } | InvalidChar { value }
| InvalidFnPtr { value } => { | InvalidFnPtr { value } => {
err.set_arg("value", value); err.arg("value", value);
} }
NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => { NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => {
add_range_arg(range, max_value, dcx, err) add_range_arg(range, max_value, dcx, err)
} }
OutOfRange { range, max_value, value } => { OutOfRange { range, max_value, value } => {
err.set_arg("value", value); err.arg("value", value);
add_range_arg(range, max_value, dcx, err); add_range_arg(range, max_value, dcx, err);
} }
UnalignedPtr { required_bytes, found_bytes, .. } => { UnalignedPtr { required_bytes, found_bytes, .. } => {
err.set_arg("required_bytes", required_bytes); err.arg("required_bytes", required_bytes);
err.set_arg("found_bytes", found_bytes); err.arg("found_bytes", found_bytes);
} }
DanglingPtrNoProvenance { pointer, .. } => { DanglingPtrNoProvenance { pointer, .. } => {
err.set_arg("pointer", pointer); err.arg("pointer", pointer);
} }
NullPtr { .. } NullPtr { .. }
| PtrToStatic { .. } | PtrToStatic { .. }
@ -814,10 +814,10 @@ impl ReportErrorExt for UnsupportedOpInfo {
// print. So it's not worth the effort of having diagnostics that can print the `info`. // print. So it's not worth the effort of having diagnostics that can print the `info`.
UnsizedLocal | Unsupported(_) | ReadPointerAsInt(_) => {} UnsizedLocal | Unsupported(_) | ReadPointerAsInt(_) => {}
OverwritePartialPointer(ptr) | ReadPartialPointer(ptr) => { OverwritePartialPointer(ptr) | ReadPartialPointer(ptr) => {
builder.set_arg("ptr", ptr); builder.arg("ptr", ptr);
} }
ThreadLocalStatic(did) | ReadExternStatic(did) => { ThreadLocalStatic(did) | ReadExternStatic(did) => {
builder.set_arg("did", format!("{did:?}")); builder.arg("did", format!("{did:?}"));
} }
} }
} }
@ -844,7 +844,7 @@ impl<'tcx> ReportErrorExt for InterpError<'tcx> {
InterpError::InvalidProgram(e) => e.add_args(dcx, builder), InterpError::InvalidProgram(e) => e.add_args(dcx, builder),
InterpError::ResourceExhaustion(e) => e.add_args(dcx, builder), InterpError::ResourceExhaustion(e) => e.add_args(dcx, builder),
InterpError::MachineStop(e) => e.add_args(&mut |name, value| { InterpError::MachineStop(e) => e.add_args(&mut |name, value| {
builder.set_arg(name, value); builder.arg(name, value);
}), }),
} }
} }
@ -880,15 +880,15 @@ impl<'tcx> ReportErrorExt for InvalidProgramInfo<'tcx> {
let diag: DiagnosticBuilder<'_, ()> = let diag: DiagnosticBuilder<'_, ()> =
e.into_diagnostic().into_diagnostic(dcx, dummy_level); e.into_diagnostic().into_diagnostic(dcx, dummy_level);
for (name, val) in diag.args() { for (name, val) in diag.args() {
builder.set_arg(name.clone(), val.clone()); builder.arg(name.clone(), val.clone());
} }
diag.cancel(); diag.cancel();
} }
InvalidProgramInfo::FnAbiAdjustForForeignAbi( InvalidProgramInfo::FnAbiAdjustForForeignAbi(
AdjustForForeignAbiError::Unsupported { arch, abi }, AdjustForForeignAbiError::Unsupported { arch, abi },
) => { ) => {
builder.set_arg("arch", arch); builder.arg("arch", arch);
builder.set_arg("abi", abi.name()); builder.arg("abi", abi.name());
} }
} }
} }

View File

@ -86,9 +86,7 @@ fn source_string(file: Lrc<SourceFile>, line: &Line) -> String {
/// Maps `Diagnostic::Level` to `snippet::AnnotationType` /// Maps `Diagnostic::Level` to `snippet::AnnotationType`
fn annotation_type_for_level(level: Level) -> AnnotationType { fn annotation_type_for_level(level: Level) -> AnnotationType {
match level { match level {
Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error { .. } => { Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error => AnnotationType::Error,
AnnotationType::Error
}
Level::Warning(_) => AnnotationType::Warning, Level::Warning(_) => AnnotationType::Warning,
Level::Note | Level::OnceNote => AnnotationType::Note, Level::Note | Level::OnceNote => AnnotationType::Note,
Level::Help | Level::OnceHelp => AnnotationType::Help, Level::Help | Level::OnceHelp => AnnotationType::Help,

View File

@ -212,6 +212,9 @@ impl StringPart {
} }
} }
// Note: most of these methods are setters that return `&mut Self`. The small
// number of simple getter functions all have `get_` prefixes to distinguish
// them from the setters.
impl Diagnostic { impl Diagnostic {
#[track_caller] #[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self { pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
@ -241,11 +244,9 @@ impl Diagnostic {
pub fn is_error(&self) -> bool { pub fn is_error(&self) -> bool {
match self.level { match self.level {
Level::Bug Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error | Level::FailureNote => {
| Level::DelayedBug true
| Level::Fatal }
| Level::Error { .. }
| Level::FailureNote => true,
Level::Warning(_) Level::Warning(_)
| Level::Note | Level::Note
@ -308,25 +309,27 @@ impl Diagnostic {
/// In the meantime, though, callsites are required to deal with the "bug" /// In the meantime, though, callsites are required to deal with the "bug"
/// locally in whichever way makes the most sense. /// locally in whichever way makes the most sense.
#[track_caller] #[track_caller]
pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self { pub fn downgrade_to_delayed_bug(&mut self) {
assert!( assert!(
self.is_error(), self.is_error(),
"downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error", "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
self.level self.level
); );
self.level = Level::DelayedBug; self.level = Level::DelayedBug;
self
} }
/// Adds a span/label to be included in the resulting snippet. /// Appends a labeled span to the diagnostic.
/// ///
/// This is pushed onto the [`MultiSpan`] that was created when the diagnostic /// Labels are used to convey additional context for the diagnostic's primary span. They will
/// was first built. That means it will be shown together with the original /// be shown together with the original diagnostic's span, *not* with spans added by
/// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods. /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
/// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
/// either.
/// ///
/// This span is *not* considered a ["primary span"][`MultiSpan`]; only /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
/// the `Span` supplied when creating the diagnostic is primary. /// the diagnostic was constructed. However, the label span is *not* considered a
/// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
/// primary.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self { pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label)); self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
@ -344,7 +347,7 @@ impl Diagnostic {
pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self { pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
let before = self.span.clone(); let before = self.span.clone();
self.set_span(after); self.span(after);
for span_label in before.span_labels() { for span_label in before.span_labels() {
if let Some(label) = span_label.label { if let Some(label) = span_label.label {
if span_label.is_primary && keep_label { if span_label.is_primary && keep_label {
@ -876,7 +879,7 @@ impl Diagnostic {
self self
} }
pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self { pub fn span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
self.span = sp.into(); self.span = sp.into();
if let Some(span) = self.span.primary_span() { if let Some(span) = self.span.primary_span() {
self.sort_span = span; self.sort_span = span;
@ -884,7 +887,7 @@ impl Diagnostic {
self self
} }
pub fn set_is_lint(&mut self) -> &mut Self { pub fn is_lint(&mut self) -> &mut Self {
self.is_lint = true; self.is_lint = true;
self self
} }
@ -903,7 +906,7 @@ impl Diagnostic {
self.code.clone() self.code.clone()
} }
pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self { pub fn primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
self.messages[0] = (msg.into(), Style::NoStyle); self.messages[0] = (msg.into(), Style::NoStyle);
self self
} }
@ -915,7 +918,7 @@ impl Diagnostic {
self.args.iter() self.args.iter()
} }
pub fn set_arg( pub fn arg(
&mut self, &mut self,
name: impl Into<Cow<'static, str>>, name: impl Into<Cow<'static, str>>,
arg: impl IntoDiagnosticArg, arg: impl IntoDiagnosticArg,

View File

@ -31,7 +31,7 @@ where
{ {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let mut diag = self.node.into_diagnostic(dcx, level); let mut diag = self.node.into_diagnostic(dcx, level);
diag.set_span(self.span); diag.span(self.span);
diag diag
} }
} }
@ -207,11 +207,11 @@ macro_rules! forward {
// Forward pattern for &mut self -> &mut Self // Forward pattern for &mut self -> &mut Self
( (
$(#[$attrs:meta])* $(#[$attrs:meta])*
pub fn $n:ident(&mut self, $($name:ident: $ty:ty),* $(,)?) -> &mut Self pub fn $n:ident(&mut self $(, $name:ident: $ty:ty)* $(,)?) -> &mut Self
) => { ) => {
$(#[$attrs])* $(#[$attrs])*
#[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")] #[doc = concat!("See [`Diagnostic::", stringify!($n), "()`].")]
pub fn $n(&mut self, $($name: $ty),*) -> &mut Self { pub fn $n(&mut self $(, $name: $ty)*) -> &mut Self {
self.diagnostic.$n($($name),*); self.diagnostic.$n($($name),*);
self self
} }
@ -356,35 +356,16 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self.emit() self.emit()
} }
forward!( forward!(pub fn span_label(
#[track_caller] &mut self,
pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self span: Span,
); label: impl Into<SubdiagnosticMessage>
) -> &mut Self);
forward!( forward!(pub fn span_labels(
/// Appends a labeled span to the diagnostic.
///
/// Labels are used to convey additional context for the diagnostic's primary span. They will
/// be shown together with the original diagnostic's span, *not* with spans added by
/// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
/// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
/// either.
///
/// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
/// the diagnostic was constructed. However, the label span is *not* considered a
/// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
/// primary.
pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self);
forward!(
/// Labels all the given spans with the provided label.
/// See [`Diagnostic::span_label()`] for more information.
pub fn span_labels(
&mut self, &mut self,
spans: impl IntoIterator<Item = Span>, spans: impl IntoIterator<Item = Span>,
label: &str, label: &str,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn note_expected_found( forward!(pub fn note_expected_found(
&mut self, &mut self,
expected_label: &dyn fmt::Display, expected_label: &dyn fmt::Display,
@ -392,7 +373,6 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
found_label: &dyn fmt::Display, found_label: &dyn fmt::Display,
found: DiagnosticStyledString, found: DiagnosticStyledString,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn note_expected_found_extra( forward!(pub fn note_expected_found_extra(
&mut self, &mut self,
expected_label: &dyn fmt::Display, expected_label: &dyn fmt::Display,
@ -402,7 +382,6 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
expected_extra: &dyn fmt::Display, expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display, found_extra: &dyn fmt::Display,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self); forward!(pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self); forward!(pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self);
forward!(pub fn span_note( forward!(pub fn span_note(
@ -428,10 +407,8 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
sp: impl Into<MultiSpan>, sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>, msg: impl Into<SubdiagnosticMessage>,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn set_is_lint(&mut self,) -> &mut Self); forward!(pub fn is_lint(&mut self) -> &mut Self);
forward!(pub fn disable_suggestions(&mut self) -> &mut Self);
forward!(pub fn disable_suggestions(&mut self,) -> &mut Self);
forward!(pub fn multipart_suggestion( forward!(pub fn multipart_suggestion(
&mut self, &mut self,
msg: impl Into<SubdiagnosticMessage>, msg: impl Into<SubdiagnosticMessage>,
@ -498,16 +475,14 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
suggestion: impl ToString, suggestion: impl ToString,
applicability: Applicability, applicability: Applicability,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self); forward!(pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self); forward!(pub fn code(&mut self, s: DiagnosticId) -> &mut Self);
forward!(pub fn set_arg( forward!(pub fn arg(
&mut self, &mut self,
name: impl Into<Cow<'static, str>>, name: impl Into<Cow<'static, str>>,
arg: impl IntoDiagnosticArg, arg: impl IntoDiagnosticArg,
) -> &mut Self); ) -> &mut Self);
forward!(pub fn subdiagnostic( forward!(pub fn subdiagnostic(
&mut self, &mut self,
subdiagnostic: impl crate::AddToDiagnostic subdiagnostic: impl crate::AddToDiagnostic

View File

@ -254,29 +254,29 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => { TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => {
diag = diag =
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_address_space); DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_address_space);
diag.set_arg("addr_space", addr_space); diag.arg("addr_space", addr_space);
diag.set_arg("cause", cause); diag.arg("cause", cause);
diag.set_arg("err", err); diag.arg("err", err);
diag diag
} }
TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => { TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits); diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits);
diag.set_arg("kind", kind); diag.arg("kind", kind);
diag.set_arg("bit", bit); diag.arg("bit", bit);
diag.set_arg("cause", cause); diag.arg("cause", cause);
diag.set_arg("err", err); diag.arg("err", err);
diag diag
} }
TargetDataLayoutErrors::MissingAlignment { cause } => { TargetDataLayoutErrors::MissingAlignment { cause } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_missing_alignment); diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_missing_alignment);
diag.set_arg("cause", cause); diag.arg("cause", cause);
diag diag
} }
TargetDataLayoutErrors::InvalidAlignment { cause, err } => { TargetDataLayoutErrors::InvalidAlignment { cause, err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_alignment); diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_alignment);
diag.set_arg("cause", cause); diag.arg("cause", cause);
diag.set_arg("err_kind", err.diag_ident()); diag.arg("err_kind", err.diag_ident());
diag.set_arg("align", err.align()); diag.arg("align", err.align());
diag diag
} }
TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => { TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => {
@ -285,8 +285,8 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
level, level,
fluent::errors_target_inconsistent_architecture, fluent::errors_target_inconsistent_architecture,
); );
diag.set_arg("dl", dl); diag.arg("dl", dl);
diag.set_arg("target", target); diag.arg("target", target);
diag diag
} }
TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => { TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => {
@ -295,13 +295,13 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
level, level,
fluent::errors_target_inconsistent_pointer_width, fluent::errors_target_inconsistent_pointer_width,
); );
diag.set_arg("pointer_size", pointer_size); diag.arg("pointer_size", pointer_size);
diag.set_arg("target", target); diag.arg("target", target);
diag diag
} }
TargetDataLayoutErrors::InvalidBitsSize { err } => { TargetDataLayoutErrors::InvalidBitsSize { err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits_size); diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits_size);
diag.set_arg("err", err); diag.arg("err", err);
diag diag
} }
} }

View File

@ -673,7 +673,7 @@ impl DiagCtxt {
let key = (span.with_parent(None), key); let key = (span.with_parent(None), key);
if diag.is_error() { if diag.is_error() {
if matches!(diag.level, Error { lint: true }) { if diag.level == Error && diag.is_lint {
inner.lint_err_count += 1; inner.lint_err_count += 1;
} else { } else {
inner.err_count += 1; inner.err_count += 1;
@ -697,7 +697,7 @@ impl DiagCtxt {
let key = (span.with_parent(None), key); let key = (span.with_parent(None), key);
let diag = inner.stashed_diagnostics.remove(&key)?; let diag = inner.stashed_diagnostics.remove(&key)?;
if diag.is_error() { if diag.is_error() {
if matches!(diag.level, Error { lint: true }) { if diag.level == Error && diag.is_lint {
inner.lint_err_count -= 1; inner.lint_err_count -= 1;
} else { } else {
inner.err_count -= 1; inner.err_count -= 1;
@ -732,7 +732,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> { ) -> DiagnosticBuilder<'_, ()> {
let mut result = self.struct_warn(msg); let mut result = self.struct_warn(msg);
result.set_span(span); result.span(span);
result result
} }
@ -789,7 +789,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_> { ) -> DiagnosticBuilder<'_> {
let mut result = self.struct_err(msg); let mut result = self.struct_err(msg);
result.set_span(span); result.span(span);
result result
} }
@ -812,7 +812,7 @@ impl DiagCtxt {
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_> { pub fn struct_err(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_> {
DiagnosticBuilder::new(self, Error { lint: false }, msg) DiagnosticBuilder::new(self, Error, msg)
} }
/// Construct a builder at the `Error` level with the `msg` and the `code`. /// Construct a builder at the `Error` level with the `msg` and the `code`.
@ -850,7 +850,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalAbort> { ) -> DiagnosticBuilder<'_, FatalAbort> {
let mut result = self.struct_fatal(msg); let mut result = self.struct_fatal(msg);
result.set_span(span); result.span(span);
result result
} }
@ -878,16 +878,6 @@ impl DiagCtxt {
DiagnosticBuilder::new(self, Fatal, msg) DiagnosticBuilder::new(self, Fatal, msg)
} }
/// Construct a builder at the `Fatal` level with the `msg`, that doesn't abort.
#[rustc_lint_diagnostics]
#[track_caller]
pub fn struct_almost_fatal(
&self,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalError> {
DiagnosticBuilder::new(self, Fatal, msg)
}
/// Construct a builder at the `Help` level with the `msg`. /// Construct a builder at the `Help` level with the `msg`.
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
@ -917,7 +907,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, BugAbort> { ) -> DiagnosticBuilder<'_, BugAbort> {
let mut result = self.struct_bug(msg); let mut result = self.struct_bug(msg);
result.set_span(span); result.span(span);
result result
} }
@ -1008,7 +998,7 @@ impl DiagCtxt {
self.span_bug(sp, msg); self.span_bug(sp, msg);
} }
let mut diagnostic = Diagnostic::new(DelayedBug, msg); let mut diagnostic = Diagnostic::new(DelayedBug, msg);
diagnostic.set_span(sp); diagnostic.span(sp);
self.emit_diagnostic(diagnostic).unwrap() self.emit_diagnostic(diagnostic).unwrap()
} }
@ -1039,7 +1029,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> { ) -> DiagnosticBuilder<'_, ()> {
let mut db = DiagnosticBuilder::new(self, Note, msg); let mut db = DiagnosticBuilder::new(self, Note, msg);
db.set_span(span); db.span(span);
db db
} }
@ -1222,7 +1212,7 @@ impl DiagCtxt {
#[track_caller] #[track_caller]
pub fn create_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> DiagnosticBuilder<'a> { pub fn create_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> DiagnosticBuilder<'a> {
err.into_diagnostic(self, Error { lint: false }) err.into_diagnostic(self, Error)
} }
#[track_caller] #[track_caller]
@ -1377,7 +1367,7 @@ impl DiagCtxtInner {
for diag in diags { for diag in diags {
// Decrement the count tracking the stash; emitting will increment it. // Decrement the count tracking the stash; emitting will increment it.
if diag.is_error() { if diag.is_error() {
if matches!(diag.level, Error { lint: true }) { if diag.level == Error && diag.is_lint {
self.lint_err_count -= 1; self.lint_err_count -= 1;
} else { } else {
self.err_count -= 1; self.err_count -= 1;
@ -1408,7 +1398,7 @@ impl DiagCtxtInner {
&mut self, &mut self,
diagnostic: &mut Diagnostic, diagnostic: &mut Diagnostic,
) -> Option<ErrorGuaranteed> { ) -> Option<ErrorGuaranteed> {
if matches!(diagnostic.level, Error { .. } | Fatal) && self.treat_err_as_bug() { if matches!(diagnostic.level, Error | Fatal) && self.treat_err_as_bug() {
diagnostic.level = Bug; diagnostic.level = Bug;
} }
@ -1509,7 +1499,7 @@ impl DiagCtxtInner {
} }
} }
if diagnostic.is_error() { if diagnostic.is_error() {
if matches!(diagnostic.level, Error { lint: true }) { if diagnostic.level == Error && diagnostic.is_lint {
self.bump_lint_err_count(); self.bump_lint_err_count();
} else { } else {
self.bump_err_count(); self.bump_err_count();
@ -1705,11 +1695,7 @@ pub enum Level {
/// most common case. /// most common case.
/// ///
/// Its `EmissionGuarantee` is `ErrorGuaranteed`. /// Its `EmissionGuarantee` is `ErrorGuaranteed`.
Error { Error,
/// If this error comes from a lint, don't abort compilation even when abort_if_errors() is
/// called.
lint: bool,
},
/// A warning about the code being compiled. Does not prevent compilation from finishing. /// A warning about the code being compiled. Does not prevent compilation from finishing.
/// ///
@ -1768,7 +1754,7 @@ impl Level {
fn color(self) -> ColorSpec { fn color(self) -> ColorSpec {
let mut spec = ColorSpec::new(); let mut spec = ColorSpec::new();
match self { match self {
Bug | DelayedBug | Fatal | Error { .. } => { Bug | DelayedBug | Fatal | Error => {
spec.set_fg(Some(Color::Red)).set_intense(true); spec.set_fg(Some(Color::Red)).set_intense(true);
} }
Warning(_) => { Warning(_) => {
@ -1789,7 +1775,7 @@ impl Level {
pub fn to_str(self) -> &'static str { pub fn to_str(self) -> &'static str {
match self { match self {
Bug | DelayedBug => "error: internal compiler error", Bug | DelayedBug => "error: internal compiler error",
Fatal | Error { .. } => "error", Fatal | Error => "error",
Warning(_) => "warning", Warning(_) => "warning",
Note | OnceNote => "note", Note | OnceNote => "note",
Help | OnceHelp => "help", Help | OnceHelp => "help",

View File

@ -855,7 +855,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
} }
Err(mut err) => { Err(mut err) => {
if err.span.is_dummy() { if err.span.is_dummy() {
err.set_span(span); err.span(span);
} }
annotate_err_with_kind(&mut err, kind, span); annotate_err_with_kind(&mut err, kind, span);
err.emit(); err.emit();

View File

@ -379,7 +379,7 @@ impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
impl ToInternal<rustc_errors::Level> for Level { impl ToInternal<rustc_errors::Level> for Level {
fn to_internal(self) -> rustc_errors::Level { fn to_internal(self) -> rustc_errors::Level {
match self { match self {
Level::Error => rustc_errors::Level::Error { lint: false }, Level::Error => rustc_errors::Level::Error,
Level::Warning => rustc_errors::Level::Warning(None), Level::Warning => rustc_errors::Level::Warning(None),
Level::Note => rustc_errors::Level::Note, Level::Note => rustc_errors::Level::Note,
Level::Help => rustc_errors::Level::Help, Level::Help => rustc_errors::Level::Help,
@ -497,7 +497,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) { fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let mut diag = let mut diag =
rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message); rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
diag.set_span(MultiSpan::from_spans(diagnostic.spans)); diag.span(MultiSpan::from_spans(diagnostic.spans));
for child in diagnostic.children { for child in diagnostic.children {
diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans)); diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));
} }

View File

@ -70,7 +70,7 @@ fn generic_arg_mismatch_err(
Res::Err => { Res::Err => {
add_braces_suggestion(arg, &mut err); add_braces_suggestion(arg, &mut err);
return err return err
.set_primary_message("unresolved item provided when a constant was expected") .primary_message("unresolved item provided when a constant was expected")
.emit(); .emit();
} }
Res::Def(DefKind::TyParam, src_def_id) => { Res::Def(DefKind::TyParam, src_def_id) => {

View File

@ -319,10 +319,10 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for MissingTypeParams {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let mut err = DiagnosticBuilder::new(dcx, level, fluent::hir_analysis_missing_type_params); let mut err = DiagnosticBuilder::new(dcx, level, fluent::hir_analysis_missing_type_params);
err.set_span(self.span); err.span(self.span);
err.code(error_code!(E0393)); err.code(error_code!(E0393));
err.set_arg("parameterCount", self.missing_type_params.len()); err.arg("parameterCount", self.missing_type_params.len());
err.set_arg( err.arg(
"parameters", "parameters",
self.missing_type_params self.missing_type_params
.iter() .iter()

View File

@ -215,7 +215,7 @@ impl AddToDiagnostic for TypeMismatchFruTypo {
where where
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage, F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{ {
diag.set_arg("expr", self.expr.as_deref().unwrap_or("NONE")); diag.arg("expr", self.expr.as_deref().unwrap_or("NONE"));
// Only explain that `a ..b` is a range if it's split up // Only explain that `a ..b` is a range if it's split up
if self.expr_span.between(self.fru_span).is_empty() { if self.expr_span.between(self.fru_span).is_empty() {

View File

@ -961,7 +961,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
but its trait bounds were not satisfied" but its trait bounds were not satisfied"
) )
}); });
err.set_primary_message(primary_message); err.primary_message(primary_message);
if let Some(label) = label { if let Some(label) = label {
custom_span_label = true; custom_span_label = true;
err.span_label(span, label); err.span_label(span, label);

View File

@ -247,8 +247,8 @@ impl AddToDiagnostic for RegionOriginNote<'_> {
} }
RegionOriginNote::WithName { span, msg, name, continues } => { RegionOriginNote::WithName { span, msg, name, continues } => {
label_or_note(span, msg); label_or_note(span, msg);
diag.set_arg("name", name); diag.arg("name", name);
diag.set_arg("continues", continues); diag.arg("continues", continues);
} }
RegionOriginNote::WithRequirement { RegionOriginNote::WithRequirement {
span, span,
@ -256,7 +256,7 @@ impl AddToDiagnostic for RegionOriginNote<'_> {
expected_found: Some((expected, found)), expected_found: Some((expected, found)),
} => { } => {
label_or_note(span, fluent::infer_subtype); label_or_note(span, fluent::infer_subtype);
diag.set_arg("requirement", requirement); diag.arg("requirement", requirement);
diag.note_expected_found(&"", expected, &"", found); diag.note_expected_found(&"", expected, &"", found);
} }
@ -265,7 +265,7 @@ impl AddToDiagnostic for RegionOriginNote<'_> {
// handling of region checking when type errors are present is // handling of region checking when type errors are present is
// *terrible*. // *terrible*.
label_or_note(span, fluent::infer_subtype_2); label_or_note(span, fluent::infer_subtype_2);
diag.set_arg("requirement", requirement); diag.arg("requirement", requirement);
} }
}; };
} }
@ -298,8 +298,8 @@ impl AddToDiagnostic for LifetimeMismatchLabels {
diag.span_label(param_span, fluent::infer_declared_different); diag.span_label(param_span, fluent::infer_declared_different);
diag.span_label(ret_span, fluent::infer_nothing); diag.span_label(ret_span, fluent::infer_nothing);
diag.span_label(span, fluent::infer_data_returned); diag.span_label(span, fluent::infer_data_returned);
diag.set_arg("label_var1_exists", label_var1.is_some()); diag.arg("label_var1_exists", label_var1.is_some());
diag.set_arg("label_var1", label_var1.map(|x| x.to_string()).unwrap_or_default()); diag.arg("label_var1", label_var1.map(|x| x.to_string()).unwrap_or_default());
} }
LifetimeMismatchLabels::Normal { LifetimeMismatchLabels::Normal {
hir_equal, hir_equal,
@ -317,16 +317,10 @@ impl AddToDiagnostic for LifetimeMismatchLabels {
diag.span_label(ty_sup, fluent::infer_types_declared_different); diag.span_label(ty_sup, fluent::infer_types_declared_different);
diag.span_label(ty_sub, fluent::infer_nothing); diag.span_label(ty_sub, fluent::infer_nothing);
diag.span_label(span, fluent::infer_data_flows); diag.span_label(span, fluent::infer_data_flows);
diag.set_arg("label_var1_exists", label_var1.is_some()); diag.arg("label_var1_exists", label_var1.is_some());
diag.set_arg( diag.arg("label_var1", label_var1.map(|x| x.to_string()).unwrap_or_default());
"label_var1", diag.arg("label_var2_exists", label_var2.is_some());
label_var1.map(|x| x.to_string()).unwrap_or_default(), diag.arg("label_var2", label_var2.map(|x| x.to_string()).unwrap_or_default());
);
diag.set_arg("label_var2_exists", label_var2.is_some());
diag.set_arg(
"label_var2",
label_var2.map(|x| x.to_string()).unwrap_or_default(),
);
} }
} }
} }
@ -417,7 +411,7 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> {
suggestions, suggestions,
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
diag.set_arg("is_impl", is_impl); diag.arg("is_impl", is_impl);
true true
}; };
if mk_suggestion() && self.add_note { if mk_suggestion() && self.add_note {
@ -878,8 +872,8 @@ impl AddToDiagnostic for MoreTargeted {
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage, F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{ {
diag.code(rustc_errors::error_code!(E0772)); diag.code(rustc_errors::error_code!(E0772));
diag.set_primary_message(fluent::infer_more_targeted); diag.primary_message(fluent::infer_more_targeted);
diag.set_arg("ident", self.ident); diag.arg("ident", self.ident);
} }
} }
@ -1299,7 +1293,7 @@ impl AddToDiagnostic for SuggestTuplePatternMany {
where where
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage, F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{ {
diag.set_arg("path", self.path); diag.arg("path", self.path);
let message = f(diag, crate::fluent_generated::infer_stp_wrap_many.into()); let message = f(diag, crate::fluent_generated::infer_stp_wrap_many.into());
diag.multipart_suggestions( diag.multipart_suggestions(
message, message,

View File

@ -164,10 +164,10 @@ impl AddToDiagnostic for RegionExplanation<'_> {
where where
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage, F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{ {
diag.set_arg("pref_kind", self.prefix); diag.arg("pref_kind", self.prefix);
diag.set_arg("suff_kind", self.suffix); diag.arg("suff_kind", self.suffix);
diag.set_arg("desc_kind", self.desc.kind); diag.arg("desc_kind", self.desc.kind);
diag.set_arg("desc_arg", self.desc.arg); diag.arg("desc_arg", self.desc.arg);
let msg = f(diag, fluent::infer_region_explanation.into()); let msg = f(diag, fluent::infer_region_explanation.into());
if let Some(span) = self.desc.span { if let Some(span) = self.desc.span {

View File

@ -31,7 +31,7 @@ impl AddToDiagnostic for OverruledAttributeSub {
match self { match self {
OverruledAttributeSub::DefaultSource { id } => { OverruledAttributeSub::DefaultSource { id } => {
diag.note(fluent::lint_default_source); diag.note(fluent::lint_default_source);
diag.set_arg("id", id); diag.arg("id", id);
} }
OverruledAttributeSub::NodeSource { span, reason } => { OverruledAttributeSub::NodeSource { span, reason } => {
diag.span_label(span, fluent::lint_node_source); diag.span_label(span, fluent::lint_node_source);

View File

@ -1069,7 +1069,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
Some(span.into()), Some(span.into()),
fluent::lint_unknown_gated_lint, fluent::lint_unknown_gated_lint,
|lint| { |lint| {
lint.set_arg("name", lint_id.lint.name_lower()); lint.arg("name", lint_id.lint.name_lower());
lint.note(fluent::lint_note); lint.note(fluent::lint_note);
rustc_session::parse::add_feature_diagnostics_for_issue( rustc_session::parse::add_feature_diagnostics_for_issue(
lint, lint,

View File

@ -5,8 +5,8 @@ use std::num::NonZeroU32;
use crate::errors::RequestedLevel; use crate::errors::RequestedLevel;
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_errors::{ use rustc_errors::{
AddToDiagnostic, Applicability, DecorateLint, DiagnosticMessage, DiagnosticStyledString, AddToDiagnostic, Applicability, DecorateLint, Diagnostic, DiagnosticBuilder, DiagnosticMessage,
SuggestionStyle, DiagnosticStyledString, SubdiagnosticMessage, SuggestionStyle,
}; };
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_macros::{LintDiagnostic, Subdiagnostic}; use rustc_macros::{LintDiagnostic, Subdiagnostic};
@ -135,7 +135,7 @@ pub struct BuiltinMissingDebugImpl<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for BuiltinMissingDebugImpl<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinMissingDebugImpl<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("debug", self.tcx.def_path_str(self.def_id)); diag.arg("debug", self.tcx.def_path_str(self.def_id));
} }
fn msg(&self) -> DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
@ -239,7 +239,7 @@ pub struct BuiltinUngatedAsyncFnTrackCaller<'a> {
} }
impl<'a> DecorateLint<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.span_label(self.label, fluent::lint_label); diag.span_label(self.label, fluent::lint_label);
rustc_session::parse::add_feature_diagnostics( rustc_session::parse::add_feature_diagnostics(
diag, diag,
@ -268,12 +268,9 @@ pub struct SuggestChangingAssocTypes<'a, 'b> {
} }
impl AddToDiagnostic for SuggestChangingAssocTypes<'_, '_> { impl AddToDiagnostic for SuggestChangingAssocTypes<'_, '_> {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
// Access to associates types should use `<T as Bound>::Assoc`, which does not need a // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
// bound. Let's see if this type does that. // bound. Let's see if this type does that.
@ -281,7 +278,7 @@ impl AddToDiagnostic for SuggestChangingAssocTypes<'_, '_> {
// We use a HIR visitor to walk the type. // We use a HIR visitor to walk the type.
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
struct WalkAssocTypes<'a> { struct WalkAssocTypes<'a> {
err: &'a mut rustc_errors::Diagnostic, err: &'a mut Diagnostic,
} }
impl Visitor<'_> for WalkAssocTypes<'_> { impl Visitor<'_> for WalkAssocTypes<'_> {
fn visit_qpath( fn visit_qpath(
@ -326,12 +323,9 @@ pub struct BuiltinTypeAliasGenericBoundsSuggestion {
} }
impl AddToDiagnostic for BuiltinTypeAliasGenericBoundsSuggestion { impl AddToDiagnostic for BuiltinTypeAliasGenericBoundsSuggestion {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
diag.multipart_suggestion( diag.multipart_suggestion(
fluent::lint_suggestion, fluent::lint_suggestion,
@ -425,8 +419,8 @@ pub struct BuiltinUnpermittedTypeInit<'a> {
} }
impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> { impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("ty", self.ty); diag.arg("ty", self.ty);
diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label); diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label);
if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) { if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) {
// Only suggest late `MaybeUninit::assume_init` initialization if the type is inhabited. // Only suggest late `MaybeUninit::assume_init` initialization if the type is inhabited.
@ -438,7 +432,7 @@ impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> {
self.sub.add_to_diagnostic(diag); self.sub.add_to_diagnostic(diag);
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
self.msg.clone() self.msg.clone()
} }
} }
@ -449,12 +443,9 @@ pub struct BuiltinUnpermittedTypeInitSub {
} }
impl AddToDiagnostic for BuiltinUnpermittedTypeInitSub { impl AddToDiagnostic for BuiltinUnpermittedTypeInitSub {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
let mut err = self.err; let mut err = self.err;
loop { loop {
@ -506,12 +497,9 @@ pub struct BuiltinClashingExternSub<'a> {
} }
impl AddToDiagnostic for BuiltinClashingExternSub<'_> { impl AddToDiagnostic for BuiltinClashingExternSub<'_> {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
let mut expected_str = DiagnosticStyledString::new(); let mut expected_str = DiagnosticStyledString::new();
expected_str.push(self.expected.fn_sig(self.tcx).to_string(), false); expected_str.push(self.expected.fn_sig(self.tcx).to_string(), false);
@ -779,12 +767,9 @@ pub struct HiddenUnicodeCodepointsDiagLabels {
} }
impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels { impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
for (c, span) in self.spans { for (c, span) in self.spans {
diag.span_label(span, format!("{c:?}")); diag.span_label(span, format!("{c:?}"));
@ -799,12 +784,9 @@ pub enum HiddenUnicodeCodepointsDiagSub {
// Used because of multiple multipart_suggestion and note // Used because of multiple multipart_suggestion and note
impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub { impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
match self { match self {
HiddenUnicodeCodepointsDiagSub::Escape { spans } => { HiddenUnicodeCodepointsDiagSub::Escape { spans } => {
@ -830,7 +812,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
// FIXME: in other suggestions we've reversed the inner spans of doc comments. We // FIXME: in other suggestions we've reversed the inner spans of doc comments. We
// should do the same here to provide the same good suggestions as we do for // should do the same here to provide the same good suggestions as we do for
// literals above. // literals above.
diag.set_arg( diag.arg(
"escaped", "escaped",
spans spans
.into_iter() .into_iter()
@ -953,12 +935,9 @@ pub struct NonBindingLetSub {
} }
impl AddToDiagnostic for NonBindingLetSub { impl AddToDiagnostic for NonBindingLetSub {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
diag.span_suggestion_verbose( diag.span_suggestion_verbose(
self.suggestion, self.suggestion,
@ -1147,8 +1126,8 @@ pub struct NonFmtPanicUnused {
// Used because of two suggestions based on one Option<Span> // Used because of two suggestions based on one Option<Span>
impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused { impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("count", self.count); diag.arg("count", self.count);
diag.note(fluent::lint_note); diag.note(fluent::lint_note);
if let Some(span) = self.suggestion { if let Some(span) = self.suggestion {
diag.span_suggestion( diag.span_suggestion(
@ -1166,7 +1145,7 @@ impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused {
} }
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_non_fmt_panic_unused fluent::lint_non_fmt_panic_unused
} }
} }
@ -1224,12 +1203,9 @@ pub enum NonSnakeCaseDiagSub {
} }
impl AddToDiagnostic for NonSnakeCaseDiagSub { impl AddToDiagnostic for NonSnakeCaseDiagSub {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
match self { match self {
NonSnakeCaseDiagSub::Label { span } => { NonSnakeCaseDiagSub::Label { span } => {
@ -1342,12 +1318,12 @@ pub struct DropTraitConstraintsDiag<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropTraitConstraintsDiag<'_> { impl<'a> DecorateLint<'a, ()> for DropTraitConstraintsDiag<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("predicate", self.predicate); diag.arg("predicate", self.predicate);
diag.set_arg("needs_drop", self.tcx.def_path_str(self.def_id)); diag.arg("needs_drop", self.tcx.def_path_str(self.def_id));
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_drop_trait_constraints fluent::lint_drop_trait_constraints
} }
} }
@ -1359,11 +1335,11 @@ pub struct DropGlue<'a> {
// Needed for def_path_str // Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropGlue<'_> { impl<'a> DecorateLint<'a, ()> for DropGlue<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("needs_drop", self.tcx.def_path_str(self.def_id)); diag.arg("needs_drop", self.tcx.def_path_str(self.def_id));
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_drop_glue fluent::lint_drop_glue
} }
} }
@ -1423,12 +1399,9 @@ pub enum OverflowingBinHexSign {
} }
impl AddToDiagnostic for OverflowingBinHexSign { impl AddToDiagnostic for OverflowingBinHexSign {
fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
where where
F: Fn( F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{ {
match self { match self {
OverflowingBinHexSign::Positive => { OverflowingBinHexSign::Positive => {
@ -1633,9 +1606,9 @@ pub struct ImproperCTypes<'a> {
// Used because of the complexity of Option<DiagnosticMessage>, DiagnosticMessage, and Option<Span> // Used because of the complexity of Option<DiagnosticMessage>, DiagnosticMessage, and Option<Span>
impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> { impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("ty", self.ty); diag.arg("ty", self.ty);
diag.set_arg("desc", self.desc); diag.arg("desc", self.desc);
diag.span_label(self.label, fluent::lint_label); diag.span_label(self.label, fluent::lint_label);
if let Some(help) = self.help { if let Some(help) = self.help {
diag.help(help); diag.help(help);
@ -1646,7 +1619,7 @@ impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> {
} }
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_improper_ctypes fluent::lint_improper_ctypes
} }
} }
@ -1776,10 +1749,10 @@ pub enum UnusedDefSuggestion {
// Needed because of def_path_str // Needed because of def_path_str
impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> { impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.set_arg("pre", self.pre); diag.arg("pre", self.pre);
diag.set_arg("post", self.post); diag.arg("post", self.post);
diag.set_arg("def", self.cx.tcx.def_path_str(self.def_id)); diag.arg("def", self.cx.tcx.def_path_str(self.def_id));
// check for #[must_use = "..."] // check for #[must_use = "..."]
if let Some(note) = self.note { if let Some(note) = self.note {
diag.note(note.to_string()); diag.note(note.to_string());
@ -1789,7 +1762,7 @@ impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> {
} }
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_unused_def fluent::lint_unused_def
} }
} }
@ -1859,14 +1832,14 @@ pub struct AsyncFnInTraitDiag {
} }
impl<'a> DecorateLint<'a, ()> for AsyncFnInTraitDiag { impl<'a> DecorateLint<'a, ()> for AsyncFnInTraitDiag {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.note(fluent::lint_note); diag.note(fluent::lint_note);
if let Some(sugg) = self.sugg { if let Some(sugg) = self.sugg {
diag.multipart_suggestion(fluent::lint_suggestion, sugg, Applicability::MaybeIncorrect); diag.multipart_suggestion(fluent::lint_suggestion, sugg, Applicability::MaybeIncorrect);
} }
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> DiagnosticMessage {
fluent::lint_async_fn_in_trait fluent::lint_async_fn_in_trait
} }
} }

View File

@ -121,7 +121,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
cx.struct_span_lint(NON_FMT_PANICS, arg_span, fluent::lint_non_fmt_panic, |lint| { cx.struct_span_lint(NON_FMT_PANICS, arg_span, fluent::lint_non_fmt_panic, |lint| {
lint.set_arg("name", symbol); lint.arg("name", symbol);
lint.note(fluent::lint_note); lint.note(fluent::lint_note);
lint.note(fluent::lint_more_info_note); lint.note(fluent::lint_more_info_note);
if !is_arg_inside_call(arg_span, span) { if !is_arg_inside_call(arg_span, span) {
@ -180,7 +180,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
fmt_applicability, fmt_applicability,
); );
} else if suggest_debug { } else if suggest_debug {
lint.set_arg("ty", ty); lint.arg("ty", ty);
lint.span_suggestion_verbose( lint.span_suggestion_verbose(
arg_span.shrink_to_lo(), arg_span.shrink_to_lo(),
fluent::lint_debug_suggestion, fluent::lint_debug_suggestion,
@ -191,7 +191,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
if suggest_panic_any { if suggest_panic_any {
if let Some((open, close, del)) = find_delimiters(cx, span) { if let Some((open, close, del)) = find_delimiters(cx, span) {
lint.set_arg("already_suggested", suggest_display || suggest_debug); lint.arg("already_suggested", suggest_display || suggest_debug);
lint.multipart_suggestion( lint.multipart_suggestion(
fluent::lint_panic_suggestion, fluent::lint_panic_suggestion,
if del == '(' { if del == '(' {

View File

@ -5,8 +5,8 @@ use crate::diagnostics::error::{
}; };
use crate::diagnostics::utils::{ use crate::diagnostics::utils::{
build_field_mapping, is_doc_comment, report_error_if_not_applied_to_span, report_type_error, build_field_mapping, is_doc_comment, report_error_if_not_applied_to_span, report_type_error,
should_generate_set_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo, should_generate_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo, FieldInnerTy,
FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
}; };
use proc_macro2::{Ident, Span, TokenStream}; use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, quote_spanned}; use quote::{format_ident, quote, quote_spanned};
@ -125,15 +125,15 @@ impl DiagnosticDeriveVariantBuilder {
} }
/// Generates calls to `span_label` and similar functions based on the attributes on fields or /// Generates calls to `span_label` and similar functions based on the attributes on fields or
/// calls to `set_arg` when no attributes are present. /// calls to `arg` when no attributes are present.
pub(crate) fn body(&mut self, variant: &VariantInfo<'_>) -> TokenStream { pub(crate) fn body(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
let mut body = quote! {}; let mut body = quote! {};
// Generate `set_arg` calls first.. // Generate `arg` calls first..
for binding in variant.bindings().iter().filter(|bi| should_generate_set_arg(bi.ast())) { for binding in variant.bindings().iter().filter(|bi| should_generate_arg(bi.ast())) {
body.extend(self.generate_field_code(binding)); body.extend(self.generate_field_code(binding));
} }
// ..and then subdiagnostic additions. // ..and then subdiagnostic additions.
for binding in variant.bindings().iter().filter(|bi| !should_generate_set_arg(bi.ast())) { for binding in variant.bindings().iter().filter(|bi| !should_generate_arg(bi.ast())) {
body.extend(self.generate_field_attrs_code(binding)); body.extend(self.generate_field_attrs_code(binding));
} }
body body
@ -253,7 +253,7 @@ impl DiagnosticDeriveVariantBuilder {
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present let ident = format_ident!("{}", ident); // strip `r#` prefix, if present
quote! { quote! {
diag.set_arg( diag.arg(
stringify!(#ident), stringify!(#ident),
#field_binding #field_binding
); );
@ -312,7 +312,7 @@ impl DiagnosticDeriveVariantBuilder {
let name = ident.to_string(); let name = ident.to_string();
match (&attr.meta, name.as_str()) { match (&attr.meta, name.as_str()) {
// Don't need to do anything - by virtue of the attribute existing, the // Don't need to do anything - by virtue of the attribute existing, the
// `set_arg` call will not be generated. // `arg` call will not be generated.
(Meta::Path(_), "skip_arg") => return Ok(quote! {}), (Meta::Path(_), "skip_arg") => return Ok(quote! {}),
(Meta::Path(_), "primary_span") => { (Meta::Path(_), "primary_span") => {
match self.kind { match self.kind {
@ -320,7 +320,7 @@ impl DiagnosticDeriveVariantBuilder {
report_error_if_not_applied_to_span(attr, &info)?; report_error_if_not_applied_to_span(attr, &info)?;
return Ok(quote! { return Ok(quote! {
diag.set_span(#binding); diag.span(#binding);
}); });
} }
DiagnosticDeriveKind::LintDiagnostic => { DiagnosticDeriveKind::LintDiagnostic => {

View File

@ -6,8 +6,8 @@ use crate::diagnostics::error::{
use crate::diagnostics::utils::{ use crate::diagnostics::utils::{
build_field_mapping, build_suggestion_code, is_doc_comment, new_code_ident, build_field_mapping, build_suggestion_code, is_doc_comment, new_code_ident,
report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span, report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span,
should_generate_set_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, should_generate_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap,
HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, SetOnce, SpannedOption, SubdiagnosticKind,
}; };
use proc_macro2::TokenStream; use proc_macro2::TokenStream;
use quote::{format_ident, quote}; use quote::{format_ident, quote};
@ -214,7 +214,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
} }
/// Generates the code for a field with no attributes. /// Generates the code for a field with no attributes.
fn generate_field_set_arg(&mut self, binding_info: &BindingInfo<'_>) -> TokenStream { fn generate_field_arg(&mut self, binding_info: &BindingInfo<'_>) -> TokenStream {
let diag = &self.parent.diag; let diag = &self.parent.diag;
let field = binding_info.ast(); let field = binding_info.ast();
@ -225,7 +225,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present let ident = format_ident!("{}", ident); // strip `r#` prefix, if present
quote! { quote! {
#diag.set_arg( #diag.arg(
stringify!(#ident), stringify!(#ident),
#field_binding #field_binding
); );
@ -505,7 +505,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
.variant .variant
.bindings() .bindings()
.iter() .iter()
.filter(|binding| !should_generate_set_arg(binding.ast())) .filter(|binding| !should_generate_arg(binding.ast()))
.map(|binding| self.generate_field_attr_code(binding, kind_stats)) .map(|binding| self.generate_field_attr_code(binding, kind_stats))
.collect(); .collect();
@ -593,8 +593,8 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
.variant .variant
.bindings() .bindings()
.iter() .iter()
.filter(|binding| should_generate_set_arg(binding.ast())) .filter(|binding| should_generate_arg(binding.ast()))
.map(|binding| self.generate_field_set_arg(binding)) .map(|binding| self.generate_field_arg(binding))
.collect(); .collect();
let formatting_init = &self.formatting_init; let formatting_init = &self.formatting_init;

View File

@ -584,7 +584,7 @@ pub(super) enum SubdiagnosticKind {
suggestion_kind: SuggestionKind, suggestion_kind: SuggestionKind,
applicability: SpannedOption<Applicability>, applicability: SpannedOption<Applicability>,
/// Identifier for variable used for formatted code, e.g. `___code_0`. Enables separation /// Identifier for variable used for formatted code, e.g. `___code_0`. Enables separation
/// of formatting and diagnostic emission so that `set_arg` calls can happen in-between.. /// of formatting and diagnostic emission so that `arg` calls can happen in-between..
code_field: syn::Ident, code_field: syn::Ident,
/// Initialization logic for `code_field`'s variable, e.g. /// Initialization logic for `code_field`'s variable, e.g.
/// `let __formatted_code = /* whatever */;` /// `let __formatted_code = /* whatever */;`
@ -863,9 +863,9 @@ impl quote::IdentFragment for SubdiagnosticKind {
} }
} }
/// Returns `true` if `field` should generate a `set_arg` call rather than any other diagnostic /// Returns `true` if `field` should generate a `arg` call rather than any other diagnostic
/// call (like `span_label`). /// call (like `span_label`).
pub(super) fn should_generate_set_arg(field: &Field) -> bool { pub(super) fn should_generate_arg(field: &Field) -> bool {
// Perhaps this should be an exhaustive list... // Perhaps this should be an exhaustive list...
field.attrs.iter().all(|attr| is_doc_comment(attr)) field.attrs.iter().all(|attr| is_doc_comment(attr))
} }

View File

@ -500,10 +500,10 @@ pub(crate) struct MultipleCandidates {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for MultipleCandidates { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for MultipleCandidates {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_multiple_candidates); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_multiple_candidates);
diag.set_arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.set_arg("flavor", self.flavor); diag.arg("flavor", self.flavor);
diag.code(error_code!(E0464)); diag.code(error_code!(E0464));
diag.set_span(self.span); diag.span(self.span);
for (i, candidate) in self.candidates.iter().enumerate() { for (i, candidate) in self.candidates.iter().enumerate() {
diag.note(format!("candidate #{}: {}", i + 1, candidate.display())); diag.note(format!("candidate #{}: {}", i + 1, candidate.display()));
} }
@ -596,10 +596,10 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidMetadataFiles {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_invalid_meta_files); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_invalid_meta_files);
diag.set_arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.set_arg("add_info", self.add_info); diag.arg("add_info", self.add_info);
diag.code(error_code!(E0786)); diag.code(error_code!(E0786));
diag.set_span(self.span); diag.span(self.span);
for crate_rejection in self.crate_rejections { for crate_rejection in self.crate_rejections {
diag.note(crate_rejection); diag.note(crate_rejection);
} }
@ -623,12 +623,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for CannotFindCrate {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_cannot_find_crate); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_cannot_find_crate);
diag.set_arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.set_arg("current_crate", self.current_crate); diag.arg("current_crate", self.current_crate);
diag.set_arg("add_info", self.add_info); diag.arg("add_info", self.add_info);
diag.set_arg("locator_triple", self.locator_triple.triple()); diag.arg("locator_triple", self.locator_triple.triple());
diag.code(error_code!(E0463)); diag.code(error_code!(E0463));
diag.set_span(self.span); diag.span(self.span);
if (self.crate_name == sym::std || self.crate_name == sym::core) if (self.crate_name == sym::std || self.crate_name == sym::core)
&& self.locator_triple != TargetTriple::from_triple(config::host_triple()) && self.locator_triple != TargetTriple::from_triple(config::host_triple())
{ {

View File

@ -314,14 +314,14 @@ pub fn struct_lint_level(
} }
Level::ForceWarn(Some(expect_id)) => rustc_errors::Level::Warning(Some(expect_id)), Level::ForceWarn(Some(expect_id)) => rustc_errors::Level::Warning(Some(expect_id)),
Level::Warn | Level::ForceWarn(None) => rustc_errors::Level::Warning(None), Level::Warn | Level::ForceWarn(None) => rustc_errors::Level::Warning(None),
Level::Deny | Level::Forbid => rustc_errors::Level::Error { lint: true }, Level::Deny | Level::Forbid => rustc_errors::Level::Error,
}; };
let mut err = DiagnosticBuilder::new(sess.dcx(), err_level, ""); let mut err = DiagnosticBuilder::new(sess.dcx(), err_level, "");
if let Some(span) = span { if let Some(span) = span {
err.set_span(span); err.span(span);
} }
err.set_is_lint(); err.is_lint();
// If this code originates in a foreign macro, aka something that this crate // If this code originates in a foreign macro, aka something that this crate
// did not itself author, then it's likely that there's nothing this crate // did not itself author, then it's likely that there's nothing this crate
@ -348,7 +348,7 @@ pub fn struct_lint_level(
// Delay evaluating and setting the primary message until after we've // Delay evaluating and setting the primary message until after we've
// suppressed the lint due to macros. // suppressed the lint due to macros.
err.set_primary_message(msg); err.primary_message(msg);
// Lint diagnostics that are covered by the expect level will not be emitted outside // Lint diagnostics that are covered by the expect level will not be emitted outside
// the compiler. It is therefore not necessary to add any information for the user. // the compiler. It is therefore not necessary to add any information for the user.

View File

@ -2,14 +2,10 @@ use super::{AllocId, AllocRange, Pointer, Scalar};
use crate::error; use crate::error;
use crate::mir::{ConstAlloc, ConstValue}; use crate::mir::{ConstAlloc, ConstValue};
use crate::query::TyCtxtAt;
use crate::ty::{layout, tls, Ty, TyCtxt, ValTree}; use crate::ty::{layout, tls, Ty, TyCtxt, ValTree};
use rustc_data_structures::sync::Lock; use rustc_data_structures::sync::Lock;
use rustc_errors::{ use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg};
struct_span_err, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed,
IntoDiagnosticArg,
};
use rustc_macros::HashStable; use rustc_macros::HashStable;
use rustc_session::CtfeBacktrace; use rustc_session::CtfeBacktrace;
use rustc_span::{def_id::DefId, Span, DUMMY_SP}; use rustc_span::{def_id::DefId, Span, DUMMY_SP};
@ -90,10 +86,6 @@ pub type EvalToConstValueResult<'tcx> = Result<ConstValue<'tcx>, ErrorHandled>;
/// This is needed in `thir::pattern::lower_inline_const`. /// This is needed in `thir::pattern::lower_inline_const`.
pub type EvalToValTreeResult<'tcx> = Result<Option<ValTree<'tcx>>, ErrorHandled>; pub type EvalToValTreeResult<'tcx> = Result<Option<ValTree<'tcx>>, ErrorHandled>;
pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'tcx> {
struct_span_err!(tcx.dcx(), tcx.span, E0080, "{}", msg)
}
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
static_assert_size!(InterpErrorInfo<'_>, 8); static_assert_size!(InterpErrorInfo<'_>, 8);

View File

@ -142,12 +142,11 @@ use crate::ty::GenericArgKind;
use crate::ty::{self, Instance, Ty, TyCtxt}; use crate::ty::{self, Instance, Ty, TyCtxt};
pub use self::error::{ pub use self::error::{
struct_error, BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalToAllocationRawResult,
EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind, InterpError, InterpErrorInfo,
InterpError, InterpErrorInfo, InterpResult, InvalidMetaKind, InvalidProgramInfo, InterpResult, InvalidMetaKind, InvalidProgramInfo, MachineStopType, Misalignment, PointerKind,
MachineStopType, Misalignment, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo, ReportedErrorInfo, ResourceExhaustionInfo, ScalarSizeMismatch, UndefinedBehaviorInfo,
ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, UnsupportedOpInfo, ValidationErrorInfo, ValidationErrorKind,
ValidationErrorKind,
}; };
pub use self::value::Scalar; pub use self::value::Scalar;

View File

@ -467,11 +467,11 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
level, level,
fluent::mir_build_non_exhaustive_patterns_type_not_empty, fluent::mir_build_non_exhaustive_patterns_type_not_empty,
); );
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0004)); diag.code(error_code!(E0004));
let peeled_ty = self.ty.peel_refs(); let peeled_ty = self.ty.peel_refs();
diag.set_arg("ty", self.ty); diag.arg("ty", self.ty);
diag.set_arg("peeled_ty", peeled_ty); diag.arg("peeled_ty", peeled_ty);
if let ty::Adt(def, _) = peeled_ty.kind() { if let ty::Adt(def, _) = peeled_ty.kind() {
let def_span = self let def_span = self
@ -855,7 +855,7 @@ impl<'tcx> AddToDiagnostic for AdtDefinedHere<'tcx> {
where where
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage, F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{ {
diag.set_arg("ty", self.ty); diag.arg("ty", self.ty);
let mut spans = MultiSpan::from(self.adt_def_span); let mut spans = MultiSpan::from(self.adt_def_span);
for Variant { span } in self.variants { for Variant { span } in self.variants {

View File

@ -67,11 +67,11 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for RequiresUnsafe {
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::mir_transform_requires_unsafe); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::mir_transform_requires_unsafe);
diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string())); diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string()));
diag.set_span(self.span); diag.span(self.span);
diag.span_label(self.span, self.details.label()); diag.span_label(self.span, self.details.label());
let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter()); let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter());
diag.set_arg("details", desc); diag.arg("details", desc);
diag.set_arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed); diag.arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed);
self.details.add_subdiagnostics(&mut diag); self.details.add_subdiagnostics(&mut diag);
if let Some(sp) = self.enclosing { if let Some(sp) = self.enclosing {
diag.span_label(sp, fluent::mir_transform_not_inherited); diag.span_label(sp, fluent::mir_transform_not_inherited);
@ -122,16 +122,16 @@ impl RequiresUnsafeDetail {
} }
CallToFunctionWith { ref missing, ref build_enabled } => { CallToFunctionWith { ref missing, ref build_enabled } => {
diag.help(fluent::mir_transform_target_feature_call_help); diag.help(fluent::mir_transform_target_feature_call_help);
diag.set_arg( diag.arg(
"missing_target_features", "missing_target_features",
DiagnosticArgValue::StrListSepByAnd( DiagnosticArgValue::StrListSepByAnd(
missing.iter().map(|feature| Cow::from(feature.as_str())).collect(), missing.iter().map(|feature| Cow::from(feature.as_str())).collect(),
), ),
); );
diag.set_arg("missing_target_features_count", missing.len()); diag.arg("missing_target_features_count", missing.len());
if !build_enabled.is_empty() { if !build_enabled.is_empty() {
diag.note(fluent::mir_transform_target_feature_call_note); diag.note(fluent::mir_transform_target_feature_call_note);
diag.set_arg( diag.arg(
"build_target_features", "build_target_features",
DiagnosticArgValue::StrListSepByAnd( DiagnosticArgValue::StrListSepByAnd(
build_enabled build_enabled
@ -140,7 +140,7 @@ impl RequiresUnsafeDetail {
.collect(), .collect(),
), ),
); );
diag.set_arg("build_target_features_count", build_enabled.len()); diag.arg("build_target_features_count", build_enabled.len());
} }
} }
} }
@ -183,7 +183,7 @@ impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
let dcx = diag.dcx().expect("lint should not yet be emitted"); let dcx = diag.dcx().expect("lint should not yet be emitted");
let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter()); let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter());
diag.set_arg("details", desc); diag.arg("details", desc);
diag.span_label(self.details.span, self.details.label()); diag.span_label(self.details.span, self.details.label());
self.details.add_subdiagnostics(diag); self.details.add_subdiagnostics(diag);
@ -213,7 +213,7 @@ impl<'a, P: std::fmt::Debug> DecorateLint<'a, ()> for AssertLint<P> {
let assert_kind = self.panic(); let assert_kind = self.panic();
let message = assert_kind.diagnostic_message(); let message = assert_kind.diagnostic_message();
assert_kind.add_args(&mut |name, value| { assert_kind.add_args(&mut |name, value| {
diag.set_arg(name, value); diag.arg(name, value);
}); });
diag.span_label(span, message); diag.span_label(span, message);
} }
@ -280,9 +280,9 @@ impl<'a> DecorateLint<'a, ()> for MustNotSupend<'_, '_> {
diag.subdiagnostic(reason); diag.subdiagnostic(reason);
} }
diag.span_help(self.src_sp, fluent::_subdiag::help); diag.span_help(self.src_sp, fluent::_subdiag::help);
diag.set_arg("pre", self.pre); diag.arg("pre", self.pre);
diag.set_arg("def_path", self.tcx.def_path_str(self.def_id)); diag.arg("def_path", self.tcx.def_path_str(self.def_id));
diag.set_arg("post", self.post); diag.arg("post", self.post);
} }
fn msg(&self) -> rustc_errors::DiagnosticMessage { fn msg(&self) -> rustc_errors::DiagnosticMessage {

View File

@ -51,7 +51,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for UnusedGenericParamsHint {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = let mut diag =
DiagnosticBuilder::new(dcx, level, fluent::monomorphize_unused_generic_params); DiagnosticBuilder::new(dcx, level, fluent::monomorphize_unused_generic_params);
diag.set_span(self.span); diag.span(self.span);
for (span, name) in self.param_spans.into_iter().zip(self.param_names) { for (span, name) in self.param_spans.into_iter().zip(self.param_names) {
// FIXME: I can figure out how to do a label with a fluent string with a fixed message, // FIXME: I can figure out how to do a label with a fluent string with a fixed message,
// or a label with a dynamic value in a hard-coded string, but I haven't figured out // or a label with a dynamic value in a hard-coded string, but I haven't figured out

View File

@ -1065,8 +1065,8 @@ impl<'a> IntoDiagnostic<'a> for ExpectedIdentifier {
None => fluent::parse_expected_identifier_found_str, None => fluent::parse_expected_identifier_found_str,
}, },
); );
diag.set_span(self.span); diag.span(self.span);
diag.set_arg("token", self.token); diag.arg("token", self.token);
if let Some(sugg) = self.suggest_raw { if let Some(sugg) = self.suggest_raw {
sugg.add_to_diagnostic(&mut diag); sugg.add_to_diagnostic(&mut diag);
@ -1123,8 +1123,8 @@ impl<'a> IntoDiagnostic<'a> for ExpectedSemi {
None => fluent::parse_expected_semi_found_str, None => fluent::parse_expected_semi_found_str,
}, },
); );
diag.set_span(self.span); diag.span(self.span);
diag.set_arg("token", self.token); diag.arg("token", self.token);
if let Some(unexpected_token_label) = self.unexpected_token_label { if let Some(unexpected_token_label) = self.unexpected_token_label {
diag.span_label(unexpected_token_label, fluent::parse_label_unexpected_token); diag.span_label(unexpected_token_label, fluent::parse_label_unexpected_token);

View File

@ -7,9 +7,7 @@ use rustc_ast::ast::{self, AttrStyle};
use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind}; use rustc_ast::token::{self, CommentKind, Delimiter, Token, TokenKind};
use rustc_ast::tokenstream::TokenStream; use rustc_ast::tokenstream::TokenStream;
use rustc_ast::util::unicode::contains_text_flow_control_chars; use rustc_ast::util::unicode::contains_text_flow_control_chars;
use rustc_errors::{ use rustc_errors::{error_code, Applicability, DiagCtxt, Diagnostic, StashKey};
error_code, Applicability, DiagCtxt, Diagnostic, DiagnosticBuilder, FatalAbort, StashKey,
};
use rustc_lexer::unescape::{self, EscapeError, Mode}; use rustc_lexer::unescape::{self, EscapeError, Mode};
use rustc_lexer::{Base, DocStyle, RawStrError}; use rustc_lexer::{Base, DocStyle, RawStrError};
use rustc_lexer::{Cursor, LiteralKind}; use rustc_lexer::{Cursor, LiteralKind};
@ -252,7 +250,7 @@ impl<'a> StringReader<'a> {
if starts_with_number { if starts_with_number {
let span = self.mk_sp(start, self.pos); let span = self.mk_sp(start, self.pos);
let mut diag = self.dcx().struct_err("lifetimes cannot start with a number"); let mut diag = self.dcx().struct_err("lifetimes cannot start with a number");
diag.set_span(span); diag.span(span);
diag.stash(span, StashKey::LifetimeIsChar); diag.stash(span, StashKey::LifetimeIsChar);
} }
let ident = Symbol::intern(lifetime_name); let ident = Symbol::intern(lifetime_name);
@ -344,18 +342,6 @@ impl<'a> StringReader<'a> {
token::Ident(sym, false) token::Ident(sym, false)
} }
fn struct_fatal_span_char(
&self,
from_pos: BytePos,
to_pos: BytePos,
m: &str,
c: char,
) -> DiagnosticBuilder<'a, FatalAbort> {
self.sess
.dcx
.struct_span_fatal(self.mk_sp(from_pos, to_pos), format!("{}: {}", m, escaped_char(c)))
}
/// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
/// complain about it. /// complain about it.
fn lint_unicode_text_flow(&self, start: BytePos) { fn lint_unicode_text_flow(&self, start: BytePos) {
@ -568,13 +554,16 @@ impl<'a> StringReader<'a> {
} }
fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! { fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
self.struct_fatal_span_char( self.sess
start, .dcx
self.pos, .struct_span_fatal(
"found invalid character; only `#` is allowed in raw string delimitation", self.mk_sp(start, self.pos),
bad_char, format!(
) "found invalid character; only `#` is allowed in raw string delimitation: {}",
.emit() escaped_char(bad_char)
),
)
.emit()
} }
fn report_unterminated_raw_string( fn report_unterminated_raw_string(

View File

@ -154,7 +154,7 @@ fn try_file_to_source_file(
let msg = format!("couldn't read {}: {}", path.display(), e); let msg = format!("couldn't read {}: {}", path.display(), e);
let mut diag = Diagnostic::new(Level::Fatal, msg); let mut diag = Diagnostic::new(Level::Fatal, msg);
if let Some(sp) = spanopt { if let Some(sp) = spanopt {
diag.set_span(sp); diag.span(sp);
} }
diag diag
}) })

View File

@ -174,7 +174,7 @@ impl<'a> Parser<'a> {
) { ) {
Ok(Some(item)) => { Ok(Some(item)) => {
// FIXME(#100717) // FIXME(#100717)
err.set_arg("item", item.kind.descr()); err.arg("item", item.kind.descr());
err.span_label(item.span, fluent::parse_label_does_not_annotate_this); err.span_label(item.span, fluent::parse_label_does_not_annotate_this);
err.span_suggestion_verbose( err.span_suggestion_verbose(
replacement_span, replacement_span,

View File

@ -846,7 +846,7 @@ impl<'a> Parser<'a> {
) => ) =>
{ {
let n_hashes: u8 = *n_hashes; let n_hashes: u8 = *n_hashes;
err.set_primary_message("too many `#` when terminating raw string"); err.primary_message("too many `#` when terminating raw string");
let str_span = self.prev_token.span; let str_span = self.prev_token.span;
let mut span = self.token.span; let mut span = self.token.span;
let mut count = 0; let mut count = 0;
@ -857,7 +857,7 @@ impl<'a> Parser<'a> {
self.bump(); self.bump();
count += 1; count += 1;
} }
err.set_span(span); err.span(span);
err.span_suggestion( err.span_suggestion(
span, span,
format!("remove the extra `#`{}", pluralize!(count)), format!("remove the extra `#`{}", pluralize!(count)),

View File

@ -925,9 +925,8 @@ impl<'a> Parser<'a> {
}); });
} }
expect_err.set_primary_message( expect_err
"closure bodies that contain statements must be surrounded by braces", .primary_message("closure bodies that contain statements must be surrounded by braces");
);
let preceding_pipe_span = closure_spans.closing_pipe; let preceding_pipe_span = closure_spans.closing_pipe;
let following_token_span = self.token.span; let following_token_span = self.token.span;
@ -951,7 +950,7 @@ impl<'a> Parser<'a> {
); );
expect_err.span_note(second_note, "the closure body may be incorrectly delimited"); expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
expect_err.set_span(vec![preceding_pipe_span, following_token_span]); expect_err.span(vec![preceding_pipe_span, following_token_span]);
let opening_suggestion_str = " {".to_string(); let opening_suggestion_str = " {".to_string();
let closing_suggestion_str = "}".to_string(); let closing_suggestion_str = "}".to_string();

View File

@ -2341,17 +2341,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
match terr { match terr {
TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => { TypeError::ArgumentMutability(idx) | TypeError::ArgumentSorts(_, idx) => {
if let Some(ty) = hir_sig.decl.inputs.get(idx) { if let Some(ty) = hir_sig.decl.inputs.get(idx) {
diag.set_span(ty.span); diag.span(ty.span);
cause.span = ty.span; cause.span = ty.span;
} else if idx == hir_sig.decl.inputs.len() { } else if idx == hir_sig.decl.inputs.len() {
let span = hir_sig.decl.output.span(); let span = hir_sig.decl.output.span();
diag.set_span(span); diag.span(span);
cause.span = span; cause.span = span;
} }
} }
TypeError::ArgCount => { TypeError::ArgCount => {
if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) { if let Some(ty) = hir_sig.decl.inputs.get(expected_sig.inputs().len()) {
diag.set_span(ty.span); diag.span(ty.span);
cause.span = ty.span; cause.span = ty.span;
} }
} }

View File

@ -868,8 +868,8 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidAttrAtCrateLevel {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = let mut diag =
DiagnosticBuilder::new(dcx, level, fluent::passes_invalid_attr_at_crate_level); DiagnosticBuilder::new(dcx, level, fluent::passes_invalid_attr_at_crate_level);
diag.set_span(self.span); diag.span(self.span);
diag.set_arg("name", self.name); diag.arg("name", self.name);
// Only emit an error with a suggestion if we can create a string out // Only emit an error with a suggestion if we can create a string out
// of the attribute span // of the attribute span
if let Some(span) = self.sugg_span { if let Some(span) = self.sugg_span {
@ -881,7 +881,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidAttrAtCrateLevel {
); );
} }
if let Some(item) = self.item { if let Some(item) = self.item {
diag.set_arg("kind", item.kind); diag.arg("kind", item.kind);
diag.span_label(item.span, fluent::passes_invalid_attr_at_crate_level_item); diag.span_label(item.span, fluent::passes_invalid_attr_at_crate_level_item);
} }
diag diag
@ -1018,9 +1018,9 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'_, G> for BreakNonLoop<'a> {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_break_non_loop); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_break_non_loop);
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0571)); diag.code(error_code!(E0571));
diag.set_arg("kind", self.kind); diag.arg("kind", self.kind);
diag.span_label(self.span, fluent::passes_label); diag.span_label(self.span, fluent::passes_label);
if let Some(head) = self.head { if let Some(head) = self.head {
diag.span_label(head, fluent::passes_label2); diag.span_label(head, fluent::passes_label2);
@ -1162,7 +1162,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for NakedFunctionsAsmBlock {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_naked_functions_asm_block); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_naked_functions_asm_block);
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0787)); diag.code(error_code!(E0787));
for span in self.multiple_asms.iter() { for span in self.multiple_asms.iter() {
diag.span_label(*span, fluent::passes_label_multiple_asm); diag.span_label(*span, fluent::passes_label_multiple_asm);
@ -1273,11 +1273,11 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for NoMainErr {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_no_main_function); let mut diag = DiagnosticBuilder::new(dcx, level, fluent::passes_no_main_function);
diag.set_span(DUMMY_SP); diag.span(DUMMY_SP);
diag.code(error_code!(E0601)); diag.code(error_code!(E0601));
diag.set_arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.set_arg("filename", self.filename); diag.arg("filename", self.filename);
diag.set_arg("has_filename", self.has_filename); diag.arg("has_filename", self.has_filename);
let note = if !self.non_main_fns.is_empty() { let note = if !self.non_main_fns.is_empty() {
for &span in &self.non_main_fns { for &span in &self.non_main_fns {
diag.span_note(span, fluent::passes_here_is_main); diag.span_note(span, fluent::passes_here_is_main);
@ -1294,7 +1294,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for NoMainErr {
if self.file_empty { if self.file_empty {
diag.note(note); diag.note(note);
} else { } else {
diag.set_span(self.sp.shrink_to_hi()); diag.span(self.sp.shrink_to_hi());
diag.span_label(self.sp.shrink_to_hi(), note); diag.span_label(self.sp.shrink_to_hi(), note);
} }
@ -1340,15 +1340,15 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for DuplicateLangItem {
}, },
); );
diag.code(error_code!(E0152)); diag.code(error_code!(E0152));
diag.set_arg("lang_item_name", self.lang_item_name); diag.arg("lang_item_name", self.lang_item_name);
diag.set_arg("crate_name", self.crate_name); diag.arg("crate_name", self.crate_name);
diag.set_arg("dependency_of", self.dependency_of); diag.arg("dependency_of", self.dependency_of);
diag.set_arg("path", self.path); diag.arg("path", self.path);
diag.set_arg("orig_crate_name", self.orig_crate_name); diag.arg("orig_crate_name", self.orig_crate_name);
diag.set_arg("orig_dependency_of", self.orig_dependency_of); diag.arg("orig_dependency_of", self.orig_dependency_of);
diag.set_arg("orig_path", self.orig_path); diag.arg("orig_path", self.orig_path);
if let Some(span) = self.local_span { if let Some(span) = self.local_span {
diag.set_span(span); diag.span(span);
} }
if let Some(span) = self.first_defined_span { if let Some(span) = self.first_defined_span {
diag.span_note(span, fluent::passes_first_defined_span); diag.span_note(span, fluent::passes_first_defined_span);

View File

@ -204,7 +204,7 @@ pub(crate) fn lint_nonexhaustive_missing_variants<'a, 'p, 'tcx>(
use rustc_errors::DecorateLint; use rustc_errors::DecorateLint;
let mut err = rcx.tcx.dcx().struct_span_warn(arm.pat.data().unwrap().span, ""); let mut err = rcx.tcx.dcx().struct_span_warn(arm.pat.data().unwrap().span, "");
err.set_primary_message(decorator.msg()); err.primary_message(decorator.msg());
decorator.decorate_lint(&mut err); decorator.decorate_lint(&mut err);
err.emit(); err.emit();
} }

View File

@ -1383,7 +1383,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
| PathSource::TupleStruct(span, _) => { | PathSource::TupleStruct(span, _) => {
// We want the main underline to cover the suggested code as well for // We want the main underline to cover the suggested code as well for
// cleaner output. // cleaner output.
err.set_span(*span); err.span(*span);
*span *span
} }
_ => span, _ => span,
@ -1615,7 +1615,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
let field_spans = match source { let field_spans = match source {
// e.g. `if let Enum::TupleVariant(field1, field2) = _` // e.g. `if let Enum::TupleVariant(field1, field2) = _`
PathSource::TupleStruct(_, pattern_spans) => { PathSource::TupleStruct(_, pattern_spans) => {
err.set_primary_message( err.primary_message(
"cannot match against a tuple struct which contains private fields", "cannot match against a tuple struct which contains private fields",
); );
@ -1628,7 +1628,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
span: call_span, span: call_span,
.. ..
})) => { })) => {
err.set_primary_message( err.primary_message(
"cannot initialize a tuple struct which contains private fields", "cannot initialize a tuple struct which contains private fields",
); );
self.suggest_alternative_construction_methods( self.suggest_alternative_construction_methods(

View File

@ -19,7 +19,7 @@ impl<'a> IntoDiagnostic<'a> for FeatureGateError {
#[track_caller] #[track_caller]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a> { fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a> {
let mut diag = DiagnosticBuilder::new(dcx, level, self.explain); let mut diag = DiagnosticBuilder::new(dcx, level, self.explain);
diag.set_span(self.span); diag.span(self.span);
diag.code(error_code!(E0658)); diag.code(error_code!(E0658));
diag diag
} }

View File

@ -19,7 +19,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TestOutput {
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
let mut diag = DiagnosticBuilder::new(dcx, level, format!("{kind}({content})")); let mut diag = DiagnosticBuilder::new(dcx, level, format!("{kind}({content})"));
diag.set_span(span); diag.span(span);
diag diag
} }
} }

View File

@ -66,12 +66,9 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for NegativePositiveConflict<'_
) -> rustc_errors::DiagnosticBuilder<'_, G> { ) -> rustc_errors::DiagnosticBuilder<'_, G> {
let mut diag = let mut diag =
DiagnosticBuilder::new(dcx, level, fluent::trait_selection_negative_positive_conflict); DiagnosticBuilder::new(dcx, level, fluent::trait_selection_negative_positive_conflict);
diag.set_arg("trait_desc", self.trait_desc.print_only_trait_path().to_string()); diag.arg("trait_desc", self.trait_desc.print_only_trait_path().to_string());
diag.set_arg( diag.arg("self_desc", self.self_ty.map_or_else(|| "none".to_string(), |ty| ty.to_string()));
"self_desc", diag.span(self.impl_span);
self.self_ty.map_or_else(|| "none".to_string(), |ty| ty.to_string()),
);
diag.set_span(self.impl_span);
diag.code(rustc_errors::error_code!(E0751)); diag.code(rustc_errors::error_code!(E0751));
match self.negative_impl_span { match self.negative_impl_span {
Ok(span) => { Ok(span) => {
@ -79,7 +76,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for NegativePositiveConflict<'_
} }
Err(cname) => { Err(cname) => {
diag.note(fluent::trait_selection_negative_implementation_in_crate); diag.note(fluent::trait_selection_negative_implementation_in_crate);
diag.set_arg("negative_impl_cname", cname.to_string()); diag.arg("negative_impl_cname", cname.to_string());
} }
} }
match self.positive_impl_span { match self.positive_impl_span {
@ -88,7 +85,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for NegativePositiveConflict<'_
} }
Err(cname) => { Err(cname) => {
diag.note(fluent::trait_selection_positive_implementation_in_crate); diag.note(fluent::trait_selection_positive_implementation_in_crate);
diag.set_arg("positive_impl_cname", cname.to_string()); diag.arg("positive_impl_cname", cname.to_string());
} }
} }
diag diag
@ -115,7 +112,7 @@ impl AddToDiagnostic for AdjustSignatureBorrow {
{ {
match self { match self {
AdjustSignatureBorrow::Borrow { to_borrow } => { AdjustSignatureBorrow::Borrow { to_borrow } => {
diag.set_arg("len", to_borrow.len()); diag.arg("len", to_borrow.len());
diag.multipart_suggestion_verbose( diag.multipart_suggestion_verbose(
fluent::trait_selection_adjust_signature_borrow, fluent::trait_selection_adjust_signature_borrow,
to_borrow, to_borrow,
@ -123,7 +120,7 @@ impl AddToDiagnostic for AdjustSignatureBorrow {
); );
} }
AdjustSignatureBorrow::RemoveBorrow { remove_borrow } => { AdjustSignatureBorrow::RemoveBorrow { remove_borrow } => {
diag.set_arg("len", remove_borrow.len()); diag.arg("len", remove_borrow.len());
diag.multipart_suggestion_verbose( diag.multipart_suggestion_verbose(
fluent::trait_selection_adjust_signature_remove_borrow, fluent::trait_selection_adjust_signature_remove_borrow,
remove_borrow, remove_borrow,

View File

@ -2007,7 +2007,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
}; };
err.code(error_code!(E0746)); err.code(error_code!(E0746));
err.set_primary_message("return type cannot have an unboxed trait object"); err.primary_message("return type cannot have an unboxed trait object");
err.children.clear(); err.children.clear();
let span = obligation.cause.span; let span = obligation.cause.span;
@ -2712,7 +2712,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") }; if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
err.clear_code(); err.clear_code();
err.set_primary_message(format!( err.primary_message(format!(
"{future_or_coroutine} cannot be {trait_verb} between threads safely" "{future_or_coroutine} cannot be {trait_verb} between threads safely"
)); ));
@ -2800,7 +2800,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
.unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}")); .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
span.push_span_label(original_span, message); span.push_span_label(original_span, message);
err.set_span(span); err.span(span);
format!("is not {trait_name}") format!("is not {trait_name}")
} else { } else {

View File

@ -3163,14 +3163,14 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
) { ) {
match obligation_cause_code { match obligation_cause_code {
ObligationCauseCode::RustCall => { ObligationCauseCode::RustCall => {
err.set_primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument"); err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
} }
ObligationCauseCode::BindingObligation(def_id, _) ObligationCauseCode::BindingObligation(def_id, _)
| ObligationCauseCode::ItemObligation(def_id) | ObligationCauseCode::ItemObligation(def_id)
if self.tcx.is_fn_trait(*def_id) => if self.tcx.is_fn_trait(*def_id) =>
{ {
err.code(rustc_errors::error_code!(E0059)); err.code(rustc_errors::error_code!(E0059));
err.set_primary_message(format!( err.primary_message(format!(
"type parameter to bare `{}` trait must be a tuple", "type parameter to bare `{}` trait must be a tuple",
self.tcx.def_path_str(*def_id) self.tcx.def_path_str(*def_id)
)); ));

View File

@ -1733,7 +1733,7 @@ fn report_diagnostic(
}; };
if let Some(sp) = span { if let Some(sp) = span {
lint.set_span(sp); lint.span(sp);
} else { } else {
// blah blah blah\nblah\nblah [blah] blah blah\nblah blah // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
// ^ ~~~~ // ^ ~~~~

View File

@ -454,12 +454,12 @@ pub fn report_msg<'tcx>(
let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span); let span = stacktrace.first().map_or(DUMMY_SP, |fi| fi.span);
let sess = machine.tcx.sess; let sess = machine.tcx.sess;
let level = match diag_level { let level = match diag_level {
DiagLevel::Error => Level::Error { lint: false }, DiagLevel::Error => Level::Error,
DiagLevel::Warning => Level::Warning(None), DiagLevel::Warning => Level::Warning(None),
DiagLevel::Note => Level::Note, DiagLevel::Note => Level::Note,
}; };
let mut err = DiagnosticBuilder::<()>::new(sess.dcx(), level, title); let mut err = DiagnosticBuilder::<()>::new(sess.dcx(), level, title);
err.set_span(span); err.span(span);
// Show main message. // Show main message.
if span != DUMMY_SP { if span != DUMMY_SP {

View File

@ -8,7 +8,7 @@ LL | arg: NotIntoDiagnosticArg,
| ^^^^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `NotIntoDiagnosticArg` | ^^^^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `NotIntoDiagnosticArg`
| |
= help: normalized in stderr = help: normalized in stderr
note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` note: required by a bound in `DiagnosticBuilder::<'a, G>::arg`
--> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:LL:CC --> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:LL:CC
= note: this error originates in the macro `forward` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the macro `forward` (in Nightly builds, run with -Z macro-backtrace for more info)
@ -22,7 +22,7 @@ LL | arg: NotIntoDiagnosticArg,
| ^^^^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `NotIntoDiagnosticArg` | ^^^^^^^^^^^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `NotIntoDiagnosticArg`
| |
= help: normalized in stderr = help: normalized in stderr
note: required by a bound in `Diagnostic::set_arg` note: required by a bound in `Diagnostic::arg`
--> $COMPILER_DIR/rustc_errors/src/diagnostic.rs:LL:CC --> $COMPILER_DIR/rustc_errors/src/diagnostic.rs:LL:CC
error: aborting due to 2 previous errors error: aborting due to 2 previous errors

View File

@ -741,7 +741,7 @@ struct SubdiagnosticEagerCorrect {
} }
// Check that formatting of `correct` in suggestion doesn't move the binding for that field, making // Check that formatting of `correct` in suggestion doesn't move the binding for that field, making
// the `set_arg` call a compile error; and that isn't worked around by moving the `set_arg` call // the `arg` call a compile error; and that isn't worked around by moving the `arg` call
// after the `span_suggestion` call - which breaks eager translation. // after the `span_suggestion` call - which breaks eager translation.
#[derive(Subdiagnostic)] #[derive(Subdiagnostic)]

View File

@ -654,7 +654,7 @@ LL | other: Hello,
| ^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` | ^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello`
| |
= help: normalized in stderr = help: normalized in stderr
note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` note: required by a bound in `DiagnosticBuilder::<'a, G>::arg`
--> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:LL:CC --> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:LL:CC
= note: this error originates in the macro `forward` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the macro `forward` (in Nightly builds, run with -Z macro-backtrace for more info)