Skip to content

Rollup of 10 pull requests #119611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 36 commits into from
Closed
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
5f56465
Make feature `negative_bounds` internal
fmease Dec 27, 2023
a251974
Deny parenthetical notation for negative bounds
fmease Dec 27, 2023
32cea61
Don't elaborate `!Sized` to `!Sized + Sized`
fmease Dec 27, 2023
977546d
rustc_middle: Pretty-print negative bounds correctly
fmease Dec 27, 2023
786e0bb
bootstrap: Move -Clto= setting from Rustc::run to rustc_cargo
xry111 Dec 29, 2023
76d616d
Handle ForeignItem as TAIT scope.
cjgillot Dec 29, 2023
7fd2d8d
Do not run check on foreign items.
cjgillot Dec 31, 2023
505c137
Rename some `Diagnostic` setters.
nnethercote Dec 23, 2023
5fe5d5d
Remove lots of `rustc_errors::` qualifiers in `lints.rs`.
nnethercote Jan 2, 2024
096b844
Remove forward for `downgrade_to_delayed_bug`.
nnethercote Jan 3, 2024
caefa55
Fix up `forward!` decls.
nnethercote Jan 3, 2024
b4a6239
Fix `forward!` so it doesn't require trailing commas in some cases.
nnethercote Jan 3, 2024
1e92223
Remove unused `DiagnosticBuilder::struct_almost_fatal`.
nnethercote Jan 3, 2024
9560c58
Avoid some `rustc_errors::` qualifiers.
nnethercote Jan 4, 2024
4d35981
Remove unused `struct_error` function.
nnethercote Jan 4, 2024
8e6bca6
Inline and remove `StringReader::struct_fatal_span_char`.
nnethercote Jan 4, 2024
03e9eff
Use `resolutions(()).effective_visiblities` to avoid cycle errors
compiler-errors Jan 4, 2024
af32054
Remove `-Zdump-mir-spanview`
Zalathar Jan 4, 2024
8388112
Remove `is_lint` field from `Level::Error`.
nnethercote Jan 4, 2024
cf9484e
Remove `-Zreport-delayed-bugs`.
nnethercote Jan 4, 2024
35ad2ae
Fix invalid handling for static method calls in jump to definition fe…
GuillaumeGomez Jan 4, 2024
5bc7687
Add regression test for jump to def static method calls
GuillaumeGomez Jan 4, 2024
073ed0e
Move `i586-unknown-netbsd` from tier 2 to tier 3 platform support table
Nemo157 Jan 4, 2024
12b92c8
Visit only reachable blocks in MIR lint
tmiasko Dec 30, 2023
a084e06
Fix validation and linting of injected MIR
tmiasko Jan 1, 2024
df116ec
Migrate memory overlap check from validator to lint
tmiasko Jan 4, 2024
98c9d72
Rollup merge of #119354 - fmease:negative_bounds-fixes, r=compiler-er…
GuillaumeGomez Jan 5, 2024
3a19a92
Rollup merge of #119414 - xry111:xry111/lto-test, r=Mark-Simulacrum
GuillaumeGomez Jan 5, 2024
2dcaadb
Rollup merge of #119420 - cjgillot:issue-119295, r=compiler-errors
GuillaumeGomez Jan 5, 2024
3eebe88
Rollup merge of #119506 - compiler-errors:visibilities-for-object-saf…
GuillaumeGomez Jan 5, 2024
c537d20
Rollup merge of #119538 - nnethercote:cleanup-errors-5, r=compiler-er…
GuillaumeGomez Jan 5, 2024
38e22ad
Rollup merge of #119566 - Zalathar:remove-spanview, r=Swatinem,Nilstrieb
GuillaumeGomez Jan 5, 2024
22a6343
Rollup merge of #119567 - nnethercote:rm-Zreport-delayed-bugs, r=oli-obk
GuillaumeGomez Jan 5, 2024
c224f4d
Rollup merge of #119577 - tmiasko:lint, r=oli-obk
GuillaumeGomez Jan 5, 2024
eef3320
Rollup merge of #119586 - GuillaumeGomez:jump-to-def-static-methods, …
GuillaumeGomez Jan 5, 2024
2a10782
Rollup merge of #119588 - Nemo157:i586-netbsd-tier-3, r=Nilstrieb
GuillaumeGomez Jan 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/rustc_ast_passes/messages.ftl
Original file line number Diff line number Diff line change
@@ -188,6 +188,9 @@ ast_passes_module_nonascii = trying to load file for module `{$name}` with non-a
ast_passes_negative_bound_not_supported =
negative bounds are not supported

ast_passes_negative_bound_with_parenthetical_notation =
parenthetical notation may not be used for negative bounds

