Use chaining for DiagnosticBuilder construction and emit.

To avoid the use of a mutable local variable, and because it reads more
nicely.
This commit is contained in:
Nicholas Nethercote 2024-01-03 17:03:10 +11:00
parent 589591efde
commit bd4e623485
22 changed files with 193 additions and 183 deletions

View File

@ -693,13 +693,14 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
0 => {} 0 => {}
1 => { 1 => {
let (sp, msg) = unused_operands.into_iter().next().unwrap(); let (sp, msg) = unused_operands.into_iter().next().unwrap();
let mut err = ecx.dcx().struct_span_err(sp, msg); ecx.dcx()
err.span_label(sp, msg); .struct_span_err(sp, msg)
err.help(format!( .span_label_mv(sp, msg)
"if this argument is intentionally unused, \ .help_mv(format!(
consider using it in an asm comment: `\"/*{help_str} */\"`" "if this argument is intentionally unused, \
)); consider using it in an asm comment: `\"/*{help_str} */\"`"
err.emit(); ))
.emit();
} }
_ => { _ => {
let mut err = ecx.dcx().struct_span_err( let mut err = ecx.dcx().struct_span_err(

View File

@ -321,9 +321,10 @@ fn dep_symbol_lookup_fn(
Linkage::NotLinked | Linkage::IncludedFromDylib => {} Linkage::NotLinked | Linkage::IncludedFromDylib => {}
Linkage::Static => { Linkage::Static => {
let name = crate_info.crate_name[&cnum]; let name = crate_info.crate_name[&cnum];
let mut err = sess.dcx().struct_err(format!("Can't load static lib {}", name)); sess.dcx()
err.note("rustc_codegen_cranelift can only load dylibs in JIT mode."); .struct_err(format!("Can't load static lib {}", name))
err.emit(); .note("rustc_codegen_cranelift can only load dylibs in JIT mode.")
.emit();
} }
Linkage::Dynamic => { Linkage::Dynamic => {
dylib_paths.push(src.dylib.as_ref().unwrap().0.clone()); dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());

View File

@ -303,14 +303,14 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// This exception needs to be kept in sync with allowing // This exception needs to be kept in sync with allowing
// `#[target_feature]` on `main` and `start`. // `#[target_feature]` on `main` and `start`.
} else if !tcx.features().target_feature_11 { } else if !tcx.features().target_feature_11 {
let mut err = feature_err( feature_err(
&tcx.sess.parse_sess, &tcx.sess.parse_sess,
sym::target_feature_11, sym::target_feature_11,
attr.span, attr.span,
"`#[target_feature(..)]` can only be applied to `unsafe` functions", "`#[target_feature(..)]` can only be applied to `unsafe` functions",
); )
err.span_label(tcx.def_span(did), "not an `unsafe` function"); .span_label_mv(tcx.def_span(did), "not an `unsafe` function")
err.emit(); .emit();
} else { } else {
check_target_feature_trait_unsafe(tcx, did, attr.span); check_target_feature_trait_unsafe(tcx, did, attr.span);
} }

View File

@ -650,9 +650,9 @@ pub(crate) fn prohibit_explicit_late_bound_lifetimes(
if position == GenericArgPosition::Value if position == GenericArgPosition::Value
&& args.num_lifetime_params() != param_counts.lifetimes && args.num_lifetime_params() != param_counts.lifetimes
{ {
let mut err = struct_span_err!(tcx.dcx(), span, E0794, "{}", msg); struct_span_err!(tcx.dcx(), span, E0794, "{}", msg)
err.span_note(span_late, note); .span_note_mv(span_late, note)
err.emit(); .emit();
} else { } else {
let mut multispan = MultiSpan::from_span(span); let mut multispan = MultiSpan::from_span(span);
multispan.push_span_label(span_late, note); multispan.push_span_label(span_late, note);

View File

@ -290,19 +290,19 @@ trait here instead: `trait NewTrait: {} {{}}`",
if references_self { if references_self {
let def_id = i.bottom().0.def_id(); let def_id = i.bottom().0.def_id();
let mut err = struct_span_err!( struct_span_err!(
tcx.dcx(), tcx.dcx(),
i.bottom().1, i.bottom().1,
E0038, E0038,
"the {} `{}` cannot be made into an object", "the {} `{}` cannot be made into an object",
tcx.def_descr(def_id), tcx.def_descr(def_id),
tcx.item_name(def_id), tcx.item_name(def_id),
); )
err.note( .note_mv(
rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![]) rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
.error_msg(), .error_msg(),
); )
err.emit(); .emit();
} }
ty::ExistentialTraitRef { def_id: trait_ref.def_id, args } ty::ExistentialTraitRef { def_id: trait_ref.def_id, args }

View File

@ -1140,13 +1140,13 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var)); let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var));
if disr_non_unit || (disr_units && has_non_units) { if disr_non_unit || (disr_units && has_non_units) {
let err = struct_span_err!( struct_span_err!(
tcx.dcx(), tcx.dcx(),
tcx.def_span(def_id), tcx.def_span(def_id),
E0732, E0732,
"`#[repr(inttype)]` must be specified" "`#[repr(inttype)]` must be specified"
); )
err.emit(); .emit();
} }
} }

