1
Fork 0

Rollup merge of #114075 - matthiaskrgr:fmt_args_rustc_3, r=wesleywiser

inline format!() args from rustc_codegen_llvm to the end (4)

r? `@WaffleLapkin`
This commit is contained in:
Matthias Krüger 2023-07-27 06:04:13 +02:00 committed by GitHub
commit fa21a8c6f8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
94 changed files with 385 additions and 498 deletions

View file

@ -37,8 +37,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
desc, desc,
); );
err.span_label(borrow_span, format!("{} is borrowed here", borrow_desc)); err.span_label(borrow_span, format!("{borrow_desc} is borrowed here"));
err.span_label(span, format!("use of borrowed {}", borrow_desc)); err.span_label(span, format!("use of borrowed {borrow_desc}"));
err err
} }
@ -51,8 +51,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
old_opt_via: &str, old_opt_via: &str,
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
let via = let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
|msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self,
new_loan_span, new_loan_span,
@ -143,9 +142,9 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
); );
err.span_label( err.span_label(
new_loan_span, new_loan_span,
format!("{} construction occurs here{}", container_name, opt_via), format!("{container_name} construction occurs here{opt_via}"),
); );
err.span_label(old_loan_span, format!("borrow occurs here{}", old_opt_via)); err.span_label(old_loan_span, format!("borrow occurs here{old_opt_via}"));
if let Some(previous_end_span) = previous_end_span { if let Some(previous_end_span) = previous_end_span {
err.span_label(previous_end_span, "borrow ends here"); err.span_label(previous_end_span, "borrow ends here");
} }
@ -173,13 +172,10 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
opt_via, opt_via,
kind_new, kind_new,
); );
err.span_label( err.span_label(new_loan_span, format!("{second_borrow_desc}borrow occurs here{opt_via}"));
new_loan_span,
format!("{}borrow occurs here{}", second_borrow_desc, opt_via),
);
err.span_label( err.span_label(
old_loan_span, old_loan_span,
format!("{} construction occurs here{}", container_name, old_opt_via), format!("{container_name} construction occurs here{old_opt_via}"),
); );
if let Some(previous_end_span) = previous_end_span { if let Some(previous_end_span) = previous_end_span {
err.span_label(previous_end_span, "borrow from closure ends here"); err.span_label(previous_end_span, "borrow from closure ends here");
@ -199,8 +195,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
msg_old: &str, msg_old: &str,
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'cx, ErrorGuaranteed> { ) -> DiagnosticBuilder<'cx, ErrorGuaranteed> {
let via = let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
|msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {})", msg) };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self,
span, span,
@ -216,22 +211,21 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
if msg_new == "" { if msg_new == "" {
// If `msg_new` is empty, then this isn't a borrow of a union field. // If `msg_new` is empty, then this isn't a borrow of a union field.
err.span_label(span, format!("{} borrow occurs here", kind_new)); err.span_label(span, format!("{kind_new} borrow occurs here"));
err.span_label(old_span, format!("{} borrow occurs here", kind_old)); err.span_label(old_span, format!("{kind_old} borrow occurs here"));
} else { } else {
// If `msg_new` isn't empty, then this a borrow of a union field. // If `msg_new` isn't empty, then this a borrow of a union field.
err.span_label( err.span_label(
span, span,
format!( format!(
"{} borrow of {} -- which overlaps with {} -- occurs here", "{kind_new} borrow of {msg_new} -- which overlaps with {msg_old} -- occurs here",
kind_new, msg_new, msg_old,
), ),
); );
err.span_label(old_span, format!("{} borrow occurs here{}", kind_old, via(msg_old))); err.span_label(old_span, format!("{} borrow occurs here{}", kind_old, via(msg_old)));
} }
if let Some(old_load_end_span) = old_load_end_span { if let Some(old_load_end_span) = old_load_end_span {
err.span_label(old_load_end_span, format!("{} borrow ends here", kind_old)); err.span_label(old_load_end_span, format!("{kind_old} borrow ends here"));
} }
err err
} }
@ -250,8 +244,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
desc, desc,
); );
err.span_label(borrow_span, format!("{} is borrowed here", desc)); err.span_label(borrow_span, format!("{desc} is borrowed here"));
err.span_label(span, format!("{} is assigned to here but it was already borrowed", desc)); err.span_label(span, format!("{desc} is assigned to here but it was already borrowed"));
err err
} }
@ -330,7 +324,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
optional_adverb_for_moved: &str, optional_adverb_for_moved: &str,
moved_path: Option<String>, moved_path: Option<String>,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
let moved_path = moved_path.map(|mp| format!(": `{}`", mp)).unwrap_or_default(); let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default();
struct_span_err!( struct_span_err!(
self, self,
@ -369,8 +363,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
immutable_place, immutable_place,
immutable_section, immutable_section,
); );
err.span_label(mutate_span, format!("cannot {}", action)); err.span_label(mutate_span, format!("cannot {action}"));
err.span_label(immutable_span, format!("value is immutable in {}", immutable_section)); err.span_label(immutable_span, format!("value is immutable in {immutable_section}"));
err err
} }
@ -428,7 +422,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
err.span_label( err.span_label(
span, span,
format!("{}s a {} data owned by the current function", return_kind, reference_desc), format!("{return_kind}s a {reference_desc} data owned by the current function"),
); );
err err
@ -449,8 +443,8 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
"{closure_kind} may outlive the current {scope}, but it borrows {borrowed_path}, \ "{closure_kind} may outlive the current {scope}, but it borrows {borrowed_path}, \
which is owned by the current {scope}", which is owned by the current {scope}",
); );
err.span_label(capture_span, format!("{} is borrowed here", borrowed_path)) err.span_label(capture_span, format!("{borrowed_path} is borrowed here"))
.span_label(closure_span, format!("may outlive borrowed value {}", borrowed_path)); .span_label(closure_span, format!("may outlive borrowed value {borrowed_path}"));
err err
} }

View file

@ -360,7 +360,7 @@ impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, 'tcx> {
return; return;
} }
let index = self.borrow_set.get_index_of(&location).unwrap_or_else(|| { let index = self.borrow_set.get_index_of(&location).unwrap_or_else(|| {
panic!("could not find BorrowIndex for location {:?}", location); panic!("could not find BorrowIndex for location {location:?}");
}); });
trans.gen(index); trans.gen(index);

View file

@ -653,7 +653,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_suggestion_verbose( err.span_suggestion_verbose(
sugg_span.shrink_to_hi(), sugg_span.shrink_to_hi(),
"consider assigning a value", "consider assigning a value",
format!(" = {}", assign_value), format!(" = {assign_value}"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -738,7 +738,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// Try to find predicates on *generic params* that would allow copying `ty` // Try to find predicates on *generic params* that would allow copying `ty`
let suggestion = let suggestion =
if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {
format!(": {}.clone()", symbol) format!(": {symbol}.clone()")
} else { } else {
".clone()".to_owned() ".clone()".to_owned()
}; };
@ -1162,8 +1162,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if union_type_name != "" { if union_type_name != "" {
err.note(format!( err.note(format!(
"{} is a field of the union `{}`, so it overlaps the field {}", "{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
msg_place, union_type_name, msg_borrow,
)); ));
} }
@ -1353,8 +1352,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let Some(trait_did) = tcx.trait_of_item(def_id) && let Some(trait_did) = tcx.trait_of_item(def_id) &&
tcx.is_diagnostic_item(sym::Iterator, trait_did) { tcx.is_diagnostic_item(sym::Iterator, trait_did) {
err.note(format!( err.note(format!(
"a for loop advances the iterator for you, the result is stored in `{}`.", "a for loop advances the iterator for you, the result is stored in `{loop_bind}`."
loop_bind
)); ));
err.help("if you want to call `next` on a iterator within the loop, consider using `while let`."); err.help("if you want to call `next` on a iterator within the loop, consider using `while let`.");
} }
@ -1825,7 +1823,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}, },
ConstraintCategory::CallArgument(None), ConstraintCategory::CallArgument(None),
var_or_use_span, var_or_use_span,
&format!("`{}`", name), &format!("`{name}`"),
"block", "block",
), ),
( (
@ -1847,7 +1845,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
region_name, region_name,
category, category,
span, span,
&format!("`{}`", name), &format!("`{name}`"),
"function", "function",
), ),
( (
@ -1921,14 +1919,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
} }
let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{}`", name)); let mut err = self.path_does_not_live_long_enough(borrow_span, &format!("`{name}`"));
if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) { if let Some(annotation) = self.annotate_argument_and_return_for_borrow(borrow) {
let region_name = annotation.emit(self, &mut err); let region_name = annotation.emit(self, &mut err);
err.span_label( err.span_label(
borrow_span, borrow_span,
format!("`{}` would have to be valid for `{}`...", name, region_name), format!("`{name}` would have to be valid for `{region_name}`..."),
); );
err.span_label( err.span_label(
@ -1939,7 +1937,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
self.infcx self.infcx
.tcx .tcx
.opt_item_name(self.mir_def_id().to_def_id()) .opt_item_name(self.mir_def_id().to_def_id())
.map(|name| format!("function `{}`", name)) .map(|name| format!("function `{name}`"))
.unwrap_or_else(|| { .unwrap_or_else(|| {
match &self.infcx.tcx.def_kind(self.mir_def_id()) { match &self.infcx.tcx.def_kind(self.mir_def_id()) {
DefKind::Closure => "enclosing closure", DefKind::Closure => "enclosing closure",
@ -1974,7 +1972,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
} else { } else {
err.span_label(borrow_span, "borrowed value does not live long enough"); err.span_label(borrow_span, "borrowed value does not live long enough");
err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name)); err.span_label(drop_span, format!("`{name}` dropped here while still borrowed"));
borrow_spans.args_subdiag(&mut err, |args_span| { borrow_spans.args_subdiag(&mut err, |args_span| {
crate::session_diagnostics::CaptureArgLabel::Capture { crate::session_diagnostics::CaptureArgLabel::Capture {
@ -2018,22 +2016,17 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let mut err = self.cannot_borrow_across_destructor(borrow_span); let mut err = self.cannot_borrow_across_destructor(borrow_span);
let what_was_dropped = match self.describe_place(place.as_ref()) { let what_was_dropped = match self.describe_place(place.as_ref()) {
Some(name) => format!("`{}`", name), Some(name) => format!("`{name}`"),
None => String::from("temporary value"), None => String::from("temporary value"),
}; };
let label = match self.describe_place(borrow.borrowed_place.as_ref()) { let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
Some(borrowed) => format!( Some(borrowed) => format!(
"here, drop of {D} needs exclusive access to `{B}`, \ "here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
because the type `{T}` implements the `Drop` trait", because the type `{dropped_ty}` implements the `Drop` trait"
D = what_was_dropped,
T = dropped_ty,
B = borrowed
), ),
None => format!( None => format!(
"here is drop of {D}; whose type `{T}` implements the `Drop` trait", "here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
D = what_was_dropped,
T = dropped_ty
), ),
}; };
err.span_label(drop_span, label); err.span_label(drop_span, label);
@ -2245,10 +2238,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} else { } else {
"local data " "local data "
}; };
( (format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here"))
format!("{}`{}`", local_kind, place_desc),
format!("`{}` is borrowed here", place_desc),
)
} else { } else {
let root_place = let root_place =
self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap(); self.prefixes(borrow.borrowed_place.as_ref(), PrefixSet::All).last().unwrap();
@ -2350,9 +2340,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_suggestion_verbose( err.span_suggestion_verbose(
sugg_span, sugg_span,
format!( format!(
"to force the {} to take ownership of {} (and any \ "to force the {kind} to take ownership of {captured_var} (and any \
other referenced variables), use the `move` keyword", other referenced variables), use the `move` keyword"
kind, captured_var
), ),
suggestion, suggestion,
Applicability::MachineApplicable, Applicability::MachineApplicable,
@ -2360,7 +2349,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
match category { match category {
ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => { ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
let msg = format!("{} is returned here", kind); let msg = format!("{kind} is returned here");
err.span_note(constraint_span, msg); err.span_note(constraint_span, msg);
} }
ConstraintCategory::CallArgument(_) => { ConstraintCategory::CallArgument(_) => {
@ -2402,21 +2391,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_label( err.span_label(
upvar_span, upvar_span,
format!("`{}` declared here, outside of the {} body", upvar_name, escapes_from), format!("`{upvar_name}` declared here, outside of the {escapes_from} body"),
); );
err.span_label(borrow_span, format!("borrow is only valid in the {} body", escapes_from)); err.span_label(borrow_span, format!("borrow is only valid in the {escapes_from} body"));
if let Some(name) = name { if let Some(name) = name {
err.span_label( err.span_label(
escape_span, escape_span,
format!("reference to `{}` escapes the {} body here", name, escapes_from), format!("reference to `{name}` escapes the {escapes_from} body here"),
); );
} else { } else {
err.span_label( err.span_label(escape_span, format!("reference escapes the {escapes_from} body here"));
escape_span,
format!("reference escapes the {} body here", escapes_from),
);
} }
err err
@ -2697,10 +2683,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}); });
if let Some(Ok(instance)) = deref_target { if let Some(Ok(instance)) = deref_target {
let deref_target_ty = instance.ty(tcx, self.param_env); 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}`"));
"borrow occurs due to deref coercion to `{}`",
deref_target_ty
));
err.span_note(tcx.def_span(instance.def_id()), "deref defined here"); err.span_note(tcx.def_span(instance.def_id()), "deref defined here");
} }
} }
@ -2756,7 +2739,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
"cannot assign twice to immutable variable" "cannot assign twice to immutable variable"
}; };
if span != assigned_span && !from_arg { if span != assigned_span && !from_arg {
err.span_label(assigned_span, format!("first assignment to {}", place_description)); err.span_label(assigned_span, format!("first assignment to {place_description}"));
} }
if let Some(decl) = local_decl if let Some(decl) = local_decl
&& let Some(name) = local_name && let Some(name) = local_name
@ -2765,7 +2748,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_suggestion( err.span_suggestion(
decl.source_info.span, decl.source_info.span,
"consider making this binding mutable", "consider making this binding mutable",
format!("mut {}", name), format!("mut {name}"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
@ -3226,7 +3209,7 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
return_span, return_span,
} => { } => {
let argument_ty_name = cx.get_name_for_ty(argument_ty, 0); let argument_ty_name = cx.get_name_for_ty(argument_ty, 0);
diag.span_label(argument_span, format!("has type `{}`", argument_ty_name)); diag.span_label(argument_span, format!("has type `{argument_ty_name}`"));
let return_ty_name = cx.get_name_for_ty(return_ty, 0); let return_ty_name = cx.get_name_for_ty(return_ty, 0);
let types_equal = return_ty_name == argument_ty_name; let types_equal = return_ty_name == argument_ty_name;
@ -3253,15 +3236,14 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
// Region of return type and arguments checked to be the same earlier. // Region of return type and arguments checked to be the same earlier.
let region_name = cx.get_region_name_for_ty(*return_ty, 0); let region_name = cx.get_region_name_for_ty(*return_ty, 0);
for (_, argument_span) in arguments { for (_, argument_span) in arguments {
diag.span_label(*argument_span, format!("has lifetime `{}`", region_name)); diag.span_label(*argument_span, format!("has lifetime `{region_name}`"));
} }
diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,)); 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 \ "use data from the highlighted arguments which match the `{region_name}` lifetime of \
the return type", the return type",
region_name,
)); ));
region_name region_name

View file

@ -202,7 +202,7 @@ trait FactCell {
impl<A: Debug> FactCell for A { impl<A: Debug> FactCell for A {
default fn to_string(&self, _location_table: &LocationTable) -> String { default fn to_string(&self, _location_table: &LocationTable) -> String {
format!("{:?}", self) format!("{self:?}")
} }
} }

View file

@ -1817,8 +1817,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} }
ProjectionElem::Subslice { .. } => { ProjectionElem::Subslice { .. } => {
panic!("we don't allow assignments to subslices, location: {:?}", panic!("we don't allow assignments to subslices, location: {location:?}");
location);
} }
ProjectionElem::Field(..) => { ProjectionElem::Field(..) => {
@ -2017,8 +2016,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
self.infcx.tcx.sess.delay_span_bug( self.infcx.tcx.sess.delay_span_bug(
span, span,
format!( format!(
"Accessing `{:?}` with the kind `{:?}` shouldn't be possible", "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
place, kind,
), ),
); );
} }

View file

