Skip to content

Commit 0d76b73

Browse files
committed
Auto merge of rust-lang#83918 - workingjubilee:stable-rangefrom-pat, r=joshtriplett
Stabilize "RangeFrom" patterns in 1.55 Implements a partial stabilization of rust-lang#67264 and rust-lang#37854. Reference PR: rust-lang/reference#900 # Stabilization Report This stabilizes the `X..` pattern, shown as such, offering an exhaustive match for unsigned integers: ```rust match x as u32 { 0 => println!("zero!"), 1.. => println!("positive number!"), } ``` Currently if a Rust author wants to write such a match on an integer, they must use `1..={integer}::MAX` . By allowing a "RangeFrom" style pattern, this simplifies the match to not require the MAX path and thus not require specifically repeating the type inside the match, allowing for easier refactoring. This is particularly useful for instances like the above case, where different behavior on "0" vs. "1 or any positive number" is desired, and the actual MAX is unimportant. Notably, this excepts slice patterns which include half-open ranges from stabilization, as the wisdom of those is still subject to some debate. ## Practical Applications Instances of this specific usage have appeared in the compiler: https://github.com/rust-lang/rust/blob/16143d10679537d3fde4247e15334e78ad9d55b9/compiler/rustc_middle/src/ty/inhabitedness/mod.rs#L219 https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/compiler/rustc_ty_utils/src/ty.rs#L524 And I have noticed there are also a handful of "in the wild" users who have deployed it to similar effect, especially in the case of rejecting any value of a certain number or greater. It simply makes it much more ergonomic to write an irrefutable match, as done in Katholieke Universiteit Leuven's [SCALE and MAMBA project](https://github.com/KULeuven-COSIC/SCALE-MAMBA/blob/05e5db00d553573534258585651c525d0da5f83f/WebAssembly/scale_std/src/fixed_point.rs#L685-L695). ## Tests There were already many tests in [src/test/ui/half-open-range/patterns](https://github.com/rust-lang/rust/tree/90a2e5e3fe59a254d4d707aa291517b3791ea5a6/src/test/ui/half-open-range-patterns), as well as [generic pattern tests that test the `exclusive_range_pattern` feature](https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/src/test/ui/pattern/usefulness/integer-ranges/reachability.rs), many dating back to the feature's introduction and remaining standing to this day. However, this stabilization comes with some additional tests to explore the... sometimes interesting behavior of interactions with other patterns. e.g. There is, at least, a mild diagnostic improvement in some edge cases, because before now, the pattern `0..=(5+1)` encounters the `half_open_range_patterns` feature gate and can thus emit the request to enable the feature flag, while also emitting the "inclusive range with no end" diagnostic. There is no intent to allow an `X..=` pattern that I am aware of, so removing the flag request is a strict improvement. The arrival of the `J | K` "or" pattern also enables some odd formations. Some of the behavior tested for here is derived from experiments in this [Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=58777b3c715c85165ac4a70d93efeefc) example, linked at rust-lang#67264 (comment), which may be useful to reference to observe the current behavior more closely. In addition tests constituting an explanation of the "slicing range patterns" syntax issue are included in this PR. ## Desiderata The exclusive range patterns and half-open range patterns are fairly strongly requested by many authors, as they make some patterns much more natural to write, but there is disagreement regarding the "closed" exclusive range pattern or the "RangeTo" pattern, especially where it creates "off by one" gaps in the presence of a "catch-all" wildcard case. Also, there are obviously no range analyses in place that will force diagnostics for e.g. highly overlapping matches. I believe these should be warned on, ideally, and I think it would be reasonable to consider such a blocker to stabilizing this feature, but there is no technical issue with the feature as-is from the purely syntactic perspective as such overlapping or missed matches can already be generated today with such a catch-all case. And part of the "point" of the feature, at least from my view, is to make it easier to omit wildcard matches: a pattern with such an "open" match produces an irrefutable match and does not need the wild card case, making it easier to benefit from exhaustiveness checking. ## History - Implemented: - Partially via exclusive ranges: rust-lang#35712 - Fully with half-open ranges: rust-lang#67258 - Unresolved Questions: - The precedence concerns of rust-lang#48501 were considered as likely requiring adjustment but probably wanting a uniform consistent change across all pattern styles, given rust-lang#67264 (comment), but it is still unknown what changes might be desired - How we want to handle slice patterns in ranges seems to be an open question still, as witnessed in the discussion of this PR! I checked but I couldn't actually find an RFC for this, and given "approved provisionally by lang team without an RFC", I believe this might require an RFC before it can land? Unsure of procedure here, on account of this being stabilizing a subset of a feature of syntax. r? `@scottmcm`
2 parents 9f2e753 + 43bad44 commit 0d76b73