View File

@ -153,12 +153,14 @@ fn check_asm_operand_type(
}; };
let Some(asm_ty) = asm_ty else { let Some(asm_ty) = asm_ty else {
let msg = format!("cannot use value of type `{ty}` for inline assembly"); let msg = format!("cannot use value of type `{ty}` for inline assembly");
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg); self.tcx
err.note( .dcx()
"only integers, floats, SIMD vectors, pointers and function pointers \ .struct_span_err(expr.span, msg)
can be used as arguments for inline assembly", .note_mv(
); "only integers, floats, SIMD vectors, pointers and function pointers \
err.emit(); can be used as arguments for inline assembly",
)
.emit();
return None; return None;
}; };
@ -166,9 +168,11 @@ fn check_asm_operand_type(
// possibly fail is for SIMD types which don't #[derive(Copy)]. // possibly fail is for SIMD types which don't #[derive(Copy)].
if !ty.is_copy_modulo_regions(self.tcx, self.param_env) { if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
let msg = "arguments for inline assembly must be copyable"; let msg = "arguments for inline assembly must be copyable";
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg); self.tcx
err.note(format!("`{ty}` does not implement the Copy trait")); .dcx()
err.emit(); .struct_span_err(expr.span, msg)
.note_mv(format!("`{ty}` does not implement the Copy trait"))
.emit();
} }
// Ideally we wouldn't need to do this, but LLVM's register allocator // Ideally we wouldn't need to do this, but LLVM's register allocator
@ -183,16 +187,17 @@ fn check_asm_operand_type(
if let Some((in_expr, Some(in_asm_ty))) = tied_input { if let Some((in_expr, Some(in_asm_ty))) = tied_input {
if in_asm_ty != asm_ty { if in_asm_ty != asm_ty {
let msg = "incompatible types for asm inout argument"; let msg = "incompatible types for asm inout argument";
let mut err = self.tcx.dcx().struct_span_err(vec![in_expr.span, expr.span], msg);
let in_expr_ty = (self.get_operand_ty)(in_expr); let in_expr_ty = (self.get_operand_ty)(in_expr);
err.span_label(in_expr.span, format!("type `{in_expr_ty}`")); self.tcx
err.span_label(expr.span, format!("type `{ty}`")); .dcx()
err.note( .struct_span_err(vec![in_expr.span, expr.span], msg)
"asm inout arguments must have the same type, \ .span_label_mv(in_expr.span, format!("type `{in_expr_ty}`"))
.span_label_mv(expr.span, format!("type `{ty}`"))
.note_mv(
"asm inout arguments must have the same type, \
unless they are both pointers or integers of the same size", unless they are both pointers or integers of the same size",
); )
err.emit(); .emit();
} }
// All of the later checks have already been done on the input, so // All of the later checks have already been done on the input, so
@ -234,13 +239,15 @@ fn check_asm_operand_type(
if let Some(feature) = feature { if let Some(feature) = feature {
if !target_features.contains(feature) { if !target_features.contains(feature) {
let msg = format!("`{feature}` target feature is not enabled"); let msg = format!("`{feature}` target feature is not enabled");
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg); self.tcx
err.note(format!( .dcx()
"this is required to use type `{}` with register class `{}`", .struct_span_err(expr.span, msg)
ty, .note_mv(format!(
reg_class.name(), "this is required to use type `{}` with register class `{}`",
)); ty,
err.emit(); reg_class.name(),
))
.emit();
return Some(asm_ty); return Some(asm_ty);
} }
} }
@ -449,14 +456,17 @@ pub fn check_asm(&self, asm: &hir::InlineAsm<'tcx>, enclosing_id: LocalDefId) {
ty::Never | ty::Error(_) => {} ty::Never | ty::Error(_) => {}
ty::FnDef(..) => {} ty::FnDef(..) => {}
_ => { _ => {
let mut err = self.tcx
self.tcx.dcx().struct_span_err(*op_sp, "invalid `sym` operand"); .dcx()
err.span_label( .struct_span_err(*op_sp, "invalid `sym` operand")
self.tcx.def_span(anon_const.def_id), .span_label_mv(
format!("is {} `{}`", ty.kind().article(), ty), self.tcx.def_span(anon_const.def_id),
); format!("is {} `{}`", ty.kind().article(), ty),
err.help("`sym` operands must refer to either a function or a static"); )
err.emit(); .help_mv(
"`sym` operands must refer to either a function or a static",
)
.emit();
} }
}; };
} }