@ -347,7 +347,7 @@ pub(super) fn dump_mir_results<'tcx>(
for_each_region_constraint( for_each_region_constraint(
infcx.tcx, infcx.tcx,
closure_region_requirements, closure_region_requirements,
&mut |msg| writeln!(out, "| {}", msg), &mut |msg| writeln!(out, "| {msg}"),
)?; )?;
writeln!(out, "|")?; writeln!(out, "|")?;
} }
@ -426,7 +426,7 @@ pub(super) fn dump_annotation<'tcx>(
}; };
if !opaque_type_values.is_empty() { 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); errors.buffer_non_error_diag(err);
@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>(
) -> io::Result<()> { ) -> io::Result<()> {
for req in &closure_region_requirements.outlives_requirements { for req in &closure_region_requirements.outlives_requirements {
let subject = match req.subject { let subject = match req.subject {
ClosureOutlivesSubject::Region(subject) => format!("{:?}", subject), ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
ClosureOutlivesSubject::Ty(ty) => { ClosureOutlivesSubject::Ty(ty) => {
format!("{:?}", ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))) format!("{:?}", ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid)))
} }

View file

@ -52,7 +52,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
writeln!(out, "|")?; writeln!(out, "|")?;
writeln!(out, "| Inference Constraints")?; writeln!(out, "| Inference Constraints")?;
self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {}", msg))?; self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {msg}"))?;
Ok(()) Ok(())
} }
@ -69,7 +69,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
for region in self.definitions.indices() { for region in self.definitions.indices() {
let value = self.liveness_constraints.region_value_str(region); let value = self.liveness_constraints.region_value_str(region);
if value != "{}" { if value != "{}" {
with_msg(&format!("{:?} live at {}", region, value))?; with_msg(&format!("{region:?} live at {value}"))?;
} }
} }
@ -81,12 +81,9 @@ impl<'tcx> RegionInferenceContext<'tcx> {
Locations::All(span) => { Locations::All(span) => {
("All", tcx.sess.source_map().span_to_embeddable_string(*span)) ("All", tcx.sess.source_map().span_to_embeddable_string(*span))
} }
Locations::Single(loc) => ("Single", format!("{:?}", loc)), Locations::Single(loc) => ("Single", format!("{loc:?}")),
}; };
with_msg(&format!( with_msg(&format!("{sup:?}: {sub:?} due to {category:?} at {name}({arg}) ({span:?}"))?;
"{:?}: {:?} due to {:?} at {}({}) ({:?}",
sup, sub, category, name, arg, span
))?;
} }
Ok(()) Ok(())

View file

@ -49,7 +49,7 @@ impl<'a, 'this, 'tcx> dot::Labeller<'this> for RawConstraints<'a, 'tcx> {
Some(dot::LabelText::LabelStr(Cow::Borrowed("box"))) Some(dot::LabelText::LabelStr(Cow::Borrowed("box")))
} }
fn node_label(&'this self, n: &RegionVid) -> dot::LabelText<'this> { fn node_label(&'this self, n: &RegionVid) -> dot::LabelText<'this> {
dot::LabelText::LabelStr(format!("{:?}", n).into()) dot::LabelText::LabelStr(format!("{n:?}").into())
} }
fn edge_label(&'this self, e: &OutlivesConstraint<'tcx>) -> dot::LabelText<'this> { fn edge_label(&'this self, e: &OutlivesConstraint<'tcx>) -> dot::LabelText<'this> {
dot::LabelText::LabelStr(format!("{:?}", e.locations).into()) dot::LabelText::LabelStr(format!("{:?}", e.locations).into())
@ -100,7 +100,7 @@ impl<'a, 'this, 'tcx> dot::Labeller<'this> for SccConstraints<'a, 'tcx> {
} }
fn node_label(&'this self, n: &ConstraintSccIndex) -> dot::LabelText<'this> { fn node_label(&'this self, n: &ConstraintSccIndex) -> dot::LabelText<'this> {
let nodes = &self.nodes_per_scc[*n]; let nodes = &self.nodes_per_scc[*n];
dot::LabelText::LabelStr(format!("{:?} = {:?}", n, nodes).into()) dot::LabelText::LabelStr(format!("{n:?} = {nodes:?}").into())
} }
} }

View file

@ -259,7 +259,7 @@ fn sccs_info<'cx, 'tcx>(
let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string(); let mut reg_vars_to_origins_str = "region variables to origins:\n".to_string();
for (reg_var, origin) in var_to_origin_sorted.into_iter() { for (reg_var, origin) in var_to_origin_sorted.into_iter() {
reg_vars_to_origins_str.push_str(&format!("{:?}: {:?}\n", reg_var, origin)); reg_vars_to_origins_str.push_str(&format!("{reg_var:?}: {origin:?}\n"));
} }
debug!("{}", reg_vars_to_origins_str); debug!("{}", reg_vars_to_origins_str);

View file

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

View file

@ -470,7 +470,7 @@ fn region_value_str(elements: impl IntoIterator<Item = RegionElement>) -> String
} }
push_sep(&mut result); push_sep(&mut result);
result.push_str(&format!("{:?}", fr)); result.push_str(&format!("{fr:?}"));
} }
RegionElement::PlaceholderRegion(placeholder) => { RegionElement::PlaceholderRegion(placeholder) => {
@ -481,7 +481,7 @@ fn region_value_str(elements: impl IntoIterator<Item = RegionElement>) -> String
} }
push_sep(&mut result); push_sep(&mut result);
result.push_str(&format!("{:?}", placeholder)); result.push_str(&format!("{placeholder:?}"));
} }
} }
} }
@ -497,7 +497,7 @@ fn region_value_str(elements: impl IntoIterator<Item = RegionElement>) -> String
fn push_location_range(str: &mut String, location1: Location, location2: Location) { fn push_location_range(str: &mut String, location1: Location, location2: Location) {
if location1 == location2 { if location1 == location2 {
str.push_str(&format!("{:?}", location1)); str.push_str(&format!("{location1:?}"));
} else { } else {
assert_eq!(location1.block, location2.block); assert_eq!(location1.block, location2.block);
str.push_str(&format!( str.push_str(&format!(

View file

@ -52,7 +52,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
trace!( trace!(
"eval_body_using_ecx: pushing stack frame for global: {}{}", "eval_body_using_ecx: pushing stack frame for global: {}{}",
with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())), with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())),
cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p)) cid.promoted.map_or_else(String::new, |p| format!("::promoted[{p:?}]"))
); );
ecx.push_stack_frame( ecx.push_stack_frame(

View file

@ -55,7 +55,7 @@ fn slice_branches<'tcx>(
place: &MPlaceTy<'tcx>, place: &MPlaceTy<'tcx>,
num_nodes: &mut usize, num_nodes: &mut usize,
) -> ValTreeCreationResult<'tcx> { ) -> ValTreeCreationResult<'tcx> {
let n = place.len(ecx).unwrap_or_else(|_| panic!("expected to use len of place {:?}", place)); let n = place.len(ecx).unwrap_or_else(|_| panic!("expected to use len of place {place:?}"));
let mut elems = Vec::with_capacity(n as usize); let mut elems = Vec::with_capacity(n as usize);
for i in 0..n { for i in 0..n {

View file

@ -1016,7 +1016,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
match self.place { match self.place {
Place::Local { frame, local, offset } => { Place::Local { frame, local, offset } => {
let mut allocs = Vec::new(); let mut allocs = Vec::new();
write!(fmt, "{:?}", local)?; write!(fmt, "{local:?}")?;
if let Some(offset) = offset { if let Some(offset) = offset {
write!(fmt, "+{:#x}", offset.bytes())?; write!(fmt, "+{:#x}", offset.bytes())?;
} }
@ -1035,7 +1035,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
fmt, fmt,
" by {} ref {:?}:", " by {} ref {:?}:",
match mplace.meta { match mplace.meta {
MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta), MemPlaceMeta::Meta(meta) => format!(" meta({meta:?})"),
MemPlaceMeta::None => String::new(), MemPlaceMeta::None => String::new(),
}, },
mplace.ptr, mplace.ptr,
@ -1043,13 +1043,13 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id)); allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id));
} }
LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => { LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
write!(fmt, " {:?}", val)?; write!(fmt, " {val:?}")?;
if let Scalar::Ptr(ptr, _size) = val { if let Scalar::Ptr(ptr, _size) = val {
allocs.push(ptr.provenance.get_alloc_id()); allocs.push(ptr.provenance.get_alloc_id());
} }
} }
LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => { LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
write!(fmt, " ({:?}, {:?})", val1, val2)?; write!(fmt, " ({val1:?}, {val2:?})")?;
if let Scalar::Ptr(ptr, _size) = val1 { if let Scalar::Ptr(ptr, _size) = val1 {
allocs.push(ptr.provenance.get_alloc_id()); allocs.push(ptr.provenance.get_alloc_id());
} }
@ -1065,7 +1065,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
Some(alloc_id) => { Some(alloc_id) => {
write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id)) write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))
} }
ptr => write!(fmt, " integral by ref: {:?}", ptr), ptr => write!(fmt, " integral by ref: {ptr:?}"),
}, },
} }
} }

View file

@ -394,17 +394,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
// For *all* intrinsics we first check `is_uninhabited` to give a more specific // For *all* intrinsics we first check `is_uninhabited` to give a more specific
// error message. // error message.
_ if layout.abi.is_uninhabited() => format!( _ if layout.abi.is_uninhabited() => format!(
"aborted execution: attempted to instantiate uninhabited type `{}`", "aborted execution: attempted to instantiate uninhabited type `{ty}`"
ty
), ),
ValidityRequirement::Inhabited => bug!("handled earlier"), ValidityRequirement::Inhabited => bug!("handled earlier"),
ValidityRequirement::Zero => format!( ValidityRequirement::Zero => format!(
"aborted execution: attempted to zero-initialize type `{}`, which is invalid", "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
ty
), ),
ValidityRequirement::UninitMitigated0x01Fill => format!( ValidityRequirement::UninitMitigated0x01Fill => format!(
"aborted execution: attempted to leave type `{}` uninitialized, which is invalid", "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
ty
), ),
ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"), ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"),
}; };
@ -420,9 +417,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
assert_eq!(input_len, dest_len, "Return vector length must match input length"); assert_eq!(input_len, dest_len, "Return vector length must match input length");
assert!( assert!(
index < dest_len, index < dest_len,
"Index `{}` must be in bounds of vector with length {}", "Index `{index}` must be in bounds of vector with length {dest_len}"
index,
dest_len
); );
for i in 0..dest_len { for i in 0..dest_len {
@ -440,9 +435,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
let (input, input_len) = self.operand_to_simd(&args[0])?; let (input, input_len) = self.operand_to_simd(&args[0])?;
assert!( assert!(
index < input_len, index < input_len,
"index `{}` must be in bounds of vector with length {}", "index `{index}` must be in bounds of vector with length {input_len}"
index,
input_len
); );
self.copy_op( self.copy_op(
&self.project_index(&input, index)?, &self.project_index(&input, index)?,

View file

@ -53,7 +53,7 @@ impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
match self { match self {
MemoryKind::Stack => write!(f, "stack variable"), MemoryKind::Stack => write!(f, "stack variable"),
MemoryKind::CallerLocation => write!(f, "caller location"), MemoryKind::CallerLocation => write!(f, "caller location"),
MemoryKind::Machine(m) => write!(f, "{}", m), MemoryKind::Machine(m) => write!(f, "{m}"),
} }
} }
} }
@ -907,7 +907,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a,
match self.ecx.memory.alloc_map.get(id) { match self.ecx.memory.alloc_map.get(id) {
Some((kind, alloc)) => { Some((kind, alloc)) => {
// normal alloc // normal alloc
write!(fmt, " ({}, ", kind)?; write!(fmt, " ({kind}, ")?;
write_allocation_track_relocs( write_allocation_track_relocs(
&mut *fmt, &mut *fmt,
*self.ecx.tcx, *self.ecx.tcx,

View file

@ -24,8 +24,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
debug_assert_eq!( debug_assert_eq!(
Ty::new_tup(self.tcx.tcx, &[ty, self.tcx.types.bool]), Ty::new_tup(self.tcx.tcx, &[ty, self.tcx.types.bool]),
dest.layout.ty, dest.layout.ty,
"type mismatch for result of {:?}", "type mismatch for result of {op:?}",
op,
); );
// Write the result to `dest`. // Write the result to `dest`.
if let Abi::ScalarPair(..) = dest.layout.abi { if let Abi::ScalarPair(..) = dest.layout.abi {
@ -56,7 +55,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
dest: &PlaceTy<'tcx, M::Provenance>, dest: &PlaceTy<'tcx, M::Provenance>,
) -> InterpResult<'tcx> { ) -> InterpResult<'tcx> {
let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?; let (val, _overflowed, ty) = self.overflowing_binary_op(op, left, right)?;
assert_eq!(ty, dest.layout.ty, "type mismatch for result of {:?}", op); assert_eq!(ty, dest.layout.ty, "type mismatch for result of {op:?}");
self.write_scalar(val, dest) self.write_scalar(val, dest)
} }
} }

View file

@ -178,7 +178,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
// The operand always has the same type as the result. // The operand always has the same type as the result.
let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?; let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?;
let val = self.unary_op(un_op, &val)?; let val = self.unary_op(un_op, &val)?;
assert_eq!(val.layout, dest.layout, "layout mismatch for result of {:?}", un_op); assert_eq!(val.layout, dest.layout, "layout mismatch for result of {un_op:?}");
self.write_immediate(*val, &dest)?; self.write_immediate(*val, &dest)?;
} }

View file

@ -164,14 +164,14 @@ fn write_path(out: &mut String, path: &[PathElem]) {
for elem in path.iter() { for elem in path.iter() {
match elem { match elem {
Field(name) => write!(out, ".{}", name), Field(name) => write!(out, ".{name}"),
EnumTag => write!(out, ".<enum-tag>"), EnumTag => write!(out, ".<enum-tag>"),
Variant(name) => write!(out, ".<enum-variant({})>", name), Variant(name) => write!(out, ".<enum-variant({name})>"),
GeneratorTag => write!(out, ".<generator-tag>"), GeneratorTag => write!(out, ".<generator-tag>"),
GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()), GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
CapturedVar(name) => write!(out, ".<captured-var({})>", name), CapturedVar(name) => write!(out, ".<captured-var({name})>"),
TupleElem(idx) => write!(out, ".{}", idx), TupleElem(idx) => write!(out, ".{idx}"),
ArrayElem(idx) => write!(out, "[{}]", idx), ArrayElem(idx) => write!(out, "[{idx}]"),
// `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and // `.<deref>` does not match Rust syntax, but it is more readable for long paths -- and
// some of the other items here also are not Rust syntax. Actually we can't // some of the other items here also are not Rust syntax. Actually we can't
// even use the usual syntax because we are just showing the projections, // even use the usual syntax because we are just showing the projections,

View file

@ -310,8 +310,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
if let Some(feature) = feature && ccx.tcx.sess.is_nightly_build() { 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", "add `#![feature({feature})]` to the crate attributes to enable",
feature,
)); ));
} }
@ -346,10 +345,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
err.help("const-stable functions can only call other const-stable functions"); err.help("const-stable functions can only call other const-stable functions");
} else if ccx.tcx.sess.is_nightly_build() { } else if ccx.tcx.sess.is_nightly_build() {
if let Some(feature) = feature { if let Some(feature) = feature {
err.help(format!( err.help(format!("add `#![feature({feature})]` to the crate attributes to enable"));
"add `#![feature({})]` to the crate attributes to enable",
feature
));
} }
} }

View file

