Skip to content

Commit cb5a69b

Browse files
committed
add first draft of guard-patterns
1 parent cab8ca9 commit cb5a69b

File tree

1 file changed

+248
-0
lines changed

1 file changed

+248
-0
lines changed

text/0000-guard-patterns.md

Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
- Feature Name: `guard_patterns`
2+
- Start Date: 2024-05-13
3+
- RFC PR: [rust-lang/rfcs#0000](https://github.com/rust-lang/rfcs/pull/0000)
4+
- Rust Issue: [rust-lang/rust#0000](https://github.com/rust-lang/rust/issues/0000)
5+
6+
# Summary
7+
[summary]: #summary
8+
9+
This RFC proposes to add a new kind of pattern, the **guard pattern.** Like match arm guards, guard patterns restrict another pattern to match only if an expression evaluates to `true`. The syntax for guard patterns, `pat if condition`, is compatible with match arm guard syntax, so existing guards can be superceded by guard patterns without breakage.
10+
11+
# Motivation
12+
[motivation]: #motivation
13+
14+
Guard patterns, unlike match arm guards, can be nested within other patterns. In particular, guard patterns nested within or-patterns can depend on the branch of the or-pattern being matched. This has the potential to simplify certain match expressions, and also enables the use of guards in other places where refutable patterns are acceptable. Furthermore, by moving the guard condition closer to the bindings upon which it depends, pattern behavior can be made more local.
15+
16+
# Guide-level explanation
17+
[guide-level-explanation]: #guide-level-explanation
18+
19+
Guard patterns allow you to write guard expressions to decide whether or not something should match anywhere you can use a pattern, not just at the top level of `match` arms.
20+
21+
For example, imagine that you're writing a function that decides whether a user has enough credit to buy an item. Regular users have to pay 100 credits, but premium subscribers get a 20% discount. You could implement this with a match expression as follows:
22+
23+
```rust
24+
match user.subscription_plan() {
25+
Plan::Regular if user.credit() >= 100 => {
26+
// complete the transaction
27+
}
28+
Plan::Premium if user.credit() >= 80 => {
29+
// complete the transaction
30+
}
31+
_ => {
32+
// the user doesn't have enough credit, return an error message
33+
}
34+
}
35+
```
36+
37+
But this isn't great, because two of the match arms have exactly the same body. Instead, we can write
38+
39+
```rust
40+
match user.subscription_plan() {
41+
(Plan::Regular if user.credit() >= 100) | (Plan::Premium if user.credit() >= 80) => {
42+
// complete the transaction
43+
}
44+
_ => {
45+
// the user doesn't have enough credit, return an error message
46+
}
47+
}
48+
```
49+
50+
Now we have just one arm for a successful transaction, with an or-pattern combining the two arms we used to have. The patterns two nested patterns are of the form
51+
52+
```rust
53+
pattern if expr
54+
```
55+
56+
This is a **guard pattern**. It matches a value if `pattern` (the pattern it wraps) matches that value, _and_ `expr` evaluates to `true`. Like in match arm guards, `expr` can use values bound in `pattern`.
57+
58+
## For New Users
59+
60+
For new users, guard patterns are better explained without reference to match arm guards. Instead, they can be explained by similar examples to the ones currently used for match arm guards, followed by an example showing that they can be nested within other patterns and used outside of match arms.
61+
62+
# Reference-level explanation
63+
[reference-level-explanation]: #reference-level-explanation
64+
65+
## Supersession of Match Arm Guards
66+
67+
Rather than being parsed as part of the match expression, guards in match arms will instead be parsed as a guard pattern. For this reason, the `if` pattern operator must have lower precedence than all other pattern operators.
68+
69+
That is,
70+
71+
```rs
72+
// Let <=> denote equivalence of patterns.
73+
74+
x @ A(..) if pred <=> (x @ A(..)) if pred
75+
&A(..) if pred <=> (&A(..)) if pred
76+
A(..) | B(..) if pred <=> (A(..) | B(..)) if pred
77+
```
78+
79+
## Interaction with Expression Operators
80+
81+
The or-pattern operator and the bitwise OR operator both use the `|` token. This creates a parsing ambiguity:
82+
83+
```rust
84+
// How is this parsed?
85+
false if foo | true
86+
// As a guard pattern nested in an or-pattern?
87+
(false if foo) | true
88+
// Or as a pattern guarded by a bitwise OR operation?
89+
false if (foo | true)
90+
```
91+
92+
For that reason, guard patterns nested within or-patterns must be explicitly parenthesized.
93+
94+
There's a similar ambiguity between `=` used as the assignment operator within the guard
95+
and used outside to indicate assignment to the pattern (e.g. in `if`-`let`, `while let`, etc.).
96+
Therefore guard patterns appearing at the top level in those places must also be parenthesized:
97+
98+
```rust
99+
while let x if guard(x) = foo() {} // not allowed
100+
while let (x if guard(x)) = foo() {} // allowed
101+
```
102+
103+
Therefore the syntax for patterns becomes
104+
105+
> **<sup>Syntax</sup>**\
106+
> _Pattern_ :\
107+
> &nbsp;&nbsp; &nbsp;&nbsp; _PatternNoTopGuard_\
108+
> &nbsp;&nbsp; | _GuardPattern_
109+
>
110+
> _PatternNoTopGuard_ :\
111+
> &nbsp;&nbsp; &nbsp;&nbsp; `|`<sup>?</sup> _PatternNoTopAlt_ ( `|` _PatternNoTopAlt_ )<sup>\*</sup>
112+
113+
With `if let`, `while let`, and `for` expressions now using `PatternNoTopGuard`. `let` statements can continue to use `PatternNoTopAlt`.
114+
115+
## Bindings Available to Guards
116+
117+
The only bindings available to guard conditions are
118+
- bindings from the scope containing the pattern match, if any; and
119+
- bindings introduced by identifier patterns _within_ the guard pattern.
120+
121+
This disallows, for example, the following uses:
122+
123+
```rust
124+
// ERROR: `x` bound outside the guard pattern
125+
let (x, y if x == y) = (0, 0) else { /* ... */ }
126+
let [x, y if x == y] = [0, 0] else { /* ... */ }
127+
let TupleStruct(x, y if x == y) = TupleStruct(0, 0) else { /* ... */ }
128+
let Struct { x, y: y if x == y } = Struct { x: 0, y: 0 } else { /* ... */ }
129+
130+
// ERROR: `x` cannot be used by other parameters' patterns
131+
fn function(x: usize, ((y if x == y, _) | (_, y)): (usize, usize)) { /* ... */ }
132+
```
133+
134+
Note that in each of these cases besides the function, the condition is still possible by moving the condition outside of the destructuring pattern:
135+
136+
```rust
137+
let ((x, y) if x == y) = (0, 0) else { /* ... */ }
138+
let ([x, y] if x == y) = [0, 0] else { /* ... */ }
139+
let (TupleStruct(x, y) if x == y) = TupleStruct(0, 0) else { /* ... */ }
140+
let (Struct { x, y } if x == y) = Struct { x: 0, y: 0 } else { /* ... */ }
141+
```
142+
143+
In general, guards can, without changing meaning, "move outwards" until they reach an or-pattern where the condition can be different in other branches, and "move inwards" until they reach a level where the identifiers they reference are not bound.
144+
145+
# Drawbacks
146+
[drawbacks]: #drawbacks
147+
148+
Rather than matching only by structural properties of ADTs, equality, and ranges of certain primitives, guards give patterns the power to express arbitrary restrictions on types. This necessarily makes patterns more complex both in implementation and in concept.
149+
150+
# Rationale and alternatives
151+
[rationale-and-alternatives]: #rationale-and-alternatives
152+
153+
## "Or-of-guards" Patterns
154+
155+
Earlier it was mentioned that guards can "move outwards" up to an or-pattern without changing meaning:
156+
157+
```rust
158+
(Ok(Ok(x if x > 0))) | (Err(Err(x if x < 0)))
159+
<=> (Ok(Ok(x) if x > 0)) | (Err(Err(x) if x < 0))
160+
<=> (Ok(Ok(x)) if x > 0) | (Err(Err(x)) if x < 0)
161+
// cannot move outwards any further, because the conditions are different
162+
```
163+
164+
In most situations, it is preferable to have the guard as far outwards as possible; that is, at the top-level of the whole pattern or immediately within one alternative of an or-pattern.
165+
Therefore, we could choose to restrict guard patterns so that they appear only in these places.
166+
This RFC refers to this as "or-of-guards" patterns, because it changes or-patterns from or-ing together a list of patterns to or-ing together a list of optionally guarded patterns.
167+
168+
Note that, currently, most patterns are actually parsed as an or-pattern with only one choice.
169+
Therefore, to achieve the effect of forcing patterns as far out as possible guards would only be allowed in or-patterns with more than one choice.
170+
171+
There are, however, a couple reasons where it could be desirable to allow guards further inwards than strictly necessary.
172+
173+
### Localization of Behavior
174+
175+
Sometimes guards are only related to information from a small part of a large structure being matched.
176+
177+
For example, consider a function that iterates over a list of customer orders and performs different actions depending on the customer's subscription plan, the item type, the payment info, and various other factors:
178+
179+
```rust
180+
match order {
181+
Order {
182+
customer: customer if customer.subscription_plan() == Plan::Premium,
183+
payment: Payment::Cash(amount) if amount.in_usd() > 100,
184+
item_type: ItemType::A,
185+
// a bunch of other conditions...
186+
} => { /* ... */ }
187+
// other similar branches...
188+
}
189+
```
190+
191+
Here, the pattern `customer if customer.subscription_plan() == Plan::Premium` has a clear meaning: it matches customers with premium subscriptions. All of the behavior of the pattern pertaining to the customer is in one place. However, if we move the guard outwards to wrap the entire order, the behavior is spread out and much harder to understand -- particularly if other its merged with conditions for other parts of the order:
192+
193+
```rust
194+
// The same match statement using or-of-guards.
195+
match order {
196+
Order {
197+
customer,
198+
payment: Payment::Cash(amount),
199+
item_type: ItemType::A,
200+
// a bunch of other conditions...
201+
} if customer.subscription_plan() == Plan::Premium && amount.in_usd() > 100 => { /* ... */ }
202+
// other similar branches...
203+
}
204+
```
205+
206+
### Pattern Macros
207+
208+
If guards can only appear immediately within or-patterns, then either
209+
- pattern macros can emit guards at the top-level, in which case they can only be called immediately within or-patterns without risking breakage if the macro definition changes (even to another valid pattern!); or
210+
- pattern macros cannot emit guards at the top-level, forcing macro authors to use terrible workarounds like `(Some(x) if guard(x)) | (Some(x) if false)` if they want to use the feature.
211+
212+
This can also be seen as a special case of the previous argument, as pattern macros fundamentally assume that patterns can be built out of composable, local pieces.
213+
214+
# Prior art
215+
[prior-art]: #prior-art
216+
217+
As far as I am aware, this feature has not been implemented in any other programming languages.
218+
219+
Guard patterns are, however, very similar to Haskell's [view patterns](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/view_patterns.html), which are more powerful and closer to a hypothetical "`if let` pattern" than a guard pattern as this RFC proposes it.
220+
221+
# Unresolved questions
222+
[unresolved-questions]: #unresolved-questions
223+
224+
- How should we refer to this feature?
225+
- "Guard pattern" will likely be most intuitive to users already familiar with match arm guards. Most likely, this includes anyone reading this, which is why this RFC uses that term.
226+
- "`if`-pattern" agrees with the naming of or-patterns, and obviously matches the syntax well. This is probably the most intuitive name for new users learning the feature.
227+
- Some other possibilities: "condition/conditioned pattern," "refinement/refined pattern," "restriction/restricted pattern," or "predicate/predicated pattern."
228+
- What anti-patterns should we lint against?
229+
- Using guard patterns to test equality or range membership when a literal or range pattern could be used instead?
230+
- Using guard patterns at the top-level of `if let` or `while let` instead of let chains?
231+
- Guard patterns within guard patterns instead of using one guard with `&&` in the condition?
232+
- `foo @ (x if guard(x))` rather than `(foo @ x) if guard(x)`? Or maybe this is valid in some cases for localizing match behavior?
233+
234+
# Future possibilities
235+
[future-possibilities]: #future-possibilities
236+
237+
## Allowing `if let`
238+
239+
Users expect to be able to write `if let` where they can write `if`. Allowing this in guard patterns would make them significantly more powerful, but also more complex.
240+
241+
One way to think about this is that patterns serve two functions:
242+
243+
1. Refinement: refutable patterns only match some subset of a type's values.
244+
2. Destructuring: patterns use the structure common to values of that subset to extract data.
245+
246+
Guard patterns as described here provide _arbitrary refinement_. That is, guard patterns can match based on whether any arbitrary expression evaluates to true.
247+
248+
Allowing `if let` allows not just arbitrary refinement, but also _arbitrary destructuring_. The value(s) bound by an `if let` pattern can depend on the value of an arbitrary expression.

0 commit comments

Comments
 (0)