From 1fc4b67256ef0691d67057231a3f3630be0ef6e6 Mon Sep 17 00:00:00 2001 From: Travis Cross Date: Wed, 14 May 2025 12:39:49 +0000 Subject: [PATCH] Fix grammar for `LiteralPattern` regarding `-` We had documented that only numeric literals in patterns can be prefixed by `-` (minus), but the Rust parser happily accepts a minus ahead of all literals in patterns. E.g.: ```rust match () { -true | -false => (), -'x' => (), -b'x' => (), -"x" => (), -r"x" => (), -br"x" => (), -c"x" => (), -cr"x" => (), -1 => (), -1.1 => (), } ``` In the compiler, this happens in `Parser::parse_literal_maybe_minus` and `Token::can_begin_literal_maybe_minus`. Let's fix this by defining `LiteralPattern` as a `LiteralExpression` optionally prefixed by the minus sign. This better matches how the `rustc` AST models this. --- src/patterns.md | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/src/patterns.md b/src/patterns.md index 2d9ddb5ac..2818190c9 100644 --- a/src/patterns.md +++ b/src/patterns.md @@ -139,23 +139,11 @@ r[patterns.literal] r[patterns.literal.syntax] ```grammar,patterns -LiteralPattern -> - `true` | `false` - | CHAR_LITERAL - | BYTE_LITERAL - | STRING_LITERAL - | RAW_STRING_LITERAL - | BYTE_STRING_LITERAL - | RAW_BYTE_STRING_LITERAL - | C_STRING_LITERAL - | RAW_C_STRING_LITERAL - | `-`? INTEGER_LITERAL - | `-`? FLOAT_LITERAL +LiteralPattern -> `-`? LiteralExpression ``` r[patterns.literal.intro] -_Literal patterns_ match exactly the same value as what is created by the literal. -Since negative numbers are not [literals], literal patterns also accept an optional minus sign before the literal, which acts like the negation operator. +_Literal patterns_ match exactly the same value as what is created by the literal. Since negative numbers are not [literals], literals in patterns may be prefixed by an optional minus sign, which acts like the negation operator. > [!WARNING] > C string and raw C string literals are accepted in literal patterns, but `&CStr` doesn't implement structural equality (`#[derive(Eq, PartialEq)]`) and therefore any such `match` on a `&CStr` will be rejected with a type error.