@ -149,7 +149,7 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> {
} }
} }
} else { } else {
self.fail(location, format!("encountered jump to invalid basic block {:?}", bb)) self.fail(location, format!("encountered jump to invalid basic block {bb:?}"))
} }
} }
@ -222,8 +222,7 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> {
self.fail( self.fail(
Location { block: bb, statement_index: 0 }, Location { block: bb, statement_index: 0 },
format!( format!(
"Cleanup control flow violation: Cycle involving edge {:?} -> {:?}", "Cleanup control flow violation: Cycle involving edge {bb:?} -> {parent:?}",
bb, parent,
), ),
); );
break; break;
@ -257,7 +256,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
if self.body.local_decls.get(local).is_none() { if self.body.local_decls.get(local).is_none() {
self.fail( self.fail(
location, location,
format!("local {:?} has no corresponding declaration in `body.local_decls`", local), format!("local {local:?} has no corresponding declaration in `body.local_decls`"),
); );
} }
@ -272,7 +271,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
self.storage_liveness.seek_after_primary_effect(location); self.storage_liveness.seek_after_primary_effect(location);
let locals_with_storage = self.storage_liveness.get(); let locals_with_storage = self.storage_liveness.get();
if !locals_with_storage.contains(local) { if !locals_with_storage.contains(local) {
self.fail(location, format!("use of local {:?}, which has no storage here", local)); self.fail(location, format!("use of local {local:?}, which has no storage here"));
} }
} }
} }
@ -323,7 +322,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
// DropsLowered`. However, this causes ICEs with generation of drop shims, which // DropsLowered`. However, this causes ICEs with generation of drop shims, which
// seem to fail to set their `MirPhase` correctly. // seem to fail to set their `MirPhase` correctly.
if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) { if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) {
self.fail(location, format!("explicit `{:?}` is forbidden", kind)); self.fail(location, format!("explicit `{kind:?}` is forbidden"));
} }
} }
StatementKind::StorageLive(local) => { StatementKind::StorageLive(local) => {
@ -556,7 +555,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let ty = place.ty(&self.body.local_decls, self.tcx).ty; let ty = place.ty(&self.body.local_decls, self.tcx).ty;
if !ty.is_copy_modulo_regions(self.tcx, self.param_env) { if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty)); self.fail(location, format!("`Operand::Copy` with non-`Copy` type {ty}"));
} }
} }
} }
@ -575,7 +574,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
ProjectionElem::Index(index) => { ProjectionElem::Index(index) => {
let index_ty = self.body.local_decls[index].ty; let index_ty = self.body.local_decls[index].ty;
if index_ty != self.tcx.types.usize { if index_ty != self.tcx.types.usize {
self.fail(location, format!("bad index ({:?} != usize)", index_ty)) self.fail(location, format!("bad index ({index_ty:?} != usize)"))
} }
} }
ProjectionElem::Deref ProjectionElem::Deref
@ -586,22 +585,21 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if base_ty.is_box() { if base_ty.is_box() {
self.fail( self.fail(
location, location,
format!("{:?} dereferenced after ElaborateBoxDerefs", base_ty), format!("{base_ty:?} dereferenced after ElaborateBoxDerefs"),
) )
} }
} }
ProjectionElem::Field(f, ty) => { ProjectionElem::Field(f, ty) => {
let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx); let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx);
let fail_out_of_bounds = |this: &mut Self, location| { let fail_out_of_bounds = |this: &mut Self, location| {
this.fail(location, format!("Out of bounds field {:?} for {:?}", f, parent_ty)); this.fail(location, format!("Out of bounds field {f:?} for {parent_ty:?}"));
}; };
let check_equal = |this: &mut Self, location, f_ty| { let check_equal = |this: &mut Self, location, f_ty| {
if !this.mir_assign_valid_types(ty, f_ty) { if !this.mir_assign_valid_types(ty, f_ty) {
this.fail( this.fail(
location, location,
format!( format!(
"Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is `{:?}`", "Field projection `{place_ref:?}.{f:?}` specified type `{ty:?}`, but actual type is `{f_ty:?}`"
place_ref, f, ty, f_ty
) )
) )
} }
@ -649,7 +647,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let Some(layout) = gen_body.generator_layout() else { let Some(layout) = gen_body.generator_layout() else {
self.fail( self.fail(
location, location,
format!("No generator layout for {:?}", parent_ty), format!("No generator layout for {parent_ty:?}"),
); );
return; return;
}; };
@ -662,7 +660,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let Some(f_ty) = layout.field_tys.get(local) else { let Some(f_ty) = layout.field_tys.get(local) else {
self.fail( self.fail(
location, location,
format!("Out of bounds local {:?} for {:?}", local, parent_ty), format!("Out of bounds local {local:?} for {parent_ty:?}"),
); );
return; return;
}; };
@ -705,7 +703,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if debuginfo.references != 0 && place.projection.last() == Some(&PlaceElem::Deref) { if debuginfo.references != 0 && place.projection.last() == Some(&PlaceElem::Deref) {
self.fail( self.fail(
START_BLOCK.start_location(), START_BLOCK.start_location(),
format!("debuginfo {:?}, has both ref and deref", debuginfo), format!("debuginfo {debuginfo:?}, has both ref and deref"),
); );
} }
} }
@ -715,7 +713,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if ty.is_union() || ty.is_enum() { if ty.is_union() || ty.is_enum() {
self.fail( self.fail(
START_BLOCK.start_location(), START_BLOCK.start_location(),
format!("invalid type {:?} for composite debuginfo", ty), format!("invalid type {ty:?} for composite debuginfo"),
); );
} }
if f.projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) { if f.projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) {
@ -742,7 +740,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
&& cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo) && cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo)
&& place.projection[1..].contains(&ProjectionElem::Deref) && place.projection[1..].contains(&ProjectionElem::Deref)
{ {
self.fail(location, format!("{:?}, has deref at the wrong place", place)); self.fail(location, format!("{place:?}, has deref at the wrong place"));
} }
self.super_place(place, cntxt, location); self.super_place(place, cntxt, location);
@ -802,7 +800,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
Offset => { Offset => {
check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..)); check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
if b != self.tcx.types.isize && b != self.tcx.types.usize { if b != self.tcx.types.isize && b != self.tcx.types.usize {
self.fail(location, format!("Cannot offset by non-isize type {:?}", b)); self.fail(location, format!("Cannot offset by non-isize type {b:?}"));
} }
} }
Eq | Lt | Le | Ne | Ge | Gt => { Eq | Lt | Le | Ne | Ge | Gt => {
@ -867,13 +865,12 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
self.fail( self.fail(
location, location,
format!( format!(
"Cannot perform checked arithmetic on unequal types {:?} and {:?}", "Cannot perform checked arithmetic on unequal types {a:?} and {b:?}"
a, b
), ),
); );
} }
} }
_ => self.fail(location, format!("There is no checked version of {:?}", op)), _ => self.fail(location, format!("There is no checked version of {op:?}")),
} }
} }
Rvalue::UnaryOp(op, operand) => { Rvalue::UnaryOp(op, operand) => {
@ -1078,7 +1075,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if !ty.is_bool() { if !ty.is_bool() {
self.fail( self.fail(
location, location,
format!("`assume` argument must be `bool`, but got: `{}`", ty), format!("`assume` argument must be `bool`, but got: `{ty}`"),
); );
} }
} }
@ -1091,7 +1088,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
} else { } else {
self.fail( self.fail(
location, location,
format!("Expected src to be ptr in copy_nonoverlapping, got: {}", src_ty), format!("Expected src to be ptr in copy_nonoverlapping, got: {src_ty}"),
); );
return; return;
}; };
@ -1101,19 +1098,19 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
} else { } else {
self.fail( self.fail(
location, location,
format!("Expected dst to be ptr in copy_nonoverlapping, got: {}", dst_ty), format!("Expected dst to be ptr in copy_nonoverlapping, got: {dst_ty}"),
); );
return; return;
}; };
// since CopyNonOverlapping is parametrized by 1 type, // since CopyNonOverlapping is parametrized by 1 type,
// we only need to check that they are equal and not keep an extra parameter. // we only need to check that they are equal and not keep an extra parameter.
if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) { if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
self.fail(location, format!("bad arg ({:?} != {:?})", op_src_ty, op_dst_ty)); self.fail(location, format!("bad arg ({op_src_ty:?} != {op_dst_ty:?})"));
} }
let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx); let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
if op_cnt_ty != self.tcx.types.usize { if op_cnt_ty != self.tcx.types.usize {
self.fail(location, format!("bad arg ({:?} != usize)", op_cnt_ty)) self.fail(location, format!("bad arg ({op_cnt_ty:?} != usize)"))
} }
} }
StatementKind::SetDiscriminant { place, .. } => { StatementKind::SetDiscriminant { place, .. } => {
@ -1125,8 +1122,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
self.fail( self.fail(
location, location,
format!( format!(
"`SetDiscriminant` is only allowed on ADTs and generators, not {:?}", "`SetDiscriminant` is only allowed on ADTs and generators, not {pty:?}"
pty
), ),
); );
} }
@ -1141,7 +1137,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
// DropsLowered`. However, this causes ICEs with generation of drop shims, which // DropsLowered`. However, this causes ICEs with generation of drop shims, which
// seem to fail to set their `MirPhase` correctly. // seem to fail to set their `MirPhase` correctly.
if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) { if matches!(kind, RetagKind::Raw | RetagKind::TwoPhase) {
self.fail(location, format!("explicit `{:?}` is forbidden", kind)); self.fail(location, format!("explicit `{kind:?}` is forbidden"));
} }
} }
StatementKind::StorageLive(_) StatementKind::StorageLive(_)
@ -1174,7 +1170,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if Scalar::<()>::try_from_uint(value, size).is_none() { if Scalar::<()>::try_from_uint(value, size).is_none() {
self.fail( self.fail(
location, location,
format!("the value {:#x} is not a proper {:?}", value, switch_ty), format!("the value {value:#x} is not a proper {switch_ty:?}"),
) )
} }
} }
@ -1185,7 +1181,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
ty::FnPtr(..) | ty::FnDef(..) => {} ty::FnPtr(..) | ty::FnDef(..) => {}
_ => self.fail( _ => self.fail(
location, location,
format!("encountered non-callable type {} in `Call` terminator", func_ty), format!("encountered non-callable type {func_ty} in `Call` terminator"),
), ),
} }
} }
@ -1195,8 +1191,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
self.fail( self.fail(
location, location,
format!( format!(
"encountered non-boolean condition of type {} in `Assert` terminator", "encountered non-boolean condition of type {cond_ty} in `Assert` terminator"
cond_ty
), ),
); );
} }

View file

@ -197,7 +197,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
} }
} }
err.span_label(span, format!("associated type `{}` not found", assoc_name)); err.span_label(span, format!("associated type `{assoc_name}` not found"));
err.emit() err.emit()
} }
@ -393,7 +393,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
.into_iter() .into_iter()
.map(|error| error.root_obligation.predicate) .map(|error| error.root_obligation.predicate)
.filter_map(format_pred) .filter_map(format_pred)
.map(|(p, _)| format!("`{}`", p)) .map(|(p, _)| format!("`{p}`"))
.collect(); .collect();
bounds.sort(); bounds.sort();
bounds.dedup(); bounds.dedup();
@ -652,7 +652,7 @@ pub(crate) fn fn_trait_to_string(
} }
.map(|s| { .map(|s| {
// `s.empty()` checks to see if the type is the unit tuple, if so we don't want a comma // `s.empty()` checks to see if the type is the unit tuple, if so we don't want a comma
if parenthesized || s.is_empty() { format!("({})", s) } else { format!("({},)", s) } if parenthesized || s.is_empty() { format!("({s})") } else { format!("({s},)") }
}) })
.ok(), .ok(),
_ => None, _ => None,

View file

@ -81,7 +81,7 @@ fn generic_arg_mismatch_err(
err.span_suggestion( err.span_suggestion(
tcx.def_span(src_def_id), tcx.def_span(src_def_id),
"consider changing this type parameter to a const parameter", "consider changing this type parameter to a const parameter",
format!("const {}: {}", param_name, param_type), format!("const {param_name}: {param_type}"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
}; };
@ -102,7 +102,7 @@ fn generic_arg_mismatch_err(
err.span_suggestion( err.span_suggestion(
arg.span(), arg.span(),
"array type provided where a `usize` was expected, try", "array type provided where a `usize` was expected, try",
format!("{{ {} }}", snippet), format!("{{ {snippet} }}"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -130,7 +130,7 @@ fn generic_arg_mismatch_err(
} else { } else {
(arg.descr(), param.kind.descr()) (arg.descr(), param.kind.descr())
}; };
err.note(format!("{} arguments must be provided before {} arguments", first, last)); err.note(format!("{first} arguments must be provided before {last} arguments"));
if let Some(help) = help { if let Some(help) = help {
err.help(help); err.help(help);
} }
@ -304,7 +304,7 @@ pub fn create_args_for_parent_generic_args<'tcx, 'a>(
"reorder the arguments: {}: `<{}>`", "reorder the arguments: {}: `<{}>`",
param_types_present param_types_present
.into_iter() .into_iter()
.map(|ord| format!("{}s", ord)) .map(|ord| format!("{ord}s"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", then "), .join(", then "),
ordered_params ordered_params

View file

@ -34,9 +34,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let param_name = generics.params.next_type_param_name(None); let param_name = generics.params.next_type_param_name(None);
let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() { let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
(span, format!(", {}: {}", param_name, impl_trait_name)) (span, format!(", {param_name}: {impl_trait_name}"))
} else { } else {
(generics.span, format!("<{}: {}>", param_name, impl_trait_name)) (generics.span, format!("<{param_name}: {impl_trait_name}>"))
}; };
diag.multipart_suggestion( diag.multipart_suggestion(
format!("alternatively use a blanket \ format!("alternatively use a blanket \

View file

@ -1128,7 +1128,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
ty_param_name ty_param_name
) )
}; };
err.span_label(span, format!("ambiguous associated type `{}`", assoc_name)); err.span_label(span, format!("ambiguous associated type `{assoc_name}`"));
let mut where_bounds = vec![]; let mut where_bounds = vec![];
for bound in bounds { for bound in bounds {
@ -1407,7 +1407,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
_ => { _ => {
let reported = if variant_resolution.is_some() { let reported = if variant_resolution.is_some() {
// Variant in type position // Variant in type position
let msg = format!("expected type, found variant `{}`", assoc_ident); 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() { } else if qself_ty.is_enum() {
let mut err = struct_span_err!( let mut err = struct_span_err!(
@ -1438,12 +1438,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
} else { } else {
err.span_label( err.span_label(
assoc_ident.span, assoc_ident.span,
format!("variant not found in `{}`", qself_ty), format!("variant not found in `{qself_ty}`"),
); );
} }
if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) { if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
err.span_label(sp, format!("variant `{}` not found here", assoc_ident)); err.span_label(sp, format!("variant `{assoc_ident}` not found here"));
} }
err.emit() err.emit()
@ -2750,7 +2750,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => { ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
"an anonymous lifetime".to_string() "an anonymous lifetime".to_string()
} }
ty::BrNamed(_, name) => format!("lifetime `{}`", name), ty::BrNamed(_, name) => format!("lifetime `{name}`"),
}; };
let mut err = generate_err(&br_name); let mut err = generate_err(&br_name);

View file

@ -345,7 +345,7 @@ pub(super) fn check_opaque_for_inheriting_lifetimes(
err.span_suggestion( err.span_suggestion(
span, span,
"consider spelling out the type instead", "consider spelling out the type instead",
name.unwrap_or_else(|| format!("{:?}", ty)), name.unwrap_or_else(|| format!("{ty:?}")),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -797,7 +797,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) {
"replace the {} parameters with concrete {}{}", "replace the {} parameters with concrete {}{}",
kinds, kinds,
kinds_pl, kinds_pl,
egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(), egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
), ),
) )
.emit(); .emit();
@ -882,7 +882,7 @@ pub(super) fn check_specialization_validity<'tcx>(
} else { } else {
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
DUMMY_SP, DUMMY_SP,
format!("parent item: {:?} not marked as default", parent_impl), format!("parent item: {parent_impl:?} not marked as default"),
); );
} }
} }

View file

@ -1744,7 +1744,7 @@ fn compare_generic_param_kinds<'tcx>(
tcx.type_of(param.def_id).instantiate_identity() tcx.type_of(param.def_id).instantiate_identity()
) )
} }
Type { .. } => format!("{} type parameter", prefix), Type { .. } => format!("{prefix} type parameter"),
Lifetime { .. } => unreachable!(), Lifetime { .. } => unreachable!(),
}; };

View file

@ -134,7 +134,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: DefId) -> hir
/// Remember to add all intrinsics here, in `compiler/rustc_codegen_llvm/src/intrinsic.rs`, /// Remember to add all intrinsics here, in `compiler/rustc_codegen_llvm/src/intrinsic.rs`,
/// and in `library/core/src/intrinsics.rs`. /// and in `library/core/src/intrinsics.rs`.
pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
let param = |n| Ty::new_param(tcx, n, Symbol::intern(&format!("P{}", n))); let param = |n| Ty::new_param(tcx, n, Symbol::intern(&format!("P{n}")));
let intrinsic_id = it.owner_id.to_def_id(); let intrinsic_id = it.owner_id.to_def_id();
let intrinsic_name = tcx.item_name(intrinsic_id); let intrinsic_name = tcx.item_name(intrinsic_id);
let name_str = intrinsic_name.as_str(); let name_str = intrinsic_name.as_str();
@ -494,7 +494,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
/// Type-check `extern "platform-intrinsic" { ... }` functions. /// Type-check `extern "platform-intrinsic" { ... }` functions.
pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
let param = |n| { let param = |n| {
let name = Symbol::intern(&format!("P{}", n)); let name = Symbol::intern(&format!("P{n}"));
Ty::new_param(tcx, n, name) Ty::new_param(tcx, n, name)
}; };

View file

@ -211,7 +211,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
// register class is usable at all. // register class is usable at all.
if let Some(feature) = feature { if let Some(feature) = feature {
if !target_features.contains(feature) { if !target_features.contains(feature) {
let msg = format!("`{}` target feature is not enabled", feature); let msg = format!("`{feature}` target feature is not enabled");
let mut err = self.tcx.sess.struct_span_err(expr.span, msg); 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 `{}`", "this is required to use type `{}` with register class `{}`",

View file

@ -214,7 +214,7 @@ fn missing_items_err(
trait_item, trait_item,
tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(), tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(),
); );
let code = format!("{}{}\n{}", padding, snippet, padding); let code = format!("{padding}{snippet}\n{padding}");
if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) { if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) {
missing_trait_item_label missing_trait_item_label
.push(errors::MissingTraitItemLabel { span, item: trait_item.name }); .push(errors::MissingTraitItemLabel { span, item: trait_item.name });

View file

@ -472,8 +472,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe
let bound = let bound =
if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" }; if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
err.note(format!( err.note(format!(
"{} currently required to ensure that impls have maximum flexibility", "{bound} currently required to ensure that impls have maximum flexibility"
bound
)); ));
err.note( err.note(
"we are soliciting feedback, see issue #87479 \ "we are soliciting feedback, see issue #87479 \
@ -989,7 +988,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b
let ty = tcx.erase_regions(ty); let ty = tcx.erase_regions(ty);
if ty.has_infer() { if ty.has_infer() {
tcx.sess 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. // Just treat unresolved type expression as if it needs drop.
true true
} else { } else {
@ -1863,8 +1862,7 @@ fn report_bivariance(
if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds { 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", "if you intended `{param_name}` to be a const parameter, use `const {param_name}: usize` instead"
param_name
)); ));
} }
err.emit() err.emit()

View file

@ -36,7 +36,7 @@ fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) {
} }
let (path, _) = item.expect_use(); let (path, _) = item.expect_use();
let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) { let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) {
format!("unused import: `{}`", snippet) format!("unused import: `{snippet}`")
} else { } else {
"unused import".to_owned() "unused import".to_owned()
}; };

