From ce3d055626283bd149dd561691a9feb095a43325 Mon Sep 17 00:00:00 2001 From: RedGuy12 <61329810+RedGuy12@users.noreply.github.com> Date: Thu, 22 Feb 2024 12:20:50 -0600 Subject: [PATCH] fix: Don't merge comments while splitting delimiters Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com> --- CHANGES.md | 2 ++ src/black/linegen.py | 11 +++++++++-- tests/data/cases/split_delimiter_comments.py | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 tests/data/cases/split_delimiter_comments.py diff --git a/CHANGES.md b/CHANGES.md index bcf6eb44fdb..e28730a3b5f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,8 @@ +- Don't move comments along with delimiters, which could cause crashes (#4248) + ### Preview style diff --git a/src/black/linegen.py b/src/black/linegen.py index cc8e41dfb20..0006f564b82 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -1194,8 +1194,11 @@ def append_to_line(leaf: Leaf) -> Iterator[Line]: for leaf_idx, leaf in enumerate(line.leaves): yield from append_to_line(leaf) - for comment_after in line.comments_after(leaf): - yield from append_to_line(comment_after) + previous_leaf = line.leaves[leaf_idx - 1] if leaf_idx > 0 else None + previous_priority = previous_leaf and bt.delimiters.get(id(previous_leaf)) + if previous_priority != delimiter_priority: + for comment_after in line.comments_after(leaf): + yield from append_to_line(comment_after) lowest_depth = min(lowest_depth, leaf.bracket_depth) if leaf.bracket_depth == lowest_depth: @@ -1215,6 +1218,10 @@ def append_to_line(leaf: Leaf) -> Iterator[Line]: leaf_priority = bt.delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: + if leaf_idx + 1 < len(line.leaves): + for comment_after in line.comments_after(line.leaves[leaf_idx + 1]): + yield from append_to_line(comment_after) + yield current_line current_line = Line( diff --git a/tests/data/cases/split_delimiter_comments.py b/tests/data/cases/split_delimiter_comments.py new file mode 100644 index 00000000000..11f29e4fcec --- /dev/null +++ b/tests/data/cases/split_delimiter_comments.py @@ -0,0 +1,18 @@ +a = ( + 1 + # type: ignore + 2 # type: ignore +) +a = ( + 1 # type: ignore + + 2 # type: ignore +) + +# output +a = ( + 1 # type: ignore + + 2 # type: ignore +) +a = ( + 1 # type: ignore + + 2 # type: ignore +)