View File

@ -197,11 +197,12 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<()
let mut res = Ok(()); let mut res = Ok(());
if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) { if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span); let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
let mut err = res = Err(tcx
tcx.dcx().struct_span_err(sp, "impls of auto traits cannot be default"); .dcx()
err.span_labels(impl_.defaultness_span, "default because of this"); .struct_span_err(sp, "impls of auto traits cannot be default")
err.span_label(sp, "auto trait"); .span_labels_mv(impl_.defaultness_span, "default because of this")
res = Err(err.emit()); .span_label_mv(sp, "auto trait")
.emit());
} }
// We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span. // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
match tcx.impl_polarity(def_id) { match tcx.impl_polarity(def_id) {
@ -489,35 +490,33 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
if !unsatisfied_bounds.is_empty() { if !unsatisfied_bounds.is_empty() {
let plural = pluralize!(unsatisfied_bounds.len()); let plural = pluralize!(unsatisfied_bounds.len());
let mut err = tcx.dcx().struct_span_err(
gat_item_hir.span,
format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
);
let suggestion = format!( let suggestion = format!(
"{} {}", "{} {}",
gat_item_hir.generics.add_where_or_trailing_comma(), gat_item_hir.generics.add_where_or_trailing_comma(),
unsatisfied_bounds.join(", "), unsatisfied_bounds.join(", "),
); );
err.span_suggestion(
gat_item_hir.generics.tail_span_for_predicate_suggestion(),
format!("add the required where clause{plural}"),
suggestion,
Applicability::MachineApplicable,
);
let bound = let bound =
if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" }; if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
err.note(format!( tcx.dcx()
"{bound} currently required to ensure that impls have maximum flexibility" .struct_span_err(
)); gat_item_hir.span,
err.note( format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
"we are soliciting feedback, see issue #87479 \ )
.span_suggestion_mv(
gat_item_hir.generics.tail_span_for_predicate_suggestion(),
format!("add the required where clause{plural}"),
suggestion,
Applicability::MachineApplicable,
)
.note_mv(format!(
"{bound} currently required to ensure that impls have maximum flexibility"
))
.note_mv(
"we are soliciting feedback, see issue #87479 \
<https://github.com/rust-lang/rust/issues/87479> \ <https://github.com/rust-lang/rust/issues/87479> \
for more information", for more information",
); )
.emit();
err.emit();
} }
} }
} }
@ -938,8 +937,8 @@ fn ty_is_local(ty: Ty<'_>) -> bool {
}; };
if may_suggest_feature && tcx.sess.is_nightly_build() { if may_suggest_feature && tcx.sess.is_nightly_build() {
diag.help( diag.help(
"add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types", "add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types",
); );
} }
Err(diag.emit()) Err(diag.emit())

View File