View file

@ -171,8 +171,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef
create_err(&format!( create_err(&format!(
"the trait `DispatchFromDyn` may only be implemented \ "the trait `DispatchFromDyn` may only be implemented \
for a coercion between structures with the same \ for a coercion between structures with the same \
definition; expected `{}`, found `{}`", definition; expected `{source_path}`, found `{target_path}`",
source_path, target_path,
)) ))
.emit(); .emit();

View file

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

View file

@ -77,8 +77,8 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
"duplicate definitions with name `{}`", "duplicate definitions with name `{}`",
ident, ident,
); );
err.span_label(span, format!("duplicate definitions for `{}`", ident)); err.span_label(span, format!("duplicate definitions for `{ident}`"));
err.span_label(*former, format!("other definition for `{}`", ident)); err.span_label(*former, format!("other definition for `{ident}`"));
err.emit(); err.emit();
} }
@ -114,11 +114,11 @@ impl<'tcx> InherentOverlapChecker<'tcx> {
); );
err.span_label( err.span_label(
self.tcx.def_span(item1.def_id), self.tcx.def_span(item1.def_id),
format!("duplicate definitions for `{}`", name), format!("duplicate definitions for `{name}`"),
); );
err.span_label( err.span_label(
self.tcx.def_span(item2.def_id), self.tcx.def_span(item2.def_id),
format!("other definition for `{}`", name), format!("other definition for `{name}`"),
); );
for cause in &overlap.intercrate_ambiguity_causes { for cause in &overlap.intercrate_ambiguity_causes {

View file

@ -412,9 +412,8 @@ fn emit_orphan_check_error<'tcx>(
.span_label( .span_label(
sp, sp,
format!( format!(
"type parameter `{}` must be covered by another type \ "type parameter `{param_ty}` must be covered by another type \
when it appears before the first local type (`{}`)", when it appears before the first local type (`{local_type}`)"
param_ty, local_type
), ),
) )
.note( .note(
@ -441,9 +440,8 @@ fn emit_orphan_check_error<'tcx>(
.span_label( .span_label(
sp, sp,
format!( format!(
"type parameter `{}` must be used as the type parameter for some \ "type parameter `{param_ty}` must be used as the type parameter for some \
local type", local type",
param_ty,
), ),
) )
.note( .note(
@ -541,17 +539,16 @@ fn lint_auto_trait_impl<'tcx>(
let self_descr = tcx.def_descr(self_type_did); let self_descr = tcx.def_descr(self_type_did);
match arg { match arg {
ty::util::NotUniqueParam::DuplicateParam(arg) => { ty::util::NotUniqueParam::DuplicateParam(arg) => {
lint.note(format!("`{}` is mentioned multiple times", arg)); lint.note(format!("`{arg}` is mentioned multiple times"));
} }
ty::util::NotUniqueParam::NotParam(arg) => { ty::util::NotUniqueParam::NotParam(arg) => {
lint.note(format!("`{}` is not a generic parameter", arg)); lint.note(format!("`{arg}` is not a generic parameter"));
} }
} }
lint.span_note( lint.span_note(
item_span, item_span,
format!( format!(
"try using the same sequence of generic parameters as the {} definition", "try using the same sequence of generic parameters as the {self_descr} definition",
self_descr,
), ),
) )
}, },

View file

@ -195,9 +195,9 @@ pub(crate) fn placeholder_type_error_diag<'tcx>(
sugg.push((arg.span, (*type_name).to_string())); sugg.push((arg.span, (*type_name).to_string()));
} else if let Some(span) = generics.span_for_param_suggestion() { } else if let Some(span) = generics.span_for_param_suggestion() {
// Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`. // Account for bounds, we want `fn foo<T: E, K>(_: K)` not `fn foo<T, K: E>(_: K)`.
sugg.push((span, format!(", {}", type_name))); sugg.push((span, format!(", {type_name}")));
} else { } else {
sugg.push((generics.span, format!("<{}>", type_name))); sugg.push((generics.span, format!("<{type_name}>")));
} }
} }
@ -329,7 +329,7 @@ fn bad_placeholder<'tcx>(
mut spans: Vec<Span>, mut spans: Vec<Span>,
kind: &'static str, kind: &'static str,
) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
let kind = if kind.ends_with('s') { format!("{}es", kind) } else { format!("{}s", kind) }; let kind = if kind.ends_with('s') { format!("{kind}es") } else { format!("{kind}s") };
spans.sort(); spans.sort();
tcx.sess.create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind }) tcx.sess.create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind })
@ -425,10 +425,8 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
| hir::ItemKind::Union(_, generics) => { | hir::ItemKind::Union(_, generics) => {
let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics); let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
let (lt_sp, sugg) = match generics.params { let (lt_sp, sugg) = match generics.params {
[] => (generics.span, format!("<{}>", lt_name)), [] => (generics.span, format!("<{lt_name}>")),
[bound, ..] => { [bound, ..] => (bound.span.shrink_to_lo(), format!("{lt_name}, ")),
(bound.span.shrink_to_lo(), format!("{}, ", lt_name))
}
}; };
mpart_sugg = Some(errors::AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion { mpart_sugg = Some(errors::AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion {
fspan: lt_sp, fspan: lt_sp,
@ -1027,7 +1025,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
} else { } else {
tcx.sess.span_err( tcx.sess.span_err(
meta.span(), meta.span(),
format!("unknown meta item passed to `rustc_deny_explicit_impl` {:?}", meta), format!("unknown meta item passed to `rustc_deny_explicit_impl` {meta:?}"),
); );
} }
} }
@ -1505,7 +1503,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
.sess .sess
.source_map() .source_map()
.span_to_snippet(ast_ty.span) .span_to_snippet(ast_ty.span)
.map_or_else(|_| String::new(), |s| format!(" `{}`", s)); .map_or_else(|_| String::new(), |s| format!(" `{s}`"));
tcx.sess.emit_err(errors::SIMDFFIHighlyExperimental { span: ast_ty.span, snip }); tcx.sess.emit_err(errors::SIMDFFIHighlyExperimental { span: ast_ty.span, snip });
} }
}; };

View file

@ -2040,8 +2040,7 @@ fn is_late_bound_map(
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
*span, *span,
format!( format!(
"Incorrect generic arg count for alias {:?}", "Incorrect generic arg count for alias {alias_def:?}"
alias_def
), ),
); );
None None

View file

@ -156,7 +156,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> {
let Some(type_dependent_def) = tables.type_dependent_def_id(parent_node_id) else { let Some(type_dependent_def) = tables.type_dependent_def_id(parent_node_id) else {
return Ty::new_error_with_message(tcx, return Ty::new_error_with_message(tcx,
tcx.def_span(def_id), tcx.def_span(def_id),
format!("unable to find type-dependent def for {:?}", parent_node_id), format!("unable to find type-dependent def for {parent_node_id:?}"),
); );
}; };
let idx = segment let idx = segment
@ -197,14 +197,14 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> {
} else { } else {
return Ty::new_error_with_message(tcx, return Ty::new_error_with_message(tcx,
tcx.def_span(def_id), tcx.def_span(def_id),
format!("unable to find const parent for {} in pat {:?}", hir_id, pat), format!("unable to find const parent for {hir_id} in pat {pat:?}"),
); );
} }
} }
_ => { _ => {
return Ty::new_error_with_message(tcx, return Ty::new_error_with_message(tcx,
tcx.def_span(def_id), tcx.def_span(def_id),
format!("unexpected const parent path {:?}", parent_node), format!("unexpected const parent path {parent_node:?}"),
); );
} }
}; };
@ -544,7 +544,7 @@ fn infer_placeholder_type<'a>(
if let Some(ty) = ty.make_suggestable(tcx, false) { if let Some(ty) = ty.make_suggestable(tcx, false) {
err.span_suggestion( err.span_suggestion(
span, span,
format!("provide a type for the {item}", item = kind), format!("provide a type for the {kind}"),
format!("{colon} {ty}"), format!("{colon} {ty}"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );

View file

@ -216,7 +216,7 @@ impl<'a> IntoDiagnostic<'a> for MissingTypeParams {
"parameters", "parameters",
self.missing_type_params self.missing_type_params
.iter() .iter()
.map(|n| format!("`{}`", n)) .map(|n| format!("`{n}`"))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
); );

View file

@ -77,8 +77,7 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId)
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
tcx.def_span(impl_def_id), tcx.def_span(impl_def_id),
format!( format!(
"potentially unconstrained type parameters weren't evaluated: {:?}", "potentially unconstrained type parameters weren't evaluated: {impl_self_ty:?}",
impl_self_ty,
), ),
); );
return; return;
@ -180,7 +179,7 @@ fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol
kind, kind,
name name
); );
err.span_label(span, format!("unconstrained {} parameter", kind)); err.span_label(span, format!("unconstrained {kind} parameter"));
if kind == "const" { if kind == "const" {
err.note( err.note(
"expressions using a const parameter must map each value to a distinct output value", "expressions using a const parameter must map each value to a distinct output value",

View file

@ -294,7 +294,7 @@ fn check_duplicate_params<'tcx>(
if let (_, [duplicate, ..]) = base_params.partition_dedup() { if let (_, [duplicate, ..]) = base_params.partition_dedup() {
let param = impl1_args[duplicate.0 as usize]; let param = impl1_args[duplicate.0 as usize];
tcx.sess tcx.sess
.struct_span_err(span, format!("specializing impl repeats parameter `{}`", param)) .struct_span_err(span, format!("specializing impl repeats parameter `{param}`"))
.emit(); .emit();
} }
} }
@ -523,7 +523,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc
} }
_ => { _ => {
tcx.sess tcx.sess
.struct_span_err(span, format!("cannot specialize on predicate `{}`", predicate)) .struct_span_err(span, format!("cannot specialize on predicate `{predicate}`"))
.emit(); .emit();
} }
} }

View file

@ -474,7 +474,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
verb verb
) )
} else { } else {
format!("missing generics for {} `{}`", def_kind, def_path) format!("missing generics for {def_kind} `{def_path}`")
} }
} }
@ -599,7 +599,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let span = self.path_segment.ident.span; let span = self.path_segment.ident.span;
// insert a suggestion of the form "Y<'a, 'b>" // insert a suggestion of the form "Y<'a, 'b>"
let sugg = format!("<{}>", suggested_args); let sugg = format!("<{suggested_args}>");
debug!("sugg: {:?}", sugg); debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose( err.span_suggestion_verbose(
@ -624,7 +624,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg_suffix = let sugg_suffix =
if is_first && (has_non_lt_args || has_bindings) { ", " } else { "" }; if is_first && (has_non_lt_args || has_bindings) { ", " } else { "" };
let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix); let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}");
debug!("sugg: {:?}", sugg); debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders); err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
@ -649,7 +649,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let span = self.path_segment.ident.span; let span = self.path_segment.ident.span;
// insert a suggestion of the form "Y<T, U>" // insert a suggestion of the form "Y<T, U>"
let sugg = format!("<{}>", suggested_args); let sugg = format!("<{suggested_args}>");
debug!("sugg: {:?}", sugg); debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose( err.span_suggestion_verbose(
@ -682,7 +682,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg_suffix = let sugg_suffix =
if is_first && !self.gen_args.bindings.is_empty() { ", " } else { "" }; if is_first && !self.gen_args.bindings.is_empty() { ", " } else { "" };
let sugg = format!("{}{}{}", sugg_prefix, suggested_args, sugg_suffix); let sugg = format!("{sugg_prefix}{suggested_args}{sugg_suffix}");
debug!("sugg: {:?}", sugg); debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders); err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
@ -1024,7 +1024,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
format!(": {}", params) format!(": {params}")
}; };
format!( format!(

View file

@ -32,8 +32,8 @@ pub enum VarianceTerm<'a> {
impl<'a> fmt::Debug for VarianceTerm<'a> { impl<'a> fmt::Debug for VarianceTerm<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
ConstantTerm(c1) => write!(f, "{:?}", c1), ConstantTerm(c1) => write!(f, "{c1:?}"),
TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2), TransformTerm(v1, v2) => write!(f, "({v1:?} \u{00D7} {v2:?})"),
InferredTerm(id) => write!(f, "[{}]", { InferredTerm(id) => write!(f, "[{}]", {
let InferredIndex(i) = id; let InferredIndex(i) = id;
i i

View file

@ -402,7 +402,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.sess .sess
.struct_span_err( .struct_span_err(
callee_expr.span, callee_expr.span,
format!("evaluate({:?}) = {:?}", predicate, result), format!("evaluate({predicate:?}) = {result:?}"),
) )
.span_label(predicate_span, "predicate") .span_label(predicate_span, "predicate")
.emit(); .emit();

View file

@ -144,7 +144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let reported = self let reported = self
.tcx .tcx
.sess .sess
.delay_span_bug(span, format!("`{:?}` should be sized but is not?", t)); .delay_span_bug(span, format!("`{t:?}` should be sized but is not?"));
return Err(reported); return Err(reported);
} }
}) })
@ -644,12 +644,12 @@ impl<'a, 'tcx> CastCheck<'tcx> {
err.span_suggestion( err.span_suggestion(
self.cast_span, self.cast_span,
"try casting to a reference instead", "try casting to a reference instead",
format!("&{}{}", mtstr, s), format!("&{mtstr}{s}"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }
Err(_) => { Err(_) => {
let msg = format!("did you mean `&{}{}`?", mtstr, tstr); let msg = format!("did you mean `&{mtstr}{tstr}`?");
err.span_help(self.cast_span, msg); err.span_help(self.cast_span, msg);
} }
} }

View file

@ -1797,8 +1797,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
err.span_note( err.span_note(
sp, sp,
format!( format!(
"return type inferred to be `{}` here", "return type inferred to be `{expected}` here"
expected
), ),
); );
} }

View file

@ -1890,7 +1890,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut truncated_fields_error = String::new(); let mut truncated_fields_error = String::new();
let remaining_fields_names = match &displayable_field_names[..] { let remaining_fields_names = match &displayable_field_names[..] {
[field1] => format!("`{}`", field1), [field1] => format!("`{field1}`"),
[field1, field2] => format!("`{field1}` and `{field2}`"), [field1, field2] => format!("`{field1}` and `{field2}`"),
[field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"), [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
_ => { _ => {
@ -2117,16 +2117,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
} }
_ => { _ => {
err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty)); err.span_label(variant_ident_span, format!("`{ty}` defined here"));
err.span_label(field.ident.span, "field does not exist"); err.span_label(field.ident.span, "field does not exist");
err.span_suggestion_verbose( err.span_suggestion_verbose(
expr_span, expr_span,
format!( format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
"`{adt}` is a tuple {kind_name}, use the appropriate syntax", format!("{ty}(/* fields */)"),
adt = ty,
kind_name = kind_name,
),
format!("{adt}(/* fields */)", adt = ty),
Applicability::HasPlaceholders, Applicability::HasPlaceholders,
); );
} }
@ -2243,7 +2239,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// dynamic limit, to never omit just one field // dynamic limit, to never omit just one field
let limit = if names.len() == 6 { 6 } else { 5 }; let limit = if names.len() == 6 { 6 } else { 5 };
let mut display = let mut display =
names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", "); names.iter().take(limit).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
if names.len() > limit { if names.len() > limit {
display = format!("{} ... and {} others", display, names.len() - limit); display = format!("{} ... and {} others", display, names.len() - limit);
} }

View file

@ -61,7 +61,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
let msg = format!("unreachable {}", kind); let msg = format!("unreachable {kind}");
self.tcx().struct_span_lint_hir( self.tcx().struct_span_lint_hir(
lint::builtin::UNREACHABLE_CODE, lint::builtin::UNREACHABLE_CODE,
id, id,
@ -134,7 +134,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
pub fn tag(&self) -> String { pub fn tag(&self) -> String {
format!("{:p}", self) format!("{self:p}")
} }
pub fn local_ty(&self, span: Span, nid: hir::HirId) -> Ty<'tcx> { pub fn local_ty(&self, span: Span, nid: hir::HirId) -> Ty<'tcx> {
@ -1412,9 +1412,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
span, span,
format!( format!(
"instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?",
self_ty,
impl_ty,
), ),
); );
} }

View file

