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 => {}
1 => {
let (sp, msg) = unused_operands.into_iter().next().unwrap();
let mut err = ecx.dcx().struct_span_err(sp, msg);
err.span_label(sp, msg);
err.help(format!(
"if this argument is intentionally unused, \
consider using it in an asm comment: `\"/*{help_str} */\"`"
));
err.emit();
ecx.dcx()
.struct_span_err(sp, msg)
.span_label_mv(sp, msg)
.help_mv(format!(
"if this argument is intentionally unused, \
consider using it in an asm comment: `\"/*{help_str} */\"`"
))
.emit();
}
_ => {
let mut err = ecx.dcx().struct_span_err(

View File

@ -321,9 +321,10 @@ fn dep_symbol_lookup_fn(
Linkage::NotLinked | Linkage::IncludedFromDylib => {}
Linkage::Static => {
let name = crate_info.crate_name[&cnum];
let mut err = sess.dcx().struct_err(format!("Can't load static lib {}", name));
err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
err.emit();
sess.dcx()
.struct_err(format!("Can't load static lib {}", name))
.note("rustc_codegen_cranelift can only load dylibs in JIT mode.")
.emit();
}
Linkage::Dynamic => {
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
// `#[target_feature]` on `main` and `start`.
} else if !tcx.features().target_feature_11 {
let mut err = feature_err(
feature_err(
&tcx.sess.parse_sess,
sym::target_feature_11,
attr.span,
"`#[target_feature(..)]` can only be applied to `unsafe` functions",
);
err.span_label(tcx.def_span(did), "not an `unsafe` function");
err.emit();
)
.span_label_mv(tcx.def_span(did), "not an `unsafe` function")
.emit();
} else {
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
&& args.num_lifetime_params() != param_counts.lifetimes
{
let mut err = struct_span_err!(tcx.dcx(), span, E0794, "{}", msg);
err.span_note(span_late, note);
err.emit();
struct_span_err!(tcx.dcx(), span, E0794, "{}", msg)
.span_note_mv(span_late, note)
.emit();
} else {
let mut multispan = MultiSpan::from_span(span);
multispan.push_span_label(span_late, note);

View File

@ -290,19 +290,19 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
if references_self {
let def_id = i.bottom().0.def_id();
let mut err = struct_span_err!(
struct_span_err!(
tcx.dcx(),
i.bottom().1,
E0038,
"the {} `{}` cannot be made into an object",
tcx.def_descr(def_id),
tcx.item_name(def_id),
);
err.note(
)
.note_mv(
rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
.error_msg(),
);
err.emit();
)
.emit();
}
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));
if disr_non_unit || (disr_units && has_non_units) {
let err = struct_span_err!(
struct_span_err!(
tcx.dcx(),
tcx.def_span(def_id),
E0732,
"`#[repr(inttype)]` must be specified"
);
err.emit();
)
.emit();
}
}

View File

@ -153,12 +153,14 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
};
let Some(asm_ty) = asm_ty else {
let msg = format!("cannot use value of type `{ty}` for inline assembly");
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg);
err.note(
"only integers, floats, SIMD vectors, pointers and function pointers \
can be used as arguments for inline assembly",
);
err.emit();
self.tcx
.dcx()
.struct_span_err(expr.span, msg)
.note_mv(
"only integers, floats, SIMD vectors, pointers and function pointers \
can be used as arguments for inline assembly",
)
.emit();
return None;
};
@ -166,9 +168,11 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
// possibly fail is for SIMD types which don't #[derive(Copy)].
if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
let msg = "arguments for inline assembly must be copyable";
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg);
err.note(format!("`{ty}` does not implement the Copy trait"));
err.emit();
self.tcx
.dcx()
.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
@ -183,16 +187,17 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
if let Some((in_expr, Some(in_asm_ty))) = tied_input {
if in_asm_ty != asm_ty {
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);
err.span_label(in_expr.span, format!("type `{in_expr_ty}`"));
err.span_label(expr.span, format!("type `{ty}`"));
err.note(
"asm inout arguments must have the same type, \
self.tcx
.dcx()
.struct_span_err(vec![in_expr.span, expr.span], msg)
.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",
);
err.emit();
)
.emit();
}
// All of the later checks have already been done on the input, so
@ -234,13 +239,15 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
if let Some(feature) = feature {
if !target_features.contains(feature) {
let msg = format!("`{feature}` target feature is not enabled");
let mut err = self.tcx.dcx().struct_span_err(expr.span, msg);
err.note(format!(
"this is required to use type `{}` with register class `{}`",
ty,
reg_class.name(),
));
err.emit();
self.tcx
.dcx()
.struct_span_err(expr.span, msg)
.note_mv(format!(
"this is required to use type `{}` with register class `{}`",
ty,
reg_class.name(),
))
.emit();
return Some(asm_ty);
}
}
@ -449,14 +456,17 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
ty::Never | ty::Error(_) => {}
ty::FnDef(..) => {}
_ => {
let mut err =
self.tcx.dcx().struct_span_err(*op_sp, "invalid `sym` operand");
err.span_label(
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();
self.tcx
.dcx()
.struct_span_err(*op_sp, "invalid `sym` operand")
.span_label_mv(
self.tcx.def_span(anon_const.def_id),
format!("is {} `{}`", ty.kind().article(), ty),
)
.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(());
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 mut err =
tcx.dcx().struct_span_err(sp, "impls of auto traits cannot be default");
err.span_labels(impl_.defaultness_span, "default because of this");
err.span_label(sp, "auto trait");
res = Err(err.emit());
res = Err(tcx
.dcx()
.struct_span_err(sp, "impls of auto traits cannot be default")
.span_labels_mv(impl_.defaultness_span, "default because of this")
.span_label_mv(sp, "auto trait")
.emit());
}
// We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
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() {
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!(
"{} {}",
gat_item_hir.generics.add_where_or_trailing_comma(),
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 =
if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
err.note(format!(
"{bound} currently required to ensure that impls have maximum flexibility"
));
err.note(
"we are soliciting feedback, see issue #87479 \
tcx.dcx()
.struct_span_err(
gat_item_hir.span,
format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
)
.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> \
for more information",
);
err.emit();
)
.emit();
}
}
}
@ -938,8 +937,8 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(),
};
if may_suggest_feature && tcx.sess.is_nightly_build() {
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())

