Crash on conditional inside # fmt: off, depending on comment indentation (original) (raw)

Describe the bug

If a condition statement is wrapped in # fmt: off/# fmt: on, Black crashes with a parse error on the subsequent line.
The crash only occurs if the # fmt: off comment is indented the same as the wrapped condition.

To Reproduce

The following minimal code breaks parsing with Black 22.10 and later:

def do_something(x, y): if x: return x # fmt: off elif y: # fmt: on return y

And run it with these arguments:

The resulting error is:

error: cannot format test.py: Cannot parse: 7:4: return y

Expected behavior

Black can parse this valid Python snippet regardless of how the # fmt: off comment is indented.
This is the case for Black 22.6 and older.

Environment

Additional context

Interestingly, Black doesn't crash if the fmt-off comment is indented one more level.
This is parsed fine:

def do_something(x, y): if x: return x # fmt: off elif y: # fmt: on return y

However, the instruction is also ignored, ie. the # fmt: off command isn't recognised as such.