Skip to content

Commit 18d6c43

Browse files
committed
Check bindings around never patterns
1 parent fb6d10d commit 18d6c43

File tree

11 files changed

+102
-104
lines changed

11 files changed

+102
-104
lines changed

compiler/rustc_resolve/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,10 @@ resolve_lowercase_self =
172172
attempt to use a non-constant value in a constant
173173
.suggestion = try using `Self`
174174
175+
resolve_binding_in_never_pattern =
176+
never patterns cannot contain variable bindings
177+
.suggestion = use a wildcard `_` instead
178+
175179
resolve_macro_expected_found =
176180
expected {$expected}, found {$found} `{$macro_path}`
177181

compiler/rustc_resolve/src/diagnostics.rs

+3
Original file line numberDiff line numberDiff line change
@@ -958,6 +958,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
958958
.create_err(errs::TraitImplDuplicate { span, name, trait_item_span, old_span }),
959959
ResolutionError::InvalidAsmSym => self.dcx().create_err(errs::InvalidAsmSym { span }),
960960
ResolutionError::LowercaseSelf => self.dcx().create_err(errs::LowercaseSelf { span }),
961+
ResolutionError::BindingInNeverPattern => {
962+
self.dcx().create_err(errs::BindingInNeverPattern { span })
963+
}
961964
}
962965
}
963966

compiler/rustc_resolve/src/errors.rs

+9
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,15 @@ pub(crate) struct LowercaseSelf {
486486
pub(crate) span: Span,
487487
}
488488

489+
#[derive(Debug)]
490+
#[derive(Diagnostic)]
491+
#[diag(resolve_binding_in_never_pattern)]
492+
pub(crate) struct BindingInNeverPattern {
493+
#[primary_span]
494+
#[suggestion(code = "_", applicability = "machine-applicable", style = "short")]
495+
pub(crate) span: Span,
496+
}
497+
489498
#[derive(Diagnostic)]
490499
#[diag(resolve_trait_impl_duplicate, code = "E0201")]
491500
pub(crate) struct TraitImplDuplicate {

compiler/rustc_resolve/src/late.rs

+37-22
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ enum IsRepeatExpr {
6565
Yes,
6666
}
6767

68+
struct IsNeverPattern;
69+
6870
/// Describes whether an `AnonConst` is a type level const arg or
6971
/// some other form of anon const (i.e. inline consts or enum discriminants)
7072
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
@@ -3182,11 +3184,15 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
31823184
}
31833185

31843186
/// Build a map from pattern identifiers to binding-info's, and check the bindings are
3185-
/// consistent when encountering or-patterns.
3187+
/// consistent when encountering or-patterns and never patterns.
31863188
/// This is done hygienically: this could arise for a macro that expands into an or-pattern
31873189
/// where one 'x' was from the user and one 'x' came from the macro.
3188-
fn compute_and_check_binding_map(&mut self, pat: &Pat) -> FxIndexMap<Ident, BindingInfo> {
3190+
fn compute_and_check_binding_map(
3191+
&mut self,
3192+
pat: &Pat,
3193+
) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
31893194
let mut binding_map = FxIndexMap::default();
3195+
let mut is_never_pat = false;
31903196

31913197
pat.walk(&mut |pat| {
31923198
match pat.kind {
@@ -3198,17 +3204,26 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
31983204
PatKind::Or(ref ps) => {
31993205
// Check the consistency of this or-pattern and
32003206
// then add all bindings to the larger map.
3201-
let bm = self.compute_and_check_or_pat_binding_map(ps);
3207+
let (bm, np) = self.compute_and_check_or_pat_binding_map(ps);
32023208
binding_map.extend(bm);
3209+
is_never_pat |= np;
32033210
return false;
32043211
}
3212+
PatKind::Never => is_never_pat = true,
32053213
_ => {}
32063214
}
32073215

32083216
true
32093217
});
32103218

3211-
binding_map
3219+
if is_never_pat {
3220+
for (_, binding) in binding_map {
3221+
self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
3222+
}
3223+
Err(IsNeverPattern)
3224+
} else {
3225+
Ok(binding_map)
3226+
}
32123227
}
32133228