View File

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

View File

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

View File

@ -3183,9 +3183,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
if !is_input && !expr.is_syntactic_place_expr() {
let mut err = self.dcx().struct_span_err(expr.span, "invalid asm output");
err.span_label(expr.span, "cannot assign to this expression");
err.emit();
self.dcx()
.struct_span_err(expr.span, "invalid asm output")
.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
@ -3278,27 +3279,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter_enumerated()
.find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
else {
let mut err = type_error_struct!(
type_error_struct!(
self.dcx(),
ident.span,
container,
E0599,
"no variant named `{ident}` found for enum `{container}`",
);
err.span_label(field.span, "variant not found");
err.emit();
)
.span_label_mv(field.span, "variant not found")
.emit();
break;
};
let Some(&subfield) = fields.next() else {
let mut err = type_error_struct!(
type_error_struct!(
self.dcx(),
ident.span,
container,
E0795,
"`{ident}` is an enum variant; expected field at end of `offset_of`",
);
err.span_label(field.span, "enum variant");
err.emit();
)
.span_label_mv(field.span, "enum variant")
.emit();
break;
};
let (subident, sub_def_scope) =
@ -3309,16 +3310,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter_enumerated()
.find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
else {
let mut err = type_error_struct!(
type_error_struct!(
self.dcx(),
ident.span,
container,
E0609,
"no field named `{subfield}` on enum variant `{container}::{ident}`",
);
err.span_label(field.span, "this enum variant...");
err.span_label(subident.span, "...does not have this field");
err.emit();
)
.span_label_mv(field.span, "this enum variant...")
.span_label_mv(subident.span, "...does not have this field")
.emit();
break;
};

View File

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

View File

@ -332,15 +332,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if inside_union
&& 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,
"not automatically applying `DerefMut` on `ManuallyDrop` union field",
);
err.help(
)
.help_mv(
"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");
err.emit();
)
.help_mv("add an explicit `*` if that is desired, or call `ptr::write` to not run the destructor")
.emit();
}
}
source = adjustment.target;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -576,10 +576,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str });
}
let mut err = self.dcx().create_err(err);
err.span_label(path.span, format!("not {article} {expected}"));
err.emit();
self.dcx()
.create_err(err)
.span_label_mv(path.span, format!("not {article} {expected}"))
.emit();
return Ok((self.dummy_ext(kind), Res::Err));
}
@ -830,7 +830,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
expected,
ident,
});
self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate);
err.emit();
}

View File

@ -3544,17 +3544,16 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
span: Span,
) -> Option<DiagnosticBuilder<'tcx>> {
if !self.tcx.features().generic_const_exprs {
let mut err = self
.dcx()
.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
// issue. However, this is currently not actually possible
// (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
//
// Note that with `feature(generic_const_exprs)` this case should not
// be reachable.
err.note("this may fail depending on what value the parameter takes");
err.emit();
self.dcx()
.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
// issue. However, this is currently not actually possible
// (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
//
// Note that with `feature(generic_const_exprs)` this case should not
// be reachable.
.note_mv("this may fail depending on what value the parameter takes")
.emit();
return None;
}

View File

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