Skip to content

Commit 3a4b5c5

Browse files
ehusstraviscross
authored andcommitted
Add a note to patterns.ident.precedent
This attempts to clarify the parsing ambiguity between `IdentifierPattern` and `PathPattern`. See [`PatKind::Ident`] and [`lower_pat_ident`]. Closes #605 [`PatKind::Ident`]: https://github.com/rust-lang/rust/blob/dc2c3564d273cf8ccce32dc4f47eaa27063bceb9/compiler/rustc_ast/src/ast.rs#L862-L866 [`lower_pat_ident`]: https://github.com/rust-lang/rust/blob/dc2c3564d273cf8ccce32dc4f47eaa27063bceb9/compiler/rustc_ast_lowering/src/pat.rs#L278-L333
1 parent 579dafe commit 3a4b5c5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/patterns.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,28 @@ 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]. In the following example, the pattern is disambiguated to mean a PathPattern to a constant:
262+
>
263+
> ```rust
264+
> const EXPECTED_VALUE: i32 = 42;
265+
>
266+
> fn check_value(x: i32) -> bool {
267+
> match x {
268+
> EXPECTED_VALUE => true, // PathPattern - matches the constant 42
269+
> _ => false,
270+
> }
271+
> }
272+
>
273+
> fn main() {
274+
> // If EXPECTED_VALUE were treated as an IdentifierPattern, it would bind
275+
> // any value to a new variable, making this function always return true
276+
> // regardless of the input.
277+
> assert_eq!(check_value(42), true); // correct behavior
278+
> assert_eq!(check_value(100), false); // would be true if misinterpreted
279+
> }
280+
> ```
281+
260282
r[patterns.ident.constraint]
261283
It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.
262284
@@ -1085,6 +1107,7 @@ For example, `x @ A(..) | B(..)` will result in an error that `x` is not bound i
10851107
[enums]: items/enumerations.md
10861108
[literals]: expressions/literal-expr.md
10871109
[literal expression]: expressions/literal-expr.md
1110+
[name resolution]: names/name-resolution.md
10881111
[negating]: expressions/operator-expr.md#negation-operators
10891112
[path]: expressions/path-expr.md
10901113
[pattern matching on unions]: items/unions.md#pattern-matching-on-unions

0 commit comments

Comments
 (0)