Rollup merge of #127980 - nyurik:compiler-refs, r=oli-obk

Avoid ref when using format! in compiler

Clean up a few minor refs in `format!` macro, as it has a performance cost. Apparently the compiler is unable to inline `format!("{}", &variable)`, and does a run-time double-reference instead (format macro already does one level referencing).  Inlining format args prevents accidental `&` misuse.

See also https://github.com/rust-lang/rust-clippy/issues/10851
This commit is contained in:
Matthias Krüger 2024-07-20 07:13:45 +02:00 committed by GitHub
commit cd8c5f78ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 61 additions and 65 deletions

View File

@ -505,7 +505,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
let nop_inst = fx.bcx.ins().nop();
fx.add_comment(
nop_inst,
format!("virtual call; self arg pass mode: {:?}", &fn_abi.args[0]),
format!("virtual call; self arg pass mode: {:?}", fn_abi.args[0]),
);
}

View File

@ -759,7 +759,7 @@ fn link_natively(
sess.dcx().abort_if_errors();
// Invoke the system linker
info!("{:?}", &cmd);
info!("{cmd:?}");
let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
let unknown_arg_regex =
Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
@ -796,7 +796,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}
@ -817,7 +817,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}
@ -878,7 +878,7 @@ fn link_natively(
cmd.arg(arg);
}
}
info!("{:?}", &cmd);
info!("{cmd:?}");
continue;
}
@ -996,7 +996,7 @@ fn link_natively(
sess.dcx().emit_err(errors::UnableToExeLinker {
linker_path,
error: e,
command_formatted: format!("{:?}", &cmd),
command_formatted: format!("{cmd:?}"),
});
}
@ -1567,7 +1567,7 @@ fn print_native_static_libs(
sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
// Prefix for greppability
// Note: This must not be translated as tools are allowed to depend on this exact string.
sess.dcx().note(format!("native-static-libs: {}", &lib_args.join(" ")));
sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
}
}
}

View File

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

View File

@ -130,7 +130,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
let symbol_name = self.symbol_name(cx.tcx()).name;
debug!("symbol {}", &symbol_name);
debug!("symbol {symbol_name}");
match *self {
MonoItem::Static(def_id) => {

View File

@ -253,7 +253,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok
for Attribute { id: Identifier { name: attr_name }, .. } in attributes {
let snake_name = Ident::new(
&format!("{}{}", &crate_prefix, &attr_name.replace('-', "_")),
&format!("{crate_prefix}{}", attr_name.replace('-', "_")),
resource_str.span(),
);
if !previous_attrs.insert(snake_name.clone()) {

View File

@ -651,7 +651,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
self.path_segment.hir_id,
num_params_to_take,
);
debug!("suggested_args: {:?}", &suggested_args);
debug!("suggested_args: {suggested_args:?}");
match self.angle_brackets {
AngleBrackets::Missing => {

View File

@ -249,7 +249,7 @@ fn check_explicit_predicates<'tcx>(
let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);
for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
debug!("outlives_predicate = {:?}", &outlives_predicate);
debug!("outlives_predicate = {outlives_predicate:?}");
// Careful: If we are inferring the effects of a `dyn Trait<..>`
// type, then when we look up the predicates for `Trait`,
@ -289,12 +289,12 @@ fn check_explicit_predicates<'tcx>(
&& let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
&& ty.walk().any(|arg| arg == self_ty.into())
{
debug!("skipping self ty = {:?}", &ty);
debug!("skipping self ty = {ty:?}");
continue;
}
let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args);
debug!("predicate = {:?}", &predicate);
debug!("predicate = {predicate:?}");
insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
}
}

View File

@ -1265,9 +1265,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
(
match parent_pred {
None => format!("`{}`", &p),
None => format!("`{p}`"),
Some(parent_pred) => match format_pred(*parent_pred) {
None => format!("`{}`", &p),
None => format!("`{p}`"),
Some((parent_p, _)) => {
if !suggested
&& !suggested_bounds.contains(pred)

View File

@ -112,7 +112,7 @@ pub fn report_unstable(
) {
let msg = match reason {
Some(r) => format!("use of unstable library feature '{feature}': {r}"),
None => format!("use of unstable library feature '{}'", &feature),
None => format!("use of unstable library feature '{feature}'"),
};
if is_soft {

View File

@ -2627,7 +2627,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> {
self.prepare_region_info(value);
}
debug!("self.used_region_names: {:?}", &self.used_region_names);
debug!("self.used_region_names: {:?}", self.used_region_names);
let mut empty = true;
let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {

View File

@ -14,7 +14,7 @@ pub fn find_self_call<'tcx>(
local: Local,
block: BasicBlock,
) -> Option<(DefId, GenericArgsRef<'tcx>)> {
debug!("find_self_call(local={:?}): terminator={:?}", local, &body[block].terminator);
debug!("find_self_call(local={:?}): terminator={:?}", local, body[block].terminator);
if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) =
&body[block].terminator
{

View File

@ -688,7 +688,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for EverInitializedPlaces<'_, '_, 'tcx> {
let init_loc_map = &move_data.init_loc_map;
let rev_lookup = &move_data.rev_lookup;
debug!("initializes move_indexes {:?}", &init_loc_map[location]);
debug!("initializes move_indexes {:?}", init_loc_map[location]);
trans.gen_all(init_loc_map[location].iter().copied());
if let mir::StatementKind::StorageDead(local) = stmt.kind {

View File

@ -102,7 +102,7 @@ pub fn eliminate<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
| StatementKind::Nop => (),
StatementKind::FakeRead(_) | StatementKind::AscribeUserType(_, _) => {
bug!("{:?} not found in this MIR phase!", &statement.kind)
bug!("{:?} not found in this MIR phase!", statement.kind)
}
}
}

View File

@ -106,11 +106,11 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch {
let parent = BasicBlock::from_usize(i);
let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { continue };
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_data)) {
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {opt_data:?}")) {
break;
}
trace!("SUCCESS: found optimization possibility to apply: {:?}", &opt_data);
trace!("SUCCESS: found optimization possibility to apply: {opt_data:?}");
should_cleanup = true;

View File

@ -904,7 +904,7 @@ impl<Cx: PatCx> Constructor<Cx> {
// be careful to detect strings here. However a string literal pattern will never
// be reported as a non-exhaustiveness witness, so we can ignore this issue.
Ref => {
write!(f, "&{:?}", &fields.next().unwrap())?;
write!(f, "&{:?}", fields.next().unwrap())?;
}
Slice(slice) => {
write!(f, "[")?;

View File

@ -149,7 +149,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
BuiltinLintDiag::AmbiguousGlobImports { diag },
);
} else {
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", &diag.msg);
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
report_ambiguity_error(&mut err, diag);
err.emit();
}
@ -798,7 +798,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}
ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
let mut err =
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {}", &label);
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
err.span_label(span, label);
if let Some((suggestions, msg, applicability)) = suggestion {
@ -2893,7 +2893,7 @@ fn show_candidates(
""
};
candidate.0 =
format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
}
match mode {

View File

@ -694,7 +694,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
.collect::<Vec<_>>();
let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{}", &msg);
let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
diag.note(note.clone());

View File

@ -339,7 +339,7 @@ pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGen
}
}
debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
debug!("path_str: {path_str:?}\nstripped segments: {stripped_segments:?}");
let stripped_path = stripped_segments.join("::");

View File

@ -238,12 +238,12 @@ fn encode_predicate<'tcx>(
match predicate.as_ref().skip_binder() {
ty::ExistentialPredicate::Trait(trait_ref) => {
let name = encode_ty_name(tcx, trait_ref.def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
}
ty::ExistentialPredicate::Projection(projection) => {
let name = encode_ty_name(tcx, projection.def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
match projection.term.unpack() {
TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
@ -258,7 +258,7 @@ fn encode_predicate<'tcx>(
}
ty::ExistentialPredicate::AutoTrait(def_id) => {
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
}
};
compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
@ -416,7 +416,7 @@ pub fn encode_ty<'tcx>(
// A<array-length><element-type>
let len = len.eval_target_usize(tcx, ty::ParamEnv::reveal_all());
let mut s = String::from("A");
let _ = write!(s, "{}", &len);
let _ = write!(s, "{len}");
s.push_str(&encode_ty(tcx, *ty0, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
@ -492,13 +492,13 @@ pub fn encode_ty<'tcx>(
// calling convention (or extern types [i.e., ty::Foreign]) as <length><name>, where
// <name> is <unscoped-name>.
let name = tcx.item_name(def_id).to_string();
let _ = write!(s, "{}{}", name.len(), &name);
let _ = write!(s, "{}{}", name.len(), name);
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
} else {
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is
// <subst>, as vendor extended type.
let name = encode_ty_name(tcx, def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
}
@ -530,7 +530,7 @@ pub fn encode_ty<'tcx>(
}
} else {
let name = tcx.item_name(*def_id).to_string();
let _ = write!(s, "{}{}", name.len(), &name);
let _ = write!(s, "{}{}", name.len(), name);
}
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
@ -542,7 +542,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
@ -553,7 +553,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
@ -565,7 +565,7 @@ pub fn encode_ty<'tcx>(
// as vendor extended type.
let mut s = String::new();
let name = encode_ty_name(tcx, *def_id);
let _ = write!(s, "u{}{}", name.len(), &name);
let _ = write!(s, "u{}{}", name.len(), name);
// Encode parent args only
s.push_str(&encode_args(
tcx,
@ -588,7 +588,7 @@ pub fn encode_ty<'tcx>(
s.push('E');
compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
if ty.is_mutable_ptr() {
s = format!("{}{}", "U3mut", &s);
s = format!("{}{}", "U3mut", s);
compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
}
typeid.push_str(&s);
@ -600,10 +600,10 @@ pub fn encode_ty<'tcx>(
let mut s = String::new();
s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
if !ty.is_mutable_ptr() {
s = format!("{}{}", "K", &s);
s = format!("{}{}", "K", s);
compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
};
s = format!("{}{}", "P", &s);
s = format!("{}{}", "P", s);
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
typeid.push_str(&s);
}
@ -722,7 +722,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
s.push('C');
s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
let crate_name = tcx.crate_name(def_path.krate).to_string();
let _ = write!(s, "{}{}", crate_name.len(), &crate_name);
let _ = write!(s, "{}{}", crate_name.len(), crate_name);
// Disambiguators and names
def_path.data.reverse();

View File

@ -65,15 +65,13 @@ impl<I: Interner> fmt::Debug for ConstKind<I> {
match self {
Param(param) => write!(f, "{param:?}"),
Infer(var) => write!(f, "{:?}", &var),
Infer(var) => write!(f, "{var:?}"),
Bound(debruijn, var) => crate::debug_bound_var(f, *debruijn, var),
Placeholder(placeholder) => write!(f, "{placeholder:?}"),
Unevaluated(uv) => {
write!(f, "{:?}", &uv)
}
Value(ty, valtree) => write!(f, "({valtree:?}: {:?})", &ty),
Unevaluated(uv) => write!(f, "{uv:?}"),
Value(ty, valtree) => write!(f, "({valtree:?}: {ty:?})"),
Error(_) => write!(f, "{{const error}}"),
Expr(expr) => write!(f, "{:?}", &expr),
Expr(expr) => write!(f, "{expr:?}"),
}
}
}

View File

@ -232,7 +232,7 @@ impl<I: Interner> fmt::Debug for RegionKind<I> {
ReStatic => f.write_str("'static"),
ReVar(vid) => write!(f, "{:?}", &vid),
ReVar(vid) => write!(f, "{vid:?}"),
RePlaceholder(placeholder) => write!(f, "{placeholder:?}"),

View File

@ -367,18 +367,16 @@ impl<I: Interner> fmt::Debug for TyKind<I> {
}
Foreign(d) => f.debug_tuple("Foreign").field(d).finish(),
Str => write!(f, "str"),
Array(t, c) => write!(f, "[{:?}; {:?}]", &t, &c),
Pat(t, p) => write!(f, "pattern_type!({:?} is {:?})", &t, &p),
Array(t, c) => write!(f, "[{t:?}; {c:?}]"),
Pat(t, p) => write!(f, "pattern_type!({t:?} is {p:?})"),
Slice(t) => write!(f, "[{:?}]", &t),
RawPtr(ty, mutbl) => write!(f, "*{} {:?}", mutbl.ptr_str(), ty),
Ref(r, t, m) => write!(f, "&{:?} {}{:?}", r, m.prefix_str(), t),
FnDef(d, s) => f.debug_tuple("FnDef").field(d).field(&s).finish(),
FnPtr(s) => write!(f, "{:?}", &s),
FnPtr(s) => write!(f, "{s:?}"),
Dynamic(p, r, repr) => match repr {
DynKind::Dyn => write!(f, "dyn {:?} + {:?}", &p, &r),
DynKind::DynStar => {
write!(f, "dyn* {:?} + {:?}", &p, &r)
}
DynKind::Dyn => write!(f, "dyn {p:?} + {r:?}"),
DynKind::DynStar => write!(f, "dyn* {p:?} + {r:?}"),
},
Closure(d, s) => f.debug_tuple("Closure").field(d).field(&s).finish(),
CoroutineClosure(d, s) => f.debug_tuple("CoroutineClosure").field(d).field(&s).finish(),
@ -392,7 +390,7 @@ impl<I: Interner> fmt::Debug for TyKind<I> {
if count > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", &ty)?;
write!(f, "{ty:?}")?;
count += 1;
}
// unary tuples need a trailing comma
@ -1050,7 +1048,7 @@ impl<I: Interner> fmt::Debug for FnSig<I> {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", &ty)?;
write!(f, "{ty:?}")?;
}
if *c_variadic {
if inputs.is_empty() {

View File

@ -179,7 +179,7 @@ fn pretty_terminator_head<W: Write>(writer: &mut W, terminator: &TerminatorKind)
if !expected {
write!(writer, "!")?;
}
write!(writer, "{}, ", &pretty_operand(cond))?;
write!(writer, "{}, ", pretty_operand(cond))?;
pretty_assert_message(writer, msg)?;
write!(writer, ")")
}
@ -325,7 +325,7 @@ fn pretty_ty_const(ct: &TyConst) -> String {
fn pretty_rvalue<W: Write>(writer: &mut W, rval: &Rvalue) -> io::Result<()> {
match rval {
Rvalue::AddressOf(mutability, place) => {
write!(writer, "&raw {}(*{:?})", &pretty_mut(*mutability), place)
write!(writer, "&raw {}(*{:?})", pretty_mut(*mutability), place)
}
Rvalue::Aggregate(aggregate_kind, operands) => {
// FIXME: Add pretty_aggregate function that returns a pretty string
@ -336,13 +336,13 @@ fn pretty_rvalue<W: Write>(writer: &mut W, rval: &Rvalue) -> io::Result<()> {
write!(writer, ")")
}
Rvalue::BinaryOp(bin, op1, op2) => {
write!(writer, "{:?}({}, {})", bin, &pretty_operand(op1), pretty_operand(op2))
write!(writer, "{:?}({}, {})", bin, pretty_operand(op1), pretty_operand(op2))
}
Rvalue::Cast(_, op, ty) => {
write!(writer, "{} as {}", pretty_operand(op), ty)
}
Rvalue::CheckedBinaryOp(bin, op1, op2) => {
write!(writer, "Checked{:?}({}, {})", bin, &pretty_operand(op1), pretty_operand(op2))
write!(writer, "Checked{:?}({}, {})", bin, pretty_operand(op1), pretty_operand(op2))
}
Rvalue::CopyForDeref(deref) => {
write!(writer, "CopyForDeref({:?})", deref)
@ -363,7 +363,7 @@ fn pretty_rvalue<W: Write>(writer: &mut W, rval: &Rvalue) -> io::Result<()> {
write!(writer, "{kind}{:?}", place)
}
Rvalue::Repeat(op, cnst) => {
write!(writer, "{} \" \" {}", &pretty_operand(op), &pretty_ty_const(cnst))
write!(writer, "{} \" \" {}", pretty_operand(op), pretty_ty_const(cnst))
}
Rvalue::ShallowInitBox(_, _) => Ok(()),
Rvalue::ThreadLocalRef(item) => {