Skip to content

Commit d29804c

Browse files
committed
try to suggest eliding redundant binding modifiers
1 parent 91108b0 commit d29804c

File tree

7 files changed

+82
-49
lines changed

7 files changed

+82
-49
lines changed

Diff for: compiler/rustc_hir_typeck/src/pat.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -2786,7 +2786,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27862786

27872787
let mut typeck_results = self.typeck_results.borrow_mut();
27882788
let mut table = typeck_results.rust_2024_migration_desugared_pats_mut();
2789-
let info = table.entry(pat_id).or_default();
2789+
// FIXME(ref_pat_eat_one_layer_2024): The migration diagnostic doesn't know how to track the
2790+
// default binding mode in the presence of Rule 3 or Rule 5. As a consequence, the labels it
2791+
// gives for default binding modes are wrong, as well as suggestions based on the default
2792+
// binding mode. This keeps it from making those suggestions, as doing so could panic.
2793+
let info = table.entry(pat_id).or_insert_with(|| ty::Rust2024IncompatiblePatInfo {
2794+
primary_labels: Vec::new(),
2795+
bad_modifiers: false,
2796+
bad_ref_pats: false,
2797+
suggest_eliding_modes: !self.tcx.features().ref_pat_eat_one_layer_2024()
2798+
&& !self.tcx.features().ref_pat_eat_one_layer_2024_structural(),
2799+
});
27902800