@ -689,7 +689,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
err.span_label( err.span_label(
full_call_span, full_call_span,
format!("arguments to this {} are incorrect", call_name), format!("arguments to this {call_name} are incorrect"),
); );
} else { } else {
err = tcx.sess.struct_span_err_with_code( err = tcx.sess.struct_span_err_with_code(
@ -796,10 +796,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None, None,
None, None,
); );
err.span_label( err.span_label(full_call_span, format!("arguments to this {call_name} are incorrect"));
full_call_span,
format!("arguments to this {} are incorrect", call_name),
);
if let hir::ExprKind::MethodCall(_, rcvr, _, _) = call_expr.kind if let hir::ExprKind::MethodCall(_, rcvr, _, _) = call_expr.kind
&& provided_idx.as_usize() == expected_idx.as_usize() && provided_idx.as_usize() == expected_idx.as_usize()
@ -874,7 +871,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if ty.is_unit() { if ty.is_unit() {
"()".to_string() "()".to_string()
} else if ty.is_suggestable(tcx, false) { } else if ty.is_suggestable(tcx, false) {
format!("/* {} */", ty) format!("/* {ty} */")
} else if let Some(fn_def_id) = fn_def_id } else if let Some(fn_def_id) = fn_def_id
&& self.tcx.def_kind(fn_def_id).is_fn_like() && self.tcx.def_kind(fn_def_id).is_fn_like()
&& let self_implicit = && let self_implicit =
@ -931,12 +928,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let (provided_ty, provided_span) = provided_arg_tys[arg_idx]; let (provided_ty, provided_span) = provided_arg_tys[arg_idx];
let provided_ty_name = if !has_error_or_infer([provided_ty]) { let provided_ty_name = if !has_error_or_infer([provided_ty]) {
// FIXME: not suggestable, use something else // FIXME: not suggestable, use something else
format!(" of type `{}`", provided_ty) format!(" of type `{provided_ty}`")
} else { } else {
"".to_string() "".to_string()
}; };
labels labels.push((provided_span, format!("unexpected argument{provided_ty_name}")));
.push((provided_span, format!("unexpected argument{}", provided_ty_name)));
let mut span = provided_span; let mut span = provided_span;
if span.can_be_used_for_suggestions() { if span.can_be_used_for_suggestions() {
if arg_idx.index() > 0 if arg_idx.index() > 0
@ -1009,11 +1005,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
args_span args_span
}; };
let rendered = if !has_error_or_infer([input_ty]) { let rendered = if !has_error_or_infer([input_ty]) {
format!(" of type `{}`", input_ty) format!(" of type `{input_ty}`")
} else { } else {
"".to_string() "".to_string()
}; };
labels.push((span, format!("an argument{} is missing", rendered))); labels.push((span, format!("an argument{rendered} is missing")));
suggestion_text = match suggestion_text { suggestion_text = match suggestion_text {
SuggestionText::None => SuggestionText::Provide(false), SuggestionText::None => SuggestionText::Provide(false),
SuggestionText::Provide(_) => SuggestionText::Provide(true), SuggestionText::Provide(_) => SuggestionText::Provide(true),
@ -1034,13 +1030,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let rendered = let rendered =
if !has_error_or_infer([first_expected_ty, second_expected_ty]) { if !has_error_or_infer([first_expected_ty, second_expected_ty]) {
format!( format!(
" of type `{}` and `{}`", " of type `{first_expected_ty}` and `{second_expected_ty}`"
first_expected_ty, second_expected_ty
) )
} else { } else {
"".to_string() "".to_string()
}; };
labels.push((span, format!("two arguments{} are missing", rendered))); labels.push((span, format!("two arguments{rendered} are missing")));
suggestion_text = match suggestion_text { suggestion_text = match suggestion_text {
SuggestionText::None | SuggestionText::Provide(_) => { SuggestionText::None | SuggestionText::Provide(_) => {
SuggestionText::Provide(true) SuggestionText::Provide(true)
@ -1066,13 +1061,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
third_expected_ty, third_expected_ty,
]) { ]) {
format!( format!(
" of type `{}`, `{}`, and `{}`", " of type `{first_expected_ty}`, `{second_expected_ty}`, and `{third_expected_ty}`"
first_expected_ty, second_expected_ty, third_expected_ty
) )
} else { } else {
"".to_string() "".to_string()
}; };
labels.push((span, format!("three arguments{} are missing", rendered))); labels.push((span, format!("three arguments{rendered} are missing")));
suggestion_text = match suggestion_text { suggestion_text = match suggestion_text {
SuggestionText::None | SuggestionText::Provide(_) => { SuggestionText::None | SuggestionText::Provide(_) => {
SuggestionText::Provide(true) SuggestionText::Provide(true)
@ -1113,25 +1107,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx]; let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx];
let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx]; let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx];
let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) { let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) {
format!(", found `{}`", first_provided_ty) format!(", found `{first_provided_ty}`")
} else { } else {
String::new() String::new()
}; };
labels.push(( labels.push((
first_span, first_span,
format!("expected `{}`{}", first_expected_ty, first_provided_ty_name), format!("expected `{first_expected_ty}`{first_provided_ty_name}"),
)); ));
let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx]; let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx];
let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx]; let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx];
let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) { let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) {
format!(", found `{}`", second_provided_ty) format!(", found `{second_provided_ty}`")
} else { } else {
String::new() String::new()
}; };
labels.push(( labels.push((
second_span, second_span,
format!("expected `{}`{}", second_expected_ty, second_provided_ty_name), format!("expected `{second_expected_ty}`{second_provided_ty_name}"),
)); ));
suggestion_text = match suggestion_text { suggestion_text = match suggestion_text {
@ -1144,13 +1138,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let (_, expected_ty) = formal_and_expected_inputs[dst_arg]; let (_, expected_ty) = formal_and_expected_inputs[dst_arg];
let (provided_ty, provided_span) = provided_arg_tys[dest_input]; let (provided_ty, provided_span) = provided_arg_tys[dest_input];
let provided_ty_name = if !has_error_or_infer([provided_ty]) { let provided_ty_name = if !has_error_or_infer([provided_ty]) {
format!(", found `{}`", provided_ty) format!(", found `{provided_ty}`")
} else { } else {
String::new() String::new()
}; };
labels.push(( labels.push((
provided_span, provided_span,
format!("expected `{}`{}", expected_ty, provided_ty_name), format!("expected `{expected_ty}`{provided_ty_name}"),
)); ));
} }
@ -2031,7 +2025,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else { } else {
("closure", self.tcx.def_span(def_id)) ("closure", self.tcx.def_span(def_id))
}; };
err.span_note(span, format!("{} defined here", kind)); err.span_note(span, format!("{kind} defined here"));
} else { } else {
err.span_note( err.span_note(
self.tcx.def_span(def_id), self.tcx.def_span(def_id),

View file

@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let struct_pat_shorthand_field = let struct_pat_shorthand_field =
self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr); self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr);
if let Some(name) = struct_pat_shorthand_field { if let Some(name) = struct_pat_shorthand_field {
sugg.insert(0, (expr.span.shrink_to_lo(), format!("{}: ", name))); sugg.insert(0, (expr.span.shrink_to_lo(), format!("{name}: ")));
} }
Some(sugg) Some(sugg)
}) })
@ -558,7 +558,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.take(4) .take(4)
.map(|(var_hir_id, upvar)| { .map(|(var_hir_id, upvar)| {
let var_name = self.tcx.hir().name(*var_hir_id).to_string(); let var_name = self.tcx.hir().name(*var_hir_id).to_string();
let msg = format!("`{}` captured here", var_name); let msg = format!("`{var_name}` captured here");
(upvar.span, msg) (upvar.span, msg)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -931,7 +931,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion( err.span_suggestion(
fn_return.span(), fn_return.span(),
"consider using an impl return type", "consider using an impl return type",
format!("impl {}", all_bounds_str), format!("impl {all_bounds_str}"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -1070,7 +1070,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.must_apply_modulo_regions() .must_apply_modulo_regions()
{ {
let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {
Some(ident) => format!(": {}.clone()", ident), Some(ident) => format!(": {ident}.clone()"),
None => ".clone()".to_string() None => ".clone()".to_string()
}; };
@ -1259,7 +1259,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {
Some(ident) => format!(": {}.is_some()", ident), Some(ident) => format!(": {ident}.is_some()"),
None => ".is_some()".to_string(), None => ".is_some()".to_string(),
}; };

View file

@ -125,8 +125,8 @@ impl Debug for TrackedValue {
write!(f, "{}", tcx.hir().node_to_string(self.hir_id())) write!(f, "{}", tcx.hir().node_to_string(self.hir_id()))
} else { } else {
match self { match self {
Self::Variable(hir_id) => write!(f, "Variable({:?})", hir_id), Self::Variable(hir_id) => write!(f, "Variable({hir_id:?})"),
Self::Temporary(hir_id) => write!(f, "Temporary({:?})", hir_id), Self::Temporary(hir_id) => write!(f, "Temporary({hir_id:?})"),
} }
} }
}) })

View file

@ -112,7 +112,7 @@ impl<'a, 'tcx> InteriorVisitor<'a, 'tcx> {
self.fcx self.fcx
.tcx .tcx
.sess .sess
.delay_span_bug(span, format!("Encountered var {:?}", unresolved_term)); .delay_span_bug(span, format!("Encountered var {unresolved_term:?}"));
} else { } else {
let note = format!( let note = format!(
"the type is part of the {} because of this {}", "the type is part of the {} because of this {}",

View file

@ -85,7 +85,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"), Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
Ok(SizeSkeleton::Known(size)) => { Ok(SizeSkeleton::Known(size)) => {
if let Some(v) = u128::from(size.bytes()).checked_mul(8) { if let Some(v) = u128::from(size.bytes()).checked_mul(8) {
format!("{} bits", v) format!("{v} bits")
} else { } else {
// `u128` should definitely be able to hold the size of different architectures // `u128` should definitely be able to hold the size of different architectures
// larger sizes should be reported as error `are too big for the current architecture` // larger sizes should be reported as error `are too big for the current architecture`

View file

@ -225,7 +225,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
assert!(mutbl.is_mut()); assert!(mutbl.is_mut());
Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: hir::Mutability::Not, ty }) Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: hir::Mutability::Not, ty })
} }
other => panic!("Cannot adjust receiver type {:?} to const ptr", other), other => panic!("Cannot adjust receiver type {other:?} to const ptr"),
}; };
adjustments.push(Adjustment { adjustments.push(Adjustment {
@ -262,8 +262,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
let impl_def_id = pick.item.container_id(self.tcx); let impl_def_id = pick.item.container_id(self.tcx);
assert!( assert!(
self.tcx.impl_trait_ref(impl_def_id).is_none(), self.tcx.impl_trait_ref(impl_def_id).is_none(),
"impl {:?} is not an inherent impl", "impl {impl_def_id:?} is not an inherent impl"
impl_def_id
); );
self.fresh_args_for_item(self.span, impl_def_id) self.fresh_args_for_item(self.span, impl_def_id)
} }

View file

@ -97,28 +97,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
pick.autoref_or_ptr_adjustment pick.autoref_or_ptr_adjustment
{ {
format!("{}{} as *const _", derefs, self_expr) format!("{derefs}{self_expr} as *const _")
} else { } else {
format!("{}{}{}", autoref, derefs, self_expr) format!("{autoref}{derefs}{self_expr}")
}; };
lint.span_suggestion( lint.span_suggestion(
sp, sp,
"disambiguate the method call", "disambiguate the method call",
format!("({})", self_adjusted), format!("({self_adjusted})"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} else { } else {
let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
pick.autoref_or_ptr_adjustment pick.autoref_or_ptr_adjustment
{ {
format!("{}(...) as *const _", derefs) format!("{derefs}(...) as *const _")
} else { } else {
format!("{}{}...", autoref, derefs) format!("{autoref}{derefs}...")
}; };
lint.span_help( lint.span_help(
sp, sp,
format!("disambiguate the method call with `({})`", self_adjusted,), format!("disambiguate the method call with `({self_adjusted})`",),
); );
} }
@ -168,7 +168,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.ok()) .ok())
{ {
// Keep turbofish. // Keep turbofish.
format!("::{}", args) format!("::{args}")
} else { } else {
String::new() String::new()
}, },
@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Glob import, so just use its name. // Glob import, so just use its name.
return None; return None;
} else { } else {
return Some(format!("{}", any_id)); return Some(format!("{any_id}"));
} }
} }
@ -396,9 +396,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) = let adjusted_text = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
pick.autoref_or_ptr_adjustment pick.autoref_or_ptr_adjustment
{ {
format!("{}{} as *const _", derefs, expr_text) format!("{derefs}{expr_text} as *const _")
} else { } else {
format!("{}{}{}", autoref, derefs, expr_text) format!("{autoref}{derefs}{expr_text}")
}; };
(adjusted_text, precise) (adjusted_text, precise)

View file

