Skip to content

Commit fe513a2

Browse files
authored
Merge pull request #2022 from ehuss/path-pattern-precedence
Add a note to patterns.ident.precedent
2 parents 579dafe + 2a45d5d commit fe513a2

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/patterns.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,31 @@ Its objective is exclusively to make the matched binding a reference, instead of
257257
r[patterns.ident.precedent]
258258
[Path patterns](#path-patterns) take precedence over identifier patterns.
259259

260+
> [!NOTE]
261+
> When a pattern is a single-segment identifier, the grammar is ambiguous whether it means an [IdentifierPattern] or a [PathPattern]. This ambiguity can only be resolved after [name resolution].
262+
>
263+
> ```rust
264+
> const EXPECTED_VALUE: u8 = 42;
265+
> // ^^^^^^^^^^^^^^ That this constant is in scope affects how the
266+
> // patterns below are treated.
267+
>
268+
> fn check_value(x: u8) -> Result<u8, u8> {
269+
> match x {
270+
> EXPECTED_VALUE => Ok(x),
271+
> // ^^^^^^^^^^^^^^ Parsed as a `PathPattern` that resolves to
272+
> // the constant `42`.
273+
> other_value => Err(x),
274+
> // ^^^^^^^^^^^ Parsed as an `IdentifierPattern`.
275+
> }
276+
> }
277+
>
278+
> // If `EXPECTED_VALUE` were treated as an `IdentifierPattern` above,
279+
> // that pattern would always match, making the function always return
280+
> // `Ok(_) regardless of the input.
281+
> assert_eq!(check_value(42), Ok(42));
282+
> assert_eq!(check_value(43), Err(43));
283+
> ```
284+
260285
r[patterns.ident.constraint]
261286
It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.
262287
@@ -1085,6 +1110,7 @@ For example, `x @ A(..) | B(..)` will result in an error that `x` is not bound i
10851110
[enums]: items/enumerations.md
10861111
[literals]: expressions/literal-expr.md
10871112
[literal expression]: expressions/literal-expr.md
1113+
[name resolution]: names/name-resolution.md
10881114
[negating]: expressions/operator-expr.md#negation-operators
10891115
[path]: expressions/path-expr.md
10901116
[pattern matching on unions]: items/unions.md#pattern-matching-on-unions

0 commit comments

Comments
 (0)