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

View File

@ -360,7 +360,7 @@ impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, 'tcx> {
return;
}
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);

View File

@ -653,7 +653,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_suggestion_verbose(
sugg_span.shrink_to_hi(),
"consider assigning a value",
format!(" = {}", assign_value),
format!(" = {assign_value}"),
Applicability::MaybeIncorrect,
);
}
@ -738,7 +738,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// Try to find predicates on *generic params* that would allow copying `ty`
let suggestion =
if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) {
format!(": {}.clone()", symbol)
format!(": {symbol}.clone()")
} else {
".clone()".to_owned()
};
@ -1162,8 +1162,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
if union_type_name != "" {
err.note(format!(
"{} is a field of the union `{}`, so it overlaps the field {}",
msg_place, union_type_name, msg_borrow,
"{msg_place} is a field of the union `{union_type_name}`, so it overlaps the field {msg_borrow}",
));
}
@ -1353,8 +1352,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let Some(trait_did) = tcx.trait_of_item(def_id) &&
tcx.is_diagnostic_item(sym::Iterator, trait_did) {
err.note(format!(
"a for loop advances the iterator for you, the result is stored in `{}`.",
loop_bind
"a for loop advances the iterator for you, the result is stored in `{loop_bind}`."
));
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),
var_or_use_span,
&format!("`{}`", name),
&format!("`{name}`"),
"block",
),
(
@ -1847,7 +1845,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
region_name,
category,
span,
&format!("`{}`", name),
&format!("`{name}`"),
"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) {
let region_name = annotation.emit(self, &mut err);
err.span_label(
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(
@ -1939,7 +1937,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
self.infcx
.tcx
.opt_item_name(self.mir_def_id().to_def_id())
.map(|name| format!("function `{}`", name))
.map(|name| format!("function `{name}`"))
.unwrap_or_else(|| {
match &self.infcx.tcx.def_kind(self.mir_def_id()) {
DefKind::Closure => "enclosing closure",
@ -1974,7 +1972,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
} else {
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| {
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 what_was_dropped = match self.describe_place(place.as_ref()) {
Some(name) => format!("`{}`", name),
Some(name) => format!("`{name}`"),
None => String::from("temporary value"),
};
let label = match self.describe_place(borrow.borrowed_place.as_ref()) {
Some(borrowed) => format!(
"here, drop of {D} needs exclusive access to `{B}`, \
because the type `{T}` implements the `Drop` trait",
D = what_was_dropped,
T = dropped_ty,
B = borrowed
"here, drop of {what_was_dropped} needs exclusive access to `{borrowed}`, \
because the type `{dropped_ty}` implements the `Drop` trait"
),
None => format!(
"here is drop of {D}; whose type `{T}` implements the `Drop` trait",
D = what_was_dropped,
T = dropped_ty
"here is drop of {what_was_dropped}; whose type `{dropped_ty}` implements the `Drop` trait"
),
};
err.span_label(drop_span, label);
@ -2245,10 +2238,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
} else {
"local data "
};
(
format!("{}`{}`", local_kind, place_desc),
format!("`{}` is borrowed here", place_desc),
)
(format!("{local_kind}`{place_desc}`"), format!("`{place_desc}` is borrowed here"))
} else {
let root_place =
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(
sugg_span,
format!(
"to force the {} to take ownership of {} (and any \
other referenced variables), use the `move` keyword",
kind, captured_var
"to force the {kind} to take ownership of {captured_var} (and any \
other referenced variables), use the `move` keyword"
),
suggestion,
Applicability::MachineApplicable,
@ -2360,7 +2349,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
match category {
ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
let msg = format!("{} is returned here", kind);
let msg = format!("{kind} is returned here");
err.span_note(constraint_span, msg);
}
ConstraintCategory::CallArgument(_) => {
@ -2402,21 +2391,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_label(
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 {
err.span_label(
escape_span,
format!("reference to `{}` escapes the {} body here", name, escapes_from),
format!("reference to `{name}` escapes the {escapes_from} body here"),
);
} else {
err.span_label(
escape_span,
format!("reference escapes the {} body here", escapes_from),
);
err.span_label(escape_span, format!("reference escapes the {escapes_from} body here"));
}
err
@ -2697,10 +2683,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
});
if let Some(Ok(instance)) = deref_target {
let deref_target_ty = instance.ty(tcx, self.param_env);
err.note(format!(
"borrow occurs due to deref coercion to `{}`",
deref_target_ty
));
err.note(format!("borrow occurs due to deref coercion to `{deref_target_ty}`"));
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"
};
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
&& let Some(name) = local_name
@ -2765,7 +2748,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
err.span_suggestion(
decl.source_info.span,
"consider making this binding mutable",
format!("mut {}", name),
format!("mut {name}"),
Applicability::MachineApplicable,
);
}
@ -3226,7 +3209,7 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
return_span,
} => {
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 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.
let region_name = cx.get_region_name_for_ty(*return_ty, 0);
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!(
"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",
region_name,
));
region_name

View File

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

View File

@ -347,7 +347,7 @@ pub(super) fn dump_mir_results<'tcx>(
for_each_region_constraint(
infcx.tcx,
closure_region_requirements,
&mut |msg| writeln!(out, "| {}", msg),
&mut |msg| writeln!(out, "| {msg}"),
)?;
writeln!(out, "|")?;
}
@ -426,7 +426,7 @@ pub(super) fn dump_annotation<'tcx>(
};
if !opaque_type_values.is_empty() {
err.note(format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
err.note(format!("Inferred opaque type values:\n{opaque_type_values:#?}"));
}
errors.buffer_non_error_diag(err);
@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>(
) -> io::Result<()> {
for req in &closure_region_requirements.outlives_requirements {
let subject = match req.subject {
ClosureOutlivesSubject::Region(subject) => format!("{:?}", subject),
ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
ClosureOutlivesSubject::Ty(ty) => {
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, "| Inference Constraints")?;
self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {}", msg))?;
self.for_each_constraint(tcx, &mut |msg| writeln!(out, "| {msg}"))?;
Ok(())
}
@ -69,7 +69,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
for region in self.definitions.indices() {
let value = self.liveness_constraints.region_value_str(region);
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) => {
("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!(
"{:?}: {:?} due to {:?} at {}({}) ({:?}",
sup, sub, category, name, arg, span
))?;
with_msg(&format!("{sup:?}: {sub:?} due to {category:?} at {name}({arg}) ({span:?}"))?;
}
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")))
}
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> {
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> {
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();
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);

View File

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

View File

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

View File

@ -52,7 +52,7 @@ fn eval_body_using_ecx<'mir, 'tcx>(
trace!(
"eval_body_using_ecx: pushing stack frame for global: {}{}",
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(

View File

@ -55,7 +55,7 @@ fn slice_branches<'tcx>(
place: &MPlaceTy<'tcx>,
num_nodes: &mut usize,
) -> 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);
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 {
Place::Local { frame, local, offset } => {
let mut allocs = Vec::new();
write!(fmt, "{:?}", local)?;
write!(fmt, "{local:?}")?;
if let Some(offset) = offset {
write!(fmt, "+{:#x}", offset.bytes())?;
}
@ -1035,7 +1035,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
fmt,
" by {} ref {:?}:",
match mplace.meta {
MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
MemPlaceMeta::Meta(meta) => format!(" meta({meta:?})"),
MemPlaceMeta::None => String::new(),
},
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));
}
LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
write!(fmt, " {:?}", val)?;
write!(fmt, " {val:?}")?;
if let Scalar::Ptr(ptr, _size) = val {
allocs.push(ptr.provenance.get_alloc_id());
}
}
LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
write!(fmt, " ({:?}, {:?})", val1, val2)?;
write!(fmt, " ({val1:?}, {val2:?})")?;
if let Scalar::Ptr(ptr, _size) = val1 {
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) => {
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
// error message.
_ if layout.abi.is_uninhabited() => format!(
"aborted execution: attempted to instantiate uninhabited type `{}`",
ty
"aborted execution: attempted to instantiate uninhabited type `{ty}`"
),
ValidityRequirement::Inhabited => bug!("handled earlier"),
ValidityRequirement::Zero => format!(
"aborted execution: attempted to zero-initialize type `{}`, which is invalid",
ty
"aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
),
ValidityRequirement::UninitMitigated0x01Fill => format!(
"aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
ty
"aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
),
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!(
index < dest_len,
"Index `{}` must be in bounds of vector with length {}",
index,
dest_len
"Index `{index}` must be in bounds of vector with length {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])?;
assert!(
index < input_len,
"index `{}` must be in bounds of vector with length {}",
index,
input_len
"index `{index}` must be in bounds of vector with length {input_len}"
);
self.copy_op(
&self.project_index(&input, index)?,

View File

@ -53,7 +53,7 @@ impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
match self {
MemoryKind::Stack => write!(f, "stack variable"),
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) {
Some((kind, alloc)) => {
// normal alloc
write!(fmt, " ({}, ", kind)?;
write!(fmt, " ({kind}, ")?;
write_allocation_track_relocs(
&mut *fmt,
*self.ecx.tcx,

View File

@ -24,8 +24,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
debug_assert_eq!(
Ty::new_tup(self.tcx.tcx, &[ty, self.tcx.types.bool]),
dest.layout.ty,
"type mismatch for result of {:?}",
op,
"type mismatch for result of {op:?}",
);
// Write the result to `dest`.
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>,
) -> InterpResult<'tcx> {
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)
}
}

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.
let val = self.read_immediate(&self.eval_operand(operand, Some(dest.layout))?)?;
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)?;
}

View File

@ -164,14 +164,14 @@ fn write_path(out: &mut String, path: &[PathElem]) {
for elem in path.iter() {
match elem {
Field(name) => write!(out, ".{}", name),
Field(name) => write!(out, ".{name}"),
EnumTag => write!(out, ".<enum-tag>"),
Variant(name) => write!(out, ".<enum-variant({})>", name),
Variant(name) => write!(out, ".<enum-variant({name})>"),
GeneratorTag => write!(out, ".<generator-tag>"),
GeneratorState(idx) => write!(out, ".<generator-state({})>", idx.index()),
CapturedVar(name) => write!(out, ".<captured-var({})>", name),
TupleElem(idx) => write!(out, ".{}", idx),
ArrayElem(idx) => write!(out, "[{}]", idx),
CapturedVar(name) => write!(out, ".<captured-var({name})>"),
TupleElem(idx) => write!(out, ".{idx}"),
ArrayElem(idx) => write!(out, "[{idx}]"),
// `.<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
// 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() {
err.help(format!(
"add `#![feature({})]` to the crate attributes to enable",
feature,
"add `#![feature({feature})]` to the crate attributes to enable",
));
}
@ -346,10 +345,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
err.help("const-stable functions can only call other const-stable functions");
} else if ccx.tcx.sess.is_nightly_build() {
if let Some(feature) = feature {
err.help(format!(
"add `#![feature({})]` to the crate attributes to enable",
feature
));
err.help(format!("add `#![feature({feature})]` to the crate attributes to enable"));
}
}

View File

@ -149,7 +149,7 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> {
}
}
} 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(
Location { block: bb, statement_index: 0 },
format!(
"Cleanup control flow violation: Cycle involving edge {:?} -> {:?}",
bb, parent,
"Cleanup control flow violation: Cycle involving edge {bb:?} -> {parent:?}",
),
);
break;
@ -257,7 +256,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
if self.body.local_decls.get(local).is_none() {
self.fail(
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);
let locals_with_storage = self.storage_liveness.get();
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
// seem to fail to set their `MirPhase` correctly.
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) => {
@ -556,7 +555,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let ty = place.ty(&self.body.local_decls, self.tcx).ty;
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) => {
let index_ty = self.body.local_decls[index].ty;
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
@ -586,22 +585,21 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if base_ty.is_box() {
self.fail(
location,
format!("{:?} dereferenced after ElaborateBoxDerefs", base_ty),
format!("{base_ty:?} dereferenced after ElaborateBoxDerefs"),
)
}
}
ProjectionElem::Field(f, ty) => {
let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx);
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| {
if !this.mir_assign_valid_types(ty, f_ty) {
this.fail(
location,
format!(
"Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is `{:?}`",
place_ref, f, ty, f_ty
"Field projection `{place_ref:?}.{f:?}` specified type `{ty:?}`, but actual type is `{f_ty:?}`"
)
)
}
@ -649,7 +647,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let Some(layout) = gen_body.generator_layout() else {
self.fail(
location,
format!("No generator layout for {:?}", parent_ty),
format!("No generator layout for {parent_ty:?}"),
);
return;
};
@ -662,7 +660,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
let Some(f_ty) = layout.field_tys.get(local) else {
self.fail(
location,
format!("Out of bounds local {:?} for {:?}", local, parent_ty),
format!("Out of bounds local {local:?} for {parent_ty:?}"),
);
return;
};
@ -705,7 +703,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if debuginfo.references != 0 && place.projection.last() == Some(&PlaceElem::Deref) {
self.fail(
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() {
self.fail(
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(..))) {
@ -742,7 +740,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
&& cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo)
&& 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);
@ -802,7 +800,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
Offset => {
check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
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 => {
@ -867,13 +865,12 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
self.fail(
location,
format!(
"Cannot perform checked arithmetic on unequal types {:?} and {:?}",
a, b
"Cannot perform checked arithmetic on unequal types {a:?} and {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) => {
@ -1078,7 +1075,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if !ty.is_bool() {
self.fail(
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 {
self.fail(
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;
};
@ -1101,19 +1098,19 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
} else {
self.fail(
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;
};
// since CopyNonOverlapping is parametrized by 1 type,
// 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) {
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);
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, .. } => {
@ -1125,8 +1122,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
self.fail(
location,
format!(
"`SetDiscriminant` is only allowed on ADTs and generators, not {:?}",
pty
"`SetDiscriminant` is only allowed on ADTs and generators, not {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
// seem to fail to set their `MirPhase` correctly.
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(_)
@ -1174,7 +1170,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
if Scalar::<()>::try_from_uint(value, size).is_none() {
self.fail(
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(..) => {}
_ => self.fail(
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(
location,
format!(
"encountered non-boolean condition of type {} in `Assert` terminator",
cond_ty
"encountered non-boolean condition of type {cond_ty} in `Assert` terminator"
),
);
}

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()
}
@ -393,7 +393,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
.into_iter()
.map(|error| error.root_obligation.predicate)
.filter_map(format_pred)
.map(|(p, _)| format!("`{}`", p))
.map(|(p, _)| format!("`{p}`"))
.collect();
bounds.sort();
bounds.dedup();
@ -652,7 +652,7 @@ pub(crate) fn fn_trait_to_string(
}
.map(|s| {
// `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(),
_ => None,

View File

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

View File

@ -1128,7 +1128,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
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![];
for bound in bounds {
@ -1407,7 +1407,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
_ => {
let reported = if variant_resolution.is_some() {
// Variant in type position
let msg = format!("expected type, found variant `{}`", assoc_ident);
let msg = format!("expected type, found variant `{assoc_ident}`");
tcx.sess.span_err(span, msg)
} else if qself_ty.is_enum() {
let mut err = struct_span_err!(
@ -1438,12 +1438,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
} else {
err.span_label(
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()) {
err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
err.span_label(sp, format!("variant `{assoc_ident}` not found here"));
}
err.emit()
@ -2750,7 +2750,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
"an anonymous lifetime".to_string()
}
ty::BrNamed(_, name) => format!("lifetime `{}`", name),
ty::BrNamed(_, name) => format!("lifetime `{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(
span,
"consider spelling out the type instead",
name.unwrap_or_else(|| format!("{:?}", ty)),
name.unwrap_or_else(|| format!("{ty:?}")),
Applicability::MaybeIncorrect,
);
}
@ -797,7 +797,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) {
"replace the {} parameters with concrete {}{}",
kinds,
kinds_pl,
egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(),
egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
),
)
.emit();
@ -882,7 +882,7 @@ pub(super) fn check_specialization_validity<'tcx>(
} else {
tcx.sess.delay_span_bug(
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()
)
}
Type { .. } => format!("{} type parameter", prefix),
Type { .. } => format!("{prefix} type parameter"),
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`,
/// and in `library/core/src/intrinsics.rs`.
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_name = tcx.item_name(intrinsic_id);
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.
pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) {
let param = |n| {
let name = Symbol::intern(&format!("P{}", n));
let name = Symbol::intern(&format!("P{n}"));
Ty::new_param(tcx, n, name)
};

View File

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

View File

@ -214,7 +214,7 @@ fn missing_items_err(
trait_item,
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) {
missing_trait_item_label
.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 =
if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
err.note(format!(
"{} currently required to ensure that impls have maximum flexibility",
bound
"{bound} currently required to ensure that impls have maximum flexibility"
));
err.note(
"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);
if ty.has_infer() {
tcx.sess
.delay_span_bug(item.span, format!("inference variables in {:?}", ty));
.delay_span_bug(item.span, format!("inference variables in {ty:?}"));
// Just treat unresolved type expression as if it needs drop.
true
} else {
@ -1863,8 +1862,7 @@ fn report_bivariance(
if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
err.help(format!(
"if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
param_name
"if you intended `{param_name}` to be a const parameter, use `const {param_name}: usize` instead"
));
}
err.emit()

View File

@ -36,7 +36,7 @@ fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) {
}
let (path, _) = item.expect_use();
let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) {
format!("unused import: `{}`", snippet)
format!("unused import: `{snippet}`")
} else {
"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!(
"the trait `DispatchFromDyn` may only be implemented \
for a coercion between structures with the same \
definition; expected `{}`, found `{}`",
source_path, target_path,
definition; expected `{source_path}`, found `{target_path}`",
))
.emit();

View File

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

View File

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

View File

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

View File

@ -195,9 +195,9 @@ pub(crate) fn placeholder_type_error_diag<'tcx>(
sugg.push((arg.span, (*type_name).to_string()));
} 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)`.
sugg.push((span, format!(", {}", type_name)));
sugg.push((span, format!(", {type_name}")));
} 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>,
kind: &'static str,
) -> 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();
tcx.sess.create_err(errors::PlaceholderNotAllowedItemSignatures { spans, kind })
@ -425,10 +425,8 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> {
| hir::ItemKind::Union(_, generics) => {
let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
let (lt_sp, sugg) = match generics.params {
[] => (generics.span, format!("<{}>", lt_name)),
[bound, ..] => {
(bound.span.shrink_to_lo(), format!("{}, ", lt_name))
}
[] => (generics.span, format!("<{lt_name}>")),
[bound, ..] => (bound.span.shrink_to_lo(), format!("{lt_name}, ")),
};
mpart_sugg = Some(errors::AssociatedTypeTraitUninferredGenericParamsMultipartSuggestion {
fspan: lt_sp,
@ -1027,7 +1025,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
} else {
tcx.sess.span_err(
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
.source_map()
.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 });
}
};

View File

@ -2040,8 +2040,7 @@ fn is_late_bound_map(
tcx.sess.delay_span_bug(
*span,
format!(
"Incorrect generic arg count for alias {:?}",
alias_def
"Incorrect generic arg count for alias {alias_def:?}"
),
);
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 {
return Ty::new_error_with_message(tcx,
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
@ -197,14 +197,14 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> {
} else {
return Ty::new_error_with_message(tcx,
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,
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) {
err.span_suggestion(
span,
format!("provide a type for the {item}", item = kind),
format!("provide a type for the {kind}"),
format!("{colon} {ty}"),
Applicability::MachineApplicable,
);

View File

@ -216,7 +216,7 @@ impl<'a> IntoDiagnostic<'a> for MissingTypeParams {
"parameters",
self.missing_type_params
.iter()
.map(|n| format!("`{}`", n))
.map(|n| format!("`{n}`"))
.collect::<Vec<_>>()
.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.def_span(impl_def_id),
format!(
"potentially unconstrained type parameters weren't evaluated: {:?}",
impl_self_ty,
"potentially unconstrained type parameters weren't evaluated: {impl_self_ty:?}",
),
);
return;
@ -180,7 +179,7 @@ fn report_unused_parameter(tcx: TyCtxt<'_>, span: Span, kind: &str, name: Symbol
kind,
name
);
err.span_label(span, format!("unconstrained {} parameter", kind));
err.span_label(span, format!("unconstrained {kind} parameter"));
if kind == "const" {
err.note(
"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() {
let param = impl1_args[duplicate.0 as usize];
tcx.sess
.struct_span_err(span, format!("specializing impl repeats parameter `{}`", param))
.struct_span_err(span, format!("specializing impl repeats parameter `{param}`"))
.emit();
}
}
@ -523,7 +523,7 @@ fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc
}
_ => {
tcx.sess
.struct_span_err(span, format!("cannot specialize on predicate `{}`", predicate))
.struct_span_err(span, format!("cannot specialize on predicate `{predicate}`"))
.emit();
}
}

View File

@ -474,7 +474,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
verb
)
} 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;
// insert a suggestion of the form "Y<'a, 'b>"
let sugg = format!("<{}>", suggested_args);
let sugg = format!("<{suggested_args}>");
debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(
@ -624,7 +624,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg_suffix =
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);
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;
// insert a suggestion of the form "Y<T, U>"
let sugg = format!("<{}>", suggested_args);
let sugg = format!("<{suggested_args}>");
debug!("sugg: {:?}", sugg);
err.span_suggestion_verbose(
@ -682,7 +682,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let sugg_suffix =
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);
err.span_suggestion_verbose(sugg_span, msg, sugg, Applicability::HasPlaceholders);
@ -1024,7 +1024,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
.collect::<Vec<_>>()
.join(", ");
format!(": {}", params)
format!(": {params}")
};
format!(

View File

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

View File

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

View File

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

View File

@ -1890,7 +1890,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut truncated_fields_error = String::new();
let remaining_fields_names = match &displayable_field_names[..] {
[field1] => format!("`{}`", field1),
[field1] => format!("`{field1}`"),
[field1, field2] => format!("`{field1}` and `{field2}`"),
[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_suggestion_verbose(
expr_span,
format!(
"`{adt}` is a tuple {kind_name}, use the appropriate syntax",
adt = ty,
kind_name = kind_name,
),
format!("{adt}(/* fields */)", adt = ty),
format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
format!("{ty}(/* fields */)"),
Applicability::HasPlaceholders,
);
}
@ -2243,7 +2239,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// dynamic limit, to never omit just one field
let limit = if names.len() == 6 { 6 } else { 5 };
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 {
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);
let msg = format!("unreachable {}", kind);
let msg = format!("unreachable {kind}");
self.tcx().struct_span_lint_hir(
lint::builtin::UNREACHABLE_CODE,
id,
@ -134,7 +134,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
pub fn tag(&self) -> String {
format!("{:p}", self)
format!("{self:p}")
}
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(
span,
format!(
"instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
self_ty,
impl_ty,
"instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?",
),
);
}

View File

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

View File

@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let struct_pat_shorthand_field =
self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr);
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)
})
@ -558,7 +558,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.take(4)
.map(|(var_hir_id, upvar)| {
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)
})
.collect::<Vec<_>>();
@ -931,7 +931,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion(
fn_return.span(),
"consider using an impl return type",
format!("impl {}", all_bounds_str),
format!("impl {all_bounds_str}"),
Applicability::MaybeIncorrect,
);
}
@ -1070,7 +1070,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.must_apply_modulo_regions()
{
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()
};
@ -1259,7 +1259,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
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(),
};

View File

@ -125,8 +125,8 @@ impl Debug for TrackedValue {
write!(f, "{}", tcx.hir().node_to_string(self.hir_id()))
} else {
match self {
Self::Variable(hir_id) => write!(f, "Variable({:?})", hir_id),
Self::Temporary(hir_id) => write!(f, "Temporary({:?})", hir_id),
Self::Variable(hir_id) => write!(f, "Variable({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
.tcx
.sess
.delay_span_bug(span, format!("Encountered var {:?}", unresolved_term));
.delay_span_bug(span, format!("Encountered var {unresolved_term:?}"));
} else {
let note = format!(
"the type is part of the {} because of this {}",

View File

@ -85,7 +85,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
Ok(SizeSkeleton::Known(size)) => {
if let Some(v) = u128::from(size.bytes()).checked_mul(8) {
format!("{} bits", v)
format!("{v} bits")
} else {
// `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`

View File

@ -225,7 +225,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
assert!(mutbl.is_mut());
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 {
@ -262,8 +262,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
let impl_def_id = pick.item.container_id(self.tcx);
assert!(
self.tcx.impl_trait_ref(impl_def_id).is_none(),
"impl {:?} is not an inherent impl",
impl_def_id
"impl {impl_def_id:?} is not an inherent impl"
);
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) =
pick.autoref_or_ptr_adjustment
{
format!("{}{} as *const _", derefs, self_expr)
format!("{derefs}{self_expr} as *const _")
} else {
format!("{}{}{}", autoref, derefs, self_expr)
format!("{autoref}{derefs}{self_expr}")
};
lint.span_suggestion(
sp,
"disambiguate the method call",
format!("({})", self_adjusted),
format!("({self_adjusted})"),
Applicability::MachineApplicable,
);
} else {
let self_adjusted = if let Some(probe::AutorefOrPtrAdjustment::ToConstPtr) =
pick.autoref_or_ptr_adjustment
{
format!("{}(...) as *const _", derefs)
format!("{derefs}(...) as *const _")
} else {
format!("{}{}...", autoref, derefs)
format!("{autoref}{derefs}...")
};
lint.span_help(
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())
{
// Keep turbofish.
format!("::{}", args)
format!("::{args}")
} else {
String::new()
},
@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Glob import, so just use its name.
return None;
} 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) =
pick.autoref_or_ptr_adjustment
{
format!("{}{} as *const _", derefs, expr_text)
format!("{derefs}{expr_text} as *const _")
} else {
format!("{}{}{}", autoref, derefs, expr_text)
format!("{autoref}{derefs}{expr_text}")
};
(adjusted_text, precise)

View File

@ -153,7 +153,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
E0034,
"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(
rcvr_ty,
@ -177,13 +177,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
kind,
item_name
);
err.span_label(item_name.span, format!("private {}", kind));
err.span_label(item_name.span, format!("private {kind}"));
let sp = self
.tcx
.hir()
.span_if_local(def_id)
.unwrap_or_else(|| self.tcx.def_span(def_id));
err.span_label(sp, format!("private {} defined here", kind));
err.span_label(sp, format!("private {kind} defined here"));
self.suggest_valid_traits(&mut err, out_of_scope_traits);
err.emit();
}
@ -218,7 +218,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
*region,
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;
while let hir::ExprKind::AddrOf(_, _, expr)
| 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.
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 obligation = format!("{} = {}", projection_ty, term);
let obligation = format!("{projection_ty} = {term}");
let quiet = with_forced_trimmed_paths!(format!(
"{} = {}",
quiet_projection_ty, term
@ -672,7 +672,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let p = poly_trait_ref.trait_ref;
let self_ty = p.self_ty();
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));
bound_span_label(self_ty, &obligation, &quiet);
Some((obligation, self_ty))
@ -825,12 +825,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut preds: Vec<_> = predicates
.iter()
.filter_map(|pred| format_pred(**pred))
.map(|(p, _)| format!("`{}`", p))
.map(|(p, _)| format!("`{p}`"))
.collect();
preds.sort();
preds.dedup();
let msg = if let [pred] = &preds[..] {
format!("trait bound {} was not satisfied", pred)
format!("trait bound {pred} was not satisfied")
} else {
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);
}
}
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()
};
err.note(format!(
"the {item_kind} was found for\n{}{}",
type_candidates, additional_types
"the {item_kind} was found for\n{type_candidates}{additional_types}"
));
} else {
'outer: for inherent_impl_did in self.tcx.inherent_impls(adt.did()) {
@ -1249,8 +1248,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
(
format!(
"the candidate is defined in an impl{} for the type `{}`",
insertion, impl_ty,
"the candidate is defined in an impl{insertion} for the type `{impl_ty}`",
),
None,
)
@ -1452,11 +1450,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion(
sugg_span,
"use associated function syntax instead",
format!("{}::{}{}", ty_str, item_name, args),
format!("{ty_str}::{item_name}{args}"),
applicability,
);
} 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);
err.multipart_suggestion(
format!(
"to call the function stored in `{}`, \
"to call the function stored in `{item_name}`, \
surround the field access with parentheses",
item_name,
),
vec![
(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" };
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;
}
false
@ -1669,8 +1666,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lit.span,
format!(
"you must specify a concrete type for this numeric value, \
like `{}`",
concrete_type
like `{concrete_type}`"
),
format!("{snippet}_{concrete_type}"),
Applicability::MaybeIncorrect,
@ -1685,8 +1681,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let parent_node =
self.tcx.hir().get_parent(hir_id);
let msg = format!(
"you must specify a type for this binding, like `{}`",
concrete_type,
"you must specify a type for this binding, like `{concrete_type}`",
);
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 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;
}
}
@ -2226,8 +2221,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
for (self_name, self_span, traits) in &derives_grouped {
err.span_suggestion_verbose(
self_span.shrink_to_lo(),
format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
format!("#[derive({})]\n", traits),
format!("consider annotating `{self_name}` with `#[derive({traits})]`"),
format!("#[derive({traits})]\n"),
Applicability::MaybeIncorrect,
);
}
@ -2475,7 +2470,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip {
err.span_label(
pick.item.ident(self.tcx).span,
format!("the method is available for `{}` here", rcvr_ty),
format!("the method is available for `{rcvr_ty}` here"),
);
}
break;
@ -2521,13 +2516,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if pick.autoderefs == 0 && !skip {
err.span_label(
pick.item.ident(self.tcx).span,
format!("the method is available for `{}` here", new_rcvr_t),
format!("the method is available for `{new_rcvr_t}` here"),
);
err.multipart_suggestion(
"consider wrapping the receiver expression with the \
appropriate type",
vec![
(rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)),
(rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
(rcvr.span.shrink_to_hi(), ")".to_string()),
],
Applicability::MaybeIncorrect,
@ -2767,7 +2762,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
err.span_suggestions(
sp,
message(format!("add {} supertrait for", article)),
message(format!("add {article} supertrait for")),
candidates.iter().map(|t| {
format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
}),
@ -2836,7 +2831,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
trait_infos => {
let mut msg = message(param_type.map_or_else(
|| "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() {
msg.push_str(&format!(
@ -2860,8 +2855,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
trait_infos => {
let mut msg = format!(
"the following traits define an item `{}`, but are explicitly unimplemented:",
item_name
"the following traits define an item `{item_name}`, but are explicitly unimplemented:"
);
for trait_info in trait_infos {
msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
@ -3027,13 +3021,13 @@ fn print_disambiguation_help<'tcx>(
.join(", "),
);
let trait_name = if !fn_has_self_parameter {
format!("<{} as {}>", rcvr_ty, trait_name)
format!("<{rcvr_ty} as {trait_name}>")
} else {
trait_name
};
(span, format!("{}::{}{}", trait_name, item_name, args))
(span, format!("{trait_name}::{item_name}{args}"))
} 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(
span,
@ -3041,7 +3035,7 @@ fn print_disambiguation_help<'tcx>(
"disambiguate the {} for {}",
def_kind_descr,
if let Some(candidate) = candidate {
format!("candidate #{}", candidate)
format!("candidate #{candidate}")
} else {
"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<'_>) {
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 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)>| {
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 { "" };
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(
&mut err,
span,
@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestion_verbose(
qpath.span().shrink_to_hi().to(pat.span.shrink_to_hi()),
"use the tuple variant pattern syntax instead",
format!("({})", sugg),
format!("({sugg})"),
appl,
);
return Some(err);
@ -1812,7 +1812,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
const LIMIT: usize = 3;
match witnesses {
[] => bug!(),
[witness] => format!("`{}`", witness),
[witness] => format!("`{witness}`"),
[head @ .., tail] if head.len() < LIMIT => {
let head: Vec<_> = head.iter().map(<_>::to_string).collect();
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",
);
lint.note(format!(
"the pattern is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
ty,
"the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
));
lint
@ -1864,10 +1863,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
let fields = unmentioned_fields
.iter()
.map(|(_, name)| format!("`{}`", name))
.map(|(_, name)| format!("`{name}`"))
.collect::<Vec<String>>()
.join(", ");
format!("fields {}{}", fields, inaccessible)
format!("fields {fields}{inaccessible}")
};
let mut err = struct_span_err!(
self.tcx.sess,
@ -1876,7 +1875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"pattern does not mention {}",
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 (prefix, postfix, sp) = match fields {
[] => match &pat.kind {
@ -1909,11 +1908,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter()
.map(|(_, name)| {
let field_name = name.to_string();
if is_number(&field_name) {
format!("{}: _", field_name)
} else {
field_name
}
if is_number(&field_name) { format!("{field_name}: _") } else { field_name }
})
.collect::<Vec<_>>()
.join(", "),
@ -1930,7 +1925,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
s = pluralize!(len),
them = if len == 1 { "it" } else { "them" },
),
format!("{}..{}", prefix, postfix),
format!("{prefix}..{postfix}"),
Applicability::MachineApplicable,
);
err

View File

@ -109,11 +109,11 @@ impl MigrationWarningReason {
fn migration_message(&self) -> String {
let base = "changes to closure capture in Rust 2021 will affect";
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 {
format!("{} drop order", base)
format!("{base} drop order")
} 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>");
let diagnostic_msg = format!(
"add a dummy let to cause {} to be fully captured",
migrated_variables_concat
"add a dummy let to cause {migrated_variables_concat} to be fully captured"
);
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();
for (i, item) in place.projections.iter().enumerate() {
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::Index => String::from("Index"),
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 {
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")
@ -1987,7 +1986,7 @@ fn construct_capture_info_string<'tcx>(
let capture_kind_str = match capture_info.capture_kind {
ty::UpvarCapture::ByValue => "ByValue".into(),
ty::UpvarCapture::ByRef(kind) => format!("{:?}", kind),
ty::UpvarCapture::ByRef(kind) => format!("{kind:?}"),
};
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
// that isn't in the type table. We assume more relevant errors have already been
// emitted, so we delay an ICE if none have. (#64638)
self.tcx().sess.delay_span_bug(e.span, format!("bad base: `{:?}`", base));
self.tcx().sess.delay_span_bug(e.span, format!("bad base: `{base:?}`"));
}
if let Some(base_ty) = base_ty
&& let ty::Ref(_, base_ty_inner, _) = *base_ty.kind()
@ -231,7 +231,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
Ty::new_error_with_message(
self.fcx.tcx,
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) {
@ -488,10 +488,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
let span = self.tcx().hir().span(hir_id);
// We need to buffer the errors in order to guarantee a consistent
// order when emitting them.
let err = self
.tcx()
.sess
.struct_span_err(span, format!("user args: {:?}", user_args));
let err =
self.tcx().sess.struct_span_err(span, format!("user args: {user_args:?}"));
err.buffer(&mut errors_buffer);
}
}

View File

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

View File

@ -411,7 +411,7 @@ impl LintStore {
}
let complete_name = if let Some(tool_name) = tool_name {
format!("{}::{}", tool_name, lint_name)
format!("{tool_name}::{lint_name}")
} else {
lint_name.to_string()
};
@ -424,7 +424,7 @@ impl LintStore {
// 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?
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)) {
self.no_lint_suggestion(&complete_name)
} else {
@ -445,11 +445,11 @@ impl LintStore {
}
match self.by_name.get(&complete_name) {
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(Removed(reason)) => CheckLintNameResult::Warning(
format!("lint `{}` has been removed: {}", complete_name, reason),
format!("lint `{complete_name}` has been removed: {reason}"),
None,
),
None => match self.lint_groups.get(&*complete_name) {
@ -503,7 +503,7 @@ impl LintStore {
lint_name: &str,
tool_name: &str,
) -> CheckLintNameResult<'_> {
let complete_name = format!("{}::{}", tool_name, lint_name);
let complete_name = format!("{tool_name}::{lint_name}");
match self.by_name.get(&complete_name) {
None => match self.lint_groups.get(&*complete_name) {
// Now we are sure, that this lint exists nowhere
@ -618,12 +618,10 @@ pub trait LintContext: Sized {
_ => ("", "s"),
};
db.span_label(span, format!(
"this comment contains {}invisible unicode text flow control codepoint{}",
an,
s,
"this comment contains {an}invisible unicode text flow control codepoint{s}",
));
for (c, span) in &spans {
db.span_label(*span, format!("{:?}", c));
db.span_label(*span, format!("{c:?}"));
}
db.note(
"these kind of unicode codepoints change the way text flows on \
@ -648,7 +646,7 @@ pub trait LintContext: Sized {
let opt_colon =
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),
};
@ -704,7 +702,7 @@ pub trait LintContext: Sized {
let introduced = if is_imported { "imported" } else { "defined" };
db.span_label(
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} => {
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 {
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);
}
@ -949,11 +947,11 @@ pub trait LintContext: Sized {
);
}
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(duplicate_reexport_span, format!("but the name `{}` in the {} namespace is also 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 `{name}` in the {namespace} namespace is also re-exported here"));
}
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());
}
BuiltinLintDiagnostics::UnusedQualifications { removal_span } => {
@ -1281,8 +1279,8 @@ impl<'tcx> LateContext<'tcx> {
// This shouldn't ever be needed, but just in case:
with_no_trimmed_paths!({
Ok(vec![match trait_ref {
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
None => Symbol::intern(&format!("<{}>", self_ty)),
Some(trait_ref) => Symbol::intern(&format!("{trait_ref:?}")),
None => Symbol::intern(&format!("<{self_ty}>")),
}])
})
}
@ -1306,7 +1304,7 @@ impl<'tcx> LateContext<'tcx> {
)))
}
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 {
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,
{
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
.into_iter()
.map(|(c, span)| {
let c = format!("{:?}", c);
let c = format!("{c:?}");
(span, c[1..c.len() - 1].to_string())
})
.collect(),
@ -823,7 +823,7 @@ impl AddToDiagnostic for HiddenUnicodeCodepointsDiagSub {
"escaped",
spans
.into_iter()
.map(|(c, _)| format!("{:?}", c))
.map(|(c, _)| format!("{c:?}"))
.collect::<Vec<String>>()
.join(", "),
);

View File

@ -414,7 +414,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
match path {
MustUsePath::Suppressed => {}
MustUsePath::Boxed(path) => {
let descr_pre = &format!("{}boxed ", descr_pre);
let descr_pre = &format!("{descr_pre}boxed ");
emit_must_use_untranslated(
cx,
path,
@ -426,7 +426,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
);
}
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(
cx,
path,
@ -438,7 +438,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
);
}
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(
cx,
path,
@ -451,7 +451,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
}
MustUsePath::TupleElement(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(
cx,
path,
@ -464,7 +464,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
}
}
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(
cx,
path,

View File

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

View File

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

View File

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

View File

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

View File

@ -94,8 +94,7 @@ fn mir_build(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> {
|| body.basic_blocks.has_free_regions()
|| body.var_debug_info.has_free_regions()
|| body.yield_ty().has_free_regions()),
"Unexpected free regions in MIR: {:?}",
body,
"Unexpected free regions in MIR: {body:?}",
);
body
@ -977,9 +976,9 @@ pub(crate) fn parse_float_into_scalar(
match float_ty {
ty::FloatTy::F32 => {
let Ok(rust_f) = num.parse::<f32>() else { return None };
let mut f = num.parse::<Single>().unwrap_or_else(|e| {
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
});
let mut f = num
.parse::<Single>()
.unwrap_or_else(|e| panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}"));
assert!(
u128::from(rust_f.to_bits()) == f.to_bits(),
@ -1000,9 +999,9 @@ pub(crate) fn parse_float_into_scalar(
}
ty::FloatTy::F64 => {
let Ok(rust_f) = num.parse::<f64>() else { return None };
let mut f = num.parse::<Double>().unwrap_or_else(|e| {
panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e)
});
let mut f = num
.parse::<Double>()
.unwrap_or_else(|e| panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}"));
assert!(
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) {
// Get the span for the empty match body `{}`.
let (indentation, more) = if let Some(snippet) = sm.indentation_before(self.span) {
(format!("\n{}", snippet), " ")
(format!("\n{snippet}"), " ")
} else {
(" ".to_string(), "")
};
suggestion = Some((
self.span.shrink_to_hi().with_hi(self.expr_span.hi()),
format!(
" {{{indentation}{more}_ => todo!(),{indentation}}}",
indentation = indentation,
more = more,
),
format!(" {{{indentation}{more}_ => todo!(),{indentation}}}",),
));
}

View File

@ -229,9 +229,7 @@ impl<'tcx> Cx<'tcx> {
let param_env_ty = self.param_env.and(discr_ty);
let size = tcx
.layout_of(param_env_ty)
.unwrap_or_else(|e| {
panic!("could not compute layout for {:?}: {:?}", param_env_ty, e)
})
.unwrap_or_else(|e| panic!("could not compute layout for {param_env_ty:?}: {e:?}"))
.size;
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(
cx.tcx.sess,
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));
patterns_len = witnesses.len();
@ -721,15 +721,13 @@ fn non_exhaustive_match<'p, 'tcx>(
&& matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
{
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",
scrut_ty,
));
if cx.tcx.sess.is_nightly_build() {
err.help(format!(
"add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
enable precise `{}` matching",
scrut_ty,
enable precise `{scrut_ty}` matching",
));
}
}
@ -745,18 +743,13 @@ fn non_exhaustive_match<'p, 'tcx>(
[] if sp.eq_ctxt(expr_span) => {
// Get the span for the empty match body `{}`.
let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
(format!("\n{}", snippet), " ")
(format!("\n{snippet}"), " ")
} else {
(" ".to_string(), "")
};
suggestion = Some((
sp.shrink_to_hi().with_hi(expr_span.hi()),
format!(
" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
indentation = indentation,
more = more,
pattern = pattern,
),
format!(" {{{indentation}{more}{pattern} => todo!(),{indentation}}}",),
));
}
[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 == ',')
&& sm.is_multiline(with_trailing)
{
(format!("\n{}", snippet), true)
(format!("\n{snippet}"), true)
} else {
(" ".to_string(), false)
};
@ -780,7 +773,7 @@ fn non_exhaustive_match<'p, 'tcx>(
};
suggestion = Some((
only.span.shrink_to_hi(),
format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
format!("{comma}{pre_indentation}{pattern} => todo!()"),
));
}
[.., prev, last] => {
@ -803,7 +796,7 @@ fn non_exhaustive_match<'p, 'tcx>(
if let Some(spacing) = spacing {
suggestion = Some((
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 {
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 bias = self.bias;
let (lo, hi) = (lo ^ bias, hi ^ bias);
write!(f, "{}", lo)?;
write!(f, "{lo}")?;
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
// the pattern is a box pattern.
let subpattern = self.iter_fields().next().unwrap();
write!(f, "box {:?}", subpattern)
write!(f, "box {subpattern:?}")
}
ty::Adt(..) | ty::Tuple(..) => {
let variant = match self.ty.kind() {
@ -1638,7 +1638,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
write!(f, "(")?;
for p in self.iter_fields() {
write!(f, "{}", start_or_comma())?;
write!(f, "{:?}", p)?;
write!(f, "{p:?}")?;
}
write!(f, ")")
}
@ -1674,11 +1674,11 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
write!(f, "]")
}
&FloatRange(lo, hi, end) => {
write!(f, "{}", lo)?;
write!(f, "{}", end)?;
write!(f, "{}", hi)
write!(f, "{lo}")?;
write!(f, "{end}")?;
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),
Or => {
for pat in self.iter_fields() {
@ -1686,7 +1686,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> {
}
Ok(())
}
Str(value) => write!(f, "{}", value),
Str(value) => write!(f, "{value}"),
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 {
write!(f, "+")?;
for pat in self.iter() {
write!(f, " {:?} +", pat)?;
write!(f, " {pat:?} +")?;
}
Ok(())
}
@ -530,7 +530,7 @@ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
let Matrix { patterns: m, .. } = self;
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);
assert!(m.iter().all(|row| row.len() == column_count));

View File

@ -282,7 +282,7 @@ impl<'a> BcbCounters<'a> {
branching_counter_operand,
Op::Subtract,
sumup_counter_operand,
|| Some(format!("{:?}", expression_branch)),
|| Some(format!("{expression_branch:?}")),
);
debug!("{:?} gets an expression: {}", expression_branch, self.format_counter(&expression));
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.
let one_path_to_target = self.bcb_has_one_path_to_target(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 {
debug!(
"{}{:?} gets a new counter: {}",
@ -392,7 +392,7 @@ impl<'a> BcbCounters<'a> {
first_edge_counter_operand,
Op::Add,
some_sumup_edge_counter_operand.unwrap(),
|| Some(format!("{:?}", bcb)),
|| Some(format!("{bcb:?}")),
);
debug!(
"{}{:?} gets a new counter (sum of predecessor counters): {}",
@ -449,7 +449,7 @@ impl<'a> BcbCounters<'a> {
// Make a new counter to count this edge.
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!(
"{}Edge {:?}->{:?} gets a new counter: {}",
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");
let crate_name = tcx.crate_name(def_id.krate);
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)
.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 {
sections.push(format!("{:?}", counter_kind));
sections.push(format!("{counter_kind:?}"));
}
let non_term_blocks = bcb_data.basic_blocks[0..len - 1]
.iter()

View File

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

View File

@ -358,8 +358,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
self.tcx.sess.delay_span_bug(
terminator.source_info.span,
format!(
"drop of untracked, uninitialized value {:?}, place {:?} ({:?})",
bb, place, path
"drop of untracked, uninitialized value {bb:?}, place {place:?} ({path:?})"
),
);
}
@ -424,7 +423,7 @@ impl<'b, 'tcx> ElaborateDropsCtxt<'b, 'tcx> {
if !replace {
self.tcx.sess.delay_span_bug(
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.

View File

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

View File

@ -57,7 +57,7 @@ struct InstSimplifyContext<'tcx, 'a> {
impl<'tcx> InstSimplifyContext<'tcx, '_> {
fn should_simplify(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool {
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.
Some(hir::ConstContext::ConstFn) => tcx.ensure_with_value().mir_for_ctfe(did),
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...");
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 mut should_cleanup = false;
'outer: for bb_idx in bbs.indices() {
if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {:?} ", def_id)) {
if !tcx.consider_optimizing(|| format!("MatchBranchSimplification {def_id:?} ")) {
continue;
}

View File

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

View File

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

View File

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

View File

@ -27,7 +27,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUnneededDrops {
if ty.ty.needs_drop(tcx, param_env) {
continue;
}
if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {:?} ", did)) {
if !tcx.consider_optimizing(|| format!("RemoveUnneededDrops {did:?} ")) {
continue;
}
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);
if self.known_to_be_zst(op_ty)
&& 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)))

View File

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

View File

@ -89,9 +89,8 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
self.error(|| {
format!(
"ItemLocalIds not assigned densely in {}. \
Max ItemLocalId = {}, missing IDs = {:#?}; seen IDs = {:#?}",
pretty_owner, max, missing_items, seen_items
"ItemLocalIds not assigned densely in {pretty_owner}. \
Max ItemLocalId = {max}, missing IDs = {missing_items:#?}; seen IDs = {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();
eprintln!("{} {}", prefix, title);
eprintln!("{prefix} {title}");
eprintln!(
"{} {:<18}{:>18}{:>14}{:>14}",
prefix, "Name", "Accumulated Size", "Count", "Item Size"
);
eprintln!("{} ----------------------------------------------------------------", prefix);
eprintln!("{prefix} ----------------------------------------------------------------");
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!("{}", 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() {
let var = Variable::from(var_idx);
if test(var) {
write!(wr, " {:?}", var)?;
write!(wr, " {var:?}")?;
}
}
Ok(())

View File

@ -133,7 +133,7 @@ where
_ => {
tcx.sess.delay_span_bug(
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));
}