@ -153,7 +153,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
E0034, E0034,
"multiple applicable items in scope" "multiple applicable items in scope"
); );
err.span_label(item_name.span, format!("multiple `{}` found", item_name)); err.span_label(item_name.span, format!("multiple `{item_name}` found"));
self.note_candidates_on_method_error( self.note_candidates_on_method_error(
rcvr_ty, rcvr_ty,
@ -177,13 +177,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
kind, kind,
item_name item_name
); );
err.span_label(item_name.span, format!("private {}", kind)); err.span_label(item_name.span, format!("private {kind}"));
let sp = self let sp = self
.tcx .tcx
.hir() .hir()
.span_if_local(def_id) .span_if_local(def_id)
.unwrap_or_else(|| self.tcx.def_span(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 {kind} defined here"));
self.suggest_valid_traits(&mut err, out_of_scope_traits); self.suggest_valid_traits(&mut err, out_of_scope_traits);
err.emit(); err.emit();
} }
@ -218,7 +218,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
*region, *region,
ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() }, ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() },
); );
let msg = format!("you need `{}` instead of `{}`", trait_type, rcvr_ty); let msg = format!("you need `{trait_type}` instead of `{rcvr_ty}`");
let mut kind = &self_expr.kind; let mut kind = &self_expr.kind;
while let hir::ExprKind::AddrOf(_, _, expr) while let hir::ExprKind::AddrOf(_, _, expr)
| hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind
@ -637,7 +637,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
// Point at the closure that couldn't satisfy the bound. // Point at the closure that couldn't satisfy the bound.
ty::Closure(def_id, _) => bound_spans ty::Closure(def_id, _) => bound_spans
.push((tcx.def_span(*def_id), format!("doesn't satisfy `{}`", quiet))), .push((tcx.def_span(*def_id), format!("doesn't satisfy `{quiet}`"))),
_ => {} _ => {}
} }
}; };
@ -659,7 +659,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let term = pred.skip_binder().term; let term = pred.skip_binder().term;
let obligation = format!("{} = {}", projection_ty, term); let obligation = format!("{projection_ty} = {term}");
let quiet = with_forced_trimmed_paths!(format!( let quiet = with_forced_trimmed_paths!(format!(
"{} = {}", "{} = {}",
quiet_projection_ty, term quiet_projection_ty, term
@ -672,7 +672,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let p = poly_trait_ref.trait_ref; let p = poly_trait_ref.trait_ref;
let self_ty = p.self_ty(); let self_ty = p.self_ty();
let path = p.print_only_trait_path(); let path = p.print_only_trait_path();
let obligation = format!("{}: {}", self_ty, path); let obligation = format!("{self_ty}: {path}");
let quiet = with_forced_trimmed_paths!(format!("_: {}", path)); let quiet = with_forced_trimmed_paths!(format!("_: {}", path));
bound_span_label(self_ty, &obligation, &quiet); bound_span_label(self_ty, &obligation, &quiet);
Some((obligation, self_ty)) Some((obligation, self_ty))
@ -825,12 +825,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut preds: Vec<_> = predicates let mut preds: Vec<_> = predicates
.iter() .iter()
.filter_map(|pred| format_pred(**pred)) .filter_map(|pred| format_pred(**pred))
.map(|(p, _)| format!("`{}`", p)) .map(|(p, _)| format!("`{p}`"))
.collect(); .collect();
preds.sort(); preds.sort();
preds.dedup(); preds.dedup();
let msg = if let [pred] = &preds[..] { let msg = if let [pred] = &preds[..] {
format!("trait bound {} was not satisfied", pred) format!("trait bound {pred} was not satisfied")
} else { } else {
format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),) format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),)
}; };
@ -875,7 +875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
suggested_bounds.insert(pred); suggested_bounds.insert(pred);
} }
} }
format!("`{}`\nwhich is required by `{}`", p, parent_p) format!("`{p}`\nwhich is required by `{parent_p}`")
} }
}, },
}, },
@ -1034,8 +1034,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"".to_string() "".to_string()
}; };
err.note(format!( err.note(format!(
"the {item_kind} was found for\n{}{}", "the {item_kind} was found for\n{type_candidates}{additional_types}"
type_candidates, additional_types
)); ));
} else { } else {
'outer: for inherent_impl_did in self.tcx.inherent_impls(adt.did()) { 'outer: for inherent_impl_did in self.tcx.inherent_impls(adt.did()) {
@ -1249,8 +1248,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else { } else {
( (
format!( format!(
"the candidate is defined in an impl{} for the type `{}`", "the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
insertion, impl_ty,
), ),
None, None,
) )
@ -1452,11 +1450,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion( err.span_suggestion(
sugg_span, sugg_span,
"use associated function syntax instead", "use associated function syntax instead",
format!("{}::{}{}", ty_str, item_name, args), format!("{ty_str}::{item_name}{args}"),
applicability, applicability,
); );
} else { } else {
err.help(format!("try with `{}::{}`", ty_str, item_name,)); err.help(format!("try with `{ty_str}::{item_name}`",));
} }
} }
@ -1491,9 +1489,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let expr_span = expr.span.to(item_name.span); let expr_span = expr.span.to(item_name.span);
err.multipart_suggestion( err.multipart_suggestion(
format!( format!(
"to call the function stored in `{}`, \ "to call the function stored in `{item_name}`, \
surround the field access with parentheses", surround the field access with parentheses",
item_name,
), ),
vec![ vec![
(expr_span.shrink_to_lo(), '('.to_string()), (expr_span.shrink_to_lo(), '('.to_string()),
@ -1516,7 +1513,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
let field_kind = if is_accessible { "field" } else { "private field" }; let field_kind = if is_accessible { "field" } else { "private field" };
err.span_label(item_name.span, format!("{}, not a method", field_kind)); err.span_label(item_name.span, format!("{field_kind}, not a method"));
return true; return true;
} }
false false
@ -1669,8 +1666,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lit.span, lit.span,
format!( format!(
"you must specify a concrete type for this numeric value, \ "you must specify a concrete type for this numeric value, \
like `{}`", like `{concrete_type}`"
concrete_type
), ),
format!("{snippet}_{concrete_type}"), format!("{snippet}_{concrete_type}"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
@ -1685,8 +1681,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let parent_node = let parent_node =
self.tcx.hir().get_parent(hir_id); self.tcx.hir().get_parent(hir_id);
let msg = format!( let msg = format!(
"you must specify a type for this binding, like `{}`", "you must specify a type for this binding, like `{concrete_type}`",
concrete_type,
); );
match (filename, parent_node) { match (filename, parent_node) {
@ -2194,7 +2189,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut() if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut()
{ {
if last_self_name == &self_name { if last_self_name == &self_name {
last_trait_names.push_str(format!(", {}", trait_name).as_str()); last_trait_names.push_str(format!(", {trait_name}").as_str());
continue; continue;
} }
} }
@ -2226,8 +2221,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
for (self_name, self_span, traits) in &derives_grouped { for (self_name, self_span, traits) in &derives_grouped {
err.span_suggestion_verbose( err.span_suggestion_verbose(
self_span.shrink_to_lo(), self_span.shrink_to_lo(),
format!("consider annotating `{}` with `#[derive({})]`", self_name, traits), format!("consider annotating `{self_name}` with `#[derive({traits})]`"),
format!("#[derive({})]\n", traits), format!("#[derive({traits})]\n"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
@ -2475,7 +2470,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip { if pick.autoderefs == 0 && !skip {
err.span_label( err.span_label(
pick.item.ident(self.tcx).span, pick.item.ident(self.tcx).span,
format!("the method is available for `{}` here", rcvr_ty), format!("the method is available for `{rcvr_ty}` here"),
); );
} }
break; break;
@ -2521,13 +2516,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip { if pick.autoderefs == 0 && !skip {
err.span_label( err.span_label(
pick.item.ident(self.tcx).span, pick.item.ident(self.tcx).span,
format!("the method is available for `{}` here", new_rcvr_t), format!("the method is available for `{new_rcvr_t}` here"),
); );
err.multipart_suggestion( err.multipart_suggestion(
"consider wrapping the receiver expression with the \ "consider wrapping the receiver expression with the \
appropriate type", appropriate type",
vec![ vec![
(rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)), (rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
(rcvr.span.shrink_to_hi(), ")".to_string()), (rcvr.span.shrink_to_hi(), ")".to_string()),
], ],
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
@ -2767,7 +2762,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
err.span_suggestions( err.span_suggestions(
sp, sp,
message(format!("add {} supertrait for", article)), message(format!("add {article} supertrait for")),
candidates.iter().map(|t| { candidates.iter().map(|t| {
format!("{} {}", sep, self.tcx.def_path_str(t.def_id),) format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
}), }),
@ -2836,7 +2831,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
trait_infos => { trait_infos => {
let mut msg = message(param_type.map_or_else( let mut msg = message(param_type.map_or_else(
|| "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented. || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
|param| format!("restrict type parameter `{}` with", param), |param| format!("restrict type parameter `{param}` with"),
)); ));
for (i, trait_info) in trait_infos.iter().enumerate() { for (i, trait_info) in trait_infos.iter().enumerate() {
msg.push_str(&format!( msg.push_str(&format!(
@ -2860,8 +2855,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
trait_infos => { trait_infos => {
let mut msg = format!( let mut msg = format!(
"the following traits define an item `{}`, but are explicitly unimplemented:", "the following traits define an item `{item_name}`, but are explicitly unimplemented:"
item_name
); );
for trait_info in trait_infos { for trait_info in trait_infos {
msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id))); msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
@ -3027,13 +3021,13 @@ fn print_disambiguation_help<'tcx>(
.join(", "), .join(", "),
); );
let trait_name = if !fn_has_self_parameter { let trait_name = if !fn_has_self_parameter {
format!("<{} as {}>", rcvr_ty, trait_name) format!("<{rcvr_ty} as {trait_name}>")
} else { } else {
trait_name trait_name
}; };
(span, format!("{}::{}{}", trait_name, item_name, args)) (span, format!("{trait_name}::{item_name}{args}"))
} else { } else {
(span.with_hi(item_name.span.lo()), format!("<{} as {}>::", rcvr_ty, trait_name)) (span.with_hi(item_name.span.lo()), format!("<{rcvr_ty} as {trait_name}>::"))
}; };
err.span_suggestion_verbose( err.span_suggestion_verbose(
span, span,
@ -3041,7 +3035,7 @@ fn print_disambiguation_help<'tcx>(
"disambiguate the {} for {}", "disambiguate the {} for {}",
def_kind_descr, def_kind_descr,
if let Some(candidate) = candidate { if let Some(candidate) = candidate {
format!("candidate #{}", candidate) format!("candidate #{candidate}")
} else { } else {
"the candidate".to_string() "the candidate".to_string()
}, },

View file

@ -516,7 +516,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn endpoint_has_type(&self, err: &mut Diagnostic, span: Span, ty: Ty<'_>) { fn endpoint_has_type(&self, err: &mut Diagnostic, span: Span, ty: Ty<'_>) {
if !ty.references_error() { if !ty.references_error() {
err.span_label(span, format!("this is of type `{}`", ty)); err.span_label(span, format!("this is of type `{ty}`"));
} }
} }
@ -540,7 +540,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
let msg = |ty| { let msg = |ty| {
let ty = self.resolve_vars_if_possible(ty); let ty = self.resolve_vars_if_possible(ty);
format!("this is of type `{}` but it should be `char` or numeric", ty) format!("this is of type `{ty}` but it should be `char` or numeric")
}; };
let mut one_side_err = |first_span, first_ty, second: Option<(bool, Ty<'tcx>, Span)>| { 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));
@ -653,7 +653,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) )
}); });
let pre = if in_match { "in the same arm, " } else { "" }; 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!("{pre}a binding must have the same type in all alternatives"));
self.suggest_adding_missing_ref_or_removing_ref( self.suggest_adding_missing_ref_or_removing_ref(
&mut err, &mut err,
span, span,
@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion_verbose( err.span_suggestion_verbose(
qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()), qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
"use the tuple variant pattern syntax instead", "use the tuple variant pattern syntax instead",
format!("({})", sugg), format!("({sugg})"),
appl, appl,
); );
return Some(err); return Some(err);
@ -1812,7 +1812,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
const LIMIT: usize = 3; const LIMIT: usize = 3;
match witnesses { match witnesses {
[] => bug!(), [] => bug!(),
[witness] => format!("`{}`", witness), [witness] => format!("`{witness}`"),
[head @ .., tail] if head.len() < LIMIT => { [head @ .., tail] if head.len() < LIMIT => {
let head: Vec<_> = head.iter().map(<_>::to_string).collect(); let head: Vec<_> = head.iter().map(<_>::to_string).collect();
format!("`{}` and `{}`", head.join("`, `"), tail) format!("`{}` and `{}`", head.join("`, `"), tail)
@ -1834,8 +1834,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"ensure that all fields are mentioned explicitly by adding the suggested fields", "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", "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
ty,
)); ));
lint lint
@ -1864,10 +1863,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else { } else {
let fields = unmentioned_fields let fields = unmentioned_fields
.iter() .iter()
.map(|(_, name)| format!("`{}`", name)) .map(|(_, name)| format!("`{name}`"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "); .join(", ");
format!("fields {}{}", fields, inaccessible) format!("fields {fields}{inaccessible}")
}; };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self.tcx.sess, self.tcx.sess,
@ -1876,7 +1875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"pattern does not mention {}", "pattern does not mention {}",
field_names field_names
); );
err.span_label(pat.span, format!("missing {}", field_names)); err.span_label(pat.span, format!("missing {field_names}"));
let len = unmentioned_fields.len(); let len = unmentioned_fields.len();
let (prefix, postfix, sp) = match fields { let (prefix, postfix, sp) = match fields {
[] => match &pat.kind { [] => match &pat.kind {
@ -1909,11 +1908,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter() .iter()
.map(|(_, name)| { .map(|(_, name)| {
let field_name = name.to_string(); let field_name = name.to_string();
if is_number(&field_name) { if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
format!("{}: _", field_name)
} else {
field_name
}
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "), .join(", "),
@ -1930,7 +1925,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
s = pluralize!(len), s = pluralize!(len),
them = if len == 1 { "it" } else { "them" }, them = if len == 1 { "it" } else { "them" },
), ),
format!("{}..{}", prefix, postfix), format!("{prefix}..{postfix}"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
err err

View file

@ -109,11 +109,11 @@ impl MigrationWarningReason {
fn migration_message(&self) -> String { fn migration_message(&self) -> String {
let base = "changes to closure capture in Rust 2021 will affect"; let base = "changes to closure capture in Rust 2021 will affect";
if !self.auto_traits.is_empty() && self.drop_order { if !self.auto_traits.is_empty() && self.drop_order {
format!("{} drop order and which traits the closure implements", base) format!("{base} drop order and which traits the closure implements")
} else if self.drop_order { } else if self.drop_order {
format!("{} drop order", base) format!("{base} drop order")
} else { } else {
format!("{} which traits the closure implements", base) format!("{base} which traits the closure implements")
} }
} }
} }
@ -824,8 +824,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lint.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>"); lint.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/disjoint-capture-in-closures.html>");
let diagnostic_msg = format!( let diagnostic_msg = format!(
"add a dummy let to cause {} to be fully captured", "add a dummy let to cause {migrated_variables_concat} to be fully captured"
migrated_variables_concat
); );
let closure_span = self.tcx.hir().span_with_body(closure_hir_id); let closure_span = self.tcx.hir().span_with_body(closure_hir_id);
@ -1943,7 +1942,7 @@ fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String
let mut projections_str = String::new(); let mut projections_str = String::new();
for (i, item) in place.projections.iter().enumerate() { for (i, item) in place.projections.iter().enumerate() {
let proj = match item.kind { let proj = match item.kind {
ProjectionKind::Field(a, b) => format!("({:?}, {:?})", a, b), ProjectionKind::Field(a, b) => format!("({a:?}, {b:?})"),
ProjectionKind::Deref => String::from("Deref"), ProjectionKind::Deref => String::from("Deref"),
ProjectionKind::Index => String::from("Index"), ProjectionKind::Index => String::from("Index"),
ProjectionKind::Subslice => String::from("Subslice"), ProjectionKind::Subslice => String::from("Subslice"),
@ -1966,7 +1965,7 @@ fn construct_capture_kind_reason_string<'tcx>(
let capture_kind_str = match capture_info.capture_kind { let capture_kind_str = match capture_info.capture_kind {
ty::UpvarCapture::ByValue => "ByValue".into(), ty::UpvarCapture::ByValue => "ByValue".into(),
ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind), ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"),
}; };
format!("{place_str} captured as {capture_kind_str} here") format!("{place_str} captured as {capture_kind_str} here")
@ -1987,7 +1986,7 @@ fn construct_capture_info_string<'tcx>(
let capture_kind_str = match capture_info.capture_kind { let capture_kind_str = match capture_info.capture_kind {
ty::UpvarCapture::ByValue => "ByValue".into(), ty::UpvarCapture::ByValue => "ByValue".into(),
ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind), ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"),
}; };
format!("{place_str} -> {capture_kind_str}") format!("{place_str} -> {capture_kind_str}")
} }

View file

@ -217,7 +217,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
// When encountering `return [0][0]` outside of a `fn` body we can encounter a base // 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 // 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) // 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(base_ty) = base_ty if let Some(base_ty) = base_ty
&& let ty::Ref(_, base_ty_inner, _) = *base_ty.kind() && let ty::Ref(_, base_ty_inner, _) = *base_ty.kind()
@ -231,7 +231,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
Ty::new_error_with_message( Ty::new_error_with_message(
self.fcx.tcx, self.fcx.tcx,
e.span, e.span,
format!("bad index {:?} for base: `{:?}`", index, base), format!("bad index {index:?} for base: `{base:?}`"),
) )
}); });
if self.is_builtin_index(e, base_ty_inner, index_ty) { if self.is_builtin_index(e, base_ty_inner, index_ty) {
@ -488,10 +488,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
let span = self.tcx().hir().span(hir_id); let span = self.tcx().hir().span(hir_id);
// We need to buffer the errors in order to guarantee a consistent // We need to buffer the errors in order to guarantee a consistent
// order when emitting them. // order when emitting them.
let err = self let err =
.tcx() self.tcx().sess.struct_span_err(span, format!("user args: {user_args:?}"));
.sess
.struct_span_err(span, format!("user args: {:?}", user_args));
err.buffer(&mut errors_buffer); err.buffer(&mut errors_buffer);
} }
} }

View file

@ -1716,7 +1716,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns {
let end = expr_to_string(&end); let end = expr_to_string(&end);
let replace = match start { let replace = match start {
Some(start) => format!("&({}..={})", expr_to_string(&start), end), Some(start) => format!("&({}..={})", expr_to_string(&start), end),
None => format!("&(..={})", end), None => format!("&(..={end})"),
}; };
if join.edition() >= Edition::Edition2021 { if join.edition() >= Edition::Edition2021 {
cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns { cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns {

View file

@ -411,7 +411,7 @@ impl LintStore {
} }
let complete_name = if let Some(tool_name) = tool_name { let complete_name = if let Some(tool_name) = tool_name {
format!("{}::{}", tool_name, lint_name) format!("{tool_name}::{lint_name}")
} else { } else {
lint_name.to_string() lint_name.to_string()
}; };
@ -424,7 +424,7 @@ impl LintStore {
// 1. The tool is currently running, so this lint really doesn't exist. // 1. The tool is currently running, so this lint really doesn't exist.
// FIXME: should this handle tools that never register a lint, like rustfmt? // FIXME: should this handle tools that never register a lint, like rustfmt?
debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>()); debug!("lints={:?}", self.by_name.keys().collect::<Vec<_>>());
let tool_prefix = format!("{}::", tool_name); let tool_prefix = format!("{tool_name}::");
return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) { return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
self.no_lint_suggestion(&complete_name) self.no_lint_suggestion(&complete_name)
} else { } else {
@ -445,11 +445,11 @@ impl LintStore {
} }
match self.by_name.get(&complete_name) { match self.by_name.get(&complete_name) {
Some(Renamed(new_name, _)) => CheckLintNameResult::Warning( Some(Renamed(new_name, _)) => CheckLintNameResult::Warning(
format!("lint `{}` has been renamed to `{}`", complete_name, new_name), format!("lint `{complete_name}` has been renamed to `{new_name}`"),
Some(new_name.to_owned()), Some(new_name.to_owned()),
), ),
Some(Removed(reason)) => CheckLintNameResult::Warning( Some(Removed(reason)) => CheckLintNameResult::Warning(
format!("lint `{}` has been removed: {}", complete_name, reason), format!("lint `{complete_name}` has been removed: {reason}"),
None, None,
), ),
None => match self.lint_groups.get(&*complete_name) { None => match self.lint_groups.get(&*complete_name) {
@ -503,7 +503,7 @@ impl LintStore {
lint_name: &str, lint_name: &str,
tool_name: &str, tool_name: &str,
) -> CheckLintNameResult<'_> { ) -> CheckLintNameResult<'_> {
let complete_name = format!("{}::{}", tool_name, lint_name); let complete_name = format!("{tool_name}::{lint_name}");
match self.by_name.get(&complete_name) { match self.by_name.get(&complete_name) {
None => match self.lint_groups.get(&*complete_name) { None => match self.lint_groups.get(&*complete_name) {
// Now we are sure, that this lint exists nowhere // Now we are sure, that this lint exists nowhere
@ -618,12 +618,10 @@ pub trait LintContext: Sized {
_ => ("", "s"), _ => ("", "s"),
}; };
db.span_label(span, format!( db.span_label(span, format!(
"this comment contains {}invisible unicode text flow control codepoint{}", "this comment contains {an}invisible unicode text flow control codepoint{s}",
an,
s,
)); ));
for (c, span) in &spans { for (c, span) in &spans {
db.span_label(*span, format!("{:?}", c)); db.span_label(*span, format!("{c:?}"));
} }
db.note( db.note(
"these kind of unicode codepoints change the way text flows on \ "these kind of unicode codepoints change the way text flows on \
@ -648,7 +646,7 @@ pub trait LintContext: Sized {
let opt_colon = let opt_colon =
if s.trim_start().starts_with("::") { "" } else { "::" }; if s.trim_start().starts_with("::") { "" } else { "::" };
(format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable) (format!("crate{opt_colon}{s}"), Applicability::MachineApplicable)
} }
Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders), Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
}; };
@ -704,7 +702,7 @@ pub trait LintContext: Sized {
let introduced = if is_imported { "imported" } else { "defined" }; let introduced = if is_imported { "imported" } else { "defined" };
db.span_label( db.span_label(
span, span,
format!("the item `{}` is already {} here", ident, introduced), format!("the item `{ident}` is already {introduced} here"),
); );
} }
} }
@ -908,7 +906,7 @@ pub trait LintContext: Sized {
BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => { BuiltinLintDiagnostics::NamedArgumentUsedPositionally{ position_sp_to_replace, position_sp_for_msg, named_arg_sp, named_arg_name, is_formatting_arg} => {
db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string"); db.span_label(named_arg_sp, "this named argument is referred to by position in formatting string");
if let Some(positional_arg_for_msg) = position_sp_for_msg { if let Some(positional_arg_for_msg) = position_sp_for_msg {
let msg = format!("this formatting argument uses named argument `{}` by position", named_arg_name); let msg = format!("this formatting argument uses named argument `{named_arg_name}` by position");
db.span_label(positional_arg_for_msg, msg); db.span_label(positional_arg_for_msg, msg);
} }
@ -949,11 +947,11 @@ pub trait LintContext: Sized {
); );
} }
BuiltinLintDiagnostics::AmbiguousGlobReexports { name, namespace, first_reexport_span, duplicate_reexport_span } => { BuiltinLintDiagnostics::AmbiguousGlobReexports { name, namespace, first_reexport_span, duplicate_reexport_span } => {
db.span_label(first_reexport_span, format!("the name `{}` in the {} namespace is first re-exported here", name, namespace)); db.span_label(first_reexport_span, format!("the name `{name}` in the {namespace} namespace is first re-exported here"));
db.span_label(duplicate_reexport_span, format!("but the name `{}` in the {} namespace is also re-exported here", name, namespace)); db.span_label(duplicate_reexport_span, format!("but the name `{name}` in the {namespace} namespace is also re-exported here"));
} }
BuiltinLintDiagnostics::HiddenGlobReexports { name, namespace, glob_reexport_span, private_item_span } => { BuiltinLintDiagnostics::HiddenGlobReexports { name, namespace, glob_reexport_span, private_item_span } => {
db.span_note(glob_reexport_span, format!("the name `{}` in the {} namespace is supposed to be publicly re-exported here", name, namespace)); db.span_note(glob_reexport_span, format!("the name `{name}` in the {namespace} namespace is supposed to be publicly re-exported here"));
db.span_note(private_item_span, "but the private item here shadows it".to_owned()); db.span_note(private_item_span, "but the private item here shadows it".to_owned());
} }
BuiltinLintDiagnostics::UnusedQualifications { removal_span } => { BuiltinLintDiagnostics::UnusedQualifications { removal_span } => {
@ -1281,8 +1279,8 @@ impl<'tcx> LateContext<'tcx> {
// This shouldn't ever be needed, but just in case: // This shouldn't ever be needed, but just in case:
with_no_trimmed_paths!({ with_no_trimmed_paths!({
Ok(vec![match trait_ref { Ok(vec![match trait_ref {
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)), Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")),
None => Symbol::intern(&format!("<{}>", self_ty)), None => Symbol::intern(&format!("<{self_ty}>")),
}]) }])
}) })
} }
@ -1306,7 +1304,7 @@ impl<'tcx> LateContext<'tcx> {
))) )))
} }
None => { None => {
with_no_trimmed_paths!(Symbol::intern(&format!("<impl {}>", self_ty))) with_no_trimmed_paths!(Symbol::intern(&format!("<impl {self_ty}>")))
} }
}); });

View file

@ -945,7 +945,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
); );
} }
} else { } else {
panic!("renamed lint does not exist: {}", new_name); panic!("renamed lint does not exist: {new_name}");
} }
} }
} }

