Skip to content

Commit aef0e34

Browse files
committed
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.
1 parent 0cd01aa commit aef0e34

File tree

23 files changed

+61
-65
lines changed

23 files changed

+61
-65
lines changed

compiler/rustc_codegen_cranelift/src/abi/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
505505
let nop_inst = fx.bcx.ins().nop();
506506
fx.add_comment(
507507
nop_inst,
508-
format!("virtual call; self arg pass mode: {:?}", &fn_abi.args[0]),
508+
format!("virtual call; self arg pass mode: {:?}", fn_abi.args[0]),
509509
);
510510
}
511511

compiler/rustc_codegen_ssa/src/back/link.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -759,7 +759,7 @@ fn link_natively(
759759
sess.dcx().abort_if_errors();
760760

761761
// Invoke the system linker
762-
info!("{:?}", &cmd);
762+
info!("{cmd:?}");
763763
let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
764764
let unknown_arg_regex =
765765
Regex::new(r"(unknown|unrecognized) (command line )?(option|argument)").unwrap();
@@ -796,7 +796,7 @@ fn link_natively(
796796
cmd.arg(arg);
797797
}
798798
}
799-
info!("{:?}", &cmd);
799+
info!("{cmd:?}");
800800
continue;
801801
}
802802

@@ -817,7 +817,7 @@ fn link_natively(
817817
cmd.arg(arg);
818818
}
819819
}
820-
info!("{:?}", &cmd);
820+
info!("{cmd:?}");
821821
continue;
822822
}
823823

@@ -878,7 +878,7 @@ fn link_natively(
878878
cmd.arg(arg);
879879
}
880880
}
881-
info!("{:?}", &cmd);
881+
info!("{cmd:?}");
882882
continue;
883883
}
884884

@@ -996,7 +996,7 @@ fn link_natively(
996996
sess.dcx().emit_err(errors::UnableToExeLinker {
997997
linker_path,
998998
error: e,
999-
command_formatted: format!("{:?}", &cmd),
999+
command_formatted: format!("{cmd:?}"),
10001000
});
10011001
}
10021002

