Handle parentheses when formatting slice expressions (#5882)

**Summary** Fix the formatter crash with `x[(1) :: ]` and related code.

**Problem** For assigning comments in slices in subscripts, we need to
find the positions of the colons to assign comments before and after the
colon to the respective lower/upper/step node (or dangling in that
section). Formatting `x[(1) :: ]` was broken because we were looking for
a `:` after the `1` but didn't consider that there could be a `)`
outside the range of the lower node, which contains just the `1` and no
optional parentheses.

**Solution** Use the simple tokenizer directly and skip all closing
parentheses.

**Test Plan** I added regression tests.

Closes #5733
This commit is contained in:
konsti 2023-07-19 17:25:25 +02:00 committed by GitHub
parent 63ed7a31e8
commit a51606a10a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 14 deletions

View file

@ -89,6 +89,11 @@ e210 = "e"[a() : 1 :]
# Regression test for https://github.com/astral-sh/ruff/issues/5605
f = "f"[:,]
# Regression test for https://github.com/astral-sh/ruff/issues/5733
g1 = "g"[(1):(2)]
g2 = "g"[(1):(2):(3)]
```
## Output
@ -176,6 +181,10 @@ e210 = "e"[a() : 1 :]
# Regression test for https://github.com/astral-sh/ruff/issues/5605
f = "f"[:,]
# Regression test for https://github.com/astral-sh/ruff/issues/5733
g1 = "g"[(1):(2)]
g2 = "g"[(1):(2):(3)]
```