Skip to content

Commit 01e33a3

Browse files
committed
Avoid &format("...") calls in error message code.
Error message all end up passing into a function as an `impl Into<{D,Subd}iagnosticMessage>`. If an error message is creatd as `&format("...")` that means we allocate a string (in the `format!` call), then take a reference, and then clone (allocating again) the reference to produce the `{D,Subd}iagnosticMessage`, which is silly. This commit removes the leading `&` from a lot of these cases. This means the original `String` is moved into the `{D,Subd}iagnosticMessage`, avoiding the double allocations. This requires changing some function argument types from `&str` to `String` (when all arguments are `String`) or `impl Into<{D,Subd}iagnosticMessage>` (when some arguments are `String` and some are `&str`).
1 parent 87a2bc0 commit 01e33a3

File tree

37 files changed

+139
-133
lines changed

37 files changed

+139
-133
lines changed

compiler/rustc_abi/src/layout.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use tracing::debug;
1212
pub trait LayoutCalculator {
1313
type TargetDataLayoutRef: Borrow<TargetDataLayout>;
1414

15-
fn delay_bug(&self, txt: &str);
15+
fn delay_bug(&self, txt: String);
1616
fn current_data_layout(&self) -> Self::TargetDataLayoutRef;
1717

1818
fn scalar_pair(&self, a: Scalar, b: Scalar) -> LayoutS {
@@ -969,7 +969,7 @@ fn univariant(
969969
for &i in &inverse_memory_index {
970970
let field = &fields[i];
971971
if !sized {
972-
this.delay_bug(&format!(
972+
this.delay_bug(format!(
973973
"univariant: field #{} comes after unsized field",
974974
offsets.len(),
975975
));

compiler/rustc_borrowck/src/nll.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ pub(super) fn dump_annotation<'tcx>(
430430
fn for_each_region_constraint<'tcx>(
431431
tcx: TyCtxt<'tcx>,
432432
closure_region_requirements: &ClosureRegionRequirements<'tcx>,
433-
with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
433+
with_msg: &mut dyn FnMut(String) -> io::Result<()>,
434434
) -> io::Result<()> {
435435
for req in &closure_region_requirements.outlives_requirements {
436436
let subject = match req.subject {
@@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>(
439439
format!("{:?}", ty.instantiate(tcx, |vid| tcx.mk_re_var(vid)))
440440
}
441441
};
442-
with_msg(&format!("where {}: {:?}", subject, req.outlived_free_region,))?;
442+
with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;
443443
}
444444
Ok(())
445445
}

compiler/rustc_borrowck/src/type_check/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ macro_rules! span_mirbug {
7171
$crate::type_check::mirbug(
7272
$context.tcx(),
7373
$context.last_span,
74-
&format!(
74+
format!(
7575
"broken MIR in {:?} ({:?}): {}",
7676
$context.body().source.def_id(),
7777
$elem,
@@ -274,7 +274,7 @@ fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
274274
}
275275

276276
#[track_caller]
277-
fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
277+
fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
278278
// We sometimes see MIR failures (notably predicate failures) due to
279279
// the fact that we check rvalue sized predicates here. So use `delay_span_bug`
280280
// to avoid reporting bugs in those cases.

compiler/rustc_builtin_macros/src/asm.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
550550
if !parser.errors.is_empty() {
551551
let err = parser.errors.remove(0);
552552
let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
553-
let msg = &format!("invalid asm template string: {}", err.description);
553+
let msg = format!("invalid asm template string: {}", err.description);
554554
let mut e = ecx.struct_span_err(err_sp, msg);
555555
e.span_label(err_sp, err.label + " in asm template string");
556556
if let Some(note) = err.note {
@@ -585,7 +585,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
585585
|| args.reg_args.contains(idx)
586586
{
587587
let msg = format!("invalid reference to argument at index {}", idx);
588-
let mut err = ecx.struct_span_err(span, &msg);
588+
let mut err = ecx.struct_span_err(span, msg);
589589
err.span_label(span, "from here");
590590

591591
let positional_args = args.operands.len()
@@ -638,7 +638,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
638638
ecx.struct_span_err(
639639
template_span
640640
.from_inner(InnerSpan::new(span.start, span.end)),
641-
&msg,
641+
msg,
642642
)
643643
.emit();
644644
None

compiler/rustc_builtin_macros/src/deriving/clone.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ fn cs_clone_simple(
145145
}
146146
_ => cx.span_bug(
147147
trait_span,
148-
&format!("unexpected substructure in simple `derive({})`", name),
148+
format!("unexpected substructure in simple `derive({})`", name),
149149
),
150150
}
151151
}
@@ -179,10 +179,10 @@ fn cs_clone(
179179
vdata = &variant.data;
180180
}
181181
EnumTag(..) | AllFieldlessEnum(..) => {
182-
cx.span_bug(trait_span, &format!("enum tags in `derive({})`", name,))
182+
cx.span_bug(trait_span, format!("enum tags in `derive({})`", name,))
183183
}
184184
StaticEnum(..) | StaticStruct(..) => {
185-
cx.span_bug(trait_span, &format!("associated function in `derive({})`", name))
185+
cx.span_bug(trait_span, format!("associated function in `derive({})`", name))
186186
}
187187
}
188188

@@ -194,7 +194,7 @@ fn cs_clone(
194194
let Some(ident) = field.name else {
195195
cx.span_bug(
196196
trait_span,
197-
&format!("unnamed field in normal struct in `derive({})`", name,),
197+
format!("unnamed field in normal struct in `derive({})`", name,),
198198
);
199199
};
200200
let call = subcall(cx, field);

compiler/rustc_builtin_macros/src/deriving/generic/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1591,7 +1591,7 @@ impl<'a> TraitDef<'a> {
15911591
BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE,
15921592
sp,
15931593
ast::CRATE_NODE_ID,
1594-
&format!(
1594+
format!(
15951595
"{} slice in a packed struct that derives a built-in trait",
15961596
ty
15971597
),

compiler/rustc_builtin_macros/src/format.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -814,7 +814,7 @@ fn report_invalid_references(
814814
};
815815
e = ecx.struct_span_err(
816816
span,
817-
&format!("invalid reference to positional {} ({})", arg_list, num_args_desc),
817+
format!("invalid reference to positional {} ({})", arg_list, num_args_desc),
818818
);
819819
e.note("positional arguments are zero-based");
820820
}

compiler/rustc_builtin_macros/src/source_util.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,12 +188,12 @@ pub fn expand_include_str(
188188
base::MacEager::expr(cx.expr_str(sp, interned_src))
189189
}
190190
Err(_) => {
191-
cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
191+
cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
192192
DummyResult::any(sp)
193193
}
194194
},
195195
Err(e) => {
196-
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
196+
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
197197
DummyResult::any(sp)
198198
}
199199
}
@@ -221,7 +221,7 @@ pub fn expand_include_bytes(
221221
base::MacEager::expr(expr)
222222
}
223223
Err(e) => {
224-
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
224+
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
225225
DummyResult::any(sp)
226226
}
227227
}

compiler/rustc_codegen_cranelift/src/pretty_clif.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ pub(crate) fn write_ir_file(
227227
// Using early_warn as no Session is available here
228228
rustc_session::early_warn(
229229
rustc_session::config::ErrorOutputType::default(),
230-
&format!("error writing ir file: {}", err),
230+
format!("error writing ir file: {}", err),
231231
);
232232
}
233233
}

compiler/rustc_driver_impl/src/args.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub fn arg_expand_all(at_args: &[String]) -> Vec<String> {
2525
Ok(arg) => args.extend(arg),
2626
Err(err) => rustc_session::early_error(
2727
rustc_session::config::ErrorOutputType::default(),
28-
&format!("Failed to load argument file: {err}"),
28+
format!("Failed to load argument file: {err}"),
2929
),
3030
}
3131
}

0 commit comments

Comments
 (0)