@ -70,17 +70,16 @@ fn check_for_duplicate_items_in_impl(&self, impl_: DefId) {
match seen_items.entry(norm_ident) { match seen_items.entry(norm_ident) {
Entry::Occupied(entry) => { Entry::Occupied(entry) => {
let former = entry.get(); let former = entry.get();
let mut err = struct_span_err!( struct_span_err!(
self.tcx.dcx(), self.tcx.dcx(),
span, span,
E0592, E0592,
"duplicate definitions with name `{}`", "duplicate definitions with name `{}`",
ident, ident,
); )
err.span_label(span, format!("duplicate definitions for `{ident}`")); .span_label_mv(span, format!("duplicate definitions for `{ident}`"))
err.span_label(*former, format!("other definition for `{ident}`")); .span_label_mv(*former, format!("other definition for `{ident}`"))
.emit();
err.emit();
} }
Entry::Vacant(entry) => { Entry::Vacant(entry) => {
entry.insert(span); entry.insert(span);

View File

@ -750,12 +750,12 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) {
kind: hir::ItemKind::OpaqueTy { .. }, .. kind: hir::ItemKind::OpaqueTy { .. }, ..
}) = self.tcx.hir_node(parent_id) }) = self.tcx.hir_node(parent_id)
{ {
let mut err = self.tcx.dcx().struct_span_err( self.tcx.dcx().struct_span_err(
lifetime.ident.span, lifetime.ident.span,
"higher kinded lifetime bounds on nested opaque types are not supported yet", "higher kinded lifetime bounds on nested opaque types are not supported yet",
); )
err.span_note(self.tcx.def_span(def_id), "lifetime declared here"); .span_note_mv(self.tcx.def_span(def_id), "lifetime declared here")
err.emit(); .emit();
self.uninsert_lifetime_on_error(lifetime, def.unwrap()); self.uninsert_lifetime_on_error(lifetime, def.unwrap());
} }
} }

View File

@ -3183,9 +3183,10 @@ fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized); self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
if !is_input && !expr.is_syntactic_place_expr() { if !is_input && !expr.is_syntactic_place_expr() {
let mut err = self.dcx().struct_span_err(expr.span, "invalid asm output"); self.dcx()
err.span_label(expr.span, "cannot assign to this expression"); .struct_span_err(expr.span, "invalid asm output")
err.emit(); .span_label_mv(expr.span, "cannot assign to this expression")
.emit();
} }
// If this is an input value, we require its type to be fully resolved // If this is an input value, we require its type to be fully resolved
@ -3278,27 +3279,27 @@ fn check_offset_of(
.iter_enumerated() .iter_enumerated()
.find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident) .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
else { else {
let mut err = type_error_struct!( type_error_struct!(
self.dcx(), self.dcx(),
ident.span, ident.span,
container, container,
E0599, E0599,
"no variant named `{ident}` found for enum `{container}`", "no variant named `{ident}` found for enum `{container}`",
); )
err.span_label(field.span, "variant not found"); .span_label_mv(field.span, "variant not found")
err.emit(); .emit();
break; break;
}; };
let Some(&subfield) = fields.next() else { let Some(&subfield) = fields.next() else {
let mut err = type_error_struct!( type_error_struct!(
self.dcx(), self.dcx(),
ident.span, ident.span,
container, container,
E0795, E0795,
"`{ident}` is an enum variant; expected field at end of `offset_of`", "`{ident}` is an enum variant; expected field at end of `offset_of`",
); )
err.span_label(field.span, "enum variant"); .span_label_mv(field.span, "enum variant")
err.emit(); .emit();
break; break;
}; };
let (subident, sub_def_scope) = let (subident, sub_def_scope) =
@ -3309,16 +3310,16 @@ fn check_offset_of(
.iter_enumerated() .iter_enumerated()
.find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident) .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
else { else {
let mut err = type_error_struct!( type_error_struct!(
self.dcx(), self.dcx(),
ident.span, ident.span,
container, container,
E0609, E0609,
"no field named `{subfield}` on enum variant `{container}::{ident}`", "no field named `{subfield}` on enum variant `{container}::{ident}`",
); )
err.span_label(field.span, "this enum variant..."); .span_label_mv(field.span, "this enum variant...")
err.span_label(subident.span, "...does not have this field"); .span_label_mv(subident.span, "...does not have this field")
err.emit(); .emit();
break; break;
}; };

View File

