Skip to content

Commit

Permalink
Disallow f-strings in match pattern literal (#7857)
Browse files Browse the repository at this point in the history
## Summary

This PR fixes a bug to disallow f-strings in match pattern literal.

```
literal_pattern ::=  signed_number
                     | signed_number "+" NUMBER
                     | signed_number "-" NUMBER
                     | strings
                     | "None"
                     | "True"
                     | "False"
                     | signed_number: NUMBER | "-" NUMBER
```

Source:
https://docs.python.org/3/reference/compound_stmts.html#grammar-token-python-grammar-literal_pattern

Also,

```console
$ python /tmp/t.py
  File "/tmp/t.py", line 4
    case "hello " f"{name}":
         ^^^^^^^^^^^^^^^^^^
SyntaxError: patterns may only match literals and attribute lookups
```

## Test Plan

Update existing test case and accordingly the snapshots. Also, add a new
test case to verify that the parser does raise an error.
  • Loading branch information
dhruvmanila authored and konstin committed Oct 11, 2023
1 parent 66f28d4 commit 0648c9e
Show file tree
Hide file tree
Showing 4 changed files with 6,265 additions and 6,174 deletions.
22 changes: 21 additions & 1 deletion crates/ruff_python_parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,24 @@ match x:
insta::assert_debug_snapshot!(parse_ast);
}

#[test]
fn test_match_pattern_fstring_literal() {
// F-string literal is not allowed in match pattern.
let parse_error = parse_suite(
r#"
match x:
case f"{y}":
pass
"#,
"<test>",
)
.err();
assert!(
parse_error.is_some(),
"expected parse error when f-string literal is used in match pattern"
);
}

#[test]
fn test_variadic_generics() {
let parse_ast = parse_suite(
Expand Down Expand Up @@ -1285,7 +1303,9 @@ f'{f"{3.1415=:.1f}":*^20}'
{"foo " f"bar {x + y} " "baz": 10}
match foo:
case "foo " f"bar {x + y} " "baz":
case "one":
pass
case "implicitly " "concatenated":
pass
f"\{foo}\{bar:\}"
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_python_parser/src/python.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ LiteralPattern: ast::Pattern = {
value: Box::new(value.into()),
range: (location..end_location).into()
}.into(),
<location:@L> <strings:StringLiteralOrFString+> <end_location:@R> =>? Ok(ast::PatternMatchValue {
<location:@L> <strings:StringLiteral+> <end_location:@R> =>? Ok(ast::PatternMatchValue {
value: Box::new(concatenate_strings(strings, (location..end_location).into())?),
range: (location..end_location).into()
}.into()),
Expand Down
Loading

0 comments on commit 0648c9e

Please sign in to comment.