Skip to content

Commit 6b62f37

Browse files
committed
Restrict From<S> for {D,Subd}iagnosticMessage.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static, str>`, which are reasonable. It also includes `&String`, which is pretty weird, and results in many places making unnecessary allocations for patterns like this: ``` self.fatal(&format!(...)) ``` This creates a string with `format!`, takes a reference, passes the reference to `fatal`, which does an `into()`, which clones the reference, doing a second allocation. Two allocations for a single string, bleh. This commit changes the `From` impls so that you can only create a `{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static, str>`. This requires changing all the places that currently create one from a `&String`. Most of these are of the `&format!(...)` form described above; each one removes an unnecessary static `&`, plus an allocation when executed. There are also a few places where the existing use of `&String` was more reasonable; these now just use `clone()` at the call site. As well as making the code nicer and more efficient, this is a step towards possibly using `Cow<'static, str>` in `{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing the `From<&'a str>` impls to `From<&'static str>`, which is doable, but I'm not yet sure if it's worthwhile.
1 parent a368898 commit 6b62f37

File tree

177 files changed

+791
-787
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

177 files changed

+791
-787
lines changed

compiler/rustc_ast_lowering/src/path.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
136136

137137
self.diagnostic().span_bug(
138138
p.span,
139-
&format!(
139+
format!(
140140
"lower_qpath: no final extension segment in {}..{}",
141141
proj_start,
142142
p.segments.len()

compiler/rustc_ast_passes/src/feature_gate.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ impl<'a> PostExpansionVisitor<'a> {
8383
&self,
8484
const_extern_fn,
8585
span,
86-
&format!("`{}` as a `const fn` ABI is unstable", abi)
86+
format!("`{}` as a `const fn` ABI is unstable", abi)
8787
),
8888
}
8989
}
@@ -104,7 +104,7 @@ impl<'a> PostExpansionVisitor<'a> {
104104
if self.sess.opts.pretty.map_or(true, |ppm| ppm.needs_hir()) {
105105
self.sess.parse_sess.span_diagnostic.delay_span_bug(
106106
span,
107-
&format!(
107+
format!(
108108
"unrecognized ABI not caught in lowering: {}",
109109
symbol_unescaped.as_str()
110110
),

compiler/rustc_attr/src/builtin.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &F
623623
let (cfg, feature, has_feature) = gated_cfg;
624624
if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
625625
let explain = format!("`cfg({cfg})` is experimental and subject to change");
626-
feature_err(sess, *feature, cfg_span, &explain).emit();
626+
feature_err(sess, *feature, cfg_span, explain).emit();
627627
}
628628
}
629629

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
158158
} else if reinits > 1 {
159159
err.span_note(
160160
MultiSpan::from_spans(reinit_spans),
161-
&if reinits <= 3 {
161+
if reinits <= 3 {
162162
format!("these {reinits} reinitializations might get skipped")
163163
} else {
164164
format!(
@@ -253,7 +253,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
253253
// We have a `&mut` ref, we need to reborrow on each iteration (#62112).
254254
err.span_suggestion_verbose(
255255
span.shrink_to_lo(),
256-
&format!(
256+
format!(
257257
"consider creating a fresh reborrow of {} here",
258258
self.describe_place(moved_place)
259259
.map(|n| format!("`{n}`"))
@@ -304,7 +304,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
304304
..
305305
} = use_spans
306306
{
307-
err.note(&format!(
307+
err.note(format!(
308308
"{} occurs due to deref coercion to `{deref_target_ty}`",
309309
desired_action.as_noun(),
310310
));
@@ -586,7 +586,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
586586
// _ => {} // We don't want to point to this.
587587
// };
588588
// ```
589-
err.span_label(sp, &label);
589+
err.span_label(sp, label);
590590
shown = true;
591591
}
592592
}
@@ -1139,7 +1139,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11391139
}
11401140

11411141
if union_type_name != "" {
1142-
err.note(&format!(
1142+
err.note(format!(
11431143
"{} is a field of the union `{}`, so it overlaps the field {}",
11441144
msg_place, union_type_name, msg_borrow,
11451145
));
@@ -1238,14 +1238,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12381238
}
12391239
err.span_help(
12401240
inner_call_span,
1241-
&format!(
1241+
format!(
12421242
"try adding a local storing this{}...",
12431243
if use_span.is_some() { "" } else { " argument" }
12441244
),
12451245
);
12461246
err.span_help(
12471247
outer_call_span,
1248-
&format!(
1248+
format!(
12491249
"...and then using that local {}",
12501250
if use_span.is_some() { "here" } else { "as the argument to this call" }
12511251
),
@@ -2281,7 +2281,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
22812281
);
22822282
err.span_suggestion_verbose(
22832283
sugg_span,
2284-
&format!(
2284+
format!(
22852285
"to force the {} to take ownership of {} (and any \
22862286
other referenced variables), use the `move` keyword",
22872287
kind, captured_var
@@ -2293,7 +2293,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
22932293
match category {
22942294
ConstraintCategory::Return(_) | ConstraintCategory::OpaqueType => {
22952295
let msg = format!("{} is returned here", kind);
2296-
err.span_note(constraint_span, &msg);
2296+
err.span_note(constraint_span, msg);
22972297
}
22982298
ConstraintCategory::CallArgument(_) => {
22992299
fr_name.highlight_region_name(&mut err);
@@ -2304,7 +2304,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
23042304
);
23052305
} else {
23062306
let msg = format!("{scope} requires argument type to outlive `{fr_name}`");
2307-
err.span_note(constraint_span, &msg);
2307+
err.span_note(constraint_span, msg);
23082308
}
23092309
}
23102310
_ => bug!(
@@ -2626,7 +2626,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
26262626
});
26272627
if let Some(Ok(instance)) = deref_target {
26282628
let deref_target_ty = instance.ty(tcx, self.param_env);
2629-
err.note(&format!(
2629+
err.note(format!(
26302630
"borrow occurs due to deref coercion to `{}`",
26312631
deref_target_ty
26322632
));
@@ -3180,7 +3180,7 @@ impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
31803180

31813181
diag.span_label(*return_span, format!("also has lifetime `{}`", region_name,));
31823182

3183-
diag.help(&format!(
3183+
diag.help(format!(
31843184
"use data from the highlighted arguments which match the `{}` lifetime of \
31853185
the return type",
31863186
region_name,

compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
9090
{
9191
err.span_label(
9292
pat.span,
93-
&format!("binding `{ident}` declared here"),
93+
format!("binding `{ident}` declared here"),
9494
);
9595
}
9696
}
@@ -323,7 +323,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
323323

324324
err.span_suggestion_verbose(
325325
span.shrink_to_hi(),
326-
&msg,
326+
msg,
327327
format!(" + {suggestable_name}"),
328328
Applicability::Unspecified,
329329
);

compiler/rustc_borrowck/src/diagnostics/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1073,7 +1073,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10731073
if !is_loop_move {
10741074
err.span_suggestion_verbose(
10751075
move_span.shrink_to_lo(),
1076-
&format!(
1076+
format!(
10771077
"consider creating a fresh reborrow of {} here",
10781078
self.describe_place(moved_place.as_ref())
10791079
.map(|n| format!("`{n}`"))

compiler/rustc_borrowck/src/diagnostics/move_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
533533
suggestions.sort_unstable_by_key(|&(span, _, _)| span);
534534
suggestions.dedup_by_key(|&mut (span, _, _)| span);
535535
for (span, msg, suggestion) in suggestions {
536-
err.span_suggestion_verbose(span, &msg, suggestion, Applicability::MachineApplicable);
536+
err.span_suggestion_verbose(span, msg, suggestion, Applicability::MachineApplicable);
537537
}
538538
}
539539

compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
573573
if !is_trait_sig {
574574
err.span_suggestion_verbose(
575575
err_help_span,
576-
&format!(
576+
format!(
577577
"consider changing this to be a mutable {pointer_desc}"
578578
),
579579
suggested_code,
@@ -582,7 +582,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
582582
} else if let Some(x) = local_trait {
583583
err.span_suggestion_verbose(
584584
x,
585-
&format!(
585+
format!(
586586
"consider changing that to be a mutable {pointer_desc}"
587587
),
588588
suggested_code,
@@ -636,14 +636,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
636636
};
637637
err.span_suggestion_verbose(
638638
span,
639-
&format!("consider {changing} this binding's type"),
639+
format!("consider {changing} this binding's type"),
640640
sugg,
641641
Applicability::HasPlaceholders,
642642
);
643643
} else {
644644
err.span_label(
645645
err_label_span,
646-
&format!(
646+
format!(
647647
"consider changing this binding's type to be: `{message}`"
648648
),
649649
);
@@ -679,13 +679,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
679679

680680
match opt_source {
681681
Some(BorrowedContentSource::OverloadedDeref(ty)) => {
682-
err.help(&format!(
682+
err.help(format!(
683683
"trait `DerefMut` is required to modify through a dereference, \
684684
but it is not implemented for `{ty}`",
685685
));
686686
}
687687
Some(BorrowedContentSource::OverloadedIndex(ty)) => {
688-
err.help(&format!(
688+
err.help(format!(
689689
"trait `IndexMut` is required to modify indexed content, \
690690
but it is not implemented for `{ty}`",
691691
));
@@ -736,7 +736,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
736736
// val[index] = rv;
737737
// ---------- place
738738
self.err.multipart_suggestions(
739-
&format!(
739+
format!(
740740
"to modify a `{}`, use `.get_mut()`, `.insert()` or the entry API",
741741
self.ty,
742742
),
@@ -788,7 +788,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
788788
{
789789
// val[index].path(args..);
790790
self.err.multipart_suggestion(
791-
&format!("to modify a `{}` use `.get_mut()`", self.ty),
791+
format!("to modify a `{}` use `.get_mut()`", self.ty),
792792
vec![
793793
(
794794
val.span.shrink_to_hi().with_hi(index.span.lo()),
@@ -822,7 +822,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
822822
let mut v = V { assign_span, err, ty, suggested: false };
823823
v.visit_body(body);
824824
if !v.suggested {
825-
err.help(&format!(
825+
err.help(format!(
826826
"to modify a `{ty}`, use `.get_mut()`, `.insert()` or the entry API",
827827
));
828828
}

compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ impl OutlivesSuggestionBuilder {
171171
if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name)
172172
&& !matches!(outlived_fr_name.source, RegionNameSource::Static)
173173
{
174-
diag.help(&format!(
174+
diag.help(format!(
175175
"consider adding the following bound: `{fr_name}: {outlived_fr_name}`",
176176
));
177177
}
@@ -207,7 +207,7 @@ impl OutlivesSuggestionBuilder {
207207
// If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a
208208
// list of diagnostics.
209209
let mut diag = if suggested.len() == 1 {
210-
mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() {
210+
mbcx.infcx.tcx.sess.diagnostic().struct_help(match suggested.last().unwrap() {
211211
SuggestedConstraint::Outlives(a, bs) => {
212212
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
213213
format!("add bound `{a}: {}`", bs.join(" + "))
@@ -232,15 +232,15 @@ impl OutlivesSuggestionBuilder {
232232
match constraint {
233233
SuggestedConstraint::Outlives(a, bs) => {
234234
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
235-
diag.help(&format!("add bound `{a}: {}`", bs.join(" + ")));
235+
diag.help(format!("add bound `{a}: {}`", bs.join(" + ")));
236236
}
237237
SuggestedConstraint::Equal(a, b) => {
238-
diag.help(&format!(
238+
diag.help(format!(
239239
"`{a}` and `{b}` must be the same: replace one with the other",
240240
));
241241
}
242242
SuggestedConstraint::Static(a) => {
243-
diag.help(&format!("replace `{a}` with `'static`"));
243+
diag.help(format!("replace `{a}` with `'static`"));
244244
}
245245
}
246246
}

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -533,8 +533,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
533533
}
534534
_ => panic!("Unexpected type {ty:?}"),
535535
};
536-
diag.note(&format!("requirement occurs because of {desc}",));
537-
diag.note(&note);
536+
diag.note(format!("requirement occurs because of {desc}",));
537+
diag.note(note);
538538
diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
539539
}
540540
}
@@ -863,7 +863,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
863863
}
864864
spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
865865
diag.multipart_suggestion_verbose(
866-
&format!(
866+
format!(
867867
"to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
868868
),
869869
spans_suggs,

compiler/rustc_borrowck/src/diagnostics/region_name.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
622622
// programs, so we need to use delay_span_bug here. See #82126.
623623
self.infcx.tcx.sess.delay_span_bug(
624624
hir_arg.span(),
625-
&format!("unmatched subst and hir arg: found {kind:?} vs {hir_arg:?}"),
625+
format!("unmatched subst and hir arg: found {kind:?} vs {hir_arg:?}"),
626626
);
627627
}
628628
}

compiler/rustc_borrowck/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2022,7 +2022,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
20222022
// been emitted (#52262).
20232023
self.infcx.tcx.sess.delay_span_bug(
20242024
span,
2025-
&format!(
2025+
format!(
20262026
"Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
20272027
place, kind,
20282028
),
@@ -2383,7 +2383,7 @@ mod error {
23832383
}
23842384
for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
23852385
if count > 10 {
2386-
diag.note(&format!("...and {} other attempted mutable borrows", count - 10));
2386+
diag.note(format!("...and {} other attempted mutable borrows", count - 10));
23872387
}
23882388
diag.buffer(&mut self.errors.buffered);
23892389
}

compiler/rustc_borrowck/src/nll.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ pub(super) fn dump_annotation<'tcx>(
399399

400400
regioncx.annotate(tcx, &mut err);
401401

402-
err.note(&format!(
402+
err.note(format!(
403403
"number of external vids: {}",
404404
closure_region_requirements.num_external_vids
405405
));
@@ -421,7 +421,7 @@ pub(super) fn dump_annotation<'tcx>(
421421
};
422422

423423
if !opaque_type_values.is_empty() {
424-
err.note(&format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
424+
err.note(format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
425425
}
426426

427427
errors.buffer_non_error_diag(err);

compiler/rustc_borrowck/src/region_infer/opaque_types.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ fn check_opaque_type_parameter_valid(
399399
return Err(tcx
400400
.sess
401401
.struct_span_err(span, "non-defining opaque type use in defining scope")
402-
.span_note(spans, &format!("{} used multiple times", descr))
402+
.span_note(spans, format!("{} used multiple times", descr))
403403
.emit());
404404
}
405405
}

compiler/rustc_borrowck/src/type_check/free_region_relations.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
249249
.infcx
250250
.tcx
251251
.sess
252-
.delay_span_bug(span, &format!("failed to normalize {:?}", ty));
252+
.delay_span_bug(span, format!("failed to normalize {:?}", ty));
253253
TypeOpOutput {
254254
output: self.infcx.tcx.ty_error(guar),
255255
constraints: None,

compiler/rustc_borrowck/src/type_check/input_output.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
106106
if body.yield_ty().is_some() != universal_regions.yield_ty.is_some() {
107107
self.tcx().sess.delay_span_bug(
108108
body.span,
109-
&format!(
109+
format!(
110110
"Expected body to have yield_ty ({:?}) iff we have a UR yield_ty ({:?})",
111111
body.yield_ty(),
112112
universal_regions.yield_ty,

compiler/rustc_borrowck/src/type_check/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ pub(crate) fn type_check<'mir, 'tcx>(
236236
if hidden_type.has_non_region_infer() {
237237
let reported = infcx.tcx.sess.delay_span_bug(
238238
decl.hidden_type.span,
239-
&format!("could not resolve {:#?}", hidden_type.ty.kind()),
239+
format!("could not resolve {:#?}", hidden_type.ty.kind()),
240240
);
241241
hidden_type.ty = infcx.tcx.ty_error(reported);
242242
}

0 commit comments

Comments
 (0)