ast_passes_nested_impl_trait = nested `impl Trait` is not allowed
.outer = outer `impl Trait`
.inner = nested `impl Trait` here
21 changes: 16 additions & 5 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
@@ -1312,13 +1312,24 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
if let GenericBound::Trait(trait_ref, modifiers) = bound
&& let BoundPolarity::Negative(_) = modifiers.polarity
&& let Some(segment) = trait_ref.trait_ref.path.segments.last()
&& let Some(ast::GenericArgs::AngleBracketed(args)) = segment.args.as_deref()
{
for arg in &args.args {
if let ast::AngleBracketedArg::Constraint(constraint) = arg {
self.dcx()
.emit_err(errors::ConstraintOnNegativeBound { span: constraint.span });
match segment.args.as_deref() {
Some(ast::GenericArgs::AngleBracketed(args)) => {
for arg in &args.args {
if let ast::AngleBracketedArg::Constraint(constraint) = arg {
self.dcx().emit_err(errors::ConstraintOnNegativeBound {
span: constraint.span,
});
}
}
}
// The lowered form of parenthesized generic args contains a type binding.
Some(ast::GenericArgs::Parenthesized(args)) => {
self.dcx().emit_err(errors::NegativeBoundWithParentheticalNotation {
span: args.span,
});
}
None => {}
}
}

11 changes: 9 additions & 2 deletions compiler/rustc_ast_passes/src/errors.rs
Original file line number Diff line number Diff line change
@@ -725,8 +725,8 @@ impl AddToDiagnostic for StableFeature {
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
{
diag.set_arg("name", self.name);
diag.set_arg("since", self.since);
diag.arg("name", self.name);
diag.arg("since", self.since);
diag.help(fluent::ast_passes_stable_since);
}
}
@@ -763,6 +763,13 @@ pub struct ConstraintOnNegativeBound {
pub span: Span,
}

#[derive(Diagnostic)]
#[diag(ast_passes_negative_bound_with_parenthetical_notation)]
pub struct NegativeBoundWithParentheticalNotation {
#[primary_span]
pub span: Span,
}

#[derive(Diagnostic)]
#[diag(ast_passes_invalid_unnamed_field_ty)]
pub struct InvalidUnnamedFieldTy {
8 changes: 4 additions & 4 deletions compiler/rustc_attr/src/session_diagnostics.rs
Original file line number Diff line number Diff line change
@@ -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> {
let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
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.set_arg("item", self.item);
diag.set_arg("expected", expected.join(", "));
diag.arg("item", self.item);
diag.arg("expected", expected.join(", "));
diag.span_label(self.span, fluent::attr_label);
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));
if self.is_bytestr {
diag.span_suggestion(
6 changes: 3 additions & 3 deletions compiler/rustc_builtin_macros/src/errors.rs
Original file line number Diff line number Diff line change
@@ -454,7 +454,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for EnvNotDefinedWithUserMe
reason = "cannot translate user-provided messages"
)]
let mut diag = DiagnosticBuilder::new(dcx, level, self.msg_from_user.to_string());
diag.set_span(self.span);
diag.span(self.span);
diag
}
}
@@ -618,7 +618,7 @@ impl AddToDiagnostic for FormatUnusedArg {
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());
diag.span_label(self.span, msg);
}
@@ -808,7 +808,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for AsmClobberNoReg {
level,
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>`
let lbl1 = dcx.eagerly_translate_to_string(
crate::fluent_generated::builtin_macros_asm_clobber_abi,
4 changes: 2 additions & 2 deletions compiler/rustc_builtin_macros/src/test.rs
Original file line number Diff line number Diff line change
@@ -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
// stable user code (#94508).
Some(ast::ItemKind::MacCall(_)) => Level::Warning(None),
_ => Level::Error { lint: false },
_ => Level::Error,
};
let mut err = DiagnosticBuilder::<()>::new(dcx, level, msg);
err.set_span(attr_sp);
err.span(attr_sp);
if let Some(item) = item {
err.span_label(
item.span,
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_gcc/src/errors.rs
Original file line number Diff line number Diff line change
@@ -119,12 +119,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnabl
fluent::codegen_gcc_target_feature_disable_or_enable
);
if let Some(span) = self.span {
diag.set_span(span);
diag.span(span);
};
if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(missing_features);
}
diag.set_arg("features", self.features.join(", "));
diag.arg("features", self.features.join(", "));
diag
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/back/write.rs
Original file line number Diff line number Diff line change
@@ -416,7 +416,7 @@ fn report_inline_asm(
cookie = 0;
}
let level = match level {
llvm::DiagnosticLevel::Error => Level::Error { lint: false },
llvm::DiagnosticLevel::Error => Level::Error,
llvm::DiagnosticLevel::Warning => Level::Warning(None),
llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
};
10 changes: 5 additions & 5 deletions compiler/rustc_codegen_llvm/src/errors.rs
Original file line number Diff line number Diff line change
@@ -107,7 +107,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ParseTargetMachineConfig<'_

let mut diag =
DiagnosticBuilder::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config);
diag.set_arg("error", message);
diag.arg("error", message);
diag
}
}
@@ -130,12 +130,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetFeatureDisableOrEnabl
fluent::codegen_llvm_target_feature_disable_or_enable,
);
if let Some(span) = self.span {
diag.set_span(span);
diag.span(span);
};
if let Some(missing_features) = self.missing_features {
diag.subdiagnostic(missing_features);
}
diag.set_arg("features", self.features.join(", "));
diag.arg("features", self.features.join(", "));
diag
}
}
@@ -205,8 +205,8 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> {
ParseBitcode => fluent::codegen_llvm_parse_bitcode_with_llvm_err,
};
let mut diag = self.0.into_diagnostic(dcx, level);
diag.set_primary_message(msg_with_llvm_err);
diag.set_arg("llvm_err", self.1);
diag.primary_message(msg_with_llvm_err);
diag.arg("llvm_err", self.1);
diag
}
}
8 changes: 4 additions & 4 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
@@ -1848,9 +1848,9 @@ impl SharedEmitterMain {
}
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
let err_level = match level {
Level::Error { lint: false } => rustc_errors::Level::Error { lint: false },
Level::Warning(_) => rustc_errors::Level::Warning(None),
Level::Note => rustc_errors::Level::Note,
Level::Error => Level::Error,
Level::Warning(_) => Level::Warning(None),
Level::Note => Level::Note,
_ => bug!("Invalid inline asm diagnostic level"),
};
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
@@ -1860,7 +1860,7 @@ impl SharedEmitterMain {
if cookie != 0 {
let pos = BytePos::from_u32(cookie);
let span = Span::with_root_ctxt(pos, pos);
err.set_span(span);
err.span(span);
};

// Point to the generated assembly if it is available.
54 changes: 27 additions & 27 deletions compiler/rustc_codegen_ssa/src/errors.rs
Original file line number Diff line number Diff line change
@@ -244,30 +244,30 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::NamelessSection(_, offset) => {
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
}
thorin::Error::RelocationWithInvalidSymbol(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol);
diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}"));
diag.arg("section", section);
diag.arg("offset", format!("0x{offset:08x}"));
diag
}
thorin::Error::MultipleRelocations(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_multiple_relocations);
diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}"));
diag.arg("section", section);
diag.arg("offset", format!("0x{offset:08x}"));
diag
}
thorin::Error::UnsupportedRelocation(section, offset) => {
diag = build(fluent::codegen_ssa_thorin_unsupported_relocation);
diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}"));
diag.arg("section", section);
diag.arg("offset", format!("0x{offset:08x}"));
diag
}
thorin::Error::MissingDwoName(id) => {
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
}
thorin::Error::NoCompilationUnits => {
@@ -284,7 +284,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::MissingRequiredSection(section) => {
diag = build(fluent::codegen_ssa_thorin_missing_required_section);
diag.set_arg("section", section);
diag.arg("section", section);
diag
}
thorin::Error::ParseUnitAbbreviations(_) => {
@@ -305,34 +305,34 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::IncompatibleIndexVersion(section, format, actual) => {
diag = build(fluent::codegen_ssa_thorin_incompatible_index_version);
diag.set_arg("section", section);
diag.set_arg("actual", actual);
diag.set_arg("format", format);
diag.arg("section", section);
diag.arg("actual", actual);
diag.arg("format", format);
diag
}
thorin::Error::OffsetAtIndex(_, index) => {
diag = build(fluent::codegen_ssa_thorin_offset_at_index);
diag.set_arg("index", index);
diag.arg("index", index);
diag
}
thorin::Error::StrAtOffset(_, 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
}
thorin::Error::ParseIndex(_, section) => {
diag = build(fluent::codegen_ssa_thorin_parse_index);
diag.set_arg("section", section);
diag.arg("section", section);
diag
}
thorin::Error::UnitNotInIndex(unit) => {
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
}
thorin::Error::RowNotInIndex(_, row) => {
diag = build(fluent::codegen_ssa_thorin_row_not_in_index);
diag.set_arg("row", row);
diag.arg("row", row);
diag
}
thorin::Error::SectionNotInRow => {
@@ -341,7 +341,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::EmptyUnit(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
}
thorin::Error::MultipleDebugInfoSection => {
@@ -358,12 +358,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::DuplicateUnit(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
}
thorin::Error::MissingReferencedUnit(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
}
thorin::Error::NoOutputObjectCreated => {
@@ -376,27 +376,27 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for ThorinErrorWrapper {
}
thorin::Error::Io(e) => {
diag = build(fluent::codegen_ssa_thorin_io);
diag.set_arg("error", format!("{e}"));
diag.arg("error", format!("{e}"));
diag
}
thorin::Error::ObjectRead(e) => {
diag = build(fluent::codegen_ssa_thorin_object_read);
diag.set_arg("error", format!("{e}"));
diag.arg("error", format!("{e}"));
diag
}
thorin::Error::ObjectWrite(e) => {
diag = build(fluent::codegen_ssa_thorin_object_write);
diag.set_arg("error", format!("{e}"));
diag.arg("error", format!("{e}"));
diag
}
thorin::Error::GimliRead(e) => {
diag = build(fluent::codegen_ssa_thorin_gimli_read);
diag.set_arg("error", format!("{e}"));
diag.arg("error", format!("{e}"));
diag
}
thorin::Error::GimliWrite(e) => {
diag = build(fluent::codegen_ssa_thorin_gimli_write);
diag.set_arg("error", format!("{e}"));
diag.arg("error", format!("{e}"));
diag
}
_ => unimplemented!("Untranslated thorin error"),
@@ -414,8 +414,8 @@ pub struct LinkingFailed<'a> {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for LinkingFailed<'_> {
fn into_diagnostic(self, dcx: &DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::codegen_ssa_linking_failed);
diag.set_arg("linker_path", format!("{}", self.linker_path.display()));
diag.set_arg("exit_status", format!("{}", self.exit_status));
diag.arg("linker_path", format!("{}", self.linker_path.display()));
diag.arg("exit_status", format!("{}", self.exit_status));

let contains_undefined_ref = self.escaped_output.contains("undefined reference to");

86 changes: 43 additions & 43 deletions compiler/rustc_const_eval/src/errors.rs
Original file line number Diff line number Diff line change
@@ -518,7 +518,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
Ub(_) => {}
Custom(custom) => {
(custom.add_args)(&mut |name, value| {
builder.set_arg(name, value);
builder.arg(name, value);
});
}
ValidationError(e) => e.add_args(dcx, builder),
@@ -536,65 +536,65 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
| UninhabitedEnumVariantWritten(_)
| UninhabitedEnumVariantRead(_) => {}
BoundsCheckFailed { len, index } => {
builder.set_arg("len", len);
builder.set_arg("index", index);
builder.arg("len", len);
builder.arg("index", index);
}
UnterminatedCString(ptr) | InvalidFunctionPointer(ptr) | InvalidVTablePointer(ptr) => {
builder.set_arg("pointer", ptr);
builder.arg("pointer", ptr);
}
PointerUseAfterFree(alloc_id, msg) => {
builder
.set_arg("alloc_id", alloc_id)
.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx));
.arg("alloc_id", alloc_id)
.arg("bad_pointer_message", bad_pointer_message(msg, dcx));
}
PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => {
builder
.set_arg("alloc_id", alloc_id)
.set_arg("alloc_size", alloc_size.bytes())
.set_arg("ptr_offset", ptr_offset)
.set_arg("ptr_size", ptr_size.bytes())
.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx));
.arg("alloc_id", alloc_id)
.arg("alloc_size", alloc_size.bytes())
.arg("ptr_offset", ptr_offset)
.arg("ptr_size", ptr_size.bytes())
.arg("bad_pointer_message", bad_pointer_message(msg, dcx));
}
DanglingIntPointer(ptr, msg) => {
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) => {
builder.set_arg("required", required.bytes());
builder.set_arg("has", has.bytes());
builder.set_arg("msg", format!("{msg:?}"));
builder.arg("required", required.bytes());
builder.arg("has", has.bytes());
builder.arg("msg", format!("{msg:?}"));
}
WriteToReadOnly(alloc) | DerefFunctionPointer(alloc) | DerefVTablePointer(alloc) => {
builder.set_arg("allocation", alloc);
builder.arg("allocation", alloc);
}
InvalidBool(b) => {
builder.set_arg("value", format!("{b:02x}"));
builder.arg("value", format!("{b:02x}"));
}
InvalidChar(c) => {
builder.set_arg("value", format!("{c:08x}"));
builder.arg("value", format!("{c:08x}"));
}
InvalidTag(tag) => {
builder.set_arg("tag", format!("{tag:x}"));
builder.arg("tag", format!("{tag:x}"));
}
InvalidStr(err) => {
builder.set_arg("err", format!("{err}"));
builder.arg("err", format!("{err}"));
}
InvalidUninitBytes(Some((alloc, info))) => {
builder.set_arg("alloc", alloc);
builder.set_arg("access", info.access);
builder.set_arg("uninit", info.bad);
builder.arg("alloc", alloc);
builder.arg("access", info.access);
builder.arg("uninit", info.bad);
}
ScalarSizeMismatch(info) => {
builder.set_arg("target_size", info.target_size);
builder.set_arg("data_size", info.data_size);
builder.arg("target_size", info.target_size);
builder.arg("data_size", info.data_size);
}
AbiMismatchArgument { caller_ty, callee_ty }
| AbiMismatchReturn { caller_ty, callee_ty } => {
builder.set_arg("caller_ty", caller_ty.to_string());
builder.set_arg("callee_ty", callee_ty.to_string());
builder.arg("caller_ty", caller_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>(
r: WrappingRange,
@@ -725,12 +725,12 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
];
let args = args.iter().map(|(a, b)| (a, b));
let message = dcx.eagerly_translate_to_string(msg, args);
err.set_arg("in_range", message);
err.arg("in_range", message);
}

match self.kind {
PtrToUninhabited { ty, .. } | UninhabitedVal { ty } => {
err.set_arg("ty", ty);
err.arg("ty", ty);
}
PointerAsInt { expected } | Uninit { expected } => {
let msg = match expected {
@@ -747,28 +747,28 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
ExpectedKind::Str => fluent::const_eval_validation_expected_str,
};
let msg = dcx.eagerly_translate_to_string(msg, [].into_iter());
err.set_arg("expected", msg);
err.arg("expected", msg);
}
InvalidEnumTag { value }
| InvalidVTablePtr { value }
| InvalidBool { value }
| InvalidChar { value }
| InvalidFnPtr { value } => {
err.set_arg("value", value);
err.arg("value", value);
}
NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => {
add_range_arg(range, max_value, dcx, err)
}
OutOfRange { range, max_value, value } => {
err.set_arg("value", value);
err.arg("value", value);
add_range_arg(range, max_value, dcx, err);
}
UnalignedPtr { required_bytes, found_bytes, .. } => {
err.set_arg("required_bytes", required_bytes);
err.set_arg("found_bytes", found_bytes);
err.arg("required_bytes", required_bytes);
err.arg("found_bytes", found_bytes);
}
DanglingPtrNoProvenance { pointer, .. } => {
err.set_arg("pointer", pointer);
err.arg("pointer", pointer);
}
NullPtr { .. }
| 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`.
UnsizedLocal | Unsupported(_) | ReadPointerAsInt(_) => {}
OverwritePartialPointer(ptr) | ReadPartialPointer(ptr) => {
builder.set_arg("ptr", ptr);
builder.arg("ptr", ptr);
}
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::ResourceExhaustion(e) => e.add_args(dcx, builder),
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<'_, ()> =
e.into_diagnostic().into_diagnostic(dcx, dummy_level);
for (name, val) in diag.args() {
builder.set_arg(name.clone(), val.clone());
builder.arg(name.clone(), val.clone());
}
diag.cancel();
}
InvalidProgramInfo::FnAbiAdjustForForeignAbi(
AdjustForForeignAbiError::Unsupported { arch, abi },
) => {
builder.set_arg("arch", arch);
builder.set_arg("abi", abi.name());
builder.arg("arch", arch);
builder.arg("abi", abi.name());
}
}
}
46 changes: 3 additions & 43 deletions compiler/rustc_const_eval/src/transform/validate.rs
Original file line number Diff line number Diff line change
@@ -74,7 +74,6 @@ impl<'tcx> MirPass<'tcx> for Validator {
mir_phase,
unwind_edge_count: 0,
reachable_blocks: traversal::reachable_as_bitset(body),
place_cache: FxHashSet::default(),
value_cache: FxHashSet::default(),
can_unwind,
};
@@ -106,7 +105,6 @@ struct CfgChecker<'a, 'tcx> {
mir_phase: MirPhase,
unwind_edge_count: usize,
reachable_blocks: BitSet<BasicBlock>,
place_cache: FxHashSet<PlaceRef<'tcx>>,
value_cache: FxHashSet<u128>,
// If `false`, then the MIR must not contain `UnwindAction::Continue` or
// `TerminatorKind::Resume`.
@@ -294,19 +292,6 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {

fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
match &statement.kind {
StatementKind::Assign(box (dest, rvalue)) => {
// FIXME(JakobDegen): Check this for all rvalues, not just this one.
if let Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) = rvalue {
// The sides of an assignment must not alias. Currently this just checks whether
// the places are identical.
if dest == src {
self.fail(
location,
"encountered `Assign` statement with overlapping memory",
);
}
}
}
StatementKind::AscribeUserType(..) => {
if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
self.fail(
@@ -341,7 +326,8 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
self.fail(location, format!("explicit `{kind:?}` is forbidden"));
}
}
StatementKind::StorageLive(_)
StatementKind::Assign(..)
| StatementKind::StorageLive(_)
| StatementKind::StorageDead(_)
| StatementKind::Intrinsic(_)
| StatementKind::Coverage(_)
@@ -404,10 +390,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
}

// The call destination place and Operand::Move place used as an argument might be
// passed by a reference to the callee. Consequently they must be non-overlapping
// and cannot be packed. Currently this simply checks for duplicate places.
self.place_cache.clear();
self.place_cache.insert(destination.as_ref());
// passed by a reference to the callee. Consequently they cannot be packed.
if is_within_packed(self.tcx, &self.body.local_decls, *destination).is_some() {
// This is bad! The callee will expect the memory to be aligned.
self.fail(
@@ -418,10 +401,8 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
),
);
}
let mut has_duplicates = false;
for arg in args {
if let Operand::Move(place) = arg {
has_duplicates |= !self.place_cache.insert(place.as_ref());
if is_within_packed(self.tcx, &self.body.local_decls, *place).is_some() {
// This is bad! The callee will expect the memory to be aligned.
self.fail(
@@ -434,16 +415,6 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
}
}
}

if has_duplicates {
self.fail(
location,
format!(
"encountered overlapping memory in `Move` arguments to `Call` terminator: {:?}",
terminator.kind,
),
);
}
}
TerminatorKind::Assert { target, unwind, .. } => {
self.check_edge(location, *target, EdgeKind::Normal);
@@ -1112,17 +1083,6 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
)
}
}
// FIXME(JakobDegen): Check this for all rvalues, not just this one.
if let Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) = rvalue {
// The sides of an assignment must not alias. Currently this just checks whether
// the places are identical.
if dest == src {
self.fail(
location,
"encountered `Assign` statement with overlapping memory",
);
}
}
}
StatementKind::AscribeUserType(..) => {
if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
4 changes: 1 addition & 3 deletions compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs
Original file line number Diff line number Diff line change
@@ -86,9 +86,7 @@ fn source_string(file: Lrc<SourceFile>, line: &Line) -> String {
/// Maps `Diagnostic::Level` to `snippet::AnnotationType`
fn annotation_type_for_level(level: Level) -> AnnotationType {
match level {
Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error { .. } => {
AnnotationType::Error
}
Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error => AnnotationType::Error,
Level::Warning(_) => AnnotationType::Warning,
Level::Note | Level::OnceNote => AnnotationType::Note,
Level::Help | Level::OnceHelp => AnnotationType::Help,
41 changes: 22 additions & 19 deletions compiler/rustc_errors/src/diagnostic.rs
Original file line number Diff line number Diff line change
@@ -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 {
#[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
@@ -241,11 +244,9 @@ impl Diagnostic {

pub fn is_error(&self) -> bool {
match self.level {
Level::Bug
| Level::DelayedBug
| Level::Fatal
| Level::Error { .. }
| Level::FailureNote => true,
Level::Bug | Level::DelayedBug | Level::Fatal | Level::Error | Level::FailureNote => {
true
}

Level::Warning(_)
| Level::Note
@@ -308,25 +309,27 @@ impl Diagnostic {
/// In the meantime, though, callsites are required to deal with the "bug"
/// locally in whichever way makes the most sense.
#[track_caller]
pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
pub fn downgrade_to_delayed_bug(&mut self) {
assert!(
self.is_error(),
"downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
self.level
);
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
/// was first built. That means it will be shown together with the original
/// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
/// 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.
///
/// This span is *not* considered a ["primary span"][`MultiSpan`]; only
/// the `Span` supplied when creating the diagnostic is primary.
/// 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.
#[rustc_lint_diagnostics]
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));
@@ -344,7 +347,7 @@ impl Diagnostic {

pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
let before = self.span.clone();
self.set_span(after);
self.span(after);
for span_label in before.span_labels() {
if let Some(label) = span_label.label {
if span_label.is_primary && keep_label {
@@ -876,15 +879,15 @@ impl Diagnostic {
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();
if let Some(span) = self.span.primary_span() {
self.sort_span = span;
}
self
}

pub fn set_is_lint(&mut self) -> &mut Self {
pub fn is_lint(&mut self) -> &mut Self {
self.is_lint = true;
self
}
@@ -903,7 +906,7 @@ impl Diagnostic {
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
}
@@ -915,7 +918,7 @@ impl Diagnostic {
self.args.iter()
}

pub fn set_arg(
pub fn arg(
&mut self,
name: impl Into<Cow<'static, str>>,
arg: impl IntoDiagnosticArg,
53 changes: 14 additions & 39 deletions compiler/rustc_errors/src/diagnostic_builder.rs
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ where
{
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
let mut diag = self.node.into_diagnostic(dcx, level);
diag.set_span(self.span);
diag.span(self.span);
diag
}
}
@@ -207,11 +207,11 @@ macro_rules! forward {
// Forward pattern for &mut self -> &mut Self
(
$(#[$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])*
#[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
}
@@ -356,43 +356,23 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
self.emit()
}

forward!(
#[track_caller]
pub fn downgrade_to_delayed_bug(&mut self,) -> &mut Self
);

forward!(
/// 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(
forward!(pub fn span_label(
&mut self,
span: Span,
label: impl Into<SubdiagnosticMessage>
) -> &mut Self);
forward!(pub fn span_labels(
&mut self,
spans: impl IntoIterator<Item = Span>,
label: &str,
) -> &mut Self);

forward!(pub fn note_expected_found(
&mut self,
expected_label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found_label: &dyn fmt::Display,
found: DiagnosticStyledString,
) -> &mut Self);

forward!(pub fn note_expected_found_extra(
&mut self,
expected_label: &dyn fmt::Display,
@@ -402,7 +382,6 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display,
) -> &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 span_note(
@@ -428,10 +407,8 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
) -> &mut Self);
forward!(pub fn set_is_lint(&mut self,) -> &mut Self);

forward!(pub fn disable_suggestions(&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 multipart_suggestion(
&mut self,
msg: impl Into<SubdiagnosticMessage>,
@@ -498,16 +475,14 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
suggestion: impl ToString,
applicability: Applicability,
) -> &mut Self);

forward!(pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self);
forward!(pub fn set_span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self);
forward!(pub fn 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 code(&mut self, s: DiagnosticId) -> &mut Self);
forward!(pub fn set_arg(
forward!(pub fn arg(
&mut self,
name: impl Into<Cow<'static, str>>,
arg: impl IntoDiagnosticArg,
) -> &mut Self);

forward!(pub fn subdiagnostic(
&mut self,
subdiagnostic: impl crate::AddToDiagnostic
32 changes: 16 additions & 16 deletions compiler/rustc_errors/src/diagnostic_impls.rs
Original file line number Diff line number Diff line change
@@ -254,29 +254,29 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => {
diag =
DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_address_space);
diag.set_arg("addr_space", addr_space);
diag.set_arg("cause", cause);
diag.set_arg("err", err);
diag.arg("addr_space", addr_space);
diag.arg("cause", cause);
diag.arg("err", err);
diag
}
TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits);
diag.set_arg("kind", kind);
diag.set_arg("bit", bit);
diag.set_arg("cause", cause);
diag.set_arg("err", err);
diag.arg("kind", kind);
diag.arg("bit", bit);
diag.arg("cause", cause);
diag.arg("err", err);
diag
}
TargetDataLayoutErrors::MissingAlignment { cause } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_missing_alignment);
diag.set_arg("cause", cause);
diag.arg("cause", cause);
diag
}
TargetDataLayoutErrors::InvalidAlignment { cause, err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_alignment);
diag.set_arg("cause", cause);
diag.set_arg("err_kind", err.diag_ident());
diag.set_arg("align", err.align());
diag.arg("cause", cause);
diag.arg("err_kind", err.diag_ident());
diag.arg("align", err.align());
diag
}
TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => {
@@ -285,8 +285,8 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
level,
fluent::errors_target_inconsistent_architecture,
);
diag.set_arg("dl", dl);
diag.set_arg("target", target);
diag.arg("dl", dl);
diag.arg("target", target);
diag
}
TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => {
@@ -295,13 +295,13 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for TargetDataLayoutErrors<'_>
level,
fluent::errors_target_inconsistent_pointer_width,
);
diag.set_arg("pointer_size", pointer_size);
diag.set_arg("target", target);
diag.arg("pointer_size", pointer_size);
diag.arg("target", target);
diag
}
TargetDataLayoutErrors::InvalidBitsSize { err } => {
diag = DiagnosticBuilder::new(dcx, level, fluent::errors_target_invalid_bits_size);
diag.set_arg("err", err);
diag.arg("err", err);
diag
}
}
62 changes: 19 additions & 43 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
@@ -525,9 +525,6 @@ pub struct DiagCtxtFlags {
/// If true, immediately emit diagnostics that would otherwise be buffered.
/// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
pub dont_buffer_diagnostics: bool,
/// If true, immediately print bugs registered with `span_delayed_bug`.
/// (rustc: see `-Z report-delayed-bugs`)
pub report_delayed_bugs: bool,
/// Show macro backtraces.
/// (rustc: see `-Z macro-backtrace`)
pub macro_backtrace: bool,
@@ -673,7 +670,7 @@ impl DiagCtxt {
let key = (span.with_parent(None), key);

if diag.is_error() {
if matches!(diag.level, Error { lint: true }) {
if diag.level == Error && diag.is_lint {
inner.lint_err_count += 1;
} else {
inner.err_count += 1;
@@ -697,7 +694,7 @@ impl DiagCtxt {
let key = (span.with_parent(None), key);
let diag = inner.stashed_diagnostics.remove(&key)?;
if diag.is_error() {
if matches!(diag.level, Error { lint: true }) {
if diag.level == Error && diag.is_lint {
inner.lint_err_count -= 1;
} else {
inner.err_count -= 1;
@@ -732,7 +729,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> {
let mut result = self.struct_warn(msg);
result.set_span(span);
result.span(span);
result
}

@@ -789,7 +786,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_> {
let mut result = self.struct_err(msg);
result.set_span(span);
result.span(span);
result
}

@@ -812,7 +809,7 @@ impl DiagCtxt {
#[rustc_lint_diagnostics]
#[track_caller]
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`.
@@ -850,7 +847,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, FatalAbort> {
let mut result = self.struct_fatal(msg);
result.set_span(span);
result.span(span);
result
}

@@ -878,16 +875,6 @@ impl DiagCtxt {
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`.
#[rustc_lint_diagnostics]
pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
@@ -917,7 +904,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, BugAbort> {
let mut result = self.struct_bug(msg);
result.set_span(span);
result.span(span);
result
}

@@ -1004,23 +991,18 @@ impl DiagCtxt {
) -> ErrorGuaranteed {
let treat_next_err_as_bug = self.inner.borrow().treat_next_err_as_bug();
if treat_next_err_as_bug {
// FIXME: don't abort here if report_delayed_bugs is off
self.span_bug(sp, msg);
}
let mut diagnostic = Diagnostic::new(DelayedBug, msg);
diagnostic.set_span(sp);
diagnostic.span(sp);
self.emit_diagnostic(diagnostic).unwrap()
}

// FIXME(eddyb) note the comment inside `impl Drop for DiagCtxtInner`, that's
// where the explanation of what "good path" is (also, it should be renamed).
pub fn good_path_delayed_bug(&self, msg: impl Into<DiagnosticMessage>) {
let mut inner = self.inner.borrow_mut();

let mut diagnostic = Diagnostic::new(DelayedBug, msg);
if inner.flags.report_delayed_bugs {
inner.emit_diagnostic_without_consuming(&mut diagnostic);
}
let diagnostic = Diagnostic::new(DelayedBug, msg);
let backtrace = std::backtrace::Backtrace::capture();
inner.good_path_delayed_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
}
@@ -1039,7 +1021,7 @@ impl DiagCtxt {
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ()> {
let mut db = DiagnosticBuilder::new(self, Note, msg);
db.set_span(span);
db.span(span);
db
}

@@ -1222,7 +1204,7 @@ impl DiagCtxt {

#[track_caller]
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]
@@ -1377,7 +1359,7 @@ impl DiagCtxtInner {
for diag in diags {
// Decrement the count tracking the stash; emitting will increment it.
if diag.is_error() {
if matches!(diag.level, Error { lint: true }) {
if diag.level == Error && diag.is_lint {
self.lint_err_count -= 1;
} else {
self.err_count -= 1;
@@ -1408,7 +1390,7 @@ impl DiagCtxtInner {
&mut self,
diagnostic: &mut Diagnostic,
) -> 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;
}

@@ -1430,10 +1412,8 @@ impl DiagCtxtInner {
self.span_delayed_bugs
.push(DelayedDiagnostic::with_backtrace(diagnostic.clone(), backtrace));

if !self.flags.report_delayed_bugs {
#[allow(deprecated)]
return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
}
#[allow(deprecated)]
return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
}

if diagnostic.has_future_breakage() {
@@ -1509,7 +1489,7 @@ impl DiagCtxtInner {
}
}
if diagnostic.is_error() {
if matches!(diagnostic.level, Error { lint: true }) {
if diagnostic.level == Error && diagnostic.is_lint {
self.bump_lint_err_count();
} else {
self.bump_err_count();
@@ -1705,11 +1685,7 @@ pub enum Level {
/// most common case.
///
/// Its `EmissionGuarantee` is `ErrorGuaranteed`.
Error {
/// If this error comes from a lint, don't abort compilation even when abort_if_errors() is
/// called.
lint: bool,
},
Error,

/// A warning about the code being compiled. Does not prevent compilation from finishing.
///
@@ -1768,7 +1744,7 @@ impl Level {
fn color(self) -> ColorSpec {
let mut spec = ColorSpec::new();
match self {
Bug | DelayedBug | Fatal | Error { .. } => {
Bug | DelayedBug | Fatal | Error => {
spec.set_fg(Some(Color::Red)).set_intense(true);
}
Warning(_) => {
@@ -1789,7 +1765,7 @@ impl Level {
pub fn to_str(self) -> &'static str {
match self {
Bug | DelayedBug => "error: internal compiler error",
Fatal | Error { .. } => "error",
Fatal | Error => "error",
Warning(_) => "warning",
Note | OnceNote => "note",
Help | OnceHelp => "help",
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
@@ -855,7 +855,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
}
Err(mut err) => {
if err.span.is_dummy() {
err.set_span(span);
err.span(span);
}
annotate_err_with_kind(&mut err, kind, span);
err.emit();
4 changes: 2 additions & 2 deletions compiler/rustc_expand/src/proc_macro_server.rs
Original file line number Diff line number Diff line change
@@ -379,7 +379,7 @@ impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
impl ToInternal<rustc_errors::Level> for Level {
fn to_internal(self) -> rustc_errors::Level {
match self {
Level::Error => rustc_errors::Level::Error { lint: false },
Level::Error => rustc_errors::Level::Error,
Level::Warning => rustc_errors::Level::Warning(None),
Level::Note => rustc_errors::Level::Note,
Level::Help => rustc_errors::Level::Help,
@@ -497,7 +497,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let mut diag =
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 {
diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));
}
2 changes: 1 addition & 1 deletion compiler/rustc_feature/src/unstable.rs
Original file line number Diff line number Diff line change
@@ -210,7 +210,7 @@ declare_features! (
/// Allows the `multiple_supertrait_upcastable` lint.
(unstable, multiple_supertrait_upcastable, "1.69.0", None),
/// Allow negative trait bounds. This is an internal-only feature for testing the trait solver!
(incomplete, negative_bounds, "1.71.0", None),
(internal, negative_bounds, "1.71.0", None),
/// Allows using `#[omit_gdb_pretty_printer_section]`.
(internal, omit_gdb_pretty_printer_section, "1.5.0", None),
/// Allows using `#[prelude_import]` on glob `use` items.
52 changes: 30 additions & 22 deletions compiler/rustc_hir_analysis/src/astconv/bounds.rs
Original file line number Diff line number Diff line change
@@ -26,23 +26,36 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
span: Span,
) {
let tcx = self.tcx();
let sized_def_id = tcx.lang_items().sized_trait();
let mut seen_negative_sized_bound = false;

// Try to find an unbound in bounds.
let mut unbounds: SmallVec<[_; 1]> = SmallVec::new();
let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| {
for ab in ast_bounds {
if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
unbounds.push(ptr)
let hir::GenericBound::Trait(ptr, modifier) = ab else {
continue;
};
match modifier {
hir::TraitBoundModifier::Maybe => unbounds.push(ptr),
hir::TraitBoundModifier::Negative => {
if let Some(sized_def_id) = sized_def_id
&& ptr.trait_ref.path.res == Res::Def(DefKind::Trait, sized_def_id)
{
seen_negative_sized_bound = true;
}
}
_ => {}
}
}
};
search_bounds(ast_bounds);
if let Some((self_ty, where_clause)) = self_ty_where_predicates {
for clause in where_clause {
if let hir::WherePredicate::BoundPredicate(pred) = clause {
if pred.is_param_bound(self_ty.to_def_id()) {
search_bounds(pred.bounds);
}
if let hir::WherePredicate::BoundPredicate(pred) = clause
&& pred.is_param_bound(self_ty.to_def_id())
{
search_bounds(pred.bounds);
}
}
}
@@ -53,15 +66,13 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
});
}

let sized_def_id = tcx.lang_items().sized_trait();

let mut seen_sized_unbound = false;
for unbound in unbounds {
if let Some(sized_def_id) = sized_def_id {
if unbound.trait_ref.path.res == Res::Def(DefKind::Trait, sized_def_id) {
seen_sized_unbound = true;
continue;
}
if let Some(sized_def_id) = sized_def_id
&& unbound.trait_ref.path.res == Res::Def(DefKind::Trait, sized_def_id)
{
seen_sized_unbound = true;
continue;
}
// There was a `?Trait` bound, but it was not `?Sized`; warn.
tcx.dcx().span_warn(
@@ -71,15 +82,12 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
);
}

// If the above loop finished there was no `?Sized` bound; add implicitly sized if `Sized` is available.
if sized_def_id.is_none() {
// No lang item for `Sized`, so we can't add it as a bound.
return;
}
if seen_sized_unbound {
// There was in fact a `?Sized` bound, return without doing anything
} else {
// There was no `?Sized` bound; add implicitly sized if `Sized` is available.
if seen_sized_unbound || seen_negative_sized_bound {
// There was in fact a `?Sized` or `!Sized` bound;
// we don't need to do anything.
} else if sized_def_id.is_some() {
// There was no `?Sized` or `!Sized` bound;
// add `Sized` if it's available.
bounds.push_sized(tcx, self_ty, span);
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/astconv/generics.rs
Original file line number Diff line number Diff line change
@@ -70,7 +70,7 @@ fn generic_arg_mismatch_err(
Res::Err => {
add_braces_suggestion(arg, &mut 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();
}
Res::Def(DefKind::TyParam, src_def_id) => {
7 changes: 7 additions & 0 deletions compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs
Original file line number Diff line number Diff line change
@@ -69,6 +69,7 @@ pub(super) fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: Local
Node::Item(it) => locator.visit_item(it),
Node::ImplItem(it) => locator.visit_impl_item(it),
Node::TraitItem(it) => locator.visit_trait_item(it),
Node::ForeignItem(it) => locator.visit_foreign_item(it),
other => bug!("{:?} is not a valid scope for an opaque type item", other),
}
}
@@ -240,6 +241,12 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
self.check(it.owner_id.def_id);
intravisit::walk_trait_item(self, it);
}
fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
trace!(?it.owner_id);
assert_ne!(it.owner_id.def_id, self.def_id);
// No need to call `check`, as we do not run borrowck on foreign items.
intravisit::walk_foreign_item(self, it);
}
}

pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>(
6 changes: 3 additions & 3 deletions compiler/rustc_hir_analysis/src/errors.rs
Original file line number Diff line number Diff line change
@@ -319,10 +319,10 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for MissingTypeParams {
#[track_caller]
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);
err.set_span(self.span);
err.span(self.span);
err.code(error_code!(E0393));
err.set_arg("parameterCount", self.missing_type_params.len());
err.set_arg(
err.arg("parameterCount", self.missing_type_params.len());
err.arg(
"parameters",
self.missing_type_params
.iter()
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/errors.rs
Original file line number Diff line number Diff line change
@@ -215,7 +215,7 @@ impl AddToDiagnostic for TypeMismatchFruTypo {
where
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
if self.expr_span.between(self.fru_span).is_empty() {
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
@@ -961,7 +961,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
but its trait bounds were not satisfied"
)
});
err.set_primary_message(primary_message);
err.primary_message(primary_message);
if let Some(label) = label {
custom_span_label = true;
err.span_label(span, label);
34 changes: 14 additions & 20 deletions compiler/rustc_infer/src/errors/mod.rs
Original file line number Diff line number Diff line change
@@ -247,16 +247,16 @@ impl AddToDiagnostic for RegionOriginNote<'_> {
}
RegionOriginNote::WithName { span, msg, name, continues } => {
label_or_note(span, msg);
diag.set_arg("name", name);
diag.set_arg("continues", continues);
diag.arg("name", name);
diag.arg("continues", continues);
}
RegionOriginNote::WithRequirement {
span,
requirement,
expected_found: Some((expected, found)),
} => {
label_or_note(span, fluent::infer_subtype);
diag.set_arg("requirement", requirement);
diag.arg("requirement", requirement);

diag.note_expected_found(&"", expected, &"", found);
}
@@ -265,7 +265,7 @@ impl AddToDiagnostic for RegionOriginNote<'_> {
// handling of region checking when type errors are present is
// *terrible*.
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(ret_span, fluent::infer_nothing);
diag.span_label(span, fluent::infer_data_returned);
diag.set_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_exists", label_var1.is_some());
diag.arg("label_var1", label_var1.map(|x| x.to_string()).unwrap_or_default());
}
LifetimeMismatchLabels::Normal {
hir_equal,
@@ -317,16 +317,10 @@ impl AddToDiagnostic for LifetimeMismatchLabels {
diag.span_label(ty_sup, fluent::infer_types_declared_different);
diag.span_label(ty_sub, fluent::infer_nothing);
diag.span_label(span, fluent::infer_data_flows);
diag.set_arg("label_var1_exists", label_var1.is_some());
diag.set_arg(
"label_var1",
label_var1.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(),
);
diag.arg("label_var1_exists", label_var1.is_some());
diag.arg("label_var1", label_var1.map(|x| x.to_string()).unwrap_or_default());
diag.arg("label_var2_exists", label_var2.is_some());
diag.arg("label_var2", label_var2.map(|x| x.to_string()).unwrap_or_default());
}
}
}
@@ -417,7 +411,7 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> {
suggestions,
Applicability::MaybeIncorrect,
);
diag.set_arg("is_impl", is_impl);
diag.arg("is_impl", is_impl);
true
};
if mk_suggestion() && self.add_note {
@@ -878,8 +872,8 @@ impl AddToDiagnostic for MoreTargeted {
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
diag.code(rustc_errors::error_code!(E0772));
diag.set_primary_message(fluent::infer_more_targeted);
diag.set_arg("ident", self.ident);
diag.primary_message(fluent::infer_more_targeted);
diag.arg("ident", self.ident);
}
}

@@ -1299,7 +1293,7 @@ impl AddToDiagnostic for SuggestTuplePatternMany {
where
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());
diag.multipart_suggestions(
message,
8 changes: 4 additions & 4 deletions compiler/rustc_infer/src/errors/note_and_explain.rs
Original file line number Diff line number Diff line change
@@ -164,10 +164,10 @@ impl AddToDiagnostic for RegionExplanation<'_> {
where
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
diag.set_arg("pref_kind", self.prefix);
diag.set_arg("suff_kind", self.suffix);
diag.set_arg("desc_kind", self.desc.kind);
diag.set_arg("desc_arg", self.desc.arg);
diag.arg("pref_kind", self.prefix);
diag.arg("suff_kind", self.suffix);
diag.arg("desc_kind", self.desc.kind);
diag.arg("desc_arg", self.desc.arg);

let msg = f(diag, fluent::infer_region_explanation.into());
if let Some(span) = self.desc.span {
5 changes: 4 additions & 1 deletion compiler/rustc_infer/src/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
@@ -132,7 +132,10 @@ pub fn report_object_safety_error<'tcx>(
};
let externally_visible = if !impls.is_empty()
&& let Some(def_id) = trait_def_id.as_local()
&& tcx.effective_visibilities(()).is_exported(def_id)
// We may be executing this during typeck, which would result in cycle
// if we used effective_visibilities query, which looks into opaque types
// (and therefore calls typeck).
&& tcx.resolutions(()).effective_visibilities.is_exported(def_id)
{
true
} else {
6 changes: 2 additions & 4 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
@@ -6,8 +6,8 @@ use rustc_session::config::{
build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg,
DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs,
FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay,
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirSpanview, NextSolverConfig,
OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy,
Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
};
use rustc_session::lint::Level;
@@ -666,7 +666,6 @@ fn test_unstable_options_tracking_hash() {
untracked!(dump_mir_dir, String::from("abc"));
untracked!(dump_mir_exclude_pass_number, true);
untracked!(dump_mir_graphviz, true);
untracked!(dump_mir_spanview, Some(MirSpanview::Statement));
untracked!(dump_mono_stats, SwitchWithOptPath::Enabled(Some("mono-items-dir/".into())));
untracked!(dump_mono_stats_format, DumpMonoStatsFormat::Json);
untracked!(dylib_lto, true);
@@ -806,7 +805,6 @@ fn test_unstable_options_tracking_hash() {
tracked!(relax_elf_relocations, Some(true));
tracked!(relro_level, Some(RelroLevel::Full));
tracked!(remap_cwd_prefix, Some(PathBuf::from("abc")));
tracked!(report_delayed_bugs, true);
tracked!(sanitizer, SanitizerSet::ADDRESS);
tracked!(sanitizer_cfi_canonical_jump_tables, None);
tracked!(sanitizer_cfi_generalize_pointers, Some(true));
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/errors.rs
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ impl AddToDiagnostic for OverruledAttributeSub {
match self {
OverruledAttributeSub::DefaultSource { id } => {
diag.note(fluent::lint_default_source);
diag.set_arg("id", id);
diag.arg("id", id);
}
OverruledAttributeSub::NodeSource { span, reason } => {
diag.span_label(span, fluent::lint_node_source);
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/levels.rs
Original file line number Diff line number Diff line change
@@ -1069,7 +1069,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
Some(span.into()),
fluent::lint_unknown_gated_lint,
|lint| {
lint.set_arg("name", lint_id.lint.name_lower());
lint.arg("name", lint_id.lint.name_lower());
lint.note(fluent::lint_note);
rustc_session::parse::add_feature_diagnostics_for_issue(
lint,
123 changes: 48 additions & 75 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ use std::num::NonZeroU32;
use crate::errors::RequestedLevel;
use crate::fluent_generated as fluent;
use rustc_errors::{
AddToDiagnostic, Applicability, DecorateLint, DiagnosticMessage, DiagnosticStyledString,
SuggestionStyle,
AddToDiagnostic, Applicability, DecorateLint, Diagnostic, DiagnosticBuilder, DiagnosticMessage,
DiagnosticStyledString, SubdiagnosticMessage, SuggestionStyle,
};
use rustc_hir::def_id::DefId;
use rustc_macros::{LintDiagnostic, Subdiagnostic};
@@ -135,7 +135,7 @@ pub struct BuiltinMissingDebugImpl<'a> {
// Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for BuiltinMissingDebugImpl<'_> {
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 {
@@ -239,7 +239,7 @@ pub struct BuiltinUngatedAsyncFnTrackCaller<'a> {
}

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);
rustc_session::parse::add_feature_diagnostics(
diag,
@@ -268,20 +268,17 @@ pub struct SuggestChangingAssocTypes<'a, 'b> {
}

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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
// Access to associates types should use `<T as Bound>::Assoc`, which does not need a
// bound. Let's see if this type does that.

// We use a HIR visitor to walk the type.
use rustc_hir::intravisit::{self, Visitor};
struct WalkAssocTypes<'a> {
err: &'a mut rustc_errors::Diagnostic,
err: &'a mut Diagnostic,
}
impl Visitor<'_> for WalkAssocTypes<'_> {
fn visit_qpath(
@@ -326,12 +323,9 @@ pub struct 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
diag.multipart_suggestion(
fluent::lint_suggestion,
@@ -425,8 +419,8 @@ pub struct BuiltinUnpermittedTypeInit<'a> {
}

impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("ty", self.ty);
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.arg("ty", self.ty);
diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label);
if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) {
// 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);
}

fn msg(&self) -> rustc_errors::DiagnosticMessage {
fn msg(&self) -> DiagnosticMessage {
self.msg.clone()
}
}
@@ -449,12 +443,9 @@ pub struct 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
let mut err = self.err;
loop {
@@ -506,12 +497,9 @@ pub struct BuiltinClashingExternSub<'a> {
}

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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
let mut expected_str = DiagnosticStyledString::new();
expected_str.push(self.expected.fn_sig(self.tcx).to_string(), false);
@@ -779,12 +767,9 @@ pub struct 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
for (c, span) in self.spans {
diag.span_label(span, format!("{c:?}"));
@@ -799,12 +784,9 @@ pub enum HiddenUnicodeCodepointsDiagSub {

// Used because of multiple multipart_suggestion and note
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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
match self {
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
// should do the same here to provide the same good suggestions as we do for
// literals above.
diag.set_arg(
diag.arg(
"escaped",
spans
.into_iter()
@@ -953,12 +935,9 @@ pub struct 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
diag.span_suggestion_verbose(
self.suggestion,
@@ -1147,8 +1126,8 @@ pub struct NonFmtPanicUnused {

// Used because of two suggestions based on one Option<Span>
impl<'a> DecorateLint<'a, ()> for NonFmtPanicUnused {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("count", self.count);
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.arg("count", self.count);
diag.note(fluent::lint_note);
if let Some(span) = self.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
}
}
@@ -1224,12 +1203,9 @@ pub enum 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
match self {
NonSnakeCaseDiagSub::Label { span } => {
@@ -1342,12 +1318,12 @@ pub struct DropTraitConstraintsDiag<'a> {

// Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropTraitConstraintsDiag<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("predicate", self.predicate);
diag.set_arg("needs_drop", self.tcx.def_path_str(self.def_id));
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.arg("predicate", self.predicate);
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
}
}
@@ -1359,11 +1335,11 @@ pub struct DropGlue<'a> {

// Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for DropGlue<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("needs_drop", self.tcx.def_path_str(self.def_id));
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
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
}
}
@@ -1423,12 +1399,9 @@ pub enum 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
F: Fn(
&mut rustc_errors::Diagnostic,
rustc_errors::SubdiagnosticMessage,
) -> rustc_errors::SubdiagnosticMessage,
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
{
match self {
OverflowingBinHexSign::Positive => {
@@ -1633,9 +1606,9 @@ pub struct ImproperCTypes<'a> {

// Used because of the complexity of Option<DiagnosticMessage>, DiagnosticMessage, and Option<Span>
impl<'a> DecorateLint<'a, ()> for ImproperCTypes<'_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("ty", self.ty);
diag.set_arg("desc", self.desc);
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.arg("ty", self.ty);
diag.arg("desc", self.desc);
diag.span_label(self.label, fluent::lint_label);
if let Some(help) = self.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
}
}
@@ -1776,10 +1749,10 @@ pub enum UnusedDefSuggestion {

// Needed because of def_path_str
impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> {
fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>) {
diag.set_arg("pre", self.pre);
diag.set_arg("post", self.post);
diag.set_arg("def", self.cx.tcx.def_path_str(self.def_id));
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
diag.arg("pre", self.pre);
diag.arg("post", self.post);
diag.arg("def", self.cx.tcx.def_path_str(self.def_id));
// check for #[must_use = "..."]
if let Some(note) = self.note {
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
}
}
@@ -1859,14 +1832,14 @@ pub struct 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);
if let Some(sugg) = self.sugg {
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
}
}
6 changes: 3 additions & 3 deletions compiler/rustc_lint/src/non_fmt_panic.rs
Original file line number Diff line number Diff line change
@@ -121,7 +121,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc

#[allow(rustc::diagnostic_outside_of_impl)]
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_more_info_note);
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,
);
} else if suggest_debug {
lint.set_arg("ty", ty);
lint.arg("ty", ty);
lint.span_suggestion_verbose(
arg_span.shrink_to_lo(),
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 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(
fluent::lint_panic_suggestion,
if del == '(' {
18 changes: 9 additions & 9 deletions compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs
Original file line number Diff line number Diff line change
@@ -5,8 +5,8 @@ use crate::diagnostics::error::{
};
use crate::diagnostics::utils::{
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,
FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
should_generate_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo, FieldInnerTy,
FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
};
use proc_macro2::{Ident, Span, TokenStream};
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
/// 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 {
let mut body = quote! {};
// Generate `set_arg` calls first..
for binding in variant.bindings().iter().filter(|bi| should_generate_set_arg(bi.ast())) {
// Generate `arg` calls first..
for binding in variant.bindings().iter().filter(|bi| should_generate_arg(bi.ast())) {
body.extend(self.generate_field_code(binding));
}
// ..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
@@ -253,7 +253,7 @@ impl DiagnosticDeriveVariantBuilder {
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present

quote! {
diag.set_arg(
diag.arg(
stringify!(#ident),
#field_binding
);
@@ -312,15 +312,15 @@ impl DiagnosticDeriveVariantBuilder {
let name = ident.to_string();
match (&attr.meta, name.as_str()) {
// 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(_), "primary_span") => {
match self.kind {
DiagnosticDeriveKind::Diagnostic => {
report_error_if_not_applied_to_span(attr, &info)?;

return Ok(quote! {
diag.set_span(#binding);
diag.span(#binding);
});
}
DiagnosticDeriveKind::LintDiagnostic => {
14 changes: 7 additions & 7 deletions compiler/rustc_macros/src/diagnostics/subdiagnostic.rs
Original file line number Diff line number Diff line change
@@ -6,8 +6,8 @@ use crate::diagnostics::error::{
use crate::diagnostics::utils::{
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,
should_generate_set_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap,
HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
should_generate_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap,
SetOnce, SpannedOption, SubdiagnosticKind,
};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
@@ -214,7 +214,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
}

/// 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 field = binding_info.ast();
@@ -225,7 +225,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present

quote! {
#diag.set_arg(
#diag.arg(
stringify!(#ident),
#field_binding
);
@@ -505,7 +505,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
.variant
.bindings()
.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))
.collect();

@@ -593,8 +593,8 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
.variant
.bindings()
.iter()
.filter(|binding| should_generate_set_arg(binding.ast()))
.map(|binding| self.generate_field_set_arg(binding))
.filter(|binding| should_generate_arg(binding.ast()))
.map(|binding| self.generate_field_arg(binding))
.collect();

let formatting_init = &self.formatting_init;
6 changes: 3 additions & 3 deletions compiler/rustc_macros/src/diagnostics/utils.rs
Original file line number Diff line number Diff line change
@@ -584,7 +584,7 @@ pub(super) enum SubdiagnosticKind {
suggestion_kind: SuggestionKind,
applicability: SpannedOption<Applicability>,
/// 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,
/// Initialization logic for `code_field`'s variable, e.g.
/// `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`).
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...
field.attrs.iter().all(|attr| is_doc_comment(attr))
}
22 changes: 11 additions & 11 deletions compiler/rustc_metadata/src/errors.rs
Original file line number Diff line number Diff line change
@@ -500,10 +500,10 @@ pub(crate) struct MultipleCandidates {
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for MultipleCandidates {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_multiple_candidates);
diag.set_arg("crate_name", self.crate_name);
diag.set_arg("flavor", self.flavor);
diag.arg("crate_name", self.crate_name);
diag.arg("flavor", self.flavor);
diag.code(error_code!(E0464));
diag.set_span(self.span);
diag.span(self.span);
for (i, candidate) in self.candidates.iter().enumerate() {
diag.note(format!("candidate #{}: {}", i + 1, candidate.display()));
}
@@ -596,10 +596,10 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for InvalidMetadataFiles {
#[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_invalid_meta_files);
diag.set_arg("crate_name", self.crate_name);
diag.set_arg("add_info", self.add_info);
diag.arg("crate_name", self.crate_name);
diag.arg("add_info", self.add_info);
diag.code(error_code!(E0786));
diag.set_span(self.span);
diag.span(self.span);
for crate_rejection in self.crate_rejections {
diag.note(crate_rejection);
}
@@ -623,12 +623,12 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for CannotFindCrate {
#[track_caller]
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::metadata_cannot_find_crate);
diag.set_arg("crate_name", self.crate_name);
diag.set_arg("current_crate", self.current_crate);
diag.set_arg("add_info", self.add_info);
diag.set_arg("locator_triple", self.locator_triple.triple());
diag.arg("crate_name", self.crate_name);
diag.arg("current_crate", self.current_crate);
diag.arg("add_info", self.add_info);
diag.arg("locator_triple", self.locator_triple.triple());
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)
&& self.locator_triple != TargetTriple::from_triple(config::host_triple())
{
8 changes: 4 additions & 4 deletions compiler/rustc_middle/src/lint.rs
Original file line number Diff line number Diff line change
@@ -314,14 +314,14 @@ pub fn struct_lint_level(
}
Level::ForceWarn(Some(expect_id)) => rustc_errors::Level::Warning(Some(expect_id)),
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, "");
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
// 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
// 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
// the compiler. It is therefore not necessary to add any information for the user.
10 changes: 1 addition & 9 deletions compiler/rustc_middle/src/mir/interpret/error.rs
Original file line number Diff line number Diff line change
@@ -2,14 +2,10 @@ use super::{AllocId, AllocRange, Pointer, Scalar};

use crate::error;
use crate::mir::{ConstAlloc, ConstValue};
use crate::query::TyCtxtAt;
use crate::ty::{layout, tls, Ty, TyCtxt, ValTree};

use rustc_data_structures::sync::Lock;
use rustc_errors::{
struct_span_err, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed,
IntoDiagnosticArg,
};
use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg};
use rustc_macros::HashStable;
use rustc_session::CtfeBacktrace;
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`.
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"))]
static_assert_size!(InterpErrorInfo<'_>, 8);

11 changes: 5 additions & 6 deletions compiler/rustc_middle/src/mir/interpret/mod.rs
Original file line number Diff line number Diff line change
@@ -142,12 +142,11 @@ use crate::ty::GenericArgKind;
use crate::ty::{self, Instance, Ty, TyCtxt};

pub use self::error::{
struct_error, BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled,
EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind,
InterpError, InterpErrorInfo, InterpResult, InvalidMetaKind, InvalidProgramInfo,
MachineStopType, Misalignment, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo,
ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo,
ValidationErrorKind,
BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalToAllocationRawResult,
EvalToConstValueResult, EvalToValTreeResult, ExpectedKind, InterpError, InterpErrorInfo,
InterpResult, InvalidMetaKind, InvalidProgramInfo, MachineStopType, Misalignment, PointerKind,
ReportedErrorInfo, ResourceExhaustionInfo, ScalarSizeMismatch, UndefinedBehaviorInfo,
UnsupportedOpInfo, ValidationErrorInfo, ValidationErrorKind,
};

pub use self::value::Scalar;
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
@@ -55,7 +55,6 @@ pub mod mono;
pub mod patch;
pub mod pretty;
mod query;
pub mod spanview;
mod statement;
mod syntax;
pub mod tcx;
11 changes: 0 additions & 11 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
@@ -5,7 +5,6 @@ use std::io::{self, Write as _};
use std::path::{Path, PathBuf};

use super::graphviz::write_mir_fn_graphviz;
use super::spanview::write_mir_fn_spanview;
use rustc_ast::InlineAsmTemplatePiece;
use rustc_middle::mir::interpret::{
alloc_range, read_target_uint, AllocBytes, AllocId, Allocation, GlobalAlloc, Pointer,
@@ -141,16 +140,6 @@ fn dump_matched_mir_node<'tcx, F>(
write_mir_fn_graphviz(tcx, body, false, &mut file)?;
};
}

if let Some(spanview) = tcx.sess.opts.unstable_opts.dump_mir_spanview {
let _: io::Result<()> = try {
let file_basename = dump_file_basename(tcx, pass_num, pass_name, disambiguator, body);
let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
if body.source.def_id().is_local() {
write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
}
};
}
}

/// Returns the file basename portion (without extension) of a filename path
642 changes: 0 additions & 642 deletions compiler/rustc_middle/src/mir/spanview.rs

This file was deleted.

72 changes: 51 additions & 21 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
@@ -912,7 +912,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {

let mut traits = FxIndexMap::default();
let mut fn_traits = FxIndexMap::default();
let mut is_sized = false;
let mut has_sized_bound = false;
let mut has_negative_sized_bound = false;
let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();

for (predicate, _) in bounds.iter_instantiated_copied(tcx, args) {
@@ -922,13 +923,24 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
ty::ClauseKind::Trait(pred) => {
let trait_ref = bound_predicate.rebind(pred.trait_ref);

// Don't print + Sized, but rather + ?Sized if absent.
// Don't print `+ Sized`, but rather `+ ?Sized` if absent.
if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
is_sized = true;
continue;
match pred.polarity {
ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {
has_sized_bound = true;
continue;
}
ty::ImplPolarity::Negative => has_negative_sized_bound = true,
}
}

self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
self.insert_trait_and_projection(
trait_ref,
pred.polarity,
None,
&mut traits,
&mut fn_traits,
);
}
ty::ClauseKind::Projection(pred) => {
let proj_ref = bound_predicate.rebind(pred);
@@ -939,6 +951,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {

self.insert_trait_and_projection(
trait_ref,
ty::ImplPolarity::Positive,
Some(proj_ty),
&mut traits,
&mut fn_traits,
@@ -955,7 +968,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {

let mut first = true;
// Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound;

for (fn_once_trait_ref, entry) in fn_traits {
write!(self, "{}", if first { "" } else { " + " })?;
@@ -1002,18 +1015,21 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
// trait_refs we collected in the OpaqueFnEntry as normal trait refs.
_ => {
if entry.has_fn_once {
traits.entry(fn_once_trait_ref).or_default().extend(
// Group the return ty with its def id, if we had one.
entry
.return_ty
.map(|ty| (tcx.require_lang_item(LangItem::FnOnce, None), ty)),
);
traits
.entry((fn_once_trait_ref, ty::ImplPolarity::Positive))
.or_default()
.extend(
// Group the return ty with its def id, if we had one.
entry.return_ty.map(|ty| {
(tcx.require_lang_item(LangItem::FnOnce, None), ty)
}),
);
}
if let Some(trait_ref) = entry.fn_mut_trait_ref {
traits.entry(trait_ref).or_default();
traits.entry((trait_ref, ty::ImplPolarity::Positive)).or_default();
}
if let Some(trait_ref) = entry.fn_trait_ref {
traits.entry(trait_ref).or_default();
traits.entry((trait_ref, ty::ImplPolarity::Positive)).or_default();
}
}
}
@@ -1023,11 +1039,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
}

// Print the rest of the trait types (that aren't Fn* family of traits)
for (trait_ref, assoc_items) in traits {
for ((trait_ref, polarity), assoc_items) in traits {
write!(self, "{}", if first { "" } else { " + " })?;

self.wrap_binder(&trait_ref, |trait_ref, cx| {
define_scoped_cx!(cx);

if polarity == ty::ImplPolarity::Negative {
p!("!");
}
p!(print(trait_ref.print_only_trait_name()));

let generics = tcx.generics_of(trait_ref.def_id);
@@ -1094,9 +1114,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
})?;
}

if !is_sized {
write!(self, "{}?Sized", if first { "" } else { " + " })?;
} else if first {
let add_sized = has_sized_bound && (first || has_negative_sized_bound);
let add_maybe_sized = !has_sized_bound && !has_negative_sized_bound;
if add_sized || add_maybe_sized {
if !first {
write!(self, " + ")?;
}
if add_maybe_sized {
write!(self, "?")?;
}
write!(self, "Sized")?;
}

@@ -1128,9 +1154,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
fn insert_trait_and_projection(
&mut self,
trait_ref: ty::PolyTraitRef<'tcx>,
polarity: ty::ImplPolarity,
proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
traits: &mut FxIndexMap<
ty::PolyTraitRef<'tcx>,
(ty::PolyTraitRef<'tcx>, ty::ImplPolarity),
FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
>,
fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
@@ -1139,7 +1166,10 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {

// If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
// super-trait ref and record it there.
if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
// We skip negative Fn* bounds since they can't use parenthetical notation anyway.
if polarity == ty::ImplPolarity::Positive
&& let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait()
{
// If we have a FnOnce, then insert it into
if trait_def_id == fn_once_trait {
let entry = fn_traits.entry(trait_ref).or_default();
@@ -1167,7 +1197,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
}

// Otherwise, just group our traits and projection types.
traits.entry(trait_ref).or_default().extend(proj_ty);
traits.entry((trait_ref, polarity)).or_default().extend(proj_ty);
}

fn pretty_print_inherent_projection(
8 changes: 4 additions & 4 deletions compiler/rustc_mir_build/src/errors.rs
Original file line number Diff line number Diff line change
@@ -467,11 +467,11 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
level,
fluent::mir_build_non_exhaustive_patterns_type_not_empty,
);
diag.set_span(self.span);
diag.span(self.span);
diag.code(error_code!(E0004));
let peeled_ty = self.ty.peel_refs();
diag.set_arg("ty", self.ty);
diag.set_arg("peeled_ty", peeled_ty);
diag.arg("ty", self.ty);
diag.arg("peeled_ty", peeled_ty);

if let ty::Adt(def, _) = peeled_ty.kind() {
let def_span = self
@@ -855,7 +855,7 @@ impl<'tcx> AddToDiagnostic for AdtDefinedHere<'tcx> {
where
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);

for Variant { span } in self.variants {
7 changes: 0 additions & 7 deletions compiler/rustc_mir_transform/src/dest_prop.rs
Original file line number Diff line number Diff line change
@@ -133,7 +133,6 @@
use std::collections::hash_map::{Entry, OccupiedEntry};

use crate::simplify::remove_dead_blocks;
use crate::MirPass;
use rustc_data_structures::fx::FxHashMap;
use rustc_index::bit_set::BitSet;
@@ -241,12 +240,6 @@ impl<'tcx> MirPass<'tcx> for DestinationPropagation {
apply_merges(body, tcx, &merges, &merged_locals);
}

if round_count != 0 {
// Merging can introduce overlap between moved arguments and/or call destination in an
// unreachable code, which validator considers to be ill-formed.
remove_dead_blocks(body);
}

trace!(round_count);
}
}
24 changes: 12 additions & 12 deletions compiler/rustc_mir_transform/src/errors.rs
Original file line number Diff line number Diff line change
@@ -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> {
let mut diag = DiagnosticBuilder::new(dcx, level, fluent::mir_transform_requires_unsafe);
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());
let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter());
diag.set_arg("details", desc);
diag.set_arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed);
diag.arg("details", desc);
diag.arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed);
self.details.add_subdiagnostics(&mut diag);
if let Some(sp) = self.enclosing {
diag.span_label(sp, fluent::mir_transform_not_inherited);
@@ -122,16 +122,16 @@ impl RequiresUnsafeDetail {
}
CallToFunctionWith { ref missing, ref build_enabled } => {
diag.help(fluent::mir_transform_target_feature_call_help);
diag.set_arg(
diag.arg(
"missing_target_features",
DiagnosticArgValue::StrListSepByAnd(
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() {
diag.note(fluent::mir_transform_target_feature_call_note);
diag.set_arg(
diag.arg(
"build_target_features",
DiagnosticArgValue::StrListSepByAnd(
build_enabled
@@ -140,7 +140,7 @@ impl RequiresUnsafeDetail {
.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, ()>) {
let dcx = diag.dcx().expect("lint should not yet be emitted");
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());
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 message = assert_kind.diagnostic_message();
assert_kind.add_args(&mut |name, value| {
diag.set_arg(name, value);
diag.arg(name, value);
});
diag.span_label(span, message);
}
@@ -280,9 +280,9 @@ impl<'a> DecorateLint<'a, ()> for MustNotSupend<'_, '_> {
diag.subdiagnostic(reason);
}
diag.span_help(self.src_sp, fluent::_subdiag::help);
diag.set_arg("pre", self.pre);
diag.set_arg("def_path", self.tcx.def_path_str(self.def_id));
diag.set_arg("post", self.post);
diag.arg("pre", self.pre);
diag.arg("def_path", self.tcx.def_path_str(self.def_id));
diag.arg("post", self.post);
}

fn msg(&self) -> rustc_errors::DiagnosticMessage {
62 changes: 48 additions & 14 deletions compiler/rustc_mir_transform/src/lint.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! This pass statically detects code which has undefined behaviour or is likely to be erroneous.
//! It can be used to locate problems in MIR building or optimizations. It assumes that all code
//! can be executed, so it has false positives.
use rustc_data_structures::fx::FxHashSet;
use rustc_index::bit_set::BitSet;
use rustc_middle::mir::visit::{PlaceContext, Visitor};
use rustc_middle::mir::*;
@@ -11,7 +12,6 @@ use rustc_mir_dataflow::{Analysis, ResultsCursor};
use std::borrow::Cow;

pub fn lint_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, when: String) {
let reachable_blocks = traversal::reachable_as_bitset(body);
let always_live_locals = &always_storage_live_locals(body);

let maybe_storage_live = MaybeStorageLive::new(Cow::Borrowed(always_live_locals))
@@ -24,17 +24,19 @@ pub fn lint_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, when: String) {
.iterate_to_fixpoint()
.into_results_cursor(body);

Lint {
let mut lint = Lint {
tcx,
when,
body,
is_fn_like: tcx.def_kind(body.source.def_id()).is_fn_like(),
always_live_locals,
reachable_blocks,
maybe_storage_live,
maybe_storage_dead,
places: Default::default(),
};
for (bb, data) in traversal::reachable(body) {
lint.visit_basic_block_data(bb, data);
}
.visit_body(body);
}

struct Lint<'a, 'tcx> {
@@ -43,9 +45,9 @@ struct Lint<'a, 'tcx> {
body: &'a Body<'tcx>,
is_fn_like: bool,
always_live_locals: &'a BitSet<Local>,
reachable_blocks: BitSet<BasicBlock>,
maybe_storage_live: ResultsCursor<'a, 'tcx, MaybeStorageLive<'a>>,
maybe_storage_dead: ResultsCursor<'a, 'tcx, MaybeStorageDead<'a>>,
places: FxHashSet<PlaceRef<'tcx>>,
}

impl<'a, 'tcx> Lint<'a, 'tcx> {
@@ -67,7 +69,7 @@ impl<'a, 'tcx> Lint<'a, 'tcx> {

impl<'a, 'tcx> Visitor<'tcx> for Lint<'a, 'tcx> {
fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
if self.reachable_blocks.contains(location.block) && context.is_use() {
if context.is_use() {
self.maybe_storage_dead.seek_after_primary_effect(location);
if self.maybe_storage_dead.get().contains(local) {
self.fail(location, format!("use of local {local:?}, which has no storage here"));
@@ -76,28 +78,38 @@ impl<'a, 'tcx> Visitor<'tcx> for Lint<'a, 'tcx> {
}

fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
match statement.kind {
StatementKind::StorageLive(local) => {
if self.reachable_blocks.contains(location.block) {
self.maybe_storage_live.seek_before_primary_effect(location);
if self.maybe_storage_live.get().contains(local) {
match &statement.kind {
StatementKind::Assign(box (dest, rvalue)) => {
if let Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) = rvalue {
// The sides of an assignment must not alias. Currently this just checks whether
// the places are identical.
if dest == src {
self.fail(
location,
format!("StorageLive({local:?}) which already has storage here"),
"encountered `Assign` statement with overlapping memory",
);
}
}
}
StatementKind::StorageLive(local) => {
self.maybe_storage_live.seek_before_primary_effect(location);
if self.maybe_storage_live.get().contains(*local) {
self.fail(
location,
format!("StorageLive({local:?}) which already has storage here"),
);
}
}
_ => {}
}

self.super_statement(statement, location);
}

fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
match terminator.kind {
match &terminator.kind {
TerminatorKind::Return => {
if self.is_fn_like && self.reachable_blocks.contains(location.block) {
if self.is_fn_like {
self.maybe_storage_live.seek_after_primary_effect(location);
for local in self.maybe_storage_live.get().iter() {
if !self.always_live_locals.contains(local) {
@@ -111,6 +123,28 @@ impl<'a, 'tcx> Visitor<'tcx> for Lint<'a, 'tcx> {
}
}
}
TerminatorKind::Call { args, destination, .. } => {
// The call destination place and Operand::Move place used as an argument might be
// passed by a reference to the callee. Consequently they must be non-overlapping.
// Currently this simply checks for duplicate places.
self.places.clear();
self.places.insert(destination.as_ref());
let mut has_duplicates = false;
for arg in args {
if let Operand::Move(place) = arg {
has_duplicates |= !self.places.insert(place.as_ref());
}
}
if has_duplicates {
self.fail(
location,
format!(
"encountered overlapping memory in `Move` arguments to `Call` terminator: {:?}",
terminator.kind,
),
);
}
}
_ => {}
}

12 changes: 9 additions & 3 deletions compiler/rustc_mir_transform/src/pass_manager.rs
Original file line number Diff line number Diff line change
@@ -109,14 +109,15 @@ fn run_passes_inner<'tcx>(
phase_change: Option<MirPhase>,
validate_each: bool,
) {
let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip();
let overridden_passes = &tcx.sess.opts.unstable_opts.mir_enable_passes;
trace!(?overridden_passes);

let prof_arg = tcx.sess.prof.enabled().then(|| format!("{:?}", body.source.def_id()));

if !body.should_skip() {
let validate = validate_each & tcx.sess.opts.unstable_opts.validate_mir;
let lint = tcx.sess.opts.unstable_opts.lint_mir;

for pass in passes {
let name = pass.name();

@@ -162,7 +163,12 @@ fn run_passes_inner<'tcx>(
body.pass_count = 0;

dump_mir_for_phase_change(tcx, body);
if validate || new_phase == MirPhase::Runtime(RuntimePhase::Optimized) {

let validate =
(validate_each & tcx.sess.opts.unstable_opts.validate_mir & !body.should_skip())
|| new_phase == MirPhase::Runtime(RuntimePhase::Optimized);
let lint = tcx.sess.opts.unstable_opts.lint_mir & !body.should_skip();
if validate {
validate_body(tcx, body, format!("after phase change to {}", new_phase.name()));
}
if lint {
2 changes: 1 addition & 1 deletion compiler/rustc_monomorphize/src/errors.rs
Original file line number Diff line number Diff line change
@@ -51,7 +51,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for UnusedGenericParamsHint {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let mut diag =
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) {
// 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
8 changes: 4 additions & 4 deletions compiler/rustc_parse/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1065,8 +1065,8 @@ impl<'a> IntoDiagnostic<'a> for ExpectedIdentifier {
None => fluent::parse_expected_identifier_found_str,
},
);
diag.set_span(self.span);
diag.set_arg("token", self.token);
diag.span(self.span);
diag.arg("token", self.token);

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

if let Some(unexpected_token_label) = self.unexpected_token_label {
diag.span_label(unexpected_token_label, fluent::parse_label_unexpected_token);
Loading