27912801
// Only provide a detailed label if the problematic subpattern isn't from an expansion.
27922802
// In the case that it's from a macro, we'll add a more detailed note in the emitter.
@@ -2797,11 +2807,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
27972807
// so, we may want to inspect the span's source callee or macro backtrace.
27982808
"occurs within macro expansion".to_owned()
27992809
} else {
2800-
let pat_kind = if matches!(subpat.kind, PatKind::Binding(_, _, _, _)) {
2810+
let pat_kind = if let PatKind::Binding(user_bind_annot, _, _, _) = subpat.kind {
28012811
info.bad_modifiers |= true;
2812+
// If the user-provided binding modifier doesn't match the default binding mode, we'll
2813+
// need to suggest reference patterns, which can affect other bindings.
2814+
// For simplicity, we opt to suggest making the pattern fully explicit.
2815+
info.suggest_eliding_modes &=
2816+
user_bind_annot == BindingMode(ByRef::Yes(def_br_mutbl), Mutability::Not);
28022817
"binding modifier"
28032818
} else {
28042819
info.bad_ref_pats |= true;
2820+
// For simplicity, we don't try to suggest eliding reference patterns. Thus, we'll
2821+
// suggest adding them instead, which can affect the types assigned to bindings.
2822+
// As such, we opt to suggest making the pattern fully explicit.
2823+
info.suggest_eliding_modes = false;
28052824
"reference pattern"
28062825
};
28072826
let dbm_str = match def_br_mutbl {

Diff for: compiler/rustc_middle/src/ty/typeck_results.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -814,12 +814,14 @@ impl<'tcx> std::fmt::Display for UserTypeKind<'tcx> {
814814

815815
/// Information on a pattern incompatible with Rust 2024, for use by the error/migration diagnostic
816816
/// emitted during THIR construction.
817-
#[derive(TyEncodable, TyDecodable, Debug, HashStable, Default)]
817+
#[derive(TyEncodable, TyDecodable, Debug, HashStable)]
818818
pub struct Rust2024IncompatiblePatInfo {
819819
/// Labeled spans for `&`s, `&mut`s, and binding modifiers incompatible with Rust 2024.
820820
pub primary_labels: Vec<(Span, String)>,
821821
/// Whether any binding modifiers occur under a non-`move` default binding mode.
822822
pub bad_modifiers: bool,
823823
/// Whether any `&` or `&mut` patterns occur under a non-`move` default binding mode.
824824
pub bad_ref_pats: bool,
825+
/// If `true`, we can give a simpler suggestion solely by eliding explicit binding modifiers.
826+
pub suggest_eliding_modes: bool,
825827
}

Diff for: compiler/rustc_mir_build/src/errors.rs

+14-9
Original file line numberDiff line numberDiff line change
@@ -1107,6 +1107,9 @@ pub(crate) struct Rust2024IncompatiblePat {
11071107
}
11081108

11091109
pub(crate) struct Rust2024IncompatiblePatSugg {
1110+
/// If true, our suggestion is to elide explicit binding modifiers.
1111+
/// If false, our suggestion is to make the pattern fully explicit.
1112+
pub(crate) suggest_eliding_modes: bool,
11101113
pub(crate) suggestion: Vec<(Span, String)>,
11111114
pub(crate) ref_pattern_count: usize,
11121115
pub(crate) binding_mode_count: usize,
@@ -1153,16 +1156,18 @@ impl Subdiagnostic for Rust2024IncompatiblePatSugg {
11531156
} else {
11541157
Applicability::MaybeIncorrect
11551158
};
1156-
let plural_derefs = pluralize!(self.ref_pattern_count);
1157-
let and_modes = if self.binding_mode_count > 0 {
1158-
format!(" and variable binding mode{}", pluralize!(self.binding_mode_count))
1159+
let msg = if self.suggest_eliding_modes {
1160+
let plural_modes = pluralize!(self.binding_mode_count);
1161+
format!("remove the unnecessary binding modifier{plural_modes}")
11591162
} else {
1160-
String::new()
1163+
let plural_derefs = pluralize!(self.ref_pattern_count);
1164+
let and_modes = if self.binding_mode_count > 0 {
1165+
format!(" and variable binding mode{}", pluralize!(self.binding_mode_count))
1166+
} else {
1167+
String::new()
1168+
};
1169+
format!("make the implied reference pattern{plural_derefs}{and_modes} explicit")
11611170
};
1162-
diag.multipart_suggestion_verbose(
1163-
format!("make the implied reference pattern{plural_derefs}{and_modes} explicit"),
1164-
self.suggestion,
1165-
applicability,
1166-
);
1171+
diag.multipart_suggestion_verbose(msg, self.suggestion, applicability);
11671172
}
11681173
}

Diff for: compiler/rustc_mir_build/src/thir/pattern/mod.rs

+31-27
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,16 @@ pub(super) fn pat_from_hir<'a, 'tcx>(
4949
tcx,
5050
typing_env,
5151
typeck_results,
52-
rust_2024_migration_suggestion: migration_info.and(Some(Rust2024IncompatiblePatSugg {
53-
suggestion: Vec::new(),
54-
ref_pattern_count: 0,
55-
binding_mode_count: 0,
56-
default_mode_span: None,
57-
default_mode_labels: Default::default(),
58-
})),
52+
rust_2024_migration_suggestion: migration_info.and_then(|info| {
53+
Some(Rust2024IncompatiblePatSugg {
54+
suggest_eliding_modes: info.suggest_eliding_modes,
55+
suggestion: Vec::new(),
56+
ref_pattern_count: 0,
57+
binding_mode_count: 0,
58+
default_mode_span: None,
59+
default_mode_labels: Default::default(),
60+
})
61+
}),
5962
};
6063
let result = pcx.lower_pattern(pat);
6164
debug!("pat_from_hir({:?}) = {:?}", pat, result);
@@ -106,27 +109,22 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
106109
if let Some(s) = &mut self.rust_2024_migration_suggestion
107110
&& !adjustments.is_empty()
108111
{
109-
let mut min_mutbl = Mutability::Mut;
110-
let suggestion_str: String = adjustments
111-
.iter()
112-
.map(|ref_ty| {
113-
let &ty::Ref(_, _, mutbl) = ref_ty.kind() else {
114-
span_bug!(pat.span, "pattern implicitly dereferences a non-ref type");
115-
};
116-
117-
match mutbl {
118-
Mutability::Not => {
119-
min_mutbl = Mutability::Not;
120-
"&"
121-
}
122-
Mutability::Mut => "&mut ",
123-
}
124-
})
125-
.collect();
126-
s.suggestion.push((pat.span.shrink_to_lo(), suggestion_str));
127-
s.ref_pattern_count += adjustments.len();
112+
let implicit_deref_mutbls = adjustments.iter().map(|ref_ty| {
113+
let &ty::Ref(_, _, mutbl) = ref_ty.kind() else {
114+
span_bug!(pat.span, "pattern implicitly dereferences a non-ref type");
115+
};
116+
mutbl
117+
});
118+
119+
if !s.suggest_eliding_modes {
120+
let suggestion_str: String =
121+
implicit_deref_mutbls.clone().map(|mutbl| mutbl.ref_prefix_str()).collect();
122+
s.suggestion.push((pat.span.shrink_to_lo(), suggestion_str));
123+
s.ref_pattern_count += adjustments.len();
124+
}
128125

129126
// Remember if this changed the default binding mode, in case we want to label it.
127+
let min_mutbl = implicit_deref_mutbls.min().unwrap();
130128
if s.default_mode_span.is_none_or(|(_, old_mutbl)| min_mutbl < old_mutbl) {
131129
opt_old_mode_span = Some(s.default_mode_span);
132130
s.default_mode_span = Some((pat.span, min_mutbl));
@@ -412,8 +410,14 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
412410
{
413411
// If this overrides a by-ref default binding mode, label the binding mode.
414412
s.default_mode_labels.insert(default_mode_span, default_ref_mutbl);
413+
// If our suggestion is to elide redundnt modes, this will be one of them.
414+
if s.suggest_eliding_modes {
415+
s.suggestion.push((pat.span.with_hi(ident.span.lo()), String::new()));
416+
s.binding_mode_count += 1;
417+
}
415418
}
416-
if explicit_ba.0 == ByRef::No
419+
if !s.suggest_eliding_modes
420+
&& explicit_ba.0 == ByRef::No
417421
&& let ByRef::Yes(mutbl) = mode.0
418422
{
419423
let sugg_str = match mutbl {

Diff for: tests/ui/pattern/rfc-3627-match-ergonomics-2024/migration_lint.fixed

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ fn main() {
3232
//~| WARN: this changes meaning in Rust 2024
3333
assert_type_eq(x, 0u8);
3434

35-
let &Foo(ref x) = &Foo(0);
35+
let Foo(x) = &Foo(0);
3636
//~^ ERROR: binding modifiers may only be written when the default binding mode is `move` in Rust 2024
3737
//~| WARN: this changes meaning in Rust 2024
3838
assert_type_eq(x, &0u8);

Diff for: tests/ui/pattern/rfc-3627-match-ergonomics-2024/migration_lint.stderr

+4-3
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,11 @@ LL | let Foo(ref x) = &Foo(0);
5858
| ^---------
5959
| |
6060
| the default binding mode is `ref`, introduced here
61-
help: make the implied reference pattern explicit
61+
help: remove the unnecessary binding modifier
62+
|
63+
LL - let Foo(ref x) = &Foo(0);
64+
LL + let Foo(x) = &Foo(0);
6265
|
63-
LL | let &Foo(ref x) = &Foo(0);
64-
| +
6566

6667
error: binding modifiers may only be written when the default binding mode is `move` in Rust 2024
6768
--> $DIR/migration_lint.rs:40:13

Diff for: tests/ui/pattern/rfc-3627-match-ergonomics-2024/min_match_ergonomics_fail.stderr

+8-6
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,11 @@ LL | test_pat_on_type![(ref x,): &(T,)];
189189
| ^-------
190190
| |
191191
| the default binding mode is `ref`, introduced here
192-
help: make the implied reference pattern explicit
192+
help: remove the unnecessary binding modifier
193+
|
194+
LL - test_pat_on_type![(ref x,): &(T,)];
195+
LL + test_pat_on_type![(x,): &(T,)];
193196
|
194-
LL | test_pat_on_type![&(ref x,): &(T,)];
195-
| +
196197

197198
error: binding modifiers may only be written when the default binding mode is `move`
198199
--> $DIR/min_match_ergonomics_fail.rs:34:20
@@ -208,10 +209,11 @@ LL | test_pat_on_type![(ref mut x,): &mut (T,)];
208209
| ^-----------
209210
| |
210211
| the default binding mode is `ref mut`, introduced here
211-
help: make the implied reference pattern explicit
212+
help: remove the unnecessary binding modifier
213+
|
214+
LL - test_pat_on_type![(ref mut x,): &mut (T,)];
215+
LL + test_pat_on_type![(x,): &mut (T,)];
212216
|
213-
LL | test_pat_on_type![&mut (ref mut x,): &mut (T,)];
214-
| ++++
215217

216218
error: reference patterns may only be written when the default binding mode is `move`
217219
--> $DIR/min_match_ergonomics_fail.rs:43:10

0 commit comments

Comments
 (0)