ruff/crates/ruff_python_parser/src/parser
Brent Westbrook 75a562d313
[syntax-errors] Parenthesized context managers before Python 3.9 (#16523)
Summary
--

I thought this was very complicated based on the comment here:
https://github.com/astral-sh/ruff/pull/16106#issuecomment-2653505671 and
on some of the discussion in the CPython issue here:
https://github.com/python/cpython/issues/56991. However, after a little
bit of experimentation, I think it boils down to this example:

```python
with (x as y): ...
```

The issue is parentheses around a `with` item with an `optional_var`, as
we (and
[Python](https://docs.python.org/3/library/ast.html#ast.withitem)) call
the trailing variable name (`y` in this case). It's not actually about
line breaks after all, except that line breaks are allowed in
parenthesized expressions, which explains the validity of cases like


```pycon
>>> with (
...     x,
...     y
... ) as foo:
...     pass
... 
```

even on Python 3.8.

I followed [pyright]'s example again here on the diagnostic range (just
the opening paren) and the wording of the error.


Test Plan
--
Inline tests

[pyright]:
https://pyright-play.net/?pythonVersion=3.7&strict=true&code=FAdwlgLgFgBAFAewA4FMB2cBEAzBCB0EAHhJgJQwCGAzjLgmQFwz6tA
2025-03-17 08:54:55 -04:00
..
snapshots Update insta snapshots (#14366) 2024-11-15 19:31:15 +01:00
expression.rs [syntax-errors] Unparenthesized assignment expressions in sets and indexes (#16404) 2025-03-14 15:06:42 -04:00
helpers.rs [syntax-errors] Improve error message and range for pre-PEP-614 decorator syntax errors (#16581) 2025-03-17 11:17:27 +00:00
mod.rs [syntax-errors] Parenthesized keyword argument names after Python 3.8 (#16482) 2025-03-06 12:18:13 -05:00
options.rs Start detecting version-related syntax errors in the parser (#16090) 2025-02-25 23:03:48 -05:00
pattern.rs Upgrade Rust toolchain to 1.83 (#14677) 2024-11-29 12:05:05 +00:00
progress.rs Replace LALRPOP parser with hand-written parser (#10036) 2024-04-18 17:57:39 +05:30
recovery.rs Use CompactString for Identifier (#12101) 2024-07-01 10:06:02 +02:00
statement.rs [syntax-errors] Parenthesized context managers before Python 3.9 (#16523) 2025-03-17 08:54:55 -04:00
tests.rs Pass ParserOptions to the parser (#16220) 2025-02-19 10:50:50 -05:00