From b8e2ec728cc09d0f00829a9cffcb54da3efa5760 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sun, 9 Jul 2023 16:28:26 -0700 Subject: [PATCH 1/1] Fix crash on type comment with trailing space (#3773) --- CHANGES.md | 2 ++ src/black/parsing.py | 9 ++++++--- tests/data/simple_cases/comments2.py | 5 +++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index bb30429..c7389ce 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -19,6 +19,8 @@ under some circumstances. (#3745) - Fix a bug where multi-line open parenthesis magic comment like `type: ignore` were not correctly parsed (#3740) +- Fix error in AST validation when Black removes trailing whitespace in a type comment + (#3773) ### Preview style diff --git a/src/black/parsing.py b/src/black/parsing.py index 455c5ee..e98e019 100644 --- a/src/black/parsing.py +++ b/src/black/parsing.py @@ -208,15 +208,18 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]: else: normalized: object - # Constant strings may be indented across newlines, if they are - # docstrings; fold spaces after newlines when comparing. Similarly, - # trailing and leading space may be removed. if ( isinstance(node, ast.Constant) and field == "value" and isinstance(value, str) ): + # Constant strings may be indented across newlines, if they are + # docstrings; fold spaces after newlines when comparing. Similarly, + # trailing and leading space may be removed. normalized = _normalize("\n", value) + elif field == "type_comment" and isinstance(value, str): + # Trailing whitespace in type comments is removed. + normalized = value.rstrip() else: normalized = value yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}" diff --git a/tests/data/simple_cases/comments2.py b/tests/data/simple_cases/comments2.py index 37e185a..1487dc4 100644 --- a/tests/data/simple_cases/comments2.py +++ b/tests/data/simple_cases/comments2.py @@ -154,6 +154,9 @@ class Test: not parsed.hostname.strip()): pass + +a = "type comment with trailing space" # type: str + ####################### ### SECTION COMMENT ### ####################### @@ -332,6 +335,8 @@ class Test: pass +a = "type comment with trailing space" # type: str + ####################### ### SECTION COMMENT ### ####################### -- 2.39.5