19 files changed

+378
-40
lines changed

compiler/rustc_ast/src/ast.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -677,7 +677,9 @@ pub enum BindingMode {
677677

678678
#[derive(Clone, Encodable, Decodable, Debug)]
679679
pub enum RangeEnd {
680+
/// `..=` or `...`
680681
Included(RangeSyntax),
682+
/// `..`
681683
Excluded,
682684
}
683685

@@ -689,6 +691,7 @@ pub enum RangeSyntax {
689691
DotDotEq,
690692
}
691693

694+
/// All the different flavors of pattern that Rust recognizes.
692695
#[derive(Clone, Encodable, Decodable, Debug)]
693696
pub enum PatKind {
694697
/// Represents a wildcard pattern (`_`).
@@ -729,7 +732,7 @@ pub enum PatKind {
729732
/// A literal.
730733
Lit(P<Expr>),
731734

732-
/// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
735+
/// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
733736
Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
734737

735738
/// A slice pattern `[a, b, c]`.

compiler/rustc_ast_passes/src/feature_gate.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,22 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
565565

566566
fn visit_pat(&mut self, pattern: &'a ast::Pat) {
567567
match &pattern.kind {
568+
PatKind::Slice(pats) => {
569+
for pat in pats {
570+
let inner_pat = match &pat.kind {
571+
PatKind::Ident(.., Some(pat)) => pat,
572+
_ => pat,
573+
};
574+
if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
575+
gate_feature_post!(
576+
&self,
577+
half_open_range_patterns,
578+
pat.span,
579+
"`X..` patterns in slices are experimental"
580+
);
581+
}
582+
}
583+
}
568584
PatKind::Box(..) => {
569585
gate_feature_post!(
570586
&self,
@@ -573,7 +589,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
573589
"box pattern syntax is experimental"
574590
);
575591
}
576-
PatKind::Range(_, _, Spanned { node: RangeEnd::Excluded, .. }) => {
592+
PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => {
577593
gate_feature_post!(
578594
&self,
579595
exclusive_range_pattern,

compiler/rustc_parse/src/parser/pat.rs

-2
Original file line numberDiff line numberDiff line change
@@ -715,7 +715,6 @@ impl<'a> Parser<'a> {
715715
} else if self.eat(&token::DotDotEq) {
716716
RangeEnd::Included(RangeSyntax::DotDotEq)
717717
} else if self.eat(&token::DotDot) {
718-
self.sess.gated_spans.gate(sym::exclusive_range_pattern, self.prev_token.span);
719718
RangeEnd::Excluded
720719
} else {
721720
return None;
@@ -735,7 +734,6 @@ impl<'a> Parser<'a> {
735734
Some(self.parse_pat_range_end()?)
736735
} else {
737736
// Parsing e.g. `X..`.
738-
self.sess.gated_spans.gate(sym::half_open_range_patterns, begin.span.to(re.span));
739737
if let RangeEnd::Included(_) = re.node {
740738
// FIXME(Centril): Consider semantic errors instead in `ast_validation`.
741739
// Possibly also do this for `X..=` in *expression* contexts.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# `exclusive_range_pattern`
2+
3+
The tracking issue for this feature is: [#37854].
4+
5+
6+
[#67264]: https://github.com/rust-lang/rust/issues/67264
7+
[#37854]: https://github.com/rust-lang/rust/issues/37854
8+
-----
9+
10+
The `exclusive_range_pattern` feature allows non-inclusive range
11+
patterns (`0..10`) to be used in appropriate pattern matching
12+
contexts. It also can be combined with `#![feature(half_open_range_patterns]`
13+
to be able to use RangeTo patterns (`..10`).
14+
15+
It also enabled RangeFrom patterns but that has since been
16+
stabilized.
17+
18+
```rust
19+
#![feature(exclusive_range_pattern)]
20+
let x = 5;
21+
match x {
22+
0..10 => println!("single digit"),
23+
10 => println!("ten isn't part of the above range"),
24+
_ => println!("nor is everything else.")
25+
}
26+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# `half_open_range_patterns`
2+
3+
The tracking issue for this feature is: [#67264]
4+
It is part of the `#![exclusive_range_pattern]` feature,
5+
tracked at [#37854].
6+
7+
[#67264]: https://github.com/rust-lang/rust/issues/67264
8+
[#37854]: https://github.com/rust-lang/rust/issues/37854
9+
-----
10+
11+
The `half_open_range_patterns` feature allows RangeTo patterns
12+
(`..10`) to be used in appropriate pattern matching contexts.
13+
This requires also enabling the `exclusive_range_pattern` feature.
14+
15+
It also enabled RangeFrom patterns but that has since been
16+
stabilized.
17+
18+
```rust
19+
#![feature(half_open_range_patterns)]
20+
#![feature(exclusive_range_pattern)]
21+
let x = 5;
22+
match x {
23+
..0 => println!("negative!"), // "RangeTo" pattern. Unstable.
24+
0 => println!("zero!"),
25+
1.. => println!("positive!"), // "RangeFrom" pattern. Stable.
26+
}
27+
```

src/test/ui/half-open-range-patterns/feature-gate-half-open-range-patterns.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,8 @@ fn foo() {
1111
//~| ERROR range-to patterns with `...` are not allowed
1212
if let ..5 = 0 {}
1313
//~^ ERROR half-open range patterns are unstable
14-
if let 5.. = 0 {}
15-
//~^ ERROR half-open range patterns are unstable
1614
if let 5..= = 0 {}
17-
//~^ ERROR half-open range patterns are unstable
18-
//~| ERROR inclusive range with no end
15+
//~^ ERROR inclusive range with no end
1916
if let 5... = 0 {}
20-
//~^ ERROR half-open range patterns are unstable
21-
//~| ERROR inclusive range with no end
17+
//~^ ERROR inclusive range with no end
2218
}

src/test/ui/half-open-range-patterns/feature-gate-half-open-range-patterns.stderr

+3-30
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@ LL | if let ...5 = 0 {}
55
| ^^^ help: use `..=` instead
66

77
error[E0586]: inclusive range with no end
8-
--> $DIR/feature-gate-half-open-range-patterns.rs:16:13
8+
--> $DIR/feature-gate-half-open-range-patterns.rs:14:13
99
|
1010
LL | if let 5..= = 0 {}
1111
| ^^^ help: use `..` instead
1212
|
1313
= note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`)
1414

1515
error[E0586]: inclusive range with no end
16-
--> $DIR/feature-gate-half-open-range-patterns.rs:19:13
16+
--> $DIR/feature-gate-half-open-range-patterns.rs:16:13
1717
|
1818
LL | if let 5... = 0 {}
1919
| ^^^ help: use `..` instead
@@ -47,34 +47,7 @@ LL | if let ..5 = 0 {}
4747
= note: see issue #67264 <https://github.com/rust-lang/rust/issues/67264> for more information
4848
= help: add `#![feature(half_open_range_patterns)]` to the crate attributes to enable
4949

50-
error[E0658]: half-open range patterns are unstable
51-
--> $DIR/feature-gate-half-open-range-patterns.rs:14:12
52-
|
53-
LL | if let 5.. = 0 {}
54-
| ^^^
55-
|
56-
= note: see issue #67264 <https://github.com/rust-lang/rust/issues/67264> for more information
57-
= help: add `#![feature(half_open_range_patterns)]` to the crate attributes to enable
58-
59-
error[E0658]: half-open range patterns are unstable
60-
--> $DIR/feature-gate-half-open-range-patterns.rs:16:12
61-
|
62-
LL | if let 5..= = 0 {}
63-
| ^^^^
64-
|
65-
= note: see issue #67264 <https://github.com/rust-lang/rust/issues/67264> for more information
66-
= help: add `#![feature(half_open_range_patterns)]` to the crate attributes to enable
67-
68-
error[E0658]: half-open range patterns are unstable
69-
--> $DIR/feature-gate-half-open-range-patterns.rs:19:12
70-
|
71-
LL | if let 5... = 0 {}
72-
| ^^^^
73-
|
74-
= note: see issue #67264 <https://github.com/rust-lang/rust/issues/67264> for more information
75-
= help: add `#![feature(half_open_range_patterns)]` to the crate attributes to enable
76-
77-
error: aborting due to 9 previous errors
50+
error: aborting due to 6 previous errors
7851

7952
Some errors have detailed explanations: E0586, E0658.
8053
For more information about an error, try `rustc --explain E0586`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// run-pass
2+
#![allow(incomplete_features)]
3+
#![feature(exclusive_range_pattern)]
4+
#![feature(half_open_range_patterns)]
5+
#![feature(inline_const)]
6+
7+
fn main() {
8+
let mut if_lettable = vec![];
9+
let mut first_or = vec![];
10+
let mut or_two = vec![];
11+
let mut range_from = vec![];
12+
let mut bottom = vec![];
13+
14+
for x in -9 + 1..=(9 - 2) {
15+
if let -1..=0 | 2..3 | 4 = x {
16+
if_lettable.push(x)
17+
}
18+
match x {
19+
1 | -3..0 => first_or.push(x),
20+
y @ (0..5 | 6) => or_two.push(y),
21+
y @ 0..const { 5 + 1 } => assert_eq!(y, 5),
22+
y @ -5.. => range_from.push(y),
23+
y @ ..-7 => assert_eq!(y, -8),
24+
y => bottom.push(y),
25+
}
26+
}
27+
assert_eq!(if_lettable, [-1, 0, 2, 4]);
28+
assert_eq!(first_or, [-3, -2, -1, 1]);
29+
assert_eq!(or_two, [0, 2, 3, 4, 6]);
30+
assert_eq!(range_from, [-5, -4, 7]);
31+
assert_eq!(bottom, [-7, -6]);
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
fn main() {
2+
let mut if_lettable = Vec::<i32>::new();
3+
let mut first_or = Vec::<i32>::new();
4+
let mut or_two = Vec::<i32>::new();
5+
let mut range_from = Vec::<i32>::new();
6+
let mut bottom = Vec::<i32>::new();
7+
let mut errors_only = Vec::<i32>::new();
8+
9+
for x in -9 + 1..=(9 - 2) {
10+
if let n @ 2..3|4 = x {
11+
//~^ error: variable `n` is not bound in all patterns
12+
//~| exclusive range pattern syntax is experimental
13+
errors_only.push(x);
14+
} else if let 2..3 | 4 = x {
15+
//~^ exclusive range pattern syntax is experimental
16+
if_lettable.push(x);
17+
}
18+
match x as i32 {
19+
0..5+1 => errors_only.push(x),
20+
//~^ error: expected one of `=>`, `if`, or `|`, found `+`
21+
1 | -3..0 => first_or.push(x),
22+
y @ (0..5 | 6) => or_two.push(y),
23+
y @ 0..const { 5 + 1 } => assert_eq!(y, 5),
24+
y @ -5.. => range_from.push(y),
25+
y @ ..-7 => assert_eq!(y, -8),
26+
y => bottom.push(y),
27+
}
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
error: expected one of `=>`, `if`, or `|`, found `+`
2+
--> $DIR/range_pat_interactions1.rs:19:17
3+
|
4+
LL | 0..5+1 => errors_only.push(x),
5+
| ^ expected one of `=>`, `if`, or `|`
6+
7+
error[E0408]: variable `n` is not bound in all patterns
8+
--> $DIR/range_pat_interactions1.rs:10:25
9+
|
10+
LL | if let n @ 2..3|4 = x {
11+
| - ^ pattern doesn't bind `n`
12+
| |
13+
| variable not in all patterns
14+
15+
error[E0658]: exclusive range pattern syntax is experimental
16+
--> $DIR/range_pat_interactions1.rs:10:20
17+
|
18+
LL | if let n @ 2..3|4 = x {
19+
| ^^^^
20+
|
21+
= note: see issue #37854 <https://github.com/rust-lang/rust/issues/37854> for more information
22+
= help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable
23+
24+
error[E0658]: exclusive range pattern syntax is experimental
25+
--> $DIR/range_pat_interactions1.rs:14:23
26+
|
27+
LL | } else if let 2..3 | 4 = x {
28+
| ^^^^
29+
|
30+
= note: see issue #37854 <https://github.com/rust-lang/rust/issues/37854> for more information
31+
= help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable
32+
33+
error: aborting due to 4 previous errors
34+
35+
Some errors have detailed explanations: E0408, E0658.
36+
For more information about an error, try `rustc --explain E0408`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
fn main() {
2+
let mut first_or = Vec::<i32>::new();
3+
let mut or_two = Vec::<i32>::new();
4+
let mut range_from = Vec::<i32>::new();
5+
let mut bottom = Vec::<i32>::new();
6+
let mut errors_only = Vec::<i32>::new();
7+
8+
for x in -9 + 1..=(9 - 2) {
9+
match x as i32 {
10+
0..=(5+1) => errors_only.push(x),
11+
//~^ error: inclusive range with no end
12+
//~| error: expected one of `=>`, `if`, or `|`, found `(`
13+
1 | -3..0 => first_or.push(x),
14+
y @ (0..5 | 6) => or_two.push(y),
15+
y @ 0..const { 5 + 1 } => assert_eq!(y, 5),
16+
y @ -5.. => range_from.push(y),
17+
y @ ..-7 => assert_eq!(y, -8),
18+
y => bottom.push(y),
19+
}
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0586]: inclusive range with no end
2+
--> $DIR/range_pat_interactions2.rs:10:14
3+
|
4+
LL | 0..=(5+1) => errors_only.push(x),
5+
| ^^^ help: use `..` instead
6+
|
7+
= note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`)
8+
9+
error: expected one of `=>`, `if`, or `|`, found `(`
10+
--> $DIR/range_pat_interactions2.rs:10:17
11+
|
12+
LL | 0..=(5+1) => errors_only.push(x),
13+
| ^ expected one of `=>`, `if`, or `|`
14+
15+
error: aborting due to 2 previous errors
16+
17+
For more information about this error, try `rustc --explain E0586`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
fn main() {
2+
let mut first_or = Vec::<i32>::new();
3+
let mut or_two = Vec::<i32>::new();
4+
let mut range_from = Vec::<i32>::new();
5+
let mut bottom = Vec::<i32>::new();
6+
7+
for x in -9 + 1..=(9 - 2) {
8+
match x as i32 {
9+
8.. => bottom.push(x),
10+
1 | -3..0 => first_or.push(x),
11+
//~^ exclusive range pattern syntax is experimental
12+
y @ (0..5 | 6) => or_two.push(y),
13+
//~^ exclusive range pattern syntax is experimental
14+
y @ 0..const { 5 + 1 } => assert_eq!(y, 5),
15+
//~^ inline-const is experimental
16+
//~| exclusive range pattern syntax is experimental
17+
y @ -5.. => range_from.push(y),
18+
y @ ..-7 => assert_eq!(y, -8),
19+
//~^ half-open range patterns are unstable
20+
//~| exclusive range pattern syntax is experimental
21+
y => bottom.push(y),
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)