@ -1541,19 +1541,19 @@ fn error_foreign_non_exhaustive_spat(&self, pat: &Pat<'_>, descr: &str, no_field
let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi())); let sp_comma = sm.end_point(pat.span.with_hi(sp_brace.hi()));
let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" }; let sugg = if no_fields || sp_brace != sp_comma { ".. }" } else { ", .. }" };
let mut err = struct_span_err!( struct_span_err!(
self.dcx(), self.dcx(),
pat.span, pat.span,
E0638, E0638,
"`..` required with {descr} marked as non-exhaustive", "`..` required with {descr} marked as non-exhaustive",
); )
err.span_suggestion_verbose( .span_suggestion_verbose_mv(
sp_comma, sp_comma,
"add `..` at the end of the field list to ignore all other fields", "add `..` at the end of the field list to ignore all other fields",
sugg, sugg,
Applicability::MachineApplicable, Applicability::MachineApplicable,
); )
err.emit(); .emit();
} }
fn error_field_already_bound( fn error_field_already_bound(

View File

@ -332,15 +332,15 @@ pub fn convert_place_derefs_to_mutable(&self, expr: &hir::Expr<'_>) {
if inside_union if inside_union
&& source.ty_adt_def().is_some_and(|adt| adt.is_manually_drop()) && source.ty_adt_def().is_some_and(|adt| adt.is_manually_drop())
{ {
let mut err = self.dcx().struct_span_err( self.dcx().struct_span_err(
expr.span, expr.span,
"not automatically applying `DerefMut` on `ManuallyDrop` union field", "not automatically applying `DerefMut` on `ManuallyDrop` union field",
); )
err.help( .help_mv(
"writing to this reference calls the destructor for the old value", "writing to this reference calls the destructor for the old value",
); )
err.help("add an explicit `*` if that is desired, or call `ptr::write` to not run the destructor"); .help_mv("add an explicit `*` if that is desired, or call `ptr::write` to not run the destructor")
err.emit(); .emit();
} }
} }
source = adjustment.target; source = adjustment.target;

View File

@ -357,7 +357,6 @@ fn struct_lint_level_impl(
if let Level::Expect(_) = level { if let Level::Expect(_) = level {
let name = lint.name_lower(); let name = lint.name_lower();
err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false }); err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false });
decorate(&mut err); decorate(&mut err);
err.emit(); err.emit();
return; return;

View File

@ -190,7 +190,7 @@ pub fn recursive_type_error(
} }
s s
}; };
let mut err = struct_span_err!( struct_span_err!(
tcx.dcx(), tcx.dcx(),
err_span, err_span,
E0072, E0072,
@ -198,13 +198,13 @@ pub fn recursive_type_error(
pluralize!(cycle_len), pluralize!(cycle_len),
items_list, items_list,
pluralize!("has", cycle_len), pluralize!("has", cycle_len),
); )
err.multipart_suggestion( .multipart_suggestion_mv(
"insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle", "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle",
suggestion, suggestion,
Applicability::HasPlaceholders, Applicability::HasPlaceholders,
); )
err.emit(); .emit();
} }
fn find_item_ty_spans( fn find_item_ty_spans(

View File

@ -2848,15 +2848,16 @@ pub(crate) fn maybe_recover_unexpected_block_label(&mut self) -> bool {
let label = self.eat_label().expect("just checked if a label exists"); let label = self.eat_label().expect("just checked if a label exists");
self.bump(); // eat `:` self.bump(); // eat `:`
let span = label.ident.span.to(self.prev_token.span); let span = label.ident.span.to(self.prev_token.span);
let mut err = self.dcx().struct_span_err(span, "block label not supported here"); self.dcx()
err.span_label(span, "not supported here"); .struct_span_err(span, "block label not supported here")
err.tool_only_span_suggestion( .span_label_mv(span, "not supported here")
label.ident.span.until(self.token.span), .tool_only_span_suggestion_mv(
"remove this block label", label.ident.span.until(self.token.span),
"", "remove this block label",
Applicability::MachineApplicable, "",
); Applicability::MachineApplicable,
err.emit(); )
.emit();
true true
} }

View File

@ -141,17 +141,18 @@ pub(crate) fn recover_const_param_with_mistyped_const(
// Parse optional const generics default value. // Parse optional const generics default value.
let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None }; let default = if self.eat(&token::Eq) { Some(self.parse_const_arg()?) } else { None };
let mut err = self.dcx().struct_span_err( self.dcx()
mistyped_const_ident.span, .struct_span_err(
format!("`const` keyword was mistyped as `{}`", mistyped_const_ident.as_str()), mistyped_const_ident.span,
); format!("`const` keyword was mistyped as `{}`", mistyped_const_ident.as_str()),
err.span_suggestion_verbose( )
mistyped_const_ident.span, .span_suggestion_verbose_mv(
"use the `const` keyword", mistyped_const_ident.span,
kw::Const.as_str(), "use the `const` keyword",
Applicability::MachineApplicable, kw::Const.as_str(),
); Applicability::MachineApplicable,
err.emit(); )
.emit();
Ok(GenericParam { Ok(GenericParam {
ident, ident,

View File

@ -1109,8 +1109,7 @@ fn parse_item_foreign_mod(
&& self.token.is_keyword(kw::Unsafe) && self.token.is_keyword(kw::Unsafe)
&& self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace)) && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
{ {
let err = self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err(); self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err().emit();
err.emit();
unsafety = Unsafe::Yes(self.token.span); unsafety = Unsafe::Yes(self.token.span);
self.eat_keyword(kw::Unsafe); self.eat_keyword(kw::Unsafe);
} }

View File

@ -3282,16 +3282,16 @@ fn mk_where_bound_predicate(
/// Report lifetime/lifetime shadowing as an error. /// Report lifetime/lifetime shadowing as an error.
pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) { pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
let mut err = struct_span_err!( struct_span_err!(
sess.dcx(), sess.dcx(),
shadower.span, shadower.span,
E0496, E0496,
"lifetime name `{}` shadows a lifetime name that is already in scope", "lifetime name `{}` shadows a lifetime name that is already in scope",
orig.name, orig.name,
); )
err.span_label(orig.span, "first declared here"); .span_label_mv(orig.span, "first declared here")
err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name)); .span_label_mv(shadower.span, format!("lifetime `{}` already in scope", orig.name))
err.emit(); .emit();
} }
struct LifetimeFinder<'ast> { struct LifetimeFinder<'ast> {
@ -3317,11 +3317,12 @@ fn visit_ty(&mut self, t: &'ast Ty) {
pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) { pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
let name = shadower.name; let name = shadower.name;
let shadower = shadower.span; let shadower = shadower.span;
let mut err = sess.dcx().struct_span_warn( sess.dcx()
shadower, .struct_span_warn(
format!("label name `{name}` shadows a label name that is already in scope"), shadower,
); format!("label name `{name}` shadows a label name that is already in scope"),
err.span_label(orig, "first declared here"); )
err.span_label(shadower, format!("label `{name}` already in scope")); .span_label_mv(orig, "first declared here")
err.emit(); .span_label_mv(shadower, format!("label `{name}` already in scope"))
.emit();
} }

View File

@ -576,10 +576,10 @@ fn smart_resolve_macro_path(
err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str }); err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
} }
let mut err = self.dcx().create_err(err); self.dcx()
err.span_label(path.span, format!("not {article} {expected}")); .create_err(err)
.span_label_mv(path.span, format!("not {article} {expected}"))
err.emit(); .emit();
return Ok((self.dummy_ext(kind), Res::Err)); return Ok((self.dummy_ext(kind), Res::Err));
} }
@ -830,7 +830,6 @@ pub(crate) fn finalize_macro_resolutions(&mut self, krate: &Crate) {
expected, expected,
ident, ident,
}); });
self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate); self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate);
err.emit(); err.emit();
} }