32143229
fn is_base_res_local(&self, nid: NodeId) -> bool {
@@ -3220,24 +3235,29 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
32203235

32213236
/// Compute the binding map for an or-pattern. Checks that all of the arms in the or-pattern
32223237
/// have exactly the same set of bindings, with the same binding modes for each.
3223-
/// Returns the computed binding map.
3238+
/// Returns the computed binding map and a boolean indicating whether the pattern is a never
3239+
/// pattern.
32243240
fn compute_and_check_or_pat_binding_map(
32253241
&mut self,
32263242
pats: &[P<Pat>],
3227-
) -> FxIndexMap<Ident, BindingInfo> {
3243+
) -> (FxIndexMap<Ident, BindingInfo>, bool) {
32283244
let mut missing_vars = FxIndexMap::default();
32293245
let mut inconsistent_vars = FxIndexMap::default();
32303246

3231-
// 1) Compute the binding maps of all arms.
3232-
let maps =
3233-
pats.iter().map(|pat| self.compute_and_check_binding_map(pat)).collect::<Vec<_>>();
3247+
// 1) Compute the binding maps of all arms; never patterns don't participate in this.
3248+
let not_never_pats = pats
3249+
.iter()
3250+
.filter_map(|pat| {
3251+
let binding_map = self.compute_and_check_binding_map(pat).ok()?;
3252+
Some((binding_map, pat))
3253+
})
3254+
.collect::<Vec<_>>();
32343255

32353256
// 2) Record any missing bindings or binding mode inconsistencies.
3236-
for (map_outer, pat_outer) in maps.iter().zip(pats.iter()) {
3257+
for (map_outer, pat_outer) in not_never_pats.iter() {
32373258
// Check against all arms except for the same pattern which is always self-consistent.
3238-
let inners = maps
3259+
let inners = not_never_pats
32393260
.iter()
3240-
.zip(pats.iter())
32413261
.filter(|(_, pat)| pat.id != pat_outer.id)
32423262
.flat_map(|(map, _)| map);
32433263

@@ -3285,22 +3305,17 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
32853305
}
32863306

32873307
// 5) Bubble up the final binding map.
3308+
let is_never_pat = not_never_pats.is_empty();
32883309
let mut binding_map = FxIndexMap::default();
3289-
for bm in maps {
3310+
for (bm, _) in not_never_pats {
32903311
binding_map.extend(bm);
32913312
}
3292-
binding_map
3313+
(binding_map, is_never_pat)
32933314
}
32943315

3295-
/// Check the consistency of bindings wrt or-patterns.
3316+
/// Check the consistency of bindings wrt or-patterns and never patterns.
32963317
fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
3297-
pat.walk(&mut |pat| match pat.kind {
3298-
PatKind::Or(ref ps) => {
3299-
let _ = self.compute_and_check_or_pat_binding_map(ps);
3300-
false
3301-
}
3302-
_ => true,
3303-
})
3318+
let _ = self.compute_and_check_binding_map(pat);
33043319
}
33053320

33063321
fn resolve_arm(&mut self, arm: &'ast Arm) {

compiler/rustc_resolve/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,8 @@ enum ResolutionError<'a> {
265265
InvalidAsmSym,
266266
/// `self` used instead of `Self` in a generic parameter
267267
LowercaseSelf,
268+
/// A never pattern has a binding.
269+
BindingInNeverPattern,
268270
}
269271

270272
enum VisResolutionError<'a> {

tests/ui/feature-gates/feature-gate-never_patterns.rs

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ fn main() {
77
let res: Result<u32, Void> = Ok(0);
88
let (Ok(_x) | Err(&!)) = res.as_ref();
99
//~^ ERROR `!` patterns are experimental
10-
//~| ERROR: is not bound in all patterns
1110

1211
unsafe {
1312
let ptr: *const Void = NonNull::dangling().as_ptr();
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: unexpected `,` in pattern
2-
--> $DIR/feature-gate-never_patterns.rs:34:16
2+
--> $DIR/feature-gate-never_patterns.rs:33:16
33
|
44
LL | Some(_),
55
| ^
@@ -13,14 +13,6 @@ help: ...or a vertical bar to match on multiple alternatives
1313
LL | Some(_) |
1414
|
1515

16-
error[E0408]: variable `_x` is not bound in all patterns
17-
--> $DIR/feature-gate-never_patterns.rs:8:19
18-
|
19-
LL | let (Ok(_x) | Err(&!)) = res.as_ref();
20-
| -- ^^^^^^^ pattern doesn't bind `_x`
21-
| |
22-
| variable not in all patterns
23-
2416
error[E0658]: `!` patterns are experimental
2517
--> $DIR/feature-gate-never_patterns.rs:8:24
2618
|
@@ -31,7 +23,7 @@ LL | let (Ok(_x) | Err(&!)) = res.as_ref();
3123
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
3224

3325
error[E0658]: `!` patterns are experimental
34-
--> $DIR/feature-gate-never_patterns.rs:15:13
26+
--> $DIR/feature-gate-never_patterns.rs:14:13
3527
|
3628
LL | !
3729
| ^
@@ -40,7 +32,7 @@ LL | !
4032
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
4133

4234
error[E0658]: `!` patterns are experimental
43-
--> $DIR/feature-gate-never_patterns.rs:21:13
35+
--> $DIR/feature-gate-never_patterns.rs:20:13
4436
|
4537
LL | !
4638
| ^
@@ -49,7 +41,7 @@ LL | !
4941
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
5042

5143
error[E0658]: `!` patterns are experimental
52-
--> $DIR/feature-gate-never_patterns.rs:26:13
44+
--> $DIR/feature-gate-never_patterns.rs:25:13
5345
|
5446
LL | ! => {}
5547
| ^
@@ -58,25 +50,25 @@ LL | ! => {}
5850
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
5951

6052
error: `match` arm with no body
61-
--> $DIR/feature-gate-never_patterns.rs:39:9
53+
--> $DIR/feature-gate-never_patterns.rs:38:9
6254
|
6355
LL | Some(_)
6456
| ^^^^^^^- help: add a body after the pattern: `=> todo!(),`
6557

6658
error: `match` arm with no body
67-
--> $DIR/feature-gate-never_patterns.rs:44:9
59+
--> $DIR/feature-gate-never_patterns.rs:43:9
6860
|
6961
LL | Some(_) if false,
7062
| ^^^^^^^- help: add a body after the pattern: `=> todo!(),`
7163

7264
error: `match` arm with no body
73-
--> $DIR/feature-gate-never_patterns.rs:46:9
65+
--> $DIR/feature-gate-never_patterns.rs:45:9
7466
|
7567
LL | Some(_) if false
7668
| ^^^^^^^- help: add a body after the pattern: `=> todo!(),`
7769

7870
error[E0658]: `!` patterns are experimental
79-
--> $DIR/feature-gate-never_patterns.rs:51:13
71+
--> $DIR/feature-gate-never_patterns.rs:50:13
8072
|
8173
LL | Err(!),
8274
| ^
@@ -85,7 +77,7 @@ LL | Err(!),
8577
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
8678

8779
error[E0658]: `!` patterns are experimental
88-
--> $DIR/feature-gate-never_patterns.rs:55:13
80+
--> $DIR/feature-gate-never_patterns.rs:54:13
8981
|
9082
LL | Err(!) if false,
9183
| ^
@@ -94,24 +86,23 @@ LL | Err(!) if false,
9486
= help: add `#![feature(never_patterns)]` to the crate attributes to enable
9587

9688
error: `match` arm with no body
97-
--> $DIR/feature-gate-never_patterns.rs:65:9
89+
--> $DIR/feature-gate-never_patterns.rs:64:9
9890
|
9991
LL | Some(_)
10092
| ^^^^^^^- help: add a body after the pattern: `=> todo!(),`
10193

10294
error: `match` arm with no body
103-
--> $DIR/feature-gate-never_patterns.rs:71:9
95+
--> $DIR/feature-gate-never_patterns.rs:70:9
10496
|
10597
LL | Some(_) if false
10698
| ^^^^^^^- help: add a body after the pattern: `=> todo!(),`
10799

108100
error: a guard on a never pattern will never be run
109-
--> $DIR/feature-gate-never_patterns.rs:55:19
101+
--> $DIR/feature-gate-never_patterns.rs:54:19
110102
|
111103
LL | Err(!) if false,
112104
| ^^^^^ help: remove this guard
113105

114-
error: aborting due to 14 previous errors
106+
error: aborting due to 13 previous errors
115107

116-
Some errors have detailed explanations: E0408, E0658.
117-
For more information about an error, try `rustc --explain E0408`.
108+
For more information about this error, try `rustc --explain E0658`.

tests/ui/pattern/never_patterns.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,9 @@ fn main() {}
77

88
// The classic use for empty types.
99
fn safe_unwrap_result<T>(res: Result<T, Void>) {
10-
let Ok(_x) = res;
11-
// FIXME(never_patterns): These should be allowed
10+
let Ok(_x) = res; //~ ERROR refutable pattern in local binding
1211
let (Ok(_x) | Err(!)) = &res;
13-
//~^ ERROR: is not bound in all patterns
1412
let (Ok(_x) | Err(&!)) = res.as_ref();
15-
//~^ ERROR: is not bound in all patterns
1613
}
1714

1815
// Check we only accept `!` where we want to.
+13-15
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
1-
error[E0408]: variable `_x` is not bound in all patterns
2-
--> $DIR/never_patterns.rs:12:19
1+
error[E0005]: refutable pattern in local binding
2+
--> $DIR/never_patterns.rs:10:9
33
|
4-
LL | let (Ok(_x) | Err(!)) = &res;
5-
| -- ^^^^^^ pattern doesn't bind `_x`
6-
| |
7-
| variable not in all patterns
8-
9-
error[E0408]: variable `_x` is not bound in all patterns
10-
--> $DIR/never_patterns.rs:14:19
4+
LL | let Ok(_x) = res;
5+
| ^^^^^^ pattern `Err(_)` not covered
6+
|
7+
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
8+
= note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
9+
= note: the matched value is of type `Result<T, Void>`
10+
help: you might want to use `let else` to handle the variant that isn't matched
1111
|
12-
LL | let (Ok(_x) | Err(&!)) = res.as_ref();
13-
| -- ^^^^^^^ pattern doesn't bind `_x`
14-
| |
15-
| variable not in all patterns
12+
LL | let Ok(_x) = res else { todo!() };
13+
| ++++++++++++++++
1614

17-
error: aborting due to 2 previous errors
15+
error: aborting due to 1 previous error
1816

19-
For more information about this error, try `rustc --explain E0408`.
17+
For more information about this error, try `rustc --explain E0005`.

tests/ui/rfcs/rfc-0000-never_patterns/bindings.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,20 @@ enum Void {}
66
fn main() {
77
let x: Result<bool, &(u32, u32, Void)> = Ok(false);
88

9-
// FIXME(never_patterns): Never patterns in or-patterns don't need to share the same bindings.
109
match x {
1110
Ok(_x) | Err(&!) => {}
12-
//~^ ERROR: is not bound in all patterns
1311
}
1412
let (Ok(_x) | Err(&!)) = x;
15-
//~^ ERROR: is not bound in all patterns
1613

17-
// FIXME(never_patterns): A never pattern mustn't have bindings.
1814
match x {
1915
Ok(_) => {}
2016
Err(&(_a, _b, !)),
17+
//~^ ERROR: never patterns cannot contain variable bindings
18+
//~| ERROR: never patterns cannot contain variable bindings
2119
}
2220
match x {
2321
Ok(_ok) | Err(&(_a, _b, !)) => {}
24-
//~^ ERROR: is not bound in all patterns
25-
//~| ERROR: is not bound in all patterns
26-
//~| ERROR: is not bound in all patterns
22+
//~^ ERROR: never patterns cannot contain variable bindings
23+
//~| ERROR: never patterns cannot contain variable bindings
2724
}
2825
}

0 commit comments

Comments
 (0)