Skip to content

Commit cacb1d9

Browse files
committed
Revise note about {Path,Identifier}Pattern parsing
Let's extend the example to demonstrate, comparatively, what is parsed as an `IdentifierPattern`. Even though this is the common case, showing this might be helpful to people less familiar with the grammar. Let's remove `main`, as that's not needed here. And, in the code, let's highlight specifically what we're commenting on by commenting below the construct.
1 parent e3469df commit cacb1d9

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/patterns.md

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -258,25 +258,28 @@ r[patterns.ident.precedent]
258258
[Path patterns](#path-patterns) take precedence over identifier patterns.
259259

260260
> [!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:
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].
262262
>
263263
> ```rust
264-
> const EXPECTED_VALUE: i32 = 42;
264+
> const EXPECTED_VALUE: u8 = 42;
265+
> // ^^^^^^^^^^^^^^ That this constant is in scope affects how the
266+
> // match below is parsed.
265267
>
266-
> fn check_value(x: i32) -> bool {
268+
> fn check_value(x: u8) -> Result<u8, u8> {
267269
> match x {
268-
> EXPECTED_VALUE => true, // PathPattern - matches the constant 42
269-
> _ => false,
270+
> EXPECTED_VALUE => Ok(x),
271+
> // ^^^^^^^^^^^^^^ Parsed as a `PathPattern` the resolves to
272+
> // the constant `42`.
273+
> other_value => Err(x),
274+
> // ^^^^^^^^^^^ Parsed as an `IdentifierPattern`.
270275
> }
271276
> }
272277
>
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-
> }
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));
280283
> ```
281284
282285
r[patterns.ident.constraint]

0 commit comments

Comments
 (0)