View file

@ -776,7 +776,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagLabels {
) -> rustc_errors::SubdiagnosticMessage, ) -> rustc_errors::SubdiagnosticMessage,
{ {
for (c, span) in self.spans { for (c, span) in self.spans {
diag.span_label(span, format!("{:?}", c)); diag.span_label(span, format!("{c:?}"));
} }
} }
} }
@ -808,7 +808,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
spans spans
.into_iter() .into_iter()
.map(|(c, span)| { .map(|(c, span)| {
let c = format!("{:?}", c); let c = format!("{c:?}");
(span, c[1..c.len() - 1].to_string()) (span, c[1..c.len() - 1].to_string())
}) })
.collect(), .collect(),
@ -823,7 +823,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
"escaped", "escaped",
spans spans
.into_iter() .into_iter()
.map(|(c, _)| format!("{:?}", c)) .map(|(c, _)| format!("{c:?}"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "), .join(", "),
); );

View file

@ -414,7 +414,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
match path { match path {
MustUsePath::Suppressed => {} MustUsePath::Suppressed => {}
MustUsePath::Boxed(path) => { MustUsePath::Boxed(path) => {
let descr_pre = &format!("{}boxed ", descr_pre); let descr_pre = &format!("{descr_pre}boxed ");
emit_must_use_untranslated( emit_must_use_untranslated(
cx, cx,
path, path,
@ -426,7 +426,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
); );
} }
MustUsePath::Opaque(path) => { MustUsePath::Opaque(path) => {
let descr_pre = &format!("{}implementer{} of ", descr_pre, plural_suffix); let descr_pre = &format!("{descr_pre}implementer{plural_suffix} of ");
emit_must_use_untranslated( emit_must_use_untranslated(
cx, cx,
path, path,
@ -438,7 +438,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
); );
} }
MustUsePath::TraitObject(path) => { MustUsePath::TraitObject(path) => {
let descr_post = &format!(" trait object{}{}", plural_suffix, descr_post); let descr_post = &format!(" trait object{plural_suffix}{descr_post}");
emit_must_use_untranslated( emit_must_use_untranslated(
cx, cx,
path, path,
@ -451,7 +451,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
} }
MustUsePath::TupleElement(elems) => { MustUsePath::TupleElement(elems) => {
for (index, path) in elems { for (index, path) in elems {
let descr_post = &format!(" in tuple element {}", index); let descr_post = &format!(" in tuple element {index}");
emit_must_use_untranslated( emit_must_use_untranslated(
cx, cx,
path, path,
@ -464,7 +464,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
} }
} }
MustUsePath::Array(path, len) => { MustUsePath::Array(path, len) => {
let descr_pre = &format!("{}array{} of ", descr_pre, plural_suffix); let descr_pre = &format!("{descr_pre}array{plural_suffix} of ");
emit_must_use_untranslated( emit_must_use_untranslated(
cx, cx,
path, path,

View file

@ -74,7 +74,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
kind @ StmtKind::Let { pattern, .. } => { kind @ StmtKind::Let { pattern, .. } => {
return Err(ParseError { return Err(ParseError {
span: pattern.span, span: pattern.span,
item_description: format!("{:?}", kind), item_description: format!("{kind:?}"),
expected: "expression".to_string(), expected: "expression".to_string(),
}); });
} }

View file

@ -774,8 +774,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Not in a closure // Not in a closure
debug_assert!( debug_assert!(
local == ty::CAPTURE_STRUCT_LOCAL, local == ty::CAPTURE_STRUCT_LOCAL,
"Expected local to be Local(1), found {:?}", "Expected local to be Local(1), found {local:?}"
local
); );
// Not in a closure // Not in a closure
debug_assert!( debug_assert!(

View file

@ -1627,9 +1627,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// at least the first candidate ought to be tested // at least the first candidate ought to be tested
assert!( assert!(
total_candidate_count > candidates.len(), total_candidate_count > candidates.len(),
"{}, {:#?}", "{total_candidate_count}, {candidates:#?}"
total_candidate_count,
candidates
); );
debug!("tested_candidates: {}", total_candidate_count - candidates.len()); debug!("tested_candidates: {}", total_candidate_count - candidates.len());
debug!("untested_candidates: {}", candidates.len()); debug!("untested_candidates: {}", candidates.len());

View file

@ -175,16 +175,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
debug_assert_ne!( debug_assert_ne!(
target_blocks[idx.index()], target_blocks[idx.index()],
otherwise_block, otherwise_block,
"no candidates for tested discriminant: {:?}", "no candidates for tested discriminant: {discr:?}",
discr,
); );
Some((discr.val, target_blocks[idx.index()])) Some((discr.val, target_blocks[idx.index()]))
} else { } else {
debug_assert_eq!( debug_assert_eq!(
target_blocks[idx.index()], target_blocks[idx.index()],
otherwise_block, otherwise_block,
"found candidates for untested discriminant: {:?}", "found candidates for untested discriminant: {discr:?}",
discr,
); );
None None
} }

View file

@ -94,8 +94,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
|| body.basic_blocks.has_free_regions() || body.basic_blocks.has_free_regions()
|| body.var_debug_info.has_free_regions() || body.var_debug_info.has_free_regions()
|| body.yield_ty().has_free_regions()), || body.yield_ty().has_free_regions()),
"Unexpected free regions in MIR: {:?}", "Unexpected free regions in MIR: {body:?}",
body,
); );
body body
@ -977,9 +976,9 @@ pub(crate) fn parse_float_into_scalar(
match float_ty { match float_ty {
ty::FloatTy::F32 => { ty::FloatTy::F32 => {
let Ok(rust_f) = num.parse::<f32>() else { return None }; let Ok(rust_f) = num.parse::<f32>() else { return None };
let mut f = num.parse::<Single>().unwrap_or_else(|e| { let mut f = num
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e) .parse::<Single>()
}); .unwrap_or_else(|e| panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}"));
assert!( assert!(
u128::from(rust_f.to_bits()) == f.to_bits(), u128::from(rust_f.to_bits()) == f.to_bits(),
@ -1000,9 +999,9 @@ pub(crate) fn parse_float_into_scalar(
} }
ty::FloatTy::F64 => { ty::FloatTy::F64 => {
let Ok(rust_f) = num.parse::<f64>() else { return None }; let Ok(rust_f) = num.parse::<f64>() else { return None };
let mut f = num.parse::<Double>().unwrap_or_else(|e| { let mut f = num
panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e) .parse::<Double>()
}); .unwrap_or_else(|e| panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}"));
assert!( assert!(
u128::from(rust_f.to_bits()) == f.to_bits(), u128::from(rust_f.to_bits()) == f.to_bits(),

View file

@ -454,17 +454,13 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
if self.span.eq_ctxt(self.expr_span) { if self.span.eq_ctxt(self.expr_span) {
// Get the span for the empty match body `{}`. // Get the span for the empty match body `{}`.
let (indentation, more) = if let Some(snippet) = sm.indentation_before(self.span) { let (indentation, more) = if let Some(snippet) = sm.indentation_before(self.span) {
(format!("\n{}", snippet), " ") (format!("\n{snippet}"), " ")
} else { } else {
(" ".to_string(), "") (" ".to_string(), "")
}; };
suggestion = Some(( suggestion = Some((
self.span.shrink_to_hi().with_hi(self.expr_span.hi()), self.span.shrink_to_hi().with_hi(self.expr_span.hi()),
format!( format!(" {{{indentation}{more}_ => todo!(),{indentation}}}",),
" {{{indentation}{more}_ => todo!(),{indentation}}}",
indentation = indentation,
more = more,
),
)); ));
} }

View file

@ -229,9 +229,7 @@ impl<'tcx> Cx<'tcx> {
let param_env_ty = self.param_env.and(discr_ty); let param_env_ty = self.param_env.and(discr_ty);
let size = tcx let size = tcx
.layout_of(param_env_ty) .layout_of(param_env_ty)
.unwrap_or_else(|e| { .unwrap_or_else(|e| panic!("could not compute layout for {param_env_ty:?}: {e:?}"))
panic!("could not compute layout for {:?}: {:?}", param_env_ty, e)
})
.size; .size;
let lit = ScalarInt::try_from_uint(discr_offset as u128, size).unwrap(); let lit = ScalarInt::try_from_uint(discr_offset as u128, size).unwrap();

View file

@ -691,7 +691,7 @@ fn non_exhaustive_match<'p, 'tcx>(
err = create_e0004( err = create_e0004(
cx.tcx.sess, cx.tcx.sess,
sp, sp,
format!("non-exhaustive patterns: {} not covered", joined_patterns), format!("non-exhaustive patterns: {joined_patterns} not covered"),
); );
err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns)); err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
patterns_len = witnesses.len(); patterns_len = witnesses.len();
@ -721,15 +721,13 @@ fn non_exhaustive_match<'p, 'tcx>(
&& matches!(witnesses[0].ctor(), Constructor::NonExhaustive) && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
{ {
err.note(format!( err.note(format!(
"`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \ "`{scrut_ty}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
exhaustively", exhaustively",
scrut_ty,
)); ));
if cx.tcx.sess.is_nightly_build() { if cx.tcx.sess.is_nightly_build() {
err.help(format!( err.help(format!(
"add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \ "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
enable precise `{}` matching", enable precise `{scrut_ty}` matching",
scrut_ty,
)); ));
} }
} }
@ -745,18 +743,13 @@ fn non_exhaustive_match<'p, 'tcx>(
[] if sp.eq_ctxt(expr_span) => { [] if sp.eq_ctxt(expr_span) => {
// Get the span for the empty match body `{}`. // Get the span for the empty match body `{}`.
let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) { let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
(format!("\n{}", snippet), " ") (format!("\n{snippet}"), " ")
} else { } else {
(" ".to_string(), "") (" ".to_string(), "")
}; };
suggestion = Some(( suggestion = Some((
sp.shrink_to_hi().with_hi(expr_span.hi()), sp.shrink_to_hi().with_hi(expr_span.hi()),
format!( format!(" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",),
" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
indentation = indentation,
more = more,
pattern = pattern,
),
)); ));
} }
[only] => { [only] => {
@ -765,7 +758,7 @@ fn non_exhaustive_match<'p, 'tcx>(
&& let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',') && let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
&& sm.is_multiline(with_trailing) && sm.is_multiline(with_trailing)
{ {
(format!("\n{}", snippet), true) (format!("\n{snippet}"), true)
} else { } else {
(" ".to_string(), false) (" ".to_string(), false)
}; };
@ -780,7 +773,7 @@ fn non_exhaustive_match<'p, 'tcx>(
}; };
suggestion = Some(( suggestion = Some((
only.span.shrink_to_hi(), only.span.shrink_to_hi(),
format!("{}{}{} => todo!()", comma, pre_indentation, pattern), format!("{comma}{pre_indentation}{pattern} => todo!()"),
)); ));
} }
[.., prev, last] => { [.., prev, last] => {
@ -803,7 +796,7 @@ fn non_exhaustive_match<'p, 'tcx>(
if let Some(spacing) = spacing { if let Some(spacing) = spacing {
suggestion = Some(( suggestion = Some((
last.span.shrink_to_hi(), last.span.shrink_to_hi(),
format!("{}{}{} => todo!()", comma, spacing, pattern), format!("{comma}{spacing}{pattern} => todo!()"),
)); ));
} }
} }
@ -900,7 +893,7 @@ fn adt_defined_here<'p, 'tcx>(
for pat in spans { for pat in spans {
span.push_span_label(pat, "not covered"); span.push_span_label(pat, "not covered");
} }
err.span_note(span, format!("`{}` defined here", ty)); err.span_note(span, format!("`{ty}` defined here"));
} }
} }

View file

@ -306,9 +306,9 @@ impl fmt::Debug for IntRange {
let (lo, hi) = self.boundaries(); let (lo, hi) = self.boundaries();
let bias = self.bias; let bias = self.bias;
let (lo, hi) = (lo ^ bias, hi ^ bias); let (lo, hi) = (lo ^ bias, hi ^ bias);
write!(f, "{}", lo)?; write!(f, "{lo}")?;
write!(f, "{}", RangeEnd::Included)?; write!(f, "{}", RangeEnd::Included)?;
write!(f, "{}", hi) write!(f, "{hi}")
} }
} }
@ -1619,7 +1619,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
// of `std`). So this branch is only reachable when the feature is enabled and // of `std`). So this branch is only reachable when the feature is enabled and
// the pattern is a box pattern. // the pattern is a box pattern.
let subpattern = self.iter_fields().next().unwrap(); let subpattern = self.iter_fields().next().unwrap();
write!(f, "box {:?}", subpattern) write!(f, "box {subpattern:?}")
} }
ty::Adt(..) | ty::Tuple(..) => { ty::Adt(..) | ty::Tuple(..) => {
let variant = match self.ty.kind() { let variant = match self.ty.kind() {
@ -1638,7 +1638,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
write!(f, "(")?; write!(f, "(")?;
for p in self.iter_fields() { for p in self.iter_fields() {
write!(f, "{}", start_or_comma())?; write!(f, "{}", start_or_comma())?;
write!(f, "{:?}", p)?; write!(f, "{p:?}")?;
} }
write!(f, ")") write!(f, ")")
} }
@ -1674,11 +1674,11 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
write!(f, "]") write!(f, "]")
} }
&FloatRange(lo, hi, end) => { &FloatRange(lo, hi, end) => {
write!(f, "{}", lo)?; write!(f, "{lo}")?;
write!(f, "{}", end)?; write!(f, "{end}")?;
write!(f, "{}", hi) write!(f, "{hi}")
} }
IntRange(range) => write!(f, "{:?}", range), // Best-effort, will render e.g. `false` as `0..=0` IntRange(range) => write!(f, "{range:?}"), // Best-effort, will render e.g. `false` as `0..=0`
Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty), Wildcard | Missing { .. } | NonExhaustive => write!(f, "_ : {:?}", self.ty),
Or => { Or => {
for pat in self.iter_fields() { for pat in self.iter_fields() {
@ -1686,7 +1686,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
} }
Ok(()) Ok(())
} }
Str(value) => write!(f, "{}", value), Str(value) => write!(f, "{value}"),
Opaque => write!(f, "<constant pattern>"), Opaque => write!(f, "<constant pattern>"),
} }
} }

View file

@ -459,7 +459,7 @@ impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "+")?; write!(f, "+")?;
for pat in self.iter() { for pat in self.iter() {
write!(f, " {:?} +", pat)?; write!(f, " {pat:?} +")?;
} }
Ok(()) Ok(())
} }
@ -530,7 +530,7 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
let Matrix { patterns: m, .. } = self; let Matrix { patterns: m, .. } = self;
let pretty_printed_matrix: Vec<Vec<String>> = let pretty_printed_matrix: Vec<Vec<String>> =
m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect(); m.iter().map(|row| row.iter().map(|pat| format!("{pat:?}")).collect()).collect();
let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0); let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
assert!(m.iter().all(|row| row.len() == column_count)); assert!(m.iter().all(|row| row.len() == column_count));

View file

@ -282,7 +282,7 @@ impl<'a> BcbCounters<'a> {
branching_counter_operand, branching_counter_operand,
Op::Subtract, Op::Subtract,
sumup_counter_operand, sumup_counter_operand,
|| Some(format!("{:?}", expression_branch)), || Some(format!("{expression_branch:?}")),
); );
debug!("{:?} gets an expression: {}", expression_branch, self.format_counter(&expression)); debug!("{:?} gets an expression: {}", expression_branch, self.format_counter(&expression));
let bcb = expression_branch.target_bcb; let bcb = expression_branch.target_bcb;
@ -324,7 +324,7 @@ impl<'a> BcbCounters<'a> {
// program results in a tight infinite loop, but it should still compile. // program results in a tight infinite loop, but it should still compile.
let one_path_to_target = self.bcb_has_one_path_to_target(bcb); let one_path_to_target = self.bcb_has_one_path_to_target(bcb);
if one_path_to_target || self.bcb_predecessors(bcb).contains(&bcb) { if one_path_to_target || self.bcb_predecessors(bcb).contains(&bcb) {
let counter_kind = self.coverage_counters.make_counter(|| Some(format!("{:?}", bcb))); let counter_kind = self.coverage_counters.make_counter(|| Some(format!("{bcb:?}")));
if one_path_to_target { if one_path_to_target {
debug!( debug!(
"{}{:?} gets a new counter: {}", "{}{:?} gets a new counter: {}",
@ -392,7 +392,7 @@ impl<'a> BcbCounters<'a> {
first_edge_counter_operand, first_edge_counter_operand,
Op::Add, Op::Add,
some_sumup_edge_counter_operand.unwrap(), some_sumup_edge_counter_operand.unwrap(),
|| Some(format!("{:?}", bcb)), || Some(format!("{bcb:?}")),
); );
debug!( debug!(
"{}{:?} gets a new counter (sum of predecessor counters): {}", "{}{:?} gets a new counter (sum of predecessor counters): {}",
@ -449,7 +449,7 @@ impl<'a> BcbCounters<'a> {
// Make a new counter to count this edge. // Make a new counter to count this edge.
let counter_kind = let counter_kind =
self.coverage_counters.make_counter(|| Some(format!("{:?}->{:?}", from_bcb, to_bcb))); self.coverage_counters.make_counter(|| Some(format!("{from_bcb:?}->{to_bcb:?}")));
debug!( debug!(
"{}Edge {:?}->{:?} gets a new counter: {}", "{}Edge {:?}->{:?} gets a new counter: {}",
NESTED_INDENT.repeat(debug_indent_level), NESTED_INDENT.repeat(debug_indent_level),

View file

@ -630,7 +630,7 @@ pub(super) fn dump_coverage_spanview<'tcx>(
.expect("Unexpected error creating MIR spanview HTML file"); .expect("Unexpected error creating MIR spanview HTML file");
let crate_name = tcx.crate_name(def_id.krate); let crate_name = tcx.crate_name(def_id.krate);
let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate(); let item_name = tcx.def_path(def_id).to_filename_friendly_no_crate();
let title = format!("{}.{} - Coverage Spans", crate_name, item_name); let title = format!("{crate_name}.{item_name} - Coverage Spans");
spanview::write_document(tcx, body_span, span_viewables, &title, &mut file) spanview::write_document(tcx, body_span, span_viewables, &title, &mut file)
.expect("Unexpected IO error dumping coverage spans as HTML"); .expect("Unexpected IO error dumping coverage spans as HTML");
} }
@ -779,7 +779,7 @@ fn bcb_to_string_sections<'tcx>(
)); ));
} }
if let Some(counter_kind) = &bcb_data.counter_kind { if let Some(counter_kind) = &bcb_data.counter_kind {
sections.push(format!("{:?}", counter_kind)); sections.push(format!("{counter_kind:?}"));
} }
let non_term_blocks = bcb_data.basic_blocks[0..len - 1] let non_term_blocks = bcb_data.basic_blocks[0..len - 1]
.iter() .iter()

View file

@ -360,8 +360,7 @@ impl BasicCoverageBlockData {
if let Some(replaced) = self.counter_kind.replace(counter_kind) { if let Some(replaced) = self.counter_kind.replace(counter_kind) {
Error::from_string(format!( Error::from_string(format!(
"attempt to set a BasicCoverageBlock coverage counter more than once; \ "attempt to set a BasicCoverageBlock coverage counter more than once; \
{:?} already had counter {:?}", {self:?} already had counter {replaced:?}",
self, replaced,
)) ))
} else { } else {
Ok(operand) Ok(operand)
@ -389,9 +388,8 @@ impl BasicCoverageBlockData {
// `BasicCoverageBlock`). // `BasicCoverageBlock`).
if self.counter_kind.as_ref().is_some_and(|c| !c.is_expression()) { if self.counter_kind.as_ref().is_some_and(|c| !c.is_expression()) {
return Error::from_string(format!( return Error::from_string(format!(
"attempt to add an incoming edge counter from {:?} when the target BCB already \ "attempt to add an incoming edge counter from {from_bcb:?} when the target BCB already \
has a `Counter`", has a `Counter`"
from_bcb
)); ));
} }
} }
@ -401,8 +399,7 @@ impl BasicCoverageBlockData {
{ {
Error::from_string(format!( Error::from_string(format!(
"attempt to set an edge counter more than once; from_bcb: \ "attempt to set an edge counter more than once; from_bcb: \
{:?} already had counter {:?}", {from_bcb:?} already had counter {replaced:?}",
from_bcb, replaced,
)) ))
} else { } else {
Ok(operand) Ok(operand)
@ -612,7 +609,7 @@ impl TraverseCoverageGraphWithLoops {
the {}", the {}",
successor_to_add, successor_to_add,
if let Some(loop_header) = some_loop_header { if let Some(loop_header) = some_loop_header {
format!("worklist for the loop headed by {:?}", loop_header) format!("worklist for the loop headed by {loop_header:?}")
} else { } else {
String::from("non-loop worklist") String::from("non-loop worklist")
}, },
@ -623,7 +620,7 @@ impl TraverseCoverageGraphWithLoops {
"{:?} successor is non-branching. Defer it to the end of the {}", "{:?} successor is non-branching. Defer it to the end of the {}",
successor_to_add, successor_to_add,
if let Some(loop_header) = some_loop_header { if let Some(loop_header) = some_loop_header {
format!("worklist for the loop headed by {:?}", loop_header) format!("worklist for the loop headed by {loop_header:?}")
} else { } else {
String::from("non-loop worklist") String::from("non-loop worklist")
}, },

View file

@ -358,8 +358,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
terminator.source_info.span, terminator.source_info.span,
format!( format!(
"drop of untracked, uninitialized value {:?}, place {:?} ({:?})", "drop of untracked, uninitialized value {bb:?}, place {place:?} ({path:?})"
bb, place, path
), ),
); );
} }
@ -424,7 +423,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
if !replace { if !replace {
self.tcx.sess.delay_span_bug( self.tcx.sess.delay_span_bug(
terminator.source_info.span, terminator.source_info.span,
format!("drop of untracked value {:?}", bb), format!("drop of untracked value {bb:?}"),
); );
} }
// A drop and replace behind a pointer/array/whatever. // A drop and replace behind a pointer/array/whatever.

View file

@ -168,15 +168,15 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
} }
}; };
let ident = self.tcx.item_name(fn_id).to_ident_string(); let ident = self.tcx.item_name(fn_id).to_ident_string();
let ty_params = fn_args.types().map(|ty| format!("{}", ty)); let ty_params = fn_args.types().map(|ty| format!("{ty}"));
let const_params = fn_args.consts().map(|c| format!("{}", c)); let const_params = fn_args.consts().map(|c| format!("{c}"));
let params = ty_params.chain(const_params).join(", "); let params = ty_params.chain(const_params).join(", ");
let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
let sugg = format!( let sugg = format!(
"{} as {}{}fn({}{}){}", "{} as {}{}fn({}{}){}",
if params.is_empty() { ident.clone() } else { format!("{}::<{}>", ident, params) }, if params.is_empty() { ident.clone() } else { format!("{ident}::<{params}>") },
unsafety, unsafety,
abi, abi,
vec!["_"; num_args].join(", "), vec!["_"; num_args].join(", "),

View file

@ -1477,7 +1477,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform {
) )
} }
_ => { _ => {
tcx.sess.delay_span_bug(body.span, format!("unexpected generator type {}", gen_ty)); tcx.sess.delay_span_bug(body.span, format!("unexpected generator type {gen_ty}"));
return; return;
} }
}; };

View file

@ -57,7 +57,7 @@ struct InstSimplifyContext<'tcx, 'a> {
impl<'tcx> InstSimplifyContext<'tcx, '_> { impl<'tcx> InstSimplifyContext<'tcx, '_> {
fn should_simplify(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool { fn should_simplify(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool {
self.tcx.consider_optimizing(|| { self.tcx.consider_optimizing(|| {
format!("InstSimplify - Rvalue: {:?} SourceInfo: {:?}", rvalue, source_info) format!("InstSimplify - Rvalue: {rvalue:?} SourceInfo: {source_info:?}")
}) })
} }

View file

@ -615,7 +615,7 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> {
// computes and caches its result. // computes and caches its result.
Some(hir::ConstContext::ConstFn) => tcx.ensure_with_value().mir_for_ctfe(did), Some(hir::ConstContext::ConstFn) => tcx.ensure_with_value().mir_for_ctfe(did),
None => {} None => {}
Some(other) => panic!("do not use `optimized_mir` for constants: {:?}", other), Some(other) => panic!("do not use `optimized_mir` for constants: {other:?}"),
} }
debug!("about to call mir_drops_elaborated..."); debug!("about to call mir_drops_elaborated...");
let body = tcx.mir_drops_elaborated_and_const_checked(did).steal(); let body = tcx.mir_drops_elaborated_and_const_checked(did).steal();

View file

@ -51,7 +51,7 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification {
let bbs = body.basic_blocks.as_mut(); let bbs = body.basic_blocks.as_mut();
let mut should_cleanup = false; let mut should_cleanup = false;
'outer: for bb_idx in bbs.indices() { 'outer: for bb_idx in bbs.indices() {
if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {:?} ", def_id)) { if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {def_id:?} ")) {
continue; continue;
} }

View file

@ -27,7 +27,7 @@ impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators {
} }
for bb in bbs { for bb in bbs {
if !tcx.consider_optimizing(|| format!("MultipleReturnTerminators {:?} ", def_id)) { if !tcx.consider_optimizing(|| format!("MultipleReturnTerminators {def_id:?} ")) {
break; break;
} }

View file

@ -45,7 +45,7 @@ impl<'tcx> MirPass<'tcx> for RenameReturnPlace {
return; return;
}; };
if !tcx.consider_optimizing(|| format!("RenameReturnPlace {:?}", def_id)) { if !tcx.consider_optimizing(|| format!("RenameReturnPlace {def_id:?}")) {
return; return;
} }

View file

@ -118,7 +118,7 @@ fn run_passes_inner<'tcx>(
dump_mir_for_pass(tcx, body, &name, false); dump_mir_for_pass(tcx, body, &name, false);
} }
if validate { if validate {
validate_body(tcx, body, format!("before pass {}", name)); validate_body(tcx, body, format!("before pass {name}"));
} }
tcx.sess.time(name, || pass.run_pass(tcx, body)); tcx.sess.time(name, || pass.run_pass(tcx, body));
@ -127,7 +127,7 @@ fn run_passes_inner<'tcx>(
dump_mir_for_pass(tcx, body, &name, true); dump_mir_for_pass(tcx, body, &name, true);
} }
if validate { if validate {
validate_body(tcx, body, format!("after pass {}", name)); validate_body(tcx, body, format!("after pass {name}"));
} }
body.pass_count += 1; body.pass_count += 1;

View file

@ -27,7 +27,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUnneededDrops {
if ty.ty.needs_drop(tcx, param_env) { if ty.ty.needs_drop(tcx, param_env) {
continue; continue;
} }
if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {:?} ", did)) { if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {did:?} ")) {
continue; continue;
} }
debug!("SUCCESS: replacing `drop` with goto({:?})", target); debug!("SUCCESS: replacing `drop` with goto({:?})", target);

View file

@ -102,7 +102,7 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> {
let op_ty = operand.ty(self.local_decls, self.tcx); let op_ty = operand.ty(self.local_decls, self.tcx);
if self.known_to_be_zst(op_ty) if self.known_to_be_zst(op_ty)
&& self.tcx.consider_optimizing(|| { && self.tcx.consider_optimizing(|| {
format!("RemoveZsts - Operand: {:?} Location: {:?}", operand, loc) format!("RemoveZsts - Operand: {operand:?} Location: {loc:?}")
}) })
{ {
*operand = Operand::Constant(Box::new(self.make_zst(op_ty))) *operand = Operand::Constant(Box::new(self.make_zst(op_ty)))

View file

@ -157,10 +157,8 @@ impl<'tcx> CheckConstVisitor<'tcx> {
// is a pretty narrow case, however. // is a pretty narrow case, however.
if tcx.sess.is_nightly_build() { if tcx.sess.is_nightly_build() {
for gate in missing_secondary { for gate in missing_secondary {
let note = format!( let note =
"add `#![feature({})]` to the crate attributes to enable", format!("add `#![feature({gate})]` to the crate attributes to enable",);
gate,
);
err.help(note); err.help(note);
} }
} }

View file

@ -89,9 +89,8 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
self.error(|| { self.error(|| {
format!( format!(
"ItemLocalIds not assigned densely in {}. \ "ItemLocalIds not assigned densely in {pretty_owner}. \
Max ItemLocalId = {}, missing IDs = {:#?}; seen IDs = {:#?}", Max ItemLocalId = {max}, missing IDs = {missing_items:#?}; seen IDs = {seen_items:#?}"
pretty_owner, max, missing_items, seen_items
) )
}); });
} }

View file

@ -126,12 +126,12 @@ impl<'k> StatCollector<'k> {
let total_size = nodes.iter().map(|(_, node)| node.stats.count * node.stats.size).sum(); let total_size = nodes.iter().map(|(_, node)| node.stats.count * node.stats.size).sum();
eprintln!("{} {}", prefix, title); eprintln!("{prefix} {title}");
eprintln!( eprintln!(
"{} {:<18}{:>18}{:>14}{:>14}", "{} {:<18}{:>18}{:>14}{:>14}",
prefix, "Name", "Accumulated Size", "Count", "Item Size" prefix, "Name", "Accumulated Size", "Count", "Item Size"
); );
eprintln!("{} ----------------------------------------------------------------", prefix); eprintln!("{prefix} ----------------------------------------------------------------");
let percent = |m, n| (m * 100) as f64 / n as f64; let percent = |m, n| (m * 100) as f64 / n as f64;
@ -163,9 +163,9 @@ impl<'k> StatCollector<'k> {
} }
} }
} }
eprintln!("{} ----------------------------------------------------------------", prefix); eprintln!("{prefix} ----------------------------------------------------------------");
eprintln!("{} {:<18}{:>10}", prefix, "Total", to_readable_str(total_size)); eprintln!("{} {:<18}{:>10}", prefix, "Total", to_readable_str(total_size));
eprintln!("{}", prefix); eprintln!("{prefix}");
} }
} }

View file

@ -605,7 +605,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
for var_idx in 0..self.ir.var_kinds.len() { for var_idx in 0..self.ir.var_kinds.len() {
let var = Variable::from(var_idx); let var = Variable::from(var_idx);
if test(var) { if test(var) {
write!(wr, " {:?}", var)?; write!(wr, " {var:?}")?;
} }
} }
Ok(()) Ok(())

View file

@ -133,7 +133,7 @@ where
_ => { _ => {
tcx.sess.delay_span_bug( tcx.sess.delay_span_bug(
tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP), tcx.hir().span_if_local(def_id).unwrap_or(DUMMY_SP),
format!("unexpected generator witness type {:?}", witness), format!("unexpected generator witness type {witness:?}"),
); );
return Some(Err(AlwaysRequiresDrop)); return Some(Err(AlwaysRequiresDrop));
} }