View File

@ -3544,17 +3544,16 @@ fn report_not_const_evaluatable_error(
span: Span, span: Span,
) -> Option<DiagnosticBuilder<'tcx>> { ) -> Option<DiagnosticBuilder<'tcx>> {
if !self.tcx.features().generic_const_exprs { if !self.tcx.features().generic_const_exprs {
let mut err = self self.dcx()
.dcx() .struct_span_err(span, "constant expression depends on a generic parameter")
.struct_span_err(span, "constant expression depends on a generic parameter"); // FIXME(const_generics): we should suggest to the user how they can resolve this
// FIXME(const_generics): we should suggest to the user how they can resolve this // issue. However, this is currently not actually possible
// issue. However, this is currently not actually possible // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
// (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083). //
// // Note that with `feature(generic_const_exprs)` this case should not
// Note that with `feature(generic_const_exprs)` this case should not // be reachable.
// be reachable. .note_mv("this may fail depending on what value the parameter takes")
err.note("this may fail depending on what value the parameter takes"); .emit();
err.emit();
return None; return None;
} }

View File

@ -495,16 +495,16 @@ fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
.intersperse("::") .intersperse("::")
.collect::<String>() .collect::<String>()
); );
let mut err = rustc_errors::struct_span_err!( rustc_errors::struct_span_err!(
self.tcx.dcx(), self.tcx.dcx(),
path.span, path.span,
E0433, E0433,
"failed to resolve: {label}", "failed to resolve: {label}",
); )
err.span_label(path.span, label); .span_label_mv(path.span, label)
err.note("this error was originally ignored because you are running `rustdoc`"); .note_mv("this error was originally ignored because you are running `rustdoc`")
err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error"); .note_mv("try running again with `rustc` or `cargo check` and you may get a more detailed error")
err.emit(); .emit();
} }
// We could have an outer resolution that succeeded, // We could have an outer resolution that succeeded,
// but with generic parameters that failed. // but with generic parameters that failed.