@@ -1567,7 +1567,7 @@ fn print_native_static_libs(
15671567
sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
15681568
// Prefix for greppability
15691569
// Note: This must not be translated as tools are allowed to depend on this exact string.
1570-
sess.dcx().note(format!("native-static-libs: {}", &lib_args.join(" ")));
1570+
sess.dcx().note(format!("native-static-libs: {}", lib_args.join(" ")));
15711571
}
15721572
}
15731573
}

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
328328
sym::link_section => {
329329
if let Some(val) = attr.value_str() {
330330
if val.as_str().bytes().any(|b| b == 0) {
331-
let msg = format!("illegal null byte in link_section value: `{}`", &val);
331+
let msg = format!("illegal null byte in link_section value: `{val}`");
332332
tcx.dcx().span_err(attr.span, msg);
333333
} else {
334334
codegen_fn_attrs.link_section = Some(val);
@@ -726,7 +726,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
726726
if *ordinal <= u16::MAX as u128 {
727727
Some(ordinal.get() as u16)
728728
} else {
729-
let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
729+
let msg = format!("ordinal value in `link_ordinal` is too large: `{ordinal}`");
730730
tcx.dcx()
731731
.struct_span_err(attr.span, msg)
732732
.with_note("the value may not exceed `u16::MAX`")

compiler/rustc_codegen_ssa/src/mono_item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
130130

131131
let symbol_name = self.symbol_name(cx.tcx()).name;
132132

133-
debug!("symbol {}", &symbol_name);
133+
debug!("symbol {symbol_name}");
134134

135135
match *self {
136136
MonoItem::Static(def_id) => {

compiler/rustc_fluent_macro/src/fluent.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok
253253

254254
for Attribute { id: Identifier { name: attr_name }, .. } in attributes {
255255
let snake_name = Ident::new(
256-
&format!("{}{}", &crate_prefix, &attr_name.replace('-', "_")),
256+
&format!("{crate_prefix}{}", attr_name.replace('-', "_")),
257257
resource_str.span(),
258258
);
259259
if !previous_attrs.insert(snake_name.clone()) {

compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
651651
self.path_segment.hir_id,
652652
num_params_to_take,
653653
);
654-
debug!("suggested_args: {:?}", &suggested_args);
654+
debug!("suggested_args: {suggested_args:?}");
655655

656656
match self.angle_brackets {
657657
AngleBrackets::Missing => {

compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ fn check_explicit_predicates<'tcx>(
249249
let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id);
250250

251251
for (outlives_predicate, &span) in explicit_predicates.as_ref().skip_binder() {
252-
debug!("outlives_predicate = {:?}", &outlives_predicate);
252+
debug!("outlives_predicate = {outlives_predicate:?}");
253253

254254
// Careful: If we are inferring the effects of a `dyn Trait<..>`
255255
// type, then when we look up the predicates for `Trait`,
@@ -289,12 +289,12 @@ fn check_explicit_predicates<'tcx>(
289289
&& let GenericArgKind::Type(ty) = outlives_predicate.0.unpack()
290290
&& ty.walk().any(|arg| arg == self_ty.into())
291291
{
292-
debug!("skipping self ty = {:?}", &ty);
292+
debug!("skipping self ty = {ty:?}");
293293
continue;
294294
}
295295

296296
let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args);
297-
debug!("predicate = {:?}", &predicate);
297+
debug!("predicate = {predicate:?}");
298298
insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates);
299299
}
300300
}

compiler/rustc_hir_typeck/src/method/suggest.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1265,9 +1265,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12651265
}
12661266
(
12671267
match parent_pred {
1268-
None => format!("`{}`", &p),
1268+
None => format!("`{p}`"),
12691269
Some(parent_pred) => match format_pred(*parent_pred) {
1270-
None => format!("`{}`", &p),
1270+
None => format!("`{p}`"),
12711271
Some((parent_p, _)) => {
12721272
if !suggested
12731273
&& !suggested_bounds.contains(pred)

compiler/rustc_middle/src/middle/stability.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ pub fn report_unstable(
112112
) {
113113
let msg = match reason {
114114
Some(r) => format!("use of unstable library feature '{feature}': {r}"),
115-
None => format!("use of unstable library feature '{}'", &feature),
115+
None => format!("use of unstable library feature '{feature}'"),
116116
};
117117

118118
if is_soft {

compiler/rustc_middle/src/ty/print/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2627,7 +2627,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> {
26272627
self.prepare_region_info(value);
26282628
}
26292629

2630-
debug!("self.used_region_names: {:?}", &self.used_region_names);
2630+
debug!("self.used_region_names: {:?}", self.used_region_names);
26312631

26322632
let mut empty = true;
26332633
let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {

compiler/rustc_middle/src/util/find_self_call.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ pub fn find_self_call<'tcx>(
1414
local: Local,
1515
block: BasicBlock,
1616
) -> Option<(DefId, GenericArgsRef<'tcx>)> {
17-
debug!("find_self_call(local={:?}): terminator={:?}", local, &body[block].terminator);
17+
debug!("find_self_call(local={:?}): terminator={:?}", local, body[block].terminator);
1818
if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) =
1919
&body[block].terminator
2020
{

compiler/rustc_mir_dataflow/src/impls/initialized.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -688,7 +688,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for EverInitializedPlaces<'_, '_, 'tcx> {
688688
let init_loc_map = &move_data.init_loc_map;
689689
let rev_lookup = &move_data.rev_lookup;
690690

691-
debug!("initializes move_indexes {:?}", &init_loc_map[location]);
691+
debug!("initializes move_indexes {:?}", init_loc_map[location]);
692692
trans.gen_all(init_loc_map[location].iter().copied());
693693

694694
if let mir::StatementKind::StorageDead(local) = stmt.kind {

compiler/rustc_mir_transform/src/dead_store_elimination.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ pub fn eliminate<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
102102
| StatementKind::Nop => (),
103103

104104
StatementKind::FakeRead(_) | StatementKind::AscribeUserType(_, _) => {
105-
bug!("{:?} not found in this MIR phase!", &statement.kind)
105+
bug!("{:?} not found in this MIR phase!", statement.kind)
106106
}
107107
}
108108
}

compiler/rustc_mir_transform/src/early_otherwise_branch.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,11 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch {
106106
let parent = BasicBlock::from_usize(i);
107107
let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { continue };
108108

109-
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_data)) {
109+
if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {opt_data:?}")) {
110110
break;
111111
}
112112

113-
trace!("SUCCESS: found optimization possibility to apply: {:?}", &opt_data);
113+
trace!("SUCCESS: found optimization possibility to apply: {opt_data:?}");
114114

115115
should_cleanup = true;
116116

compiler/rustc_pattern_analysis/src/constructor.rs

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

compiler/rustc_resolve/src/diagnostics.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
149149
BuiltinLintDiag::AmbiguousGlobImports { diag },
150150
);
151151
} else {
152-
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", &diag.msg);
152+
let mut err = struct_span_code_err!(self.dcx(), diag.span, E0659, "{}", diag.msg);
153153
report_ambiguity_error(&mut err, diag);
154154
err.emit();
155155
}
@@ -798,7 +798,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
798798
}
799799
ResolutionError::FailedToResolve { segment, label, suggestion, module } => {
800800
let mut err =
801-
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {}", &label);
801+
struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {label}");
802802
err.span_label(span, label);
803803

804804
if let Some((suggestions, msg, applicability)) = suggestion {
@@ -2893,7 +2893,7 @@ fn show_candidates(
28932893
""
28942894
};
28952895
candidate.0 =
2896-
format!("{add_use}{}{append}{trailing}{additional_newline}", &candidate.0);
2896+
format!("{add_use}{}{append}{trailing}{additional_newline}", candidate.0);
28972897
}
28982898

28992899
match mode {

compiler/rustc_resolve/src/imports.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
694694
.collect::<Vec<_>>();
695695
let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
696696

697-
let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{}", &msg);
697+
let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
698698

699699
if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
700700
diag.note(note.clone());

compiler/rustc_resolve/src/rustdoc.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGen
339339
}
340340
}
341341

342-
debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
342+
debug!("path_str: {path_str:?}\nstripped segments: {stripped_segments:?}");
343343

344344
let stripped_path = stripped_segments.join("::");
345345

compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,12 @@ fn encode_predicate<'tcx>(
238238
match predicate.as_ref().skip_binder() {
239239
ty::ExistentialPredicate::Trait(trait_ref) => {
240240
let name = encode_ty_name(tcx, trait_ref.def_id);
241-
let _ = write!(s, "u{}{}", name.len(), &name);
241+
let _ = write!(s, "u{}{}", name.len(), name);
242242
s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
243243
}
244244
ty::ExistentialPredicate::Projection(projection) => {
245245
let name = encode_ty_name(tcx, projection.def_id);
246-
let _ = write!(s, "u{}{}", name.len(), &name);
246+
let _ = write!(s, "u{}{}", name.len(), name);
247247
s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
248248
match projection.term.unpack() {
249249
TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
@@ -258,7 +258,7 @@ fn encode_predicate<'tcx>(
258258
}
259259
ty::ExistentialPredicate::AutoTrait(def_id) => {
260260
let name = encode_ty_name(tcx, *def_id);
261-
let _ = write!(s, "u{}{}", name.len(), &name);
261+
let _ = write!(s, "u{}{}", name.len(), name);
262262
}
263263
};
264264
compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
@@ -416,7 +416,7 @@ pub fn encode_ty<'tcx>(
416416
// A<array-length><element-type>
417417
let len = len.eval_target_usize(tcx, ty::ParamEnv::reveal_all());
418418
let mut s = String::from("A");
419-
let _ = write!(s, "{}", &len);
419+
let _ = write!(s, "{len}");
420420
s.push_str(&encode_ty(tcx, *ty0, dict, options));
421421
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
422422
typeid.push_str(&s);
@@ -492,13 +492,13 @@ pub fn encode_ty<'tcx>(
492492
// calling convention (or extern types [i.e., ty::Foreign]) as <length><name>, where
493493
// <name> is <unscoped-name>.
494494
let name = tcx.item_name(def_id).to_string();
495-
let _ = write!(s, "{}{}", name.len(), &name);
495+
let _ = write!(s, "{}{}", name.len(), name);
496496
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
497497
} else {
498498
// u<length><name>[I<element-type1..element-typeN>E], where <element-type> is
499499
// <subst>, as vendor extended type.
500500
let name = encode_ty_name(tcx, def_id);
501-
let _ = write!(s, "u{}{}", name.len(), &name);
501+
let _ = write!(s, "u{}{}", name.len(), name);
502502
s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
503503
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
504504
}
@@ -530,7 +530,7 @@ pub fn encode_ty<'tcx>(
530530
}
531531
} else {
532532
let name = tcx.item_name(*def_id).to_string();
533-
let _ = write!(s, "{}{}", name.len(), &name);
533+
let _ = write!(s, "{}{}", name.len(), name);
534534
}
535535
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
536536
typeid.push_str(&s);
@@ -542,7 +542,7 @@ pub fn encode_ty<'tcx>(
542542
// as vendor extended type.
543543
let mut s = String::new();
544544
let name = encode_ty_name(tcx, *def_id);
545-
let _ = write!(s, "u{}{}", name.len(), &name);
545+
let _ = write!(s, "u{}{}", name.len(), name);
546546
s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
547547
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
548548
typeid.push_str(&s);
@@ -553,7 +553,7 @@ pub fn encode_ty<'tcx>(
553553
// as vendor extended type.
554554
let mut s = String::new();
555555
let name = encode_ty_name(tcx, *def_id);
556-
let _ = write!(s, "u{}{}", name.len(), &name);
556+
let _ = write!(s, "u{}{}", name.len(), name);
557557
let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
558558
s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
559559
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
@@ -565,7 +565,7 @@ pub fn encode_ty<'tcx>(
565565
// as vendor extended type.
566566
let mut s = String::new();
567567
let name = encode_ty_name(tcx, *def_id);
568-
let _ = write!(s, "u{}{}", name.len(), &name);
568+
let _ = write!(s, "u{}{}", name.len(), name);
569569
// Encode parent args only
570570
s.push_str(&encode_args(
571571
tcx,
@@ -588,7 +588,7 @@ pub fn encode_ty<'tcx>(
588588
s.push('E');
589589
compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
590590
if ty.is_mutable_ptr() {
591-
s = format!("{}{}", "U3mut", &s);
591+
s = format!("{}{}", "U3mut", s);
592592
compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
593593
}
594594
typeid.push_str(&s);
@@ -600,10 +600,10 @@ pub fn encode_ty<'tcx>(
600600
let mut s = String::new();
601601
s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
602602
if !ty.is_mutable_ptr() {
603-
s = format!("{}{}", "K", &s);
603+
s = format!("{}{}", "K", s);
604604
compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
605605
};
606-
s = format!("{}{}", "P", &s);
606+
s = format!("{}{}", "P", s);
607607
compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
608608
typeid.push_str(&s);
609609
}
@@ -722,7 +722,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
722722
s.push('C');
723723
s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
724724
let crate_name = tcx.crate_name(def_path.krate).to_string();
725-
let _ = write!(s, "{}{}", crate_name.len(), &crate_name);
725+
let _ = write!(s, "{}{}", crate_name.len(), crate_name);
726726

727727
// Disambiguators and names
728728
def_path.data.reverse();

compiler/rustc_type_ir/src/const_kind.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -65,15 +65,13 @@ impl<I: Interner> fmt::Debug for ConstKind<I> {
6565

6666
match self {
6767
Param(param) => write!(f, "{param:?}"),
68-
Infer(var) => write!(f, "{:?}", &var),
68+
Infer(var) => write!(f, "{var:?}"),
6969
Bound(debruijn, var) => crate::debug_bound_var(f, *debruijn, var),
7070
Placeholder(placeholder) => write!(f, "{placeholder:?}"),
71-
Unevaluated(uv) => {
72-
write!(f, "{:?}", &uv)
73-
}
74-
Value(ty, valtree) => write!(f, "({valtree:?}: {:?})", &ty),
71+
Unevaluated(uv) => write!(f, "{uv:?}"),
72+
Value(ty, valtree) => write!(f, "({valtree:?}: {ty:?})"),
7573
Error(_) => write!(f, "{{const error}}"),
76-
Expr(expr) => write!(f, "{:?}", &expr),
74+
Expr(expr) => write!(f, "{expr:?}"),
7775
}
7876
}
7977
}

0 commit comments

Comments
 (0)