Auto merge of #110579 - nnethercote:restrict-From-for-Diagnostics, r=davidtwco

Restrict `From<S>` for `{D,Subd}iagnosticMessage`.

Currently a `{D,Subd}iagnosticMessage` can be created from any type that impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static, str>`, which are reasonable. It also includes `&String`, which is pretty weird, and results in many places making unnecessary allocations for patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the reference to `fatal`, which does an `into()`, which clones the reference, doing a second allocation. Two allocations for a single string, bleh.

This commit changes the `From` impls so that you can only create a `{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static, str>`. This requires changing all the places that currently create one from a `&String`. Most of these are of the `&format!(...)` form described above; each one removes an unnecessary static `&`, plus an allocation when executed. There are also a few places where the existing use of `&String` was more reasonable; these now just use `clone()` at the call site.

As well as making the code nicer and more efficient, this is a step towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing the `From<&'a str>` impls to `From<&'static str>`, which is doable, but I'm not yet sure if it's worthwhile.

r? `@davidtwco`
This commit is contained in:
bors 2023-05-03 00:22:19 +00:00
commit 71af5c4074
177 changed files with 791 additions and 787 deletions

View File

@ -136,7 +136,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.diagnostic().span_bug(
p.span,
&format!(
format!(
"lower_qpath: no final extension segment in {}..{}",
proj_start,
p.segments.len()

View File

@ -83,7 +83,7 @@ impl<'a> PostExpansionVisitor<'a> {
&self,
const_extern_fn,
span,
&format!("`{}` as a `const fn` ABI is unstable", abi)
format!("`{}` as a `const fn` ABI is unstable", abi)
),
}
}
@ -104,7 +104,7 @@ impl<'a> PostExpansionVisitor<'a> {
if self.sess.opts.pretty.map_or(true, |ppm| ppm.needs_hir()) {
self.sess.parse_sess.span_diagnostic.delay_span_bug(
span,
&format!(
format!(
"unrecognized ABI not caught in lowering: {}",
symbol_unescaped.as_str()
),

View File

@ -623,7 +623,7 @@ fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &F
let (cfg, feature, has_feature) = gated_cfg;
if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
let explain = format!("`cfg({cfg})` is experimental and subject to change");
feature_err(sess, *feature, cfg_span, &explain).emit();
feature_err(sess, *feature, cfg_span, explain).emit();
}
}

View File

@ -158,7 +158,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} else if reinits > 1 {
err.span_note(
MultiSpan::from_spans(reinit_spans),
&if reinits <= 3 {
if reinits <= 3 {
format!("these {reinits} reinitializations might get skipped")
} else {
format!(
@ -253,7 +253,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// We have a `&mut` ref, we need to reborrow on each iteration (#62112).
err.span_suggestion_verbose(
span.shrink_to_lo(),
&format!(
format!(
"consider creating a fresh reborrow of {} here",
self.describe_place(moved_place)
.map(|n| format!("`{n}`"))
@ -304,7 +304,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
..
} = use_spans
{
err.note(&format!(
err.note(format!(
"{} occurs due to deref coercion to `{deref_target_ty}`",
desired_action.as_noun(),
));
@ -586,7 +586,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// _ => {} // We don't want to point to this.
// };
// ```
err.span_label(sp, &label);
err.span_label(sp, label);
shown = true;
}
}
@ -1139,7 +1139,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
if union_type_name != "" {
err.note(&format!(
err.note(format!(
"{} is a field of the union `{}`, so it overlaps the field {}",
msg_place, union_type_name, msg_borrow,
));
@ -1238,14 +1238,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
err.span_help(
inner_call_span,
&format!(
format!(
"try adding a local storing this{}...",
if use_span.is_some() { "" } else { " argument" }
),
);
err.span_help(
outer_call_span,
&format!(
format!(
"...and then using that local {}",
if use_span.is_some() { "here" } else { "as the argument to this call" }
),
@ -2281,7 +2281,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
);
err.span_suggestion_verbose(
sugg_span,
&format!(
format!(
"to force the {} to take ownership of {} (and any \
other referenced variables), use the `move` keyword",
kind, captured_var
@ -2293,7 +2293,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
match category {
ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
let msg = format!("{} is returned here", kind);
err.span_note(constraint_span, &msg);
err.span_note(constraint_span, msg);
}
ConstraintCategory::CallArgument(_) => {
fr_name.highlight_region_name(&mut err);
@ -2304,7 +2304,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
);
} else {
let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
err.span_note(constraint_span, &msg);
err.span_note(constraint_span, msg);
}
}
_ => bug!(
@ -2626,7 +2626,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
});
if let Some(Ok(instance)) = deref_target {
let deref_target_ty = instance.ty(tcx, self.param_env);
err.note(&format!(
err.note(format!(
"borrow occurs due to deref coercion to `{}`",
deref_target_ty
));
@ -3180,7 +3180,7 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,));
diag.help(&format!(
diag.help(format!(
"use data from the highlighted arguments which match the `{}` lifetime of \
the return type",
region_name,

View File

@ -90,7 +90,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
{
err.span_label(
pat.span,
&format!("binding `{ident}` declared here"),
format!("binding `{ident}` declared here"),
);
}
}
@ -323,7 +323,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
err.span_suggestion_verbose(
span.shrink_to_hi(),
&msg,
msg,
format!(" + {suggestable_name}"),
Applicability::Unspecified,
);

View File

@ -1073,7 +1073,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if !is_loop_move {
err.span_suggestion_verbose(
move_span.shrink_to_lo(),
&format!(
format!(
"consider creating a fresh reborrow of {} here",
self.describe_place(moved_place.as_ref())
.map(|n| format!("`{n}`"))

View File

@ -533,7 +533,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
suggestions.sort_unstable_by_key(|&(span, _, _)| span);
suggestions.dedup_by_key(|&mut (span, _, _)| span);
for (span, msg, suggestion) in suggestions {
err.span_suggestion_verbose(span, &msg, suggestion, Applicability::MachineApplicable);
err.span_suggestion_verbose(span, msg, suggestion, Applicability::MachineApplicable);
}
}

View File

@ -573,7 +573,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
if !is_trait_sig {
err.span_suggestion_verbose(
err_help_span,
&format!(
format!(
"consider changing this to be a mutable {pointer_desc}"
),
suggested_code,
@ -582,7 +582,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} else if let Some(x) = local_trait {
err.span_suggestion_verbose(
x,
&format!(
format!(
"consider changing that to be a mutable {pointer_desc}"
),
suggested_code,
@ -636,14 +636,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
};
err.span_suggestion_verbose(
span,
&format!("consider {changing} this binding's type"),
format!("consider {changing} this binding's type"),
sugg,
Applicability::HasPlaceholders,
);
} else {
err.span_label(
err_label_span,
&format!(
format!(
"consider changing this binding's type to be: `{message}`"
),
);
@ -679,13 +679,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
match opt_source {
Some(BorrowedContentSource::OverloadedDeref(ty)) => {
err.help(&format!(
err.help(format!(
"trait `DerefMut` is required to modify through a dereference, \
but it is not implemented for `{ty}`",
));
}
Some(BorrowedContentSource::OverloadedIndex(ty)) => {
err.help(&format!(
err.help(format!(
"trait `IndexMut` is required to modify indexed content, \
but it is not implemented for `{ty}`",
));
@ -736,7 +736,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
// val[index] = rv;
// ---------- place
self.err.multipart_suggestions(
&format!(
format!(
"to modify a `{}`, use `.get_mut()`, `.insert()` or the entry API",
self.ty,
),
@ -788,7 +788,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{
// val[index].path(args..);
self.err.multipart_suggestion(
&format!("to modify a `{}` use `.get_mut()`", self.ty),
format!("to modify a `{}` use `.get_mut()`", self.ty),
vec![
(
val.span.shrink_to_hi().with_hi(index.span.lo()),
@ -822,7 +822,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
let mut v = V { assign_span, err, ty, suggested: false };
v.visit_body(body);
if !v.suggested {
err.help(&format!(
err.help(format!(
"to modify a `{ty}`, use `.get_mut()`, `.insert()` or the entry API",
));
}

View File

@ -171,7 +171,7 @@ impl OutlivesSuggestionBuilder {
if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name)
&& !matches!(outlived_fr_name.source, RegionNameSource::Static)
{
diag.help(&format!(
diag.help(format!(
"consider adding the following bound: `{fr_name}: {outlived_fr_name}`",
));
}
@ -207,7 +207,7 @@ impl OutlivesSuggestionBuilder {
// If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a
// list of diagnostics.
let mut diag = if suggested.len() == 1 {
mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() {
mbcx.infcx.tcx.sess.diagnostic().struct_help(match suggested.last().unwrap() {
SuggestedConstraint::Outlives(a, bs) => {
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
format!("add bound `{a}: {}`", bs.join(" + "))
@ -232,15 +232,15 @@ impl OutlivesSuggestionBuilder {
match constraint {
SuggestedConstraint::Outlives(a, bs) => {
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
diag.help(&format!("add bound `{a}: {}`", bs.join(" + ")));
diag.help(format!("add bound `{a}: {}`", bs.join(" + ")));
}
SuggestedConstraint::Equal(a, b) => {
diag.help(&format!(
diag.help(format!(
"`{a}` and `{b}` must be the same: replace one with the other",
));
}
SuggestedConstraint::Static(a) => {
diag.help(&format!("replace `{a}` with `'static`"));
diag.help(format!("replace `{a}` with `'static`"));
}
}
}

View File

@ -533,8 +533,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
_ => panic!("Unexpected type {ty:?}"),
};
diag.note(&format!("requirement occurs because of {desc}",));
diag.note(&note);
diag.note(format!("requirement occurs because of {desc}",));
diag.note(note);
diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
}
}
@ -863,7 +863,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
diag.multipart_suggestion_verbose(
&format!(
format!(
"to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
),
spans_suggs,

View File

@ -622,7 +622,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
// programs, so we need to use delay_span_bug here. See #82126.
self.infcx.tcx.sess.delay_span_bug(
hir_arg.span(),
&format!("unmatched subst and hir arg: found {kind:?} vs {hir_arg:?}"),
format!("unmatched subst and hir arg: found {kind:?} vs {hir_arg:?}"),
);
}
}

View File

@ -2022,7 +2022,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// been emitted (#52262).
self.infcx.tcx.sess.delay_span_bug(
span,
&format!(
format!(
"Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
place, kind,
),
@ -2383,7 +2383,7 @@ mod error {
}
for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
if count > 10 {
diag.note(&format!("...and {} other attempted mutable borrows", count - 10));
diag.note(format!("...and {} other attempted mutable borrows", count - 10));
}
diag.buffer(&mut self.errors.buffered);
}

View File

@ -399,7 +399,7 @@ pub(super) fn dump_annotation<'tcx>(
regioncx.annotate(tcx, &mut err);
err.note(&format!(
err.note(format!(
"number of external vids: {}",
closure_region_requirements.num_external_vids
));
@ -421,7 +421,7 @@ pub(super) fn dump_annotation<'tcx>(
};
if !opaque_type_values.is_empty() {
err.note(&format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
err.note(format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
}
errors.buffer_non_error_diag(err);

View File

@ -399,7 +399,7 @@ fn check_opaque_type_parameter_valid(
return Err(tcx
.sess
.struct_span_err(span, "non-defining opaque type use in defining scope")
.span_note(spans, &format!("{} used multiple times", descr))
.span_note(spans, format!("{} used multiple times", descr))
.emit());
}
}

View File

@ -249,7 +249,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
.infcx
.tcx
.sess
.delay_span_bug(span, &format!("failed to normalize {:?}", ty));
.delay_span_bug(span, format!("failed to normalize {:?}", ty));
TypeOpOutput {
output: self.infcx.tcx.ty_error(guar),
constraints: None,

View File

@ -106,7 +106,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
if body.yield_ty().is_some() != universal_regions.yield_ty.is_some() {
self.tcx().sess.delay_span_bug(
body.span,
&format!(
format!(
"Expected body to have yield_ty ({:?}) iff we have a UR yield_ty ({:?})",
body.yield_ty(),
universal_regions.yield_ty,

View File

@ -236,7 +236,7 @@ pub(crate) fn type_check<'mir, 'tcx>(
if hidden_type.has_non_region_infer() {
let reported = infcx.tcx.sess.delay_span_bug(
decl.hidden_type.span,
&format!("could not resolve {:#?}", hidden_type.ty.kind()),
format!("could not resolve {:#?}", hidden_type.ty.kind()),
);
hidden_type.ty = infcx.tcx.ty_error(reported);
}

View File

@ -335,7 +335,7 @@ impl<'tcx> UniversalRegions<'tcx> {
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
match self.defining_ty {
DefiningTy::Closure(def_id, substs) => {
err.note(&format!(
err.note(format!(
"defining type: {} with closure substs {:#?}",
tcx.def_path_str_with_substs(def_id, substs),
&substs[tcx.generics_of(def_id).parent_count..],
@ -347,11 +347,11 @@ impl<'tcx> UniversalRegions<'tcx> {
// and other things that are not stable across tests!
// So we just include the region-vid. Annoying.
for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
err.note(&format!("late-bound region is {:?}", self.to_region_vid(r)));
err.note(format!("late-bound region is {:?}", self.to_region_vid(r)));
});
}
DefiningTy::Generator(def_id, substs, _) => {
err.note(&format!(
err.note(format!(
"defining type: {} with generator substs {:#?}",
tcx.def_path_str_with_substs(def_id, substs),
&substs[tcx.generics_of(def_id).parent_count..],
@ -361,23 +361,23 @@ impl<'tcx> UniversalRegions<'tcx> {
// `r` but doing so is not stable across architectures
// and so forth.
for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
err.note(&format!("late-bound region is {:?}", self.to_region_vid(r)));
err.note(format!("late-bound region is {:?}", self.to_region_vid(r)));
});
}
DefiningTy::FnDef(def_id, substs) => {
err.note(&format!(
err.note(format!(
"defining type: {}",
tcx.def_path_str_with_substs(def_id, substs),
));
}
DefiningTy::Const(def_id, substs) => {
err.note(&format!(
err.note(format!(
"defining constant type: {}",
tcx.def_path_str_with_substs(def_id, substs),
));
}
DefiningTy::InlineConst(def_id, substs) => {
err.note(&format!(
err.note(format!(
"defining inline constant type: {}",
tcx.def_path_str_with_substs(def_id, substs),
));

View File

@ -553,7 +553,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
let mut e = ecx.struct_span_err(err_sp, msg);
e.span_label(err_sp, err.label + " in asm template string");
if let Some(note) = err.note {
e.note(&note);
e.note(note);
}
if let Some((label, span)) = err.secondary_label {
let err_sp = template_span.from_inner(InnerSpan::new(span.start, span.end));
@ -600,7 +600,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
1 => format!("there is 1 {}argument", positional),
x => format!("there are {} {}arguments", x, positional),
};
err.note(&msg);
err.note(msg);
if named_pos.contains_key(&idx) {
err.span_label(args.operands[idx].1, "named argument");
@ -703,7 +703,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
let (sp, msg) = unused_operands.into_iter().next().unwrap();
let mut err = ecx.struct_span_err(sp, msg);
err.span_label(sp, msg);
err.help(&format!(
err.help(format!(
"if this argument is intentionally unused, \
consider using it in an asm comment: `\"/*{} */\"`",
help_str
@ -718,7 +718,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
for (sp, msg) in unused_operands {
err.span_label(sp, msg);
}
err.help(&format!(
err.help(format!(
"if these arguments are intentionally unused, \
consider using them in an asm comment: `\"/*{} */\"`",
help_str

View File

@ -616,14 +616,14 @@ fn report_missing_placeholders(
} else {
diag.span_note(
sp,
&format!("format specifiers use curly braces, and {}", trn),
format!("format specifiers use curly braces, and {}", trn),
);
}
} else {
if success {
diag.help(&format!("`{}` should be written as `{}`", sub, trn));
diag.help(format!("`{}` should be written as `{}`", sub, trn));
} else {
diag.note(&format!("`{}` should use curly braces, and {}", sub, trn));
diag.note(format!("`{}` should use curly braces, and {}", sub, trn));
}
}
}
@ -777,7 +777,7 @@ fn report_invalid_references(
has_precision_star = true;
e.span_label(
*span,
&format!(
format!(
"this precision flag adds an extra required argument at position {}, which is why there {} expected",
index,
if num_placeholders == 1 {

View File

@ -194,7 +194,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
};
self.handler
.struct_span_err(attr.span, &msg)
.struct_span_err(attr.span, msg)
.span_label(prev_attr.span, "previous attribute here")
.emit();
@ -219,7 +219,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
pprust::path_to_string(&attr.get_normal_item().path),
);
self.handler.span_err(attr.span, &msg);
self.handler.span_err(attr.span, msg);
return;
}
@ -233,7 +233,7 @@ impl<'a> Visitor<'a> for CollectProcMacros<'a> {
pprust::path_to_string(&attr.get_normal_item().path),
);
self.handler.span_err(attr.span, &msg);
self.handler.span_err(attr.span, msg);
return;
}

View File

@ -150,7 +150,7 @@ pub fn expand_include<'cx>(
if self.p.token != token::Eof {
let token = pprust::token_to_string(&self.p.token);
let msg = format!("expected item, found `{}`", token);
self.p.struct_span_err(self.p.token.span, &msg).emit();
self.p.struct_span_err(self.p.token.span, msg).emit();
}
break;

View File

@ -88,10 +88,10 @@ pub(crate) fn import_function<'tcx>(
let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst);
match module.declare_function(name, Linkage::Import, &sig) {
Ok(func_id) => func_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
"attempt to declare `{name}` as function, but it was already declared as static"
)),
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(&format!(
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(format!(
"attempt to declare `{name}` with signature {new_sig:?}, \
but it was already declared with signature {prev_sig:?}"
)),
@ -548,7 +548,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
if !matches!(fn_sig.abi(), Abi::C { .. }) {
fx.tcx.sess.span_fatal(
source_info.span,
&format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
);
}
let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap();
@ -560,7 +560,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
// FIXME set %al to upperbound on float args once floats are supported
fx.tcx.sess.span_fatal(
source_info.span,
&format!("Non int ty {:?} for variadic call", ty),
format!("Non int ty {:?} for variadic call", ty),
);
}
AbiParam::new(ty)

View File

@ -220,13 +220,13 @@ pub(crate) fn verify_func(
match cranelift_codegen::verify_function(&func, &flags) {
Ok(_) => {}
Err(err) => {
tcx.sess.err(&format!("{:?}", err));
tcx.sess.err(format!("{:?}", err));
let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
&func,
Some(Box::new(writer)),
err,
);
tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
tcx.sess.fatal(format!("cranelift verify error:\n{}", pretty_error));
}
}
});

View File

@ -481,7 +481,7 @@ impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
#[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
if let layout::LayoutError::SizeOverflow(_) = err {
self.0.sess.span_fatal(span, &err.to_string())
self.0.sess.span_fatal(span, err.to_string())
} else {
span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
}
@ -499,7 +499,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
fn_abi_request: FnAbiRequest<'tcx>,
) -> ! {
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
self.0.sess.span_fatal(span, &err.to_string())
self.0.sess.span_fatal(span, err.to_string())
} else {
match fn_abi_request {
FnAbiRequest::OfFnPtr { sig, extra_args } => {

View File

@ -65,7 +65,7 @@ impl ConcurrencyLimiter {
// Make sure to drop the mutex guard first to prevent poisoning the mutex.
drop(state);
if let Some(err) = err {
handler.fatal(&err).raise();
handler.fatal(err).raise();
} else {
// The error was already emitted, but compilation continued. Raise a silent
// fatal error.

View File

@ -308,7 +308,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) {
Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
)),
Err(err) => Err::<_, _>(err).unwrap(),
@ -356,7 +356,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) {
Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
)),
Err(err) => Err::<_, _>(err).unwrap(),
@ -404,7 +404,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
if let Some(names) = section_name.split_once(',') {
names
} else {
tcx.sess.fatal(&format!(
tcx.sess.fatal(format!(
"#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
section_name
));
@ -449,7 +449,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
GlobalAlloc::Static(def_id) => {
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
{
tcx.sess.fatal(&format!(
tcx.sess.fatal(format!(
"Allocation {:?} contains reference to TLS value {:?}",
alloc_id, def_id
));

View File

@ -69,7 +69,7 @@ impl OngoingCodegen {
let module_codegen_result = match module_codegen_result {
Ok(module_codegen_result) => module_codegen_result,
Err(err) => sess.fatal(&err),
Err(err) => sess.fatal(err),
};
let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } =
module_codegen_result;
@ -468,7 +468,7 @@ pub(crate) fn run_aot(
let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name);
if let Err(err) = std::fs::write(&tmp_file, obj) {
tcx.sess.fatal(&format!("error writing metadata object file: {}", err));
tcx.sess.fatal(format!("error writing metadata object file: {}", err));
}
(metadata_cgu_name, tmp_file)

View File

@ -42,7 +42,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
_ => {
fx.tcx
.sess
.warn(&format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
.warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic);
return;
}

View File

@ -207,7 +207,7 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
}
*/
_ => {
fx.tcx.sess.warn(&format!(
fx.tcx.sess.warn(format!(
"unsupported AArch64 llvm intrinsic {}; replacing with trap",
intrinsic
));

View File

@ -138,10 +138,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
llvm_add_sub(fx, BinOp::Sub, ret, b_in, a, b);
}
_ => {
fx.tcx.sess.warn(&format!(
"unsupported x86 llvm intrinsic {}; replacing with trap",
intrinsic
));
fx.tcx
.sess
.warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic);
return;
}

View File

@ -42,7 +42,7 @@ fn report_atomic_type_validation_error<'tcx>(
) {
fx.tcx.sess.span_err(
span,
&format!(
format!(
"`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`",
intrinsic, ty
),
@ -1202,7 +1202,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
_ => {
fx.tcx
.sess
.span_fatal(source_info.span, &format!("unsupported intrinsic {}", intrinsic));
.span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic));
}
}

View File

@ -13,7 +13,7 @@ fn report_simd_type_validation_error(
span: Span,
ty: Ty<'_>,
) {
fx.tcx.sess.span_err(span, &format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
fx.tcx.sess.span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
// Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
}
@ -150,7 +150,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
_ => {
fx.tcx.sess.span_err(
span,
&format!(
format!(
"simd_shuffle index must be an array of `u32`, got `{}`",
idx_ty,
),
@ -248,7 +248,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
if idx >= lane_count.into() {
fx.tcx.sess.span_fatal(
fx.mir.span,
&format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
);
}
@ -296,7 +296,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
if idx >= lane_count.into() {
fx.tcx.sess.span_fatal(
fx.mir.span,
&format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
);
}
@ -699,7 +699,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
_ => {
fx.tcx.sess.span_fatal(
span,
&format!(
format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \
vector argument `{}`'s element type `{}`, expected integer element \
type",
@ -739,7 +739,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
_ => {
fx.tcx.sess.span_fatal(
span,
&format!(
format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \
cannot return `{}`, expected `u{}` or `[u8; {}]`",
ret.layout().ty,
@ -875,7 +875,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
}
_ => {
fx.tcx.sess.span_err(span, &format!("Unknown SIMD intrinsic {}", intrinsic));
fx.tcx.sess.span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic));
// Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
}

View File

@ -185,7 +185,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
let mut config = self.config.borrow_mut();
if config.is_none() {
let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
.unwrap_or_else(|err| sess.fatal(&err));
.unwrap_or_else(|err| sess.fatal(err));
*config = Some(new_config);
}
}
@ -245,7 +245,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
fn target_triple(sess: &Session) -> target_lexicon::Triple {
match sess.target.llvm_target.parse() {
Ok(triple) => triple,
Err(err) => sess.fatal(&format!("target not recognized: {}", err)),
Err(err) => sess.fatal(format!("target not recognized: {}", err)),
}
}
@ -307,7 +307,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
Some(value) => {
let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
sess.fatal(format!("can't compile for {}: {}", target_triple, err));
});
if let Err(_) = builder.enable(value) {
sess.fatal("the specified target cpu isn't currently supported by Cranelift.");
@ -317,7 +317,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
None => {
let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(&format!("can't compile for {}: {}", target_triple, err));
sess.fatal(format!("can't compile for {}: {}", target_triple, err));
});
if target_triple.architecture == target_lexicon::Architecture::X86_64 {
// Don't use "haswell" as the default, as it implies `has_lzcnt`.
@ -330,7 +330,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
match isa_builder.finish(flags) {
Ok(target_isa) => target_isa,
Err(err) => sess.fatal(&format!("failed to build TargetIsa: {}", err)),
Err(err) => sess.fatal(format!("failed to build TargetIsa: {}", err)),
}
}

View File

@ -75,7 +75,7 @@ pub(crate) fn maybe_create_entry_wrapper(
Ok(func_id) => func_id,
Err(err) => {
tcx.sess
.fatal(&format!("entry symbol `{entry_name}` declared multiple times: {err}"));
.fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}"));
}
};
@ -171,7 +171,7 @@ pub(crate) fn maybe_create_entry_wrapper(
}
if let Err(err) = m.define_function(cmain_func_id, &mut ctx) {
tcx.sess.fatal(&format!("entry symbol `{entry_name}` defined multiple times: {err}"));
tcx.sess.fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}"));
}
unwind_context.add_function(cmain_func_id, &ctx, m.isa());

View File

@ -344,7 +344,7 @@ impl<'tcx> CPlace<'tcx> {
if layout.size.bytes() >= u64::from(u32::MAX - 16) {
fx.tcx
.sess
.fatal(&format!("values of type {} are too big to store on the stack", layout.ty));
.fatal(format!("values of type {} are too big to store on the stack", layout.ty));
}
let stack_slot = fx.bcx.create_sized_stack_slot(StackSlotData {

View File

@ -53,7 +53,7 @@ use std::{env, fmt, fs, io, mem, str};
pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
if let Err(e) = fs::remove_file(path) {
if e.kind() != io::ErrorKind::NotFound {
diag_handler.err(&format!("failed to remove {}: {}", path.display(), e));
diag_handler.err(format!("failed to remove {}: {}", path.display(), e));
}
}
}
@ -1405,7 +1405,7 @@ fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
sess.emit_note(errors::StaticLibraryNativeArtifacts);
// Prefix for greppability
// Note: This must not be translated as tools are allowed to depend on this exact string.
sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
sess.note_without_error(format!("native-static-libs: {}", &lib_args.join(" ")));
}
}

View File

@ -1631,7 +1631,7 @@ impl<'a> Linker for AixLinker<'a> {
}
};
if let Err(e) = res {
self.sess.fatal(&format!("failed to write export file: {}", e));
self.sess.fatal(format!("failed to write export file: {}", e));
}
self.cmd.arg(format!("-bE:{}", path.to_str().unwrap()));
}

View File

@ -1833,7 +1833,7 @@ impl SharedEmitterMain {
sess.abort_if_errors();
}
Ok(SharedEmitterMessage::Fatal(msg)) => {
sess.fatal(&msg);
sess.fatal(msg);
}
Err(_) => {
break;

View File

@ -301,7 +301,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if let Some(val) = attr.value_str() {
if val.as_str().bytes().any(|b| b == 0) {
let msg = format!("illegal null byte in link_section value: `{}`", &val);
tcx.sess.span_err(attr.span, &msg);
tcx.sess.span_err(attr.span, msg);
} else {
codegen_fn_attrs.link_section = Some(val);
}
@ -631,7 +631,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
} else {
let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
tcx.sess
.struct_span_err(attr.span, &msg)
.struct_span_err(attr.span, msg)
.note("the value may not exceed `u16::MAX`")
.emit();
None

View File

@ -94,7 +94,7 @@ fn push_debuginfo_type_name<'tcx>(
// Computing the layout can still fail here, e.g. if the target architecture
// cannot represent the type. See https://github.com/rust-lang/rust/issues/94961.
// FIXME: migrate once `rustc_middle::mir::interpret::InterpError` is translatable.
tcx.sess.fatal(&format!("{}", e));
tcx.sess.fatal(format!("{}", e));
}
}
} else {

View File

@ -370,7 +370,7 @@ pub fn from_target_feature(
let Some(feature_gate) = supported_target_features.get(feature) else {
let msg =
format!("the feature named `{}` is not valid for this target", feature);
let mut err = tcx.sess.struct_span_err(item.span(), &msg);
let mut err = tcx.sess.struct_span_err(item.span(), msg);
err.span_label(
item.span(),
format!("`{}` is not valid for this target", feature),
@ -408,7 +408,7 @@ pub fn from_target_feature(
&tcx.sess.parse_sess,
feature_gate.unwrap(),
item.span(),
&format!("the target feature `{}` is currently unstable", feature),
format!("the target feature `{}` is currently unstable", feature),
)
.emit();
}

View File

@ -104,13 +104,13 @@ impl<'tcx> ConstEvalErr<'tcx> {
// Add spans for the stacktrace. Don't print a single-line backtrace though.
if self.stacktrace.len() > 1 {
// Helper closure to print duplicated lines.
let mut flush_last_line = |last_frame, times| {
let mut flush_last_line = |last_frame: Option<(String, _)>, times| {
if let Some((line, span)) = last_frame {
err.span_note(span, &line);
err.span_note(span, line.clone());
// Don't print [... additional calls ...] if the number of lines is small
if times < 3 {
for _ in 0..times {
err.span_note(span, &line);
err.span_note(span, line.clone());
}
} else {
err.span_note(

View File

@ -368,7 +368,7 @@ pub fn eval_to_allocation_raw_provider<'tcx>(
if matches!(err.error, InterpError::UndefinedBehavior(_)) {
diag.note(NOTE_ON_UNDEFINED_BEHAVIOR_ERROR);
}
diag.note(&format!(
diag.note(format!(
"the raw bytes of the constant ({}",
display_allocation(
*ecx.tcx,

View File

@ -83,7 +83,7 @@ pub(crate) fn eval_to_valtree<'tcx>(
Some(span) => {
tcx.sess.create_err(MaxNumNodesInConstErr { span, global_const_id })
}
None => tcx.sess.struct_err(&msg),
None => tcx.sess.struct_err(msg),
};
diag.emit();

View File

@ -387,7 +387,7 @@ pub fn intern_const_alloc_recursive<
Err(error) => {
ecx.tcx.sess.delay_span_bug(
ecx.tcx.span,
&format!(
format!(
"error during interning should later cause validation failure: {}",
error
),

View File

@ -293,7 +293,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
// FIXME: This should be a span_bug (#80742)
self.tcx.sess.delay_span_bug(
self.frame().current_span(),
&format!("{null_op:?} MIR operator called for unsized type {ty}"),
format!("{null_op:?} MIR operator called for unsized type {ty}"),
);
throw_inval!(SizeOfUnsizedType(ty));
}

View File

@ -77,7 +77,7 @@ impl<'tcx> NonConstOp<'tcx> for FloatingPointOp {
&ccx.tcx.sess.parse_sess,
sym::const_fn_floating_point_arithmetic,
span,
&format!("floating point arithmetic is not allowed in {}s", ccx.const_kind()),
format!("floating point arithmetic is not allowed in {}s", ccx.const_kind()),
)
}
}
@ -211,13 +211,13 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
err.span_note(span, "function defined here, but it is not `const`");
}
FnPtr(..) => {
err.note(&format!(
err.note(format!(
"function pointers need an RFC before allowed to be called in {}s",
ccx.const_kind()
));
}
Closure(..) => {
err.note(&format!(
err.note(format!(
"closures need an RFC before allowed to be called in {}s",
ccx.const_kind()
));
@ -289,7 +289,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
ccx.const_kind()
);
err.note(&format!("attempting to deref into `{}`", deref_target_ty));
err.note(format!("attempting to deref into `{}`", deref_target_ty));
// Check first whether the source is accessible (issue #87060)
if tcx.sess.source_map().is_span_accessible(deref_target) {
@ -310,14 +310,14 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
}),
};
err.note(&format!(
err.note(format!(
"calls in {}s are limited to constant functions, \
tuple structs and tuple variants",
ccx.const_kind(),
));
if let Some(feature) = feature && ccx.tcx.sess.is_nightly_build() {
err.help(&format!(
err.help(format!(
"add `#![feature({})]` to the crate attributes to enable",
feature,
));
@ -354,7 +354,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
err.help("const-stable functions can only call other const-stable functions");
} else if ccx.tcx.sess.is_nightly_build() {
if let Some(feature) = feature {
err.help(&format!(
err.help(format!(
"add `#![feature({})]` to the crate attributes to enable",
feature
));
@ -637,7 +637,7 @@ impl<'tcx> NonConstOp<'tcx> for RawMutPtrDeref {
&ccx.tcx.sess.parse_sess,
sym::const_mut_refs,
span,
&format!("dereferencing raw mutable pointers in {}s is unstable", ccx.const_kind(),),
format!("dereferencing raw mutable pointers in {}s is unstable", ccx.const_kind(),),
)
}
}
@ -724,7 +724,7 @@ pub mod ty {
&ccx.tcx.sess.parse_sess,
sym::const_mut_refs,
span,
&format!("mutable references are not allowed in {}s", ccx.const_kind()),
format!("mutable references are not allowed in {}s", ccx.const_kind()),
)
}
}

View File

@ -107,7 +107,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
// occurred.
self.tcx.sess.diagnostic().delay_span_bug(
span,
&format!(
format!(
"broken MIR in {:?} ({}) at {:?}:\n{}",
self.body.source.instance,
self.when,
@ -1094,7 +1094,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if self.body.source_scopes.get(scope).is_none() {
self.tcx.sess.diagnostic().delay_span_bug(
self.body.span,
&format!(
format!(
"broken MIR in {:?} ({}):\ninvalid source scope {:?}",
self.body.source.instance, self.when, scope,
),

View File

@ -287,11 +287,19 @@ pub enum SubdiagnosticMessage {
FluentAttr(FluentId),
}
/// `From` impl that enables existing diagnostic calls to functions which now take
/// `impl Into<SubdiagnosticMessage>` to continue to work as before.
impl<S: Into<String>> From<S> for SubdiagnosticMessage {
fn from(s: S) -> Self {
SubdiagnosticMessage::Str(s.into())
impl From<String> for SubdiagnosticMessage {
fn from(s: String) -> Self {
SubdiagnosticMessage::Str(s)
}
}
impl<'a> From<&'a str> for SubdiagnosticMessage {
fn from(s: &'a str) -> Self {
SubdiagnosticMessage::Str(s.to_string())
}
}
impl From<Cow<'static, str>> for SubdiagnosticMessage {
fn from(s: Cow<'static, str>) -> Self {
SubdiagnosticMessage::Str(s.to_string())
}
}
@ -352,11 +360,19 @@ impl DiagnosticMessage {
}
}
/// `From` impl that enables existing diagnostic calls to functions which now take
/// `impl Into<DiagnosticMessage>` to continue to work as before.
impl<S: Into<String>> From<S> for DiagnosticMessage {
fn from(s: S) -> Self {
DiagnosticMessage::Str(s.into())
impl From<String> for DiagnosticMessage {
fn from(s: String) -> Self {
DiagnosticMessage::Str(s)
}
}
impl<'a> From<&'a str> for DiagnosticMessage {
fn from(s: &'a str) -> Self {
DiagnosticMessage::Str(s.to_string())
}
}
impl From<Cow<'static, str>> for DiagnosticMessage {
fn from(s: Cow<'static, str>) -> Self {
DiagnosticMessage::Str(s.to_string())
}
}

View File

@ -791,7 +791,7 @@ macro_rules! struct_span_err {
($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
$session.struct_span_err_with_code(
$span,
&format!($($message)*),
format!($($message)*),
$crate::error_code!($code),
)
})

View File

@ -601,7 +601,7 @@ impl Emitter for SilentEmitter {
if d.level == Level::Fatal {
let mut d = d.clone();
if let Some(ref note) = self.fatal_note {
d.note(note);
d.note(note.clone());
}
self.fatal_handler.emit_diagnostic(&mut d);
}

View File

@ -1462,10 +1462,10 @@ impl HandlerInner {
DiagnosticMessage::Str(warnings),
)),
(_, 0) => {
let _ = self.fatal(&errors);
let _ = self.fatal(errors);
}
(_, _) => {
let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
let _ = self.fatal(format!("{}; {}", &errors, &warnings));
}
}
@ -1486,18 +1486,18 @@ impl HandlerInner {
error_codes.sort();
if error_codes.len() > 1 {
let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
self.failure(&format!(
self.failure(format!(
"Some errors have detailed explanations: {}{}",
error_codes[..limit].join(", "),
if error_codes.len() > 9 { "..." } else { "." }
));
self.failure(&format!(
self.failure(format!(
"For more information about an error, try \
`rustc --explain {}`.",
&error_codes[0]
));
} else {
self.failure(&format!(
self.failure(format!(
"For more information about this error, try \
`rustc --explain {}`.",
&error_codes[0]
@ -1663,7 +1663,7 @@ impl HandlerInner {
if bug.level != Level::DelayedBug {
// NOTE(eddyb) not panicking here because we're already producing
// an ICE, and the more information the merrier.
bug.note(&format!(
bug.note(format!(
"`flushed_delayed` got diagnostic with level {:?}, \
instead of the expected `DelayedBug`",
bug.level,
@ -1732,7 +1732,7 @@ impl DelayedDiagnostic {
}
fn decorate(mut self) -> Diagnostic {
self.inner.note(&format!("delayed at {}", self.note));
self.inner.note(format!("delayed at {}", self.note));
self.inner
}
}
@ -1831,7 +1831,7 @@ pub fn add_elided_lifetime_in_path_suggestion(
if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
diag.span_suggestion_verbose(
insertion_span.shrink_to_hi(),
&format!("indicate the anonymous lifetime{}", pluralize!(n)),
format!("indicate the anonymous lifetime{}", pluralize!(n)),
suggestion,
Applicability::MachineApplicable,
);

View File

@ -1146,7 +1146,7 @@ impl<'a> ExtCtxt<'a> {
for (span, notes) in self.expansions.iter() {
let mut db = self.sess.parse_sess.create_note(errors::TraceMacro { span: *span });
for note in notes {
db.note(note);
db.note(note.clone());
}
db.emit();
}

View File

@ -797,7 +797,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
&self.cx.sess.parse_sess,
sym::proc_macro_hygiene,
span,
&format!("custom attributes cannot be applied to {}", kind),
format!("custom attributes cannot be applied to {}", kind),
)
.emit();
}

View File

@ -474,7 +474,7 @@ pub fn compile_declarative_macro(
let s = parse_failure_msg(&token);
let sp = token.span.substitute_dummy(def.span);
let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, &s);
let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, s);
err.span_label(sp, msg);
annotate_doc_comment(&mut err, sess.source_map(), sp);
err.emit();
@ -483,7 +483,7 @@ pub fn compile_declarative_macro(
Error(sp, msg) => {
sess.parse_sess
.span_diagnostic
.struct_span_err(sp.substitute_dummy(def.span), &msg)
.struct_span_err(sp.substitute_dummy(def.span), msg)
.emit();
return dummy_syn_ext();
}
@ -555,7 +555,7 @@ pub fn compile_declarative_macro(
let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
match transparency_error {
Some(TransparencyError::UnknownTransparency(value, span)) => {
diag.span_err(span, &format!("unknown macro transparency: `{}`", value));
diag.span_err(span, format!("unknown macro transparency: `{}`", value));
}
Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes");
@ -1164,7 +1164,7 @@ fn check_matcher_core<'tt>(
let sp = next_token.span();
let mut err = sess.span_diagnostic.struct_span_err(
sp,
&format!(
format!(
"`${name}:{frag}` {may_be} followed by `{next}`, which \
is not allowed for `{frag}` fragments",
name = name,
@ -1196,13 +1196,13 @@ fn check_matcher_core<'tt>(
match possible {
&[] => {}
&[t] => {
err.note(&format!(
err.note(format!(
"only {} is allowed after `{}` fragments",
t, kind,
));
}
ts => {
err.note(&format!(
err.note(format!(
"{}{} or {}",
msg,
ts[..ts.len() - 1].to_vec().join(", "),

View File

@ -78,7 +78,7 @@ fn check_trailing_token<'sess>(
if let Some(tt) = iter.next() {
let mut diag = sess
.span_diagnostic
.struct_span_err(tt.span(), &format!("unexpected token: {}", pprust::tt_to_string(tt)));
.struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt)));
diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
Err(diag)
} else {
@ -137,11 +137,11 @@ fn parse_ident<'sess>(
let token_str = pprust::token_to_string(token);
let mut err = sess.span_diagnostic.struct_span_err(
span,
&format!("expected identifier, found `{}`", &token_str)
format!("expected identifier, found `{}`", &token_str)
);
err.span_suggestion(
token.span,
&format!("try removing `{}`", &token_str),
format!("try removing `{}`", &token_str),
"",
Applicability::MaybeIncorrect,
);

View File

@ -85,7 +85,7 @@ pub(super) fn parse(
frag.name
);
sess.span_diagnostic
.struct_span_err(span, &msg)
.struct_span_err(span, msg)
.help(VALID_FRAGMENT_NAMES_MSG)
.emit();
token::NonterminalKind::Ident
@ -195,7 +195,7 @@ fn parse_tree(
_ => {
let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
let msg = format!("expected `(` or `{{`, found `{}`", tok);
sess.span_diagnostic.span_err(delim_span.entire(), &msg);
sess.span_diagnostic.span_err(delim_span.entire(), msg);
}
}
}
@ -246,7 +246,7 @@ fn parse_tree(
"expected identifier, found `{}`",
pprust::token_to_string(&token),
);
sess.span_diagnostic.span_err(token.span, &msg);
sess.span_diagnostic.span_err(token.span, msg);
TokenTree::MetaVar(token.span, Ident::empty())
}
@ -358,7 +358,7 @@ fn parse_sep_and_kleene_op(
// For example, `macro_rules! foo { ( ${length()} ) => {} }`
fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &ParseSess, token: &Token) {
sess.span_diagnostic
.span_err(token.span, &format!("unexpected token: {}", pprust::token_to_string(token)));
.span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token)));
sess.span_diagnostic.span_note_without_error(
token.span,
"`$$` and meta-variable expressions are not allowed inside macro parameter definitions",

View File

@ -95,7 +95,7 @@ impl base::AttrProcMacro for AttrProcMacro {
|e| {
let mut err = ecx.struct_span_err(span, "custom attribute panicked");
if let Some(s) = e.as_str() {
err.help(&format!("message: {}", s));
err.help(format!("message: {}", s));
}
err.emit()
},
@ -148,7 +148,7 @@ impl MultiItemModifier for DeriveProcMacro {
Err(e) => {
let mut err = ecx.struct_span_err(span, "proc-macro derive panicked");
if let Some(s) = e.as_str() {
err.help(&format!("message: {}", s));
err.help(format!("message: {}", s));
}
err.emit();
return ExpandResult::Ready(vec![]);

View File

@ -243,13 +243,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let note = format!("{title} is defined in an impl for the type `{impl_ty}`");
if let Some(span) = note_span {
err.span_note(span, &note);
err.span_note(span, note);
} else {
err.note(&note);
err.note(note);
}
}
if candidates.len() > limit {
err.note(&format!("and {} others", candidates.len() - limit));
err.note(format!("and {} others", candidates.len() - limit));
}
}
@ -303,7 +303,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
"associated type `{name}` not found for `{self_ty}` in the current scope"
);
err.span_label(name.span, format!("associated item not found in `{self_ty}`"));
err.note(&format!(
err.note(format!(
"the associated type was found for\n{type_candidates}{additional_types}",
));
add_def_label(&mut err);
@ -390,10 +390,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let mut err = tcx.sess.struct_span_err(
name.span,
&format!("the associated type `{name}` exists for `{self_ty}`, but its trait bounds were not satisfied")
format!("the associated type `{name}` exists for `{self_ty}`, but its trait bounds were not satisfied")
);
if !bounds.is_empty() {
err.note(&format!(
err.note(format!(
"the following trait bounds were not satisfied:\n{}",
bounds.join("\n")
));
@ -409,7 +409,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
if !tcx.sess.source_map().is_span_accessible(span) {
continue;
}
err.span_label(span, &msg);
err.span_label(span, msg);
}
add_def_label(&mut err);
err.emit()
@ -589,7 +589,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
if !suggestions.is_empty() {
err.multipart_suggestion(
&format!("specify the associated type{}", pluralize!(types_count)),
format!("specify the associated type{}", pluralize!(types_count)),
suggestions,
Applicability::HasPlaceholders,
);

View File

@ -112,7 +112,7 @@ fn generic_arg_mismatch_err(
if let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) = body.value.kind
{
if let Res::Def(DefKind::Fn { .. }, id) = path.res {
err.help(&format!("`{}` is a function item, not a type", tcx.item_name(id)));
err.help(format!("`{}` is a function item, not a type", tcx.item_name(id)));
err.help("function item types cannot be named directly");
}
}
@ -130,7 +130,7 @@ fn generic_arg_mismatch_err(
} else {
(arg.descr(), param.kind.descr())
};
err.note(&format!("{} arguments must be provided before {} arguments", first, last));
err.note(format!("{} arguments must be provided before {} arguments", first, last));
if let Some(help) = help {
err.help(help);
}

View File

@ -1168,9 +1168,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
tcx.sess
.struct_span_err(
binding.span,
&format!("{} `{}` is private", assoc_item.kind, binding.item_name),
format!("{} `{}` is private", assoc_item.kind, binding.item_name),
)
.span_label(binding.span, &format!("private {}", assoc_item.kind))
.span_label(binding.span, format!("private {}", assoc_item.kind))
.emit();
}
tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
@ -1342,11 +1342,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let expected = tcx.def_descr(assoc_item_def_id);
let mut err = tcx.sess.struct_span_err(
binding.span,
&format!("expected {expected} bound, found {got}"),
format!("expected {expected} bound, found {got}"),
);
err.span_note(
tcx.def_span(assoc_item_def_id),
&format!("{expected} defined here"),
format!("{expected} defined here"),
);
if let hir::def::DefKind::AssocConst = def_kind
@ -1508,7 +1508,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
"additional use",
);
first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
err.help(&format!(
err.help(format!(
"consider creating a new trait with all of these as supertraits and using that \
trait here instead: `trait NewTrait: {} {{}}`",
regular_traits
@ -1818,7 +1818,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
([], []) => {
err.span_suggestion_verbose(
span,
&format!(
format!(
"if there were a type named `Type` that implements a trait named \
`Trait` with associated type `{name}`, you could use the \
fully-qualified path",
@ -1830,7 +1830,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
([], [trait_str]) => {
err.span_suggestion_verbose(
span,
&format!(
format!(
"if there were a type named `Example` that implemented `{trait_str}`, \
you could use the fully-qualified path",
),
@ -1841,7 +1841,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
([], traits) => {
err.span_suggestions(
span,
&format!(
format!(
"if there were a type named `Example` that implemented one of the \
traits with associated type `{name}`, you could use the \
fully-qualified path",
@ -1856,7 +1856,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
([type_str], []) => {
err.span_suggestion_verbose(
span,
&format!(
format!(
"if there were a trait named `Example` with associated type `{name}` \
implemented for `{type_str}`, you could use the fully-qualified path",
),
@ -1867,7 +1867,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
(types, []) => {
err.span_suggestions(
span,
&format!(
format!(
"if there were a trait named `Example` with associated type `{name}` \
implemented for one of the types, you could use the fully-qualified \
path",
@ -2033,7 +2033,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
);
}
} else {
err.note(&format!(
err.note(format!(
"associated type `{}` could derive from `{}`",
ty_param_name,
bound.print_only_trait_path(),
@ -2041,7 +2041,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
}
if !where_bounds.is_empty() {
err.help(&format!(
err.help(format!(
"consider introducing a new type parameter `T` and adding `where` constraints:\
\n where\n T: {},\n{}",
ty_param_name,
@ -2109,14 +2109,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// work for the `enum`, instead of just looking if it takes *any*.
err.span_suggestion_verbose(
args_span,
&format!("{type_name} doesn't have generic parameters"),
format!("{type_name} doesn't have generic parameters"),
"",
Applicability::MachineApplicable,
);
return;
}
let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
err.note(&msg);
err.note(msg);
return;
};
let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
@ -2150,12 +2150,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
kw::SelfUpper == segment.ident.name,
),
_ => {
err.note(&msg);
err.note(msg);
return;
}
}
} else {
err.note(&msg);
err.note(msg);
return;
};
let suggestion = vec![
@ -2170,7 +2170,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
(args_span, String::new()),
];
err.multipart_suggestion_verbose(
&msg,
msg,
suggestion,
Applicability::MaybeIncorrect,
);
@ -2222,7 +2222,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let reported = if variant_resolution.is_some() {
// Variant in type position
let msg = format!("expected type, found variant `{}`", assoc_ident);
tcx.sess.span_err(span, &msg)
tcx.sess.span_err(span, msg)
} else if qself_ty.is_enum() {
let mut err = struct_span_err!(
tcx.sess,
@ -2293,7 +2293,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// Assume that if it's not matched, there must be a const defined with the same name
// but it was used in a type position.
let msg = format!("found associated const `{assoc_ident}` when type was expected");
let guar = tcx.sess.struct_span_err(span, &msg).emit();
let guar = tcx.sess.struct_span_err(span, msg).emit();
return Err(guar);
};
@ -2313,7 +2313,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
also,
tcx.def_kind_descr(kind, def_id)
);
lint.span_note(tcx.def_span(def_id), &note_msg);
lint.span_note(tcx.def_span(def_id), note_msg);
};
could_refer_to(DefKind::Variant, variant_def_id, "");
@ -2510,9 +2510,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let msg = format!("{kind} `{name}` is private");
let def_span = tcx.def_span(item);
tcx.sess
.struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
.span_label(span, &format!("private {kind}"))
.span_label(def_span, &format!("{kind} defined here"))
.struct_span_err_with_code(span, msg, rustc_errors::error_code!(E0624))
.span_label(span, format!("private {kind}"))
.span_label(def_span, format!("{kind} defined here"))
.emit();
}
tcx.check_stability(item, Some(block), span, None);
@ -2960,7 +2960,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
self.prohibit_generics(path.segments.iter(), |err| {
if let Some(span) = tcx.def_ident_span(def_id) {
let name = tcx.item_name(def_id);
err.span_note(span, &format!("type parameter `{name}` defined here"));
err.span_note(span, format!("type parameter `{name}` defined here"));
}
});
@ -3021,7 +3021,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let mut span: MultiSpan = vec![t_sp].into();
span.push_span_label(
i_sp,
&format!("`Self` is on type `{type_name}` in this `impl`"),
format!("`Self` is on type `{type_name}` in this `impl`"),
);
let mut postfix = "";
if generics == 0 {
@ -3029,11 +3029,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
span.push_span_label(
t_sp,
&format!("`Self` corresponds to this type{postfix}"),
format!("`Self` corresponds to this type{postfix}"),
);
err.span_note(span, &msg);
err.span_note(span, msg);
} else {
err.note(&msg);
err.note(msg);
}
for segment in path.segments {
if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
@ -3124,7 +3124,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
if let Some(args) = segment.args {
err.span_suggestion_verbose(
segment.ident.span.shrink_to_hi().to(args.span_ext),
&format!("primitive type `{name}` doesn't have generic parameters"),
format!("primitive type `{name}` doesn't have generic parameters"),
"",
Applicability::MaybeIncorrect,
);
@ -3415,7 +3415,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
if !infer_replacements.is_empty() {
diag.multipart_suggestion(
&format!(
format!(
"try replacing `_` with the type{} in the corresponding trait method signature",
rustc_errors::pluralize!(infer_replacements.len()),
),

View File

@ -175,7 +175,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
}
// Generic statics are rejected, but we still reach this case.
Err(e) => {
tcx.sess.delay_span_bug(span, &e.to_string());
tcx.sess.delay_span_bug(span, e.to_string());
return;
}
};
@ -334,7 +334,7 @@ pub(super) fn check_opaque_for_inheriting_lifetimes(
&tcx.sess.parse_sess,
sym::impl_trait_projections,
span,
&format!(
format!(
"`{}` return type cannot contain a projection or `Self` that references \
lifetimes from a parent scope",
if is_async { "async fn" } else { "impl Trait" },
@ -428,7 +428,7 @@ fn check_opaque_meets_bounds<'tcx>(
let ty_err = ty_err.to_string(tcx);
tcx.sess.delay_span_bug(
span,
&format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
);
}
}
@ -618,11 +618,11 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) {
E0044,
"foreign items may not have {kinds} parameters",
)
.span_label(item.span, &format!("can't have {kinds} parameters"))
.span_label(item.span, format!("can't have {kinds} parameters"))
.help(
// FIXME: once we start storing spans for type arguments, turn this
// into a suggestion.
&format!(
format!(
"replace the {} parameters with concrete {}{}",
kinds,
kinds_pl,
@ -985,10 +985,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
err.span_note(
tcx.def_span(def_spans[0].0),
&format!(
"`{}` has a `#[repr(align)]` attribute",
tcx.item_name(def_spans[0].0)
),
format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
);
if def_spans.len() > 2 {
@ -997,7 +994,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
let ident = tcx.item_name(*adt_def);
err.span_note(
*span,
&if first {
if first {
format!(
"`{}` contains a field of type `{}`",
tcx.type_of(def.did()).subst_identity(),
@ -1466,10 +1463,10 @@ fn opaque_type_cycle_error(
let ty_span = tcx.def_span(def_id);
if !seen.contains(&ty_span) {
let descr = if ty.is_impl_trait() { "opaque " } else { "" };
err.span_label(ty_span, &format!("returning this {descr}type `{ty}`"));
err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
seen.insert(ty_span);
}
err.span_label(sp, &format!("returning here with type `{ty}`"));
err.span_label(sp, format!("returning here with type `{ty}`"));
}
for closure_def_id in visitor.closures {

View File

@ -1273,7 +1273,7 @@ fn compare_number_of_generics<'tcx>(
let mut err = tcx.sess.struct_span_err_with_code(
spans,
&format!(
format!(
"{} `{}` has {} {kind} parameter{} but its trait \
declaration has {} {kind} parameter{}",
item_kind,

View File

@ -52,7 +52,7 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro
let span = tcx.def_span(drop_impl_did);
let reported = tcx.sess.delay_span_bug(
span,
&format!("should have been rejected by coherence check: {dtor_self_type}"),
format!("should have been rejected by coherence check: {dtor_self_type}"),
);
Err(reported)
}
@ -76,15 +76,15 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>(
struct_span_err!(tcx.sess, drop_impl_span, E0366, "`Drop` impls cannot be specialized");
match arg {
ty::util::NotUniqueParam::DuplicateParam(arg) => {
err.note(&format!("`{arg}` is mentioned multiple times"))
err.note(format!("`{arg}` is mentioned multiple times"))
}
ty::util::NotUniqueParam::NotParam(arg) => {
err.note(&format!("`{arg}` is not a generic parameter"))
err.note(format!("`{arg}` is not a generic parameter"))
}
};
err.span_note(
item_span,
&format!(
format!(
"use the same sequence of generic lifetime, type and const parameters \
as the {self_descr} definition",
),

View File

@ -547,14 +547,14 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>)
Err(_) => {
let msg =
format!("unrecognized platform-specific intrinsic function: `{name}`");
tcx.sess.struct_span_err(it.span, &msg).emit();
tcx.sess.struct_span_err(it.span, msg).emit();
return;
}
}
}
_ => {
let msg = format!("unrecognized platform-specific intrinsic function: `{name}`");
tcx.sess.struct_span_err(it.span, &msg).emit();
tcx.sess.struct_span_err(it.span, msg).emit();
return;
}
};

View File

@ -130,7 +130,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
_ => None,
};
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.sess.struct_span_err(expr.span, msg);
err.note(
"only integers, floats, SIMD vectors, pointers and function pointers \
@ -145,7 +145,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
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.sess.struct_span_err(expr.span, msg);
err.note(&format!("`{ty}` does not implement the Copy trait"));
err.note(format!("`{ty}` does not implement the Copy trait"));
err.emit();
}
@ -164,8 +164,8 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
let mut err = self.tcx.sess.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.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, \
unless they are both pointers or integers of the same size",
@ -184,17 +184,17 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
let reg_class = reg.reg_class();
let supported_tys = reg_class.supported_types(asm_arch);
let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
let msg = &format!("type `{ty}` cannot be used with this register class");
let msg = format!("type `{ty}` cannot be used with this register class");
let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
let supported_tys: Vec<_> =
supported_tys.iter().map(|(t, _)| t.to_string()).collect();
err.note(&format!(
err.note(format!(
"register class `{}` supports these types: {}",
reg_class.name(),
supported_tys.join(", "),
));
if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
err.help(&format!(
err.help(format!(
"consider using the `{}` register class instead",
suggest.name()
));
@ -215,9 +215,9 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
// register class is usable at all.
if let Some(feature) = feature {
if !target_features.contains(feature) {
let msg = &format!("`{}` target feature is not enabled", feature);
let msg = format!("`{}` target feature is not enabled", feature);
let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
err.note(&format!(
err.note(format!(
"this is required to use type `{}` with register class `{}`",
ty,
reg_class.name(),
@ -252,10 +252,10 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
"formatting may not be suitable for sub-register argument",
|lint| {
lint.span_label(expr.span, "for this argument");
lint.help(&format!(
lint.help(format!(
"use `{{{idx}:{suggested_modifier}}}` to have the register formatted as `{suggested_result}`",
));
lint.help(&format!(
lint.help(format!(
"or use `{{{idx}:{default_modifier}}}` to keep the default formatting of `{default_result}`",
));
lint
@ -301,7 +301,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
op.is_clobber(),
) {
let msg = format!("cannot use register `{}`: {}", reg.name(), msg);
self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
self.tcx.sess.struct_span_err(*op_sp, msg).emit();
continue;
}
}
@ -340,7 +340,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
reg_class.name(),
feature
);
self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
self.tcx.sess.struct_span_err(*op_sp, msg).emit();
// register isn't enabled, don't do more checks
continue;
}
@ -354,7 +354,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
.intersperse(", ")
.collect::<String>(),
);
self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
self.tcx.sess.struct_span_err(*op_sp, msg).emit();
// register isn't enabled, don't do more checks
continue;
}
@ -436,7 +436,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
self.tcx.sess.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),
format!("is {} `{}`", ty.kind().article(), ty),
);
err.help("`sym` operands must refer to either a function or a static");
err.emit();

View File

@ -445,7 +445,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe
let plural = pluralize!(unsatisfied_bounds.len());
let mut err = tcx.sess.struct_span_err(
gat_item_hir.span,
&format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
);
let suggestion = format!(
@ -455,14 +455,14 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe
);
err.span_suggestion(
gat_item_hir.generics.tail_span_for_predicate_suggestion(),
&format!("add the required where clause{plural}"),
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!(
err.note(format!(
"{} currently required to ensure that impls have maximum flexibility",
bound
));
@ -916,14 +916,14 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
if is_ptr {
tcx.sess.span_err(
hir_ty.span,
&format!(
format!(
"using {unsupported_type} as const generic parameters is forbidden",
),
);
} else {
let mut err = tcx.sess.struct_span_err(
hir_ty.span,
&format!(
format!(
"{unsupported_type} is forbidden as the type of a const generic parameter",
),
);
@ -1029,7 +1029,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b
let ty = tcx.erase_regions(ty);
if ty.has_infer() {
tcx.sess
.delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
.delay_span_bug(item.span, format!("inference variables in {:?}", ty));
// Just treat unresolved type expression as if it needs drop.
true
} else {
@ -1651,7 +1651,7 @@ fn check_method_receiver<'tcx>(
&tcx.sess.parse_sess,
sym::arbitrary_self_types,
span,
&format!(
format!(
"`{receiver_ty}` cannot be used as the type of `self` without \
the `arbitrary_self_types` feature",
),
@ -1874,10 +1874,10 @@ fn report_bivariance(
} else {
format!("consider removing `{param_name}` or referring to it in a field")
};
err.help(&msg);
err.help(msg);
if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
err.help(&format!(
err.help(format!(
"if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
param_name
));

View File

@ -213,7 +213,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef
for structs containing the field being coerced, \
ZST fields with 1 byte alignment, and nothing else",
)
.note(&format!(
.note(format!(
"extra field `{}` of type `{}` is not allowed",
field.name, ty_a,
))
@ -241,7 +241,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef
for a coercion between structures with a single field \
being coerced",
)
.note(&format!(
.note(format!(
"currently, {} fields need coercions: {}",
coerced_fields.len(),
coerced_fields
@ -298,7 +298,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe
let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, Some(span));
let unsize_trait = tcx.lang_items().require(LangItem::Unsize).unwrap_or_else(|err| {
tcx.sess.fatal(&format!("`CoerceUnsized` implementation {}", err.to_string()));
tcx.sess.fatal(format!("`CoerceUnsized` implementation {}", err.to_string()));
});
let source = tcx.type_of(impl_did).subst_identity();
@ -469,7 +469,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe
"`CoerceUnsized` may only be implemented for \
a coercion between structures with one field being coerced",
)
.note(&format!(
.note(format!(
"currently, {} fields need coercions: {}",
diff_fields.len(),
diff_fields

View File

@ -146,7 +146,7 @@ impl<'tcx> InherentCollect<'tcx> {
);
err.help("consider using an extension trait instead");
if let ty::Ref(_, subty, _) = ty.kind() {
err.note(&format!(
err.note(format!(
"you could also try moving the reference to \
uses of `{}` (such as `self`) within the implementation",
subty

View File

@ -372,10 +372,10 @@ fn emit_orphan_check_error<'tcx>(
if is_target_ty {
// Point at `D<A>` in `impl<A, B> for C<B> in D<A>`
err.span_label(self_ty_span, &msg);
err.span_label(self_ty_span, msg);
} else {
// Point at `C<B>` in `impl<A, B> for C<B> in D<A>`
err.span_label(trait_span, &msg);
err.span_label(trait_span, msg);
}
}
err.note("define and implement a trait or new type instead");
@ -531,15 +531,15 @@ fn lint_auto_trait_impl<'tcx>(
let self_descr = tcx.def_descr(self_type_did);
match arg {
ty::util::NotUniqueParam::DuplicateParam(arg) => {
lint.note(&format!("`{}` is mentioned multiple times", arg));
lint.note(format!("`{}` is mentioned multiple times", arg));
}
ty::util::NotUniqueParam::NotParam(arg) => {
lint.note(&format!("`{}` is not a generic parameter", arg));
lint.note(format!("`{}` is not a generic parameter", arg));
}
}
lint.span_note(
item_span,
&format!(
format!(
"try using the same sequence of generic parameters as the {} definition",
self_descr,
),

View File

@ -987,7 +987,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
lifetime.ident
),
|lint| {
let help = &format!(
let help = format!(
"you can use the `'static` lifetime directly, in place of `{}`",
lifetime.ident,
);
@ -1365,7 +1365,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
self.tcx.sess.delay_span_bug(
lifetime_ref.ident.span,
&format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
);
}

View File

@ -828,14 +828,14 @@ fn infer_placeholder_type<'a>(
if let Some(ty) = ty.make_suggestable(tcx, false) {
err.span_suggestion(
span,
&format!("provide a type for the {item}", item = kind),
format!("provide a type for the {item}", item = kind),
format!("{colon} {ty}"),
Applicability::MachineApplicable,
);
} else {
with_forced_trimmed_paths!(err.span_note(
tcx.hir().body(body_id).value.span,
&format!("however, the inferred type `{ty}` cannot be named"),
format!("however, the inferred type `{ty}` cannot be named"),
));
}
}
@ -856,7 +856,7 @@ fn infer_placeholder_type<'a>(
} else {
with_forced_trimmed_paths!(diag.span_note(
tcx.hir().body(body_id).value.span,
&format!("however, the inferred type `{ty}` cannot be named"),
format!("however, the inferred type `{ty}` cannot be named"),
));
}
}

View File

@ -76,7 +76,7 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
// (#36836)
tcx.sess.delay_span_bug(
tcx.def_span(impl_def_id),
&format!(
format!(
"potentially unconstrained type parameters weren't evaluated: {:?}",
impl_self_ty,
),

View File

@ -272,7 +272,7 @@ fn check_duplicate_params<'tcx>(
if let (_, [duplicate, ..]) = base_params.partition_dedup() {
let param = impl1_substs[duplicate.0 as usize];
tcx.sess
.struct_span_err(span, &format!("specializing impl repeats parameter `{}`", param))
.struct_span_err(span, format!("specializing impl repeats parameter `{}`", param))
.emit();
}
}
@ -464,7 +464,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc
tcx.sess
.struct_span_err(
span,
&format!(
format!(
"cannot specialize on trait `{}`",
tcx.def_path_str(trait_ref.def_id),
),
@ -479,7 +479,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc
tcx.sess
.struct_span_err(
span,
&format!("cannot specialize on associated type `{projection_ty} == {term}`",),
format!("cannot specialize on associated type `{projection_ty} == {term}`",),
)
.emit();
}
@ -495,7 +495,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc
}
_ => {
tcx.sess
.struct_span_err(span, &format!("cannot specialize on predicate `{}`", predicate))
.struct_span_err(span, format!("cannot specialize on predicate `{}`", predicate))
.emit();
}
}

View File

@ -61,7 +61,7 @@ fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[(ty::Clau
let span = tcx.def_span(item_def_id);
let mut err = tcx.sess.struct_span_err(span, "rustc_outlives");
for p in &pred {
for p in pred {
err.note(p);
}
err.emit();

View File

@ -48,7 +48,7 @@ impl<'tcx> StructuredDiagnostic<'tcx> for MissingCastForVariadicArg<'tcx, '_> {
&self,
mut err: DiagnosticBuilder<'tcx, ErrorGuaranteed>,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
err.note(&format!(
err.note(format!(
"certain types, like `{}`, must be casted before passing them to a \
variadic function, because of arcane ABI rules dictated by the C \
standard",

View File

@ -480,7 +480,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let span = self.path_segment.ident.span;
let msg = self.create_error_message();
self.tcx.sess.struct_span_err_with_code(span, &msg, self.code())
self.tcx.sess.struct_span_err_with_code(span, msg, self.code())
}
/// Builds the `expected 1 type argument / supplied 2 type arguments` message.
@ -602,7 +602,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
err.span_suggestion_verbose(
span.shrink_to_hi(),
&msg,
msg,
sugg,
Applicability::HasPlaceholders,
);
@ -625,7 +625,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix);
debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(sugg_span, &msg, sugg, Applicability::HasPlaceholders);
err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
}
AngleBrackets::Implied => {
// We never encounter missing lifetimes in situations in which lifetimes are elided
@ -652,7 +652,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
err.span_suggestion_verbose(
span.shrink_to_hi(),
&msg,
msg,
sugg,
Applicability::HasPlaceholders,
);
@ -683,7 +683,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix);
debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(sugg_span, &msg, sugg, Applicability::HasPlaceholders);
err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
}
}
}
@ -885,7 +885,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
err.span_suggestion(
span_redundant_lt_args,
&msg_lifetimes,
msg_lifetimes,
"",
Applicability::MaybeIncorrect,
);
@ -927,7 +927,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
err.span_suggestion(
span_redundant_type_or_const_args,
&msg_types_or_consts,
msg_types_or_consts,
"",
Applicability::MaybeIncorrect,
);
@ -943,7 +943,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
if !suggestions.is_empty() {
err.multipart_suggestion_verbose(
&format!(
format!(
"replace the generic bound{s} with the associated type{s}",
s = pluralize!(unbound_types.len())
),
@ -969,7 +969,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
},
);
err.span_suggestion(span, &msg, "", Applicability::MaybeIncorrect);
err.span_suggestion(span, msg, "", Applicability::MaybeIncorrect);
} else if redundant_lifetime_args && redundant_type_or_const_args {
remove_lifetime_args(err);
remove_type_or_const_args(err);
@ -1029,7 +1029,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
)
};
err.span_note(spans, &msg);
err.span_note(spans, msg);
}
/// Add note if `impl Trait` is explicitly specified.

View File

@ -271,7 +271,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&cause,
&mut |err| {
if let Some((span, msg)) = &ret_reason {
err.span_label(*span, msg);
err.span_label(*span, msg.clone());
} else if let ExprKind::Block(block, _) = &then_expr.kind
&& let Some(expr) = &block.expr
{

View File

@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.sess
.struct_span_err(
callee_expr.span,
&format!("evaluate({:?}) = {:?}", predicate, result),
format!("evaluate({:?}) = {:?}", predicate, result),
)
.span_label(predicate_span, "predicate")
.emit();
@ -630,7 +630,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some((removal_span, kind, path)) = &unit_variant {
err.span_suggestion_verbose(
*removal_span,
&format!(
format!(
"`{path}` is a unit {kind}, and does not take parentheses to be constructed",
),
"",

View File

@ -146,7 +146,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let reported = self
.tcx
.sess
.delay_span_bug(span, &format!("`{:?}` should be sized but is not?", t));
.delay_span_bug(span, format!("`{:?}` should be sized but is not?", t));
return Err(reported);
}
})
@ -270,7 +270,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
fcx,
);
if self.cast_ty.is_integral() {
err.help(&format!(
err.help(format!(
"cast through {} first",
match e {
CastError::NeedViaPtr => "a raw pointer",
@ -292,7 +292,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
self.cast_ty,
fcx,
)
.help(&format!(
.help(format!(
"cast through {} first",
match e {
CastError::NeedViaInt => "an integer",
@ -651,13 +651,13 @@ impl<'a, 'tcx> CastCheck<'tcx> {
);
}
Err(_) => {
let msg = &format!("did you mean `&{}{}`?", mtstr, tstr);
let msg = format!("did you mean `&{}{}`?", mtstr, tstr);
err.span_help(self.cast_span, msg);
}
}
} else {
let msg =
&format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
format!("consider using an implicit coercion to `&{mtstr}{tstr}` instead");
err.span_help(self.span, msg);
}
}
@ -674,7 +674,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
Err(_) => {
err.span_help(
self.cast_span,
&format!("you might have meant `Box<{tstr}>`"),
format!("you might have meant `Box<{tstr}>`"),
);
}
}

View File

@ -707,9 +707,9 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
&self.tcx.sess.parse_sess,
sym::trait_upcasting,
self.cause.span,
&format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
);
err.note(&format!("required when coercing `{source}` into `{target}`"));
err.note(format!("required when coercing `{source}` into `{target}`"));
err.emit();
}
@ -1657,7 +1657,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
"the function expects a value to always be returned, but loops might run zero times",
);
if MAXITER < ret_exprs.len() {
err.note(&format!(
err.note(format!(
"if the loop doesn't execute, {} other values would never get returned",
ret_exprs.len() - MAXITER
));
@ -1767,7 +1767,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
{
err.span_note(
sp,
&format!(
format!(
"return type inferred to be `{}` here",
expected
),
@ -1864,7 +1864,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
Applicability::MaybeIncorrect,
);
} else {
err.help(&format!(
err.help(format!(
"if the trait `{}` were object safe, you could return a boxed trait object",
&snippet[5..]
));

View File

@ -543,13 +543,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// We are pointing at the binding's type or initializer value, but it's pattern
// is in a different line, so we point at both.
err.span_label(secondary_span, "expected due to the type of this binding");
err.span_label(primary_span, &format!("expected due to this{post_message}"));
err.span_label(primary_span, format!("expected due to this{post_message}"));
} else if post_message == "" {
// We are pointing at either the assignment lhs or the binding def pattern.
err.span_label(primary_span, "expected due to the type of this binding");
} else {
// We are pointing at the binding's type or initializer value.
err.span_label(primary_span, &format!("expected due to this{post_message}"));
err.span_label(primary_span, format!("expected due to this{post_message}"));
}
if !lhs.is_syntactic_place_expr() {
@ -566,7 +566,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) if rhs.hir_id == expr.hir_id
&& self.typeck_results.borrow().expr_ty_adjusted_opt(lhs) == Some(expected) =>
{
err.span_label(lhs.span, &format!("expected because this is `{expected}`"));
err.span_label(lhs.span, format!("expected because this is `{expected}`"));
}
_ => {}
}
@ -704,19 +704,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
});
err.span_note(
path_span,
&format!(
format!(
"the `{}` call is resolved to the method in `{container}`, shadowing {tail}",
path.ident,
),
);
if suggestions.len() > other_methods_in_scope.len() {
err.note(&format!(
err.note(format!(
"additionally, there are {} other available methods that aren't in scope",
suggestions.len() - other_methods_in_scope.len()
));
}
err.multipart_suggestions(
&format!(
format!(
"you might have meant to call {}; you can use the fully-qualified path to call {} \
explicitly",
if suggestions.len() == 1 {
@ -941,7 +941,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
[(variant, ctor_kind, field_name, note)] => {
// Just a single matching variant.
err.multipart_suggestion_verbose(
&format!(
format!(
"try wrapping the expression in `{variant}`{note}",
note = note.as_deref().unwrap_or("")
),
@ -953,7 +953,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
_ => {
// More than one matching variant.
err.multipart_suggestions(
&format!(
format!(
"try wrapping the expression in a variant of `{}`",
self.tcx.def_path_str(expected_adt.did())
),
@ -1726,7 +1726,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
];
(msg, suggestion)
} else {
let msg = format!("{msg} and panic if the converted value doesn't fit");
let msg =
format!("{} and panic if the converted value doesn't fit", msg.clone());
let mut suggestion = sugg.clone();
suggestion.push((
expr.span.shrink_to_hi(),
@ -1734,11 +1735,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
));
(msg, suggestion)
};
err.multipart_suggestion_verbose(
&msg,
suggestion,
Applicability::MachineApplicable,
);
err.multipart_suggestion_verbose(msg, suggestion, Applicability::MachineApplicable);
};
let suggest_to_change_suffix_or_into =
@ -1755,13 +1752,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let always_fallible = found_to_exp_is_fallible
&& (exp_to_found_is_fallible || expected_ty_expr.is_none());
let msg = if literal_is_ty_suffixed(expr) {
&lit_msg
lit_msg.clone()
} else if always_fallible && (is_negative_int(expr) && is_uint(expected_ty)) {
// We now know that converting either the lhs or rhs is fallible. Before we
// suggest a fallible conversion, check if the value can never fit in the
// expected type.
let msg = format!("`{src}` cannot fit into type `{expected_ty}`");
err.note(&msg);
err.note(msg);
return;
} else if in_const_context {
// Do not recommend `into` or `try_into` in const contexts.
@ -1769,7 +1766,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else if found_to_exp_is_fallible {
return suggest_fallible_into_or_lhs_from(err, exp_to_found_is_fallible);
} else {
&msg
msg.clone()
};
let suggestion = if literal_is_ty_suffixed(expr) {
suffix_suggestion.clone()
@ -1831,14 +1828,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
suggest_to_change_suffix_or_into(err, false, true);
} else if literal_is_ty_suffixed(expr) {
err.multipart_suggestion_verbose(
&lit_msg,
lit_msg,
suffix_suggestion,
Applicability::MachineApplicable,
);
} else if can_cast {
// Missing try_into implementation for `f64` to `f32`
err.multipart_suggestion_verbose(
&format!("{cast_msg}, producing the closest possible value"),
format!("{cast_msg}, producing the closest possible value"),
cast_suggestion,
Applicability::MaybeIncorrect, // lossy conversion
);
@ -1848,14 +1845,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(&ty::Uint(_) | &ty::Int(_), &ty::Float(_)) => {
if literal_is_ty_suffixed(expr) {
err.multipart_suggestion_verbose(
&lit_msg,
lit_msg,
suffix_suggestion,
Applicability::MachineApplicable,
);
} else if can_cast {
// Missing try_into implementation for `{float}` to `{integer}`
err.multipart_suggestion_verbose(
&format!("{msg}, rounding the float towards zero"),
format!("{msg}, rounding the float towards zero"),
cast_suggestion,
Applicability::MaybeIncorrect, // lossy conversion
);
@ -1866,7 +1863,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
if exp.bit_width() > found.bit_width().unwrap_or(256) {
err.multipart_suggestion_verbose(
&format!(
format!(
"{msg}, producing the floating point representation of the integer",
),
into_suggestion,
@ -1874,14 +1871,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
} else if literal_is_ty_suffixed(expr) {
err.multipart_suggestion_verbose(
&lit_msg,
lit_msg,
suffix_suggestion,
Applicability::MachineApplicable,
);
} else {
// Missing try_into implementation for `{integer}` to `{float}`
err.multipart_suggestion_verbose(
&format!(
format!(
"{cast_msg}, producing the floating point representation of the integer, \
rounded if necessary",
),
@ -1895,23 +1892,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
if exp.bit_width() > found.bit_width().unwrap_or(256) {
err.multipart_suggestion_verbose(
&format!(
format!(
"{}, producing the floating point representation of the integer",
&msg,
msg.clone(),
),
into_suggestion,
Applicability::MachineApplicable,
);
} else if literal_is_ty_suffixed(expr) {
err.multipart_suggestion_verbose(
&lit_msg,
lit_msg,
suffix_suggestion,
Applicability::MachineApplicable,
);
} else {
// Missing try_into implementation for `{integer}` to `{float}`
err.multipart_suggestion_verbose(
&format!(
format!(
"{}, producing the floating point representation of the integer, \
rounded if necessary",
&msg,
@ -1928,7 +1925,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&ty::Char,
) => {
err.multipart_suggestion_verbose(
&format!("{cast_msg}, since a `char` always occupies 4 bytes"),
format!("{cast_msg}, since a `char` always occupies 4 bytes"),
cast_suggestion,
Applicability::MachineApplicable,
);

View File

@ -1944,12 +1944,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
private_fields: Vec<&ty::FieldDef>,
used_fields: &'tcx [hir::ExprField<'tcx>],
) {
let mut err = self.tcx.sess.struct_span_err(
span,
&format!(
"cannot construct `{adt_ty}` with struct literal syntax due to private fields",
),
);
let mut err =
self.tcx.sess.struct_span_err(
span,
format!(
"cannot construct `{adt_ty}` with struct literal syntax due to private fields",
),
);
let (used_private_fields, remaining_private_fields): (
Vec<(Symbol, Span, bool)>,
Vec<(Symbol, Span, bool)>,
@ -2045,7 +2046,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_label(field.ident.span, "field does not exist");
err.span_suggestion_verbose(
expr_span,
&format!(
format!(
"`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
adt = ty,
variant = variant.name,
@ -2063,7 +2064,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_label(field.ident.span, "field does not exist");
err.span_suggestion_verbose(
expr_span,
&format!(
format!(
"`{adt}` is a tuple {kind_name}, use the appropriate syntax",
adt = ty,
kind_name = kind_name,
@ -2105,7 +2106,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let available_field_names =
self.available_field_names(variant, expr_span);
if !available_field_names.is_empty() {
err.note(&format!(
err.note(format!(
"available fields are: {}",
self.name_series_display(available_field_names)
));
@ -2384,7 +2385,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
if add_label {
err.span_label(field_ident.span, &format!("field not found in `{ty}`"));
err.span_label(field_ident.span, format!("field not found in `{ty}`"));
}
}
@ -2565,7 +2566,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let param_span = self.tcx.hir().span(param_hir_id);
let param_name = self.tcx.hir().ty_param_name(param_def_id.expect_local());
err.span_label(param_span, &format!("type parameter '{param_name}' declared here"));
err.span_label(param_span, format!("type parameter '{param_name}' declared here"));
}
fn suggest_fields_on_recordish(
@ -2589,7 +2590,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let struct_variant_def = def.non_enum_variant();
let field_names = self.available_field_names(struct_variant_def, access_span);
if !field_names.is_empty() {
err.note(&format!(
err.note(format!(
"available fields are: {}",
self.name_series_display(field_names),
));
@ -2630,7 +2631,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
let msg = format!("`{base}` is a raw pointer; try dereferencing it");
let suggestion = format!("(*{base}).{field}");
err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
err.span_suggestion(expr.span, msg, suggestion, Applicability::MaybeIncorrect);
}
}

View File

@ -63,9 +63,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lint::builtin::UNREACHABLE_CODE,
id,
span,
&msg,
msg.clone(),
|lint| {
lint.span_label(span, &msg).span_label(
lint.span_label(span, msg).span_label(
orig_span,
custom_note
.unwrap_or("any code following this expression is unreachable"),
@ -275,7 +275,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
_ => {
self.tcx.sess.delay_span_bug(
expr.span,
&format!(
format!(
"while adjusting {:?}, can't compose {:?} and {:?}",
expr,
entry.get(),
@ -1034,15 +1034,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rcvr.span,
"you probably want to use this value after calling the method...",
);
err.span_note(sp, &modifies_rcvr_note);
err.note(&format!("...instead of the `()` output of method `{}`", path_segment.ident));
err.span_note(sp, modifies_rcvr_note);
err.note(format!("...instead of the `()` output of method `{}`", path_segment.ident));
} else if let ExprKind::MethodCall(..) = rcvr.kind {
err.span_note(
sp,
modifies_rcvr_note.clone() + ", it is not meant to be used in method chains.",
);
} else {
err.span_note(sp, &modifies_rcvr_note);
err.span_note(sp, modifies_rcvr_note);
}
}
@ -1374,7 +1374,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Err(_) => {
self.tcx.sess.delay_span_bug(
span,
&format!(
format!(
"instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
self_ty,
impl_ty,

View File

@ -685,7 +685,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
err = tcx.sess.struct_span_err_with_code(
full_call_span,
&format!(
format!(
"{call_name} takes {}{} but {} {} supplied",
if c_variadic { "at least " } else { "" },
potentially_plural_count(
@ -828,7 +828,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
tcx.sess.struct_span_err_with_code(
full_call_span,
&format!(
format!(
"this {} takes {}{} but {} {} supplied",
call_name,
if c_variadic { "at least " } else { "" },
@ -1203,7 +1203,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
SuggestionText::Remove(plural) => {
err.multipart_suggestion(
&format!("remove the extra argument{}", if plural { "s" } else { "" }),
format!("remove the extra argument{}", if plural { "s" } else { "" }),
suggestions,
Applicability::HasPlaceholders,
);
@ -1253,7 +1253,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
suggestion += ")";
err.span_suggestion_verbose(
suggestion_span,
&suggestion_text,
suggestion_text,
suggestion,
Applicability::HasPlaceholders,
);
@ -1947,7 +1947,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
spans.push_span_label(param.span, "");
}
err.span_note(spans, &format!("{} defined here", self.tcx.def_descr(def_id)));
err.span_note(spans, format!("{} defined here", self.tcx.def_descr(def_id)));
} else if let Some(hir::Node::Expr(e)) = self.tcx.hir().get_if_local(def_id)
&& let hir::ExprKind::Closure(hir::Closure { body, .. }) = &e.kind
{
@ -1958,11 +1958,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
("closure", self.tcx.def_span(def_id))
};
err.span_note(span, &format!("{} defined here", kind));
err.span_note(span, format!("{} defined here", kind));
} else {
err.span_note(
self.tcx.def_span(def_id),
&format!("{} defined here", self.tcx.def_descr(def_id)),
format!("{} defined here", self.tcx.def_descr(def_id)),
);
}
}

View File

@ -278,9 +278,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.check_ref(expr, found, expected)
{
if verbose {
err.span_suggestion_verbose(sp, &msg, suggestion, applicability);
err.span_suggestion_verbose(sp, msg, suggestion, applicability);
} else {
err.span_suggestion(sp, &msg, suggestion, applicability);
err.span_suggestion(sp, msg, suggestion, applicability);
}
if annotation {
let suggest_annotation = match expr.peel_drop_temps().kind {
@ -1449,7 +1449,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
diag.span_note(
callee_expr.span,
&format!(
format!(
"`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead"
),
);

View File

@ -205,7 +205,7 @@ impl<'tcx> expr_use_visitor::Delegate<'tcx> for ExprUseDelegate<'tcx> {
if ty.has_infer() {
self.tcx.sess.delay_span_bug(
self.tcx.hir().span(assignee_place.hir_id),
&format!("inference variables in {ty}"),
format!("inference variables in {ty}"),
);
} else if ty.needs_drop(self.tcx, self.param_env) {
self.places

View File

@ -112,7 +112,7 @@ impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
self.fcx
.tcx
.sess
.delay_span_bug(span, &format!("Encountered var {:?}", unresolved_term));
.delay_span_bug(span, format!("Encountered var {:?}", unresolved_term));
} else {
let note = format!(
"the type is part of the {} because of this {}",
@ -464,7 +464,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
self.fcx
.tcx
.sess
.delay_span_bug(expr.span, &format!("inference variables in {ty}"));
.delay_span_bug(expr.span, format!("inference variables in {ty}"));
true
} else {
ty.needs_drop(self.fcx.tcx, self.fcx.param_env)

View File

@ -72,8 +72,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let from = unpack_option_like(tcx, from);
if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer(dl.instruction_address_space).size(&tcx) {
struct_span_err!(tcx.sess, span, E0591, "can't transmute zero-sized type")
.note(&format!("source type: {from}"))
.note(&format!("target type: {to}"))
.note(format!("source type: {from}"))
.note(format!("target type: {to}"))
.help("cast with `as` to a pointer instead")
.emit();
return;
@ -109,10 +109,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
or dependently-sized types"
);
if from == to {
err.note(&format!("`{from}` does not have a fixed size"));
err.note(format!("`{from}` does not have a fixed size"));
} else {
err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
.note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
err.note(format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
.note(format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
let mut should_delay_as_bug = false;
if let Err(LayoutError::Unknown(bad_from)) = sk_from && bad_from.references_error() {
should_delay_as_bug = true;

View File

@ -448,7 +448,7 @@ fn fatally_break_rust(sess: &Session) {
"we would appreciate a joke overview: \
https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
);
handler.note_without_error(&format!(
handler.note_without_error(format!(
"rustc {} running on {}",
option_env!("CFG_VERSION").unwrap_or("unknown_version"),
config::host_triple(),

View File

@ -118,7 +118,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
lint.span_help(
sp,
&format!("disambiguate the method call with `({})`", self_adjusted,),
format!("disambiguate the method call with `({})`", self_adjusted,),
);
}
@ -180,7 +180,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
lint.span_help(
sp,
&format!(
format!(
"disambiguate the associated function with `{}::{}(...)`",
trait_name, segment.ident,
),

View File

@ -1396,7 +1396,7 @@ impl<'tcx> Pick<'tcx> {
// However `self.span` only
// highlights the method name, so we can't use it. Also consider reusing
// the code from `report_method_error()`.
lint.help(&format!(
lint.help(format!(
"call with fully qualified syntax `{}(...)` to keep using the current \
method",
tcx.def_path_str(self.item.def_id),
@ -1420,7 +1420,7 @@ impl<'tcx> Pick<'tcx> {
}
if tcx.sess.is_nightly_build() {
for (candidate, feature) in &self.unstable_candidates {
lint.help(&format!(
lint.help(format!(
"add `#![feature({})]` to the crate attributes to enable `{}`",
feature,
tcx.def_path_str(candidate.item.def_id),

View File

@ -169,13 +169,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
kind,
item_name
);
err.span_label(item_name.span, &format!("private {}", kind));
err.span_label(item_name.span, format!("private {}", kind));
let sp = self
.tcx
.hir()
.span_if_local(def_id)
.unwrap_or_else(|| self.tcx.def_span(def_id));
err.span_label(sp, &format!("private {} defined here", kind));
err.span_label(sp, format!("private {} defined here", kind));
self.suggest_valid_traits(&mut err, out_of_scope_traits);
err.emit();
}
@ -188,7 +188,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
format!("the `{item_name}` method cannot be invoked on a trait object")
};
let mut err = self.sess().struct_span_err(span, &msg);
let mut err = self.sess().struct_span_err(span, msg);
if !needs_mut {
err.span_label(bound_span, "this has a `Sized` requirement");
}
@ -228,12 +228,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
err.span_suggestion_verbose(
mut_ty.ty.span.shrink_to_lo(),
&msg,
msg,
"mut ",
Applicability::MachineApplicable,
);
} else {
err.help(&msg);
err.help(msg);
}
}
}
@ -374,14 +374,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ty_str
};
if let Some(file) = ty_file {
err.note(&format!("the full type name has been written to '{}'", file.display(),));
err.note(format!("the full type name has been written to '{}'", file.display(),));
}
if rcvr_ty.references_error() {
err.downgrade_to_delayed_bug();
}
if tcx.ty_is_opaque_future(rcvr_ty) && item_name.name == sym::poll {
err.help(&format!(
err.help(format!(
"method `poll` found on `Pin<&mut {ty_str}>`, \
see documentation for `std::pin::Pin`"
));
@ -510,7 +510,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
let iterator_trait = self.tcx.def_path_str(iterator_trait);
err.note(&format!(
err.note(format!(
"`count` is defined on `{iterator_trait}`, which `{rcvr_ty}` does not implement"
));
}
@ -810,7 +810,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
for (sp, label) in span_labels {
span.push_span_label(sp, label);
}
err.span_note(span, &msg);
err.span_note(span, msg);
unsatisfied_bounds = true;
}
@ -867,7 +867,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
obligations.sort();
err.span_suggestion_verbose(
span,
&format!(
format!(
"consider restricting the type parameter{s} to satisfy the \
trait bound{s}",
s = pluralize!(obligations.len())
@ -912,13 +912,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
but its trait bounds were not satisfied"
)
});
err.set_primary_message(&primary_message);
err.set_primary_message(primary_message);
if let Some(label) = label {
custom_span_label = true;
err.span_label(span, label);
}
if !bound_list.is_empty() {
err.note(&format!(
err.note(format!(
"the following trait bounds were not satisfied:\n{bound_list}"
));
}
@ -1002,7 +1002,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
"".to_string()
};
err.note(&format!(
err.note(format!(
"the {item_kind} was found for\n{}{}",
type_candidates, additional_types
));
@ -1049,7 +1049,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
bound_spans.sort();
bound_spans.dedup();
for (span, msg) in bound_spans.into_iter() {
err.span_label(span, &msg);
err.span_label(span, msg);
}
if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params {
@ -1119,7 +1119,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
err.span_suggestion(
span,
&format!(
format!(
"there is {} {} with a similar name",
self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id),
self.tcx.def_kind_descr(def_kind, similar_candidate.def_id)
@ -1203,9 +1203,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
if let Some(note_span) = note_span {
// We have a span pointing to the method. Show note with snippet.
err.span_note(note_span, &note_str);
err.span_note(note_span, note_str);
} else {
err.note(&note_str);
err.note(note_str);
}
if let Some(sugg_span) = sugg_span
&& let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
@ -1243,7 +1243,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let Some(item) = self.associated_value(trait_did, item_name) else { continue };
let item_span = self.tcx.def_span(item.def_id);
let idx = if sources.len() > 1 {
let msg = &format!(
let msg = format!(
"candidate #{} is defined in the trait `{}`",
idx + 1,
self.tcx.def_path_str(trait_did)
@ -1251,7 +1251,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_note(item_span, msg);
Some(idx + 1)
} else {
let msg = &format!(
let msg = format!(
"the candidate is defined in the trait `{}`",
self.tcx.def_path_str(trait_did)
);
@ -1278,7 +1278,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
if sources.len() > limit {
err.note(&format!("and {} others", sources.len() - limit));
err.note(format!("and {} others", sources.len() - limit));
}
}
@ -1402,7 +1402,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
applicability,
);
} else {
err.help(&format!("try with `{}::{}`", ty_str, item_name,));
err.help(format!("try with `{}::{}`", ty_str, item_name,));
}
}
@ -1436,7 +1436,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if self.is_fn_ty(field_ty, span) {
let expr_span = expr.span.to(item_name.span);
err.multipart_suggestion(
&format!(
format!(
"to call the function stored in `{}`, \
surround the field access with parentheses",
item_name,
@ -1612,7 +1612,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);
err.span_suggestion(
lit.span,
&format!(
format!(
"you must specify a concrete type for this numeric value, \
like `{}`",
concrete_type
@ -1648,7 +1648,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// account for `let x: _ = 42;`
// ^^^
type_span,
&msg,
msg,
format!(": {concrete_type}"),
Applicability::MaybeIncorrect,
);
@ -1861,7 +1861,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let self_ty = field.ty(tcx, substs);
err.span_note(
tcx.def_span(pick.item.def_id),
&format!("the method `{item_name}` exists on the type `{self_ty}`"),
format!("the method `{item_name}` exists on the type `{self_ty}`"),
);
let (article, kind, variant, question) =
if tcx.is_diagnostic_item(sym::Result, kind.did()) {
@ -1975,7 +1975,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_note(
tcx.def_span(pick.item.def_id),
&format!("the method `{item_name}` exists on the type `{ty}`"),
format!("the method `{item_name}` exists on the type `{ty}`"),
);
}
}
@ -2046,7 +2046,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pluralize!(preds.len()),
)
};
err.span_note(spans, &msg);
err.span_note(spans, msg);
}
let preds: Vec<_> = errors
@ -2160,14 +2160,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
err.span_note(
span,
&format!("the trait{} {} must be implemented", pluralize!(len), names),
format!("the trait{} {} must be implemented", pluralize!(len), names),
);
}
for (self_name, self_span, traits) in &derives_grouped {
err.span_suggestion_verbose(
self_span.shrink_to_lo(),
&format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
format!("#[derive({})]\n", traits),
Applicability::MaybeIncorrect,
);
@ -2313,7 +2313,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestions(
span,
&msg,
msg,
path_strings.chain(glob_path_strings),
Applicability::MaybeIncorrect,
);
@ -2345,7 +2345,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.suggest_use_candidates(err, msg, candidates);
if let Some(did) = edition_fix {
err.note(&format!(
err.note(format!(
"'{}' is included in the prelude starting in Edition 2021",
with_crate_prefix!(self.tcx.def_path_str(did))
));
@ -2413,7 +2413,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip {
err.span_label(
pick.item.ident(self.tcx).span,
&format!("the method is available for `{}` here", rcvr_ty),
format!("the method is available for `{}` here", rcvr_ty),
);
}
break;
@ -2459,7 +2459,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip {
err.span_label(
pick.item.ident(self.tcx).span,
&format!("the method is available for `{}` here", new_rcvr_t),
format!("the method is available for `{}` here", new_rcvr_t),
);
err.multipart_suggestion(
"consider wrapping the receiver expression with the \
@ -2655,7 +2655,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
err.span_suggestions(
sp,
&message(format!(
message(format!(
"restrict type parameter `{}` with",
param.name.ident(),
)),
@ -2687,7 +2687,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
err.span_suggestions(
sp,
&message(format!("add {} supertrait for", article)),
message(format!("add {} supertrait for", article)),
candidates.iter().map(|t| {
format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
}),
@ -2746,7 +2746,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
[trait_info] if trait_info.def_id.is_local() => {
err.span_note(
self.tcx.def_span(trait_info.def_id),
&format!(
format!(
"`{}` defines an item `{}`, perhaps you need to {} it",
self.tcx.def_path_str(trait_info.def_id),
item_name,
@ -2763,7 +2763,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.tcx.def_path_str(trait_info.def_id),
));
}
err.note(&msg);
err.note(msg);
}
}
match &explicitly_negative[..] {
@ -2774,7 +2774,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.tcx.def_path_str(trait_info.def_id),
item_name
);
err.note(&msg);
err.note(msg);
}
trait_infos => {
let mut msg = format!(
@ -2784,7 +2784,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
for trait_info in trait_infos {
msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
}
err.note(&msg);
err.note(msg);
}
}
}
@ -2836,7 +2836,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_args.len() == args.len() + 1 {
err.span_suggestion_verbose(
method_name.span.shrink_to_hi(),
&format!("try calling `{}` instead", new_name.name.as_str()),
format!("try calling `{}` instead", new_name.name.as_str()),
"_else",
Applicability::MaybeIncorrect,
);
@ -2956,7 +2956,7 @@ fn print_disambiguation_help<'tcx>(
};
err.span_suggestion_verbose(
span,
&format!(
format!(
"disambiguate the {} for {}",
def_kind_descr,
if let Some(candidate) = candidate {

View File

@ -390,7 +390,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
)
.is_ok()
{
let msg = &format!(
let msg = format!(
"`{}{}` can be used on `{}` if you dereference the left-hand side",
op.node.as_str(),
match is_assign {
@ -515,7 +515,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
// When we know that a missing bound is responsible, we don't show
// this note as it is redundant.
err.note(&format!(
err.note(format!(
"the trait `{missing_trait}` is not implemented for `{lhs_ty}`"
));
}
@ -690,7 +690,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
err.span_suggestion(
ex.span,
&format!(
format!(
"you may have meant the maximum value of `{actual}`",
),
format!("{actual}::MAX"),

View File

@ -517,7 +517,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn endpoint_has_type(&self, err: &mut Diagnostic, span: Span, ty: Ty<'_>) {
if !ty.references_error() {
err.span_label(span, &format!("this is of type `{}`", ty));
err.span_label(span, format!("this is of type `{}`", ty));
}
}
@ -544,7 +544,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
format!("this is of type `{}` but it should be `char` or numeric", ty)
};
let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| {
err.span_label(first_span, &msg(first_ty));
err.span_label(first_span, msg(first_ty));
if let Some((_, ty, sp)) = second {
let ty = self.resolve_vars_if_possible(ty);
self.endpoint_has_type(&mut err, sp, ty);
@ -552,8 +552,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
match (lhs, rhs) {
(Some((true, lhs_ty, lhs_sp)), Some((true, rhs_ty, rhs_sp))) => {
err.span_label(lhs_sp, &msg(lhs_ty));
err.span_label(rhs_sp, &msg(rhs_ty));
err.span_label(lhs_sp, msg(lhs_ty));
err.span_label(rhs_sp, msg(rhs_ty));
}
(Some((true, lhs_ty, lhs_sp)), rhs) => one_side_err(lhs_sp, lhs_ty, rhs),
(lhs, Some((true, rhs_ty, rhs_sp))) => one_side_err(rhs_sp, rhs_ty, lhs),
@ -651,7 +651,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
)
});
let pre = if in_match { "in the same arm, " } else { "" };
err.note(&format!("{}a binding must have the same type in all alternatives", pre));
err.note(format!("{}a binding must have the same type in all alternatives", pre));
self.suggest_adding_missing_ref_or_removing_ref(
&mut err,
span,
@ -958,11 +958,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) {
let pat_span = pat.span;
if let Some(span) = self.tcx.hir().res_span(pat_res) {
e.span_label(span, &format!("{} defined here", res.descr()));
e.span_label(span, format!("{} defined here", res.descr()));
if let [hir::PathSegment { ident, .. }] = &*segments {
e.span_label(
pat_span,
&format!(
format!(
"`{}` is interpreted as {} {}, not a new binding",
ident,
res.article(),
@ -1158,7 +1158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
err.span_label(
last_subpat_span,
&format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
format!("expected {} field{}, found {}", fields.len(), fields_ending, subpats.len()),
);
if self.tcx.sess.source_map().is_multiline(qpath.span().between(last_subpat_span)) {
err.span_label(qpath.span(), "");
@ -1171,7 +1171,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
err.span_label(
last_field_def_span,
&format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
format!("{} has {} field{}", res.descr(), fields.len(), fields_ending),
);
// Identify the case `Some(x, y)` where the expected type is e.g. `Option<(T, U)>`.
@ -1641,7 +1641,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let unmentioned_field = unmentioned_fields[0].1.name;
err.span_suggestion_short(
pat_field.ident.span,
&format!(
format!(
"`{}` has a field named `{}`",
tcx.def_path_str(variant.def_id),
unmentioned_field
@ -1831,7 +1831,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lint.help(
"ensure that all fields are mentioned explicitly by adding the suggested fields",
);
lint.note(&format!(
lint.note(format!(
"the pattern is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
ty,
));
@ -1895,7 +1895,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
err.span_suggestion(
sp,
&format!(
format!(
"include the missing field{} in the pattern{}",
pluralize!(len),
if have_inaccessible_fields { " and ignore the inaccessible fields" } else { "" }
@ -1922,7 +1922,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
err.span_suggestion(
sp,
&format!(
format!(
"if you don't care about {these} missing field{s}, you can explicitly ignore {them}",
these = pluralize!("this", len),
s = pluralize!(len),

View File

@ -73,16 +73,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let ty = self.resolve_vars_if_possible(ty);
let mut err = self.tcx.sess.struct_span_err(
span,
&format!("negative integers cannot be used to index on a `{ty}`"),
format!("negative integers cannot be used to index on a `{ty}`"),
);
err.span_label(span, &format!("cannot use a negative integer for indexing on `{ty}`"));
err.span_label(span, format!("cannot use a negative integer for indexing on `{ty}`"));
if let (hir::ExprKind::Path(..), Ok(snippet)) =
(&base_expr.kind, self.tcx.sess.source_map().span_to_snippet(base_expr.span))
{
// `foo[-1]` to `foo[foo.len() - 1]`
err.span_suggestion_verbose(
span.shrink_to_lo(),
&format!(
format!(
"to access an element starting from the end of the `{ty}`, compute the index",
),
format!("{snippet}.len() "),

View File

@ -713,7 +713,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.tcx.sess.delay_span_bug(
closure_span,
&format!(
format!(
"two identical projections: ({:?}, {:?})",
capture1.place.projections, capture2.place.projections
),
@ -863,7 +863,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
lint.span_suggestion(
closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
&diagnostic_msg,
diagnostic_msg,
format!("\n{indent}{migration_string};"),
Applicability::MachineApplicable,
);
@ -874,7 +874,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// directly after the `{`.
lint.span_suggestion(
closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
&diagnostic_msg,
diagnostic_msg,
format!(" {migration_string};"),
Applicability::MachineApplicable,
);
@ -882,7 +882,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// This is a closure without braces around the body.
// We add braces to add the `let` before the body.
lint.multipart_suggestion(
&diagnostic_msg,
diagnostic_msg,
vec![
(closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
(closure_body_span.shrink_to_hi(), " }".to_string()),
@ -893,7 +893,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
lint.span_suggestion(
closure_span,
&diagnostic_msg,
diagnostic_msg,
migration_string,
Applicability::HasPlaceholders
);
@ -1519,7 +1519,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let span =
capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir().span(e));
diag.span_note(span, &output_str);
diag.span_note(span, output_str);
}
diag.emit();
}
@ -1560,13 +1560,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
multi_span.push_span_label(path_span, path_label);
multi_span.push_span_label(capture_kind_span, capture_kind_label);
diag.span_note(multi_span, &output_str);
diag.span_note(multi_span, output_str);
} else {
let span = capture_info
.path_expr_id
.map_or(closure_span, |e| self.tcx.hir().span(e));
diag.span_note(span, &output_str);
diag.span_note(span, output_str);
};
}
}

View File

@ -227,7 +227,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
// When encountering `return [0][0]` outside of a `fn` body we can encounter a base
// that isn't in the type table. We assume more relevant errors have already been
// emitted, so we delay an ICE if none have. (#64638)
self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base));
self.tcx().sess.delay_span_bug(e.span, format!("bad base: `{:?}`", base));
}
if let Some(ty::Ref(_, base_ty, _)) = base_ty {
let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| {
@ -491,7 +491,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
let err = self
.tcx()
.sess
.struct_span_err(span, &format!("user substs: {:?}", user_substs));
.struct_span_err(span, format!("user substs: {:?}", user_substs));
err.buffer(&mut errors_buffer);
}
}

View File

@ -205,7 +205,7 @@ impl CanonicalizeMode for CanonicalizeQueryResponse {
// `delay_span_bug` to allow type error over an ICE.
canonicalizer.tcx.sess.delay_span_bug(
rustc_span::DUMMY_SP,
&format!("unexpected region in query response: `{:?}`", r),
format!("unexpected region in query response: `{:?}`", r),
);
r
}

Some files were not shown because too many files have changed in this diff Show More