]> git.madduck.net Git - etc/vim.git/blob - src/black/linegen.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Improve multiline string handling (#1879)
[etc/vim.git] / src / black / linegen.py
1 """
2 Generating lines of code.
3 """
4 import sys
5 from dataclasses import dataclass, replace
6 from enum import Enum, auto
7 from functools import partial, wraps
8 from typing import Collection, Iterator, List, Optional, Set, Union, cast
9
10 from black.brackets import (
11     COMMA_PRIORITY,
12     DOT_PRIORITY,
13     get_leaves_inside_matching_brackets,
14     max_delimiter_priority_in_atom,
15 )
16 from black.comments import FMT_OFF, generate_comments, list_comments
17 from black.lines import (
18     Line,
19     append_leaves,
20     can_be_split,
21     can_omit_invisible_parens,
22     is_line_short_enough,
23     line_to_string,
24 )
25 from black.mode import Feature, Mode, Preview
26 from black.nodes import (
27     ASSIGNMENTS,
28     BRACKETS,
29     CLOSING_BRACKETS,
30     OPENING_BRACKETS,
31     RARROW,
32     STANDALONE_COMMENT,
33     STATEMENT,
34     WHITESPACE,
35     Visitor,
36     ensure_visible,
37     is_arith_like,
38     is_atom_with_invisible_parens,
39     is_docstring,
40     is_empty_tuple,
41     is_lpar_token,
42     is_multiline_string,
43     is_name_token,
44     is_one_sequence_between,
45     is_one_tuple,
46     is_rpar_token,
47     is_stub_body,
48     is_stub_suite,
49     is_tuple_containing_walrus,
50     is_vararg,
51     is_walrus_assignment,
52     is_yield,
53     syms,
54     wrap_in_parentheses,
55 )
56 from black.numerics import normalize_numeric_literal
57 from black.strings import (
58     fix_docstring,
59     get_string_prefix,
60     normalize_string_prefix,
61     normalize_string_quotes,
62     normalize_unicode_escape_sequences,
63 )
64 from black.trans import (
65     CannotTransform,
66     StringMerger,
67     StringParenStripper,
68     StringParenWrapper,
69     StringSplitter,
70     Transformer,
71     hug_power_op,
72 )
73 from blib2to3.pgen2 import token
74 from blib2to3.pytree import Leaf, Node
75
76 # types
77 LeafID = int
78 LN = Union[Leaf, Node]
79
80
81 class CannotSplit(CannotTransform):
82     """A readable split that fits the allotted line length is impossible."""
83
84
85 # This isn't a dataclass because @dataclass + Generic breaks mypyc.
86 # See also https://github.com/mypyc/mypyc/issues/827.
87 class LineGenerator(Visitor[Line]):
88     """Generates reformatted Line objects.  Empty lines are not emitted.
89
90     Note: destroys the tree it's visiting by mutating prefixes of its leaves
91     in ways that will no longer stringify to valid Python code on the tree.
92     """
93
94     def __init__(self, mode: Mode, features: Collection[Feature]) -> None:
95         self.mode = mode
96         self.features = features
97         self.current_line: Line
98         self.__post_init__()
99
100     def line(self, indent: int = 0) -> Iterator[Line]:
101         """Generate a line.
102
103         If the line is empty, only emit if it makes sense.
104         If the line is too long, split it first and then generate.
105
106         If any lines were generated, set up a new current_line.
107         """
108         if not self.current_line:
109             self.current_line.depth += indent
110             return  # Line is empty, don't emit. Creating a new one unnecessary.
111
112         complete_line = self.current_line
113         self.current_line = Line(mode=self.mode, depth=complete_line.depth + indent)
114         yield complete_line
115
116     def visit_default(self, node: LN) -> Iterator[Line]:
117         """Default `visit_*()` implementation. Recurses to children of `node`."""
118         if isinstance(node, Leaf):
119             any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
120             for comment in generate_comments(node):
121                 if any_open_brackets:
122                     # any comment within brackets is subject to splitting
123                     self.current_line.append(comment)
124                 elif comment.type == token.COMMENT:
125                     # regular trailing comment
126                     self.current_line.append(comment)
127                     yield from self.line()
128
129                 else:
130                     # regular standalone comment
131                     yield from self.line()
132
133                     self.current_line.append(comment)
134                     yield from self.line()
135
136             normalize_prefix(node, inside_brackets=any_open_brackets)
137             if self.mode.string_normalization and node.type == token.STRING:
138                 node.value = normalize_string_prefix(node.value)
139                 node.value = normalize_string_quotes(node.value)
140             if node.type == token.NUMBER:
141                 normalize_numeric_literal(node)
142             if node.type not in WHITESPACE:
143                 self.current_line.append(node)
144         yield from super().visit_default(node)
145
146     def visit_test(self, node: Node) -> Iterator[Line]:
147         """Visit an `x if y else z` test"""
148
149         if Preview.parenthesize_conditional_expressions in self.mode:
150             already_parenthesized = (
151                 node.prev_sibling and node.prev_sibling.type == token.LPAR
152             )
153
154             if not already_parenthesized:
155                 lpar = Leaf(token.LPAR, "")
156                 rpar = Leaf(token.RPAR, "")
157                 node.insert_child(0, lpar)
158                 node.append_child(rpar)
159
160         yield from self.visit_default(node)
161
162     def visit_INDENT(self, node: Leaf) -> Iterator[Line]:
163         """Increase indentation level, maybe yield a line."""
164         # In blib2to3 INDENT never holds comments.
165         yield from self.line(+1)
166         yield from self.visit_default(node)
167
168     def visit_DEDENT(self, node: Leaf) -> Iterator[Line]:
169         """Decrease indentation level, maybe yield a line."""
170         # The current line might still wait for trailing comments.  At DEDENT time
171         # there won't be any (they would be prefixes on the preceding NEWLINE).
172         # Emit the line then.
173         yield from self.line()
174
175         # While DEDENT has no value, its prefix may contain standalone comments
176         # that belong to the current indentation level.  Get 'em.
177         yield from self.visit_default(node)
178
179         # Finally, emit the dedent.
180         yield from self.line(-1)
181
182     def visit_stmt(
183         self, node: Node, keywords: Set[str], parens: Set[str]
184     ) -> Iterator[Line]:
185         """Visit a statement.
186
187         This implementation is shared for `if`, `while`, `for`, `try`, `except`,
188         `def`, `with`, `class`, `assert`, and assignments.
189
190         The relevant Python language `keywords` for a given statement will be
191         NAME leaves within it. This methods puts those on a separate line.
192
193         `parens` holds a set of string leaf values immediately after which
194         invisible parens should be put.
195         """
196         normalize_invisible_parens(
197             node, parens_after=parens, mode=self.mode, features=self.features
198         )
199         for child in node.children:
200             if is_name_token(child) and child.value in keywords:
201                 yield from self.line()
202
203             yield from self.visit(child)
204
205     def visit_dictsetmaker(self, node: Node) -> Iterator[Line]:
206         if Preview.wrap_long_dict_values_in_parens in self.mode:
207             for i, child in enumerate(node.children):
208                 if i == 0:
209                     continue
210                 if node.children[i - 1].type == token.COLON:
211                     if child.type == syms.atom and child.children[0].type == token.LPAR:
212                         if maybe_make_parens_invisible_in_atom(
213                             child,
214                             parent=node,
215                             remove_brackets_around_comma=False,
216                         ):
217                             wrap_in_parentheses(node, child, visible=False)
218                     else:
219                         wrap_in_parentheses(node, child, visible=False)
220         yield from self.visit_default(node)
221
222     def visit_funcdef(self, node: Node) -> Iterator[Line]:
223         """Visit function definition."""
224         yield from self.line()
225
226         # Remove redundant brackets around return type annotation.
227         is_return_annotation = False
228         for child in node.children:
229             if child.type == token.RARROW:
230                 is_return_annotation = True
231             elif is_return_annotation:
232                 if child.type == syms.atom and child.children[0].type == token.LPAR:
233                     if maybe_make_parens_invisible_in_atom(
234                         child,
235                         parent=node,
236                         remove_brackets_around_comma=False,
237                     ):
238                         wrap_in_parentheses(node, child, visible=False)
239                 else:
240                     wrap_in_parentheses(node, child, visible=False)
241                 is_return_annotation = False
242
243         for child in node.children:
244             yield from self.visit(child)
245
246     def visit_match_case(self, node: Node) -> Iterator[Line]:
247         """Visit either a match or case statement."""
248         normalize_invisible_parens(
249             node, parens_after=set(), mode=self.mode, features=self.features
250         )
251
252         yield from self.line()
253         for child in node.children:
254             yield from self.visit(child)
255
256     def visit_suite(self, node: Node) -> Iterator[Line]:
257         """Visit a suite."""
258         if self.mode.is_pyi and is_stub_suite(node):
259             yield from self.visit(node.children[2])
260         else:
261             yield from self.visit_default(node)
262
263     def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
264         """Visit a statement without nested statements."""
265         prev_type: Optional[int] = None
266         for child in node.children:
267             if (prev_type is None or prev_type == token.SEMI) and is_arith_like(child):
268                 wrap_in_parentheses(node, child, visible=False)
269             prev_type = child.type
270
271         is_suite_like = node.parent and node.parent.type in STATEMENT
272         if is_suite_like:
273             if self.mode.is_pyi and is_stub_body(node):
274                 yield from self.visit_default(node)
275             else:
276                 yield from self.line(+1)
277                 yield from self.visit_default(node)
278                 yield from self.line(-1)
279
280         else:
281             if (
282                 not self.mode.is_pyi
283                 or not node.parent
284                 or not is_stub_suite(node.parent)
285             ):
286                 yield from self.line()
287             yield from self.visit_default(node)
288
289     def visit_async_stmt(self, node: Node) -> Iterator[Line]:
290         """Visit `async def`, `async for`, `async with`."""
291         yield from self.line()
292
293         children = iter(node.children)
294         for child in children:
295             yield from self.visit(child)
296
297             if child.type == token.ASYNC or child.type == STANDALONE_COMMENT:
298                 # STANDALONE_COMMENT happens when `# fmt: skip` is applied on the async
299                 # line.
300                 break
301
302         internal_stmt = next(children)
303         for child in internal_stmt.children:
304             yield from self.visit(child)
305
306     def visit_decorators(self, node: Node) -> Iterator[Line]:
307         """Visit decorators."""
308         for child in node.children:
309             yield from self.line()
310             yield from self.visit(child)
311
312     def visit_power(self, node: Node) -> Iterator[Line]:
313         for idx, leaf in enumerate(node.children[:-1]):
314             next_leaf = node.children[idx + 1]
315
316             if not isinstance(leaf, Leaf):
317                 continue
318
319             value = leaf.value.lower()
320             if (
321                 leaf.type == token.NUMBER
322                 and next_leaf.type == syms.trailer
323                 # Ensure that we are in an attribute trailer
324                 and next_leaf.children[0].type == token.DOT
325                 # It shouldn't wrap hexadecimal, binary and octal literals
326                 and not value.startswith(("0x", "0b", "0o"))
327                 # It shouldn't wrap complex literals
328                 and "j" not in value
329             ):
330                 wrap_in_parentheses(node, leaf)
331
332         remove_await_parens(node)
333
334         yield from self.visit_default(node)
335
336     def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
337         """Remove a semicolon and put the other statement on a separate line."""
338         yield from self.line()
339
340     def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
341         """End of file. Process outstanding comments and end with a newline."""
342         yield from self.visit_default(leaf)
343         yield from self.line()
344
345     def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
346         if not self.current_line.bracket_tracker.any_open_brackets():
347             yield from self.line()
348         yield from self.visit_default(leaf)
349
350     def visit_factor(self, node: Node) -> Iterator[Line]:
351         """Force parentheses between a unary op and a binary power:
352
353         -2 ** 8 -> -(2 ** 8)
354         """
355         _operator, operand = node.children
356         if (
357             operand.type == syms.power
358             and len(operand.children) == 3
359             and operand.children[1].type == token.DOUBLESTAR
360         ):
361             lpar = Leaf(token.LPAR, "(")
362             rpar = Leaf(token.RPAR, ")")
363             index = operand.remove() or 0
364             node.insert_child(index, Node(syms.atom, [lpar, operand, rpar]))
365         yield from self.visit_default(node)
366
367     def visit_STRING(self, leaf: Leaf) -> Iterator[Line]:
368         if Preview.hex_codes_in_unicode_sequences in self.mode:
369             normalize_unicode_escape_sequences(leaf)
370
371         if is_docstring(leaf) and "\\\n" not in leaf.value:
372             # We're ignoring docstrings with backslash newline escapes because changing
373             # indentation of those changes the AST representation of the code.
374             if self.mode.string_normalization:
375                 docstring = normalize_string_prefix(leaf.value)
376                 # visit_default() does handle string normalization for us, but
377                 # since this method acts differently depending on quote style (ex.
378                 # see padding logic below), there's a possibility for unstable
379                 # formatting as visit_default() is called *after*. To avoid a
380                 # situation where this function formats a docstring differently on
381                 # the second pass, normalize it early.
382                 docstring = normalize_string_quotes(docstring)
383             else:
384                 docstring = leaf.value
385             prefix = get_string_prefix(docstring)
386             docstring = docstring[len(prefix) :]  # Remove the prefix
387             quote_char = docstring[0]
388             # A natural way to remove the outer quotes is to do:
389             #   docstring = docstring.strip(quote_char)
390             # but that breaks on """""x""" (which is '""x').
391             # So we actually need to remove the first character and the next two
392             # characters but only if they are the same as the first.
393             quote_len = 1 if docstring[1] != quote_char else 3
394             docstring = docstring[quote_len:-quote_len]
395             docstring_started_empty = not docstring
396             indent = " " * 4 * self.current_line.depth
397
398             if is_multiline_string(leaf):
399                 docstring = fix_docstring(docstring, indent)
400             else:
401                 docstring = docstring.strip()
402
403             has_trailing_backslash = False
404             if docstring:
405                 # Add some padding if the docstring starts / ends with a quote mark.
406                 if docstring[0] == quote_char:
407                     docstring = " " + docstring
408                 if docstring[-1] == quote_char:
409                     docstring += " "
410                 if docstring[-1] == "\\":
411                     backslash_count = len(docstring) - len(docstring.rstrip("\\"))
412                     if backslash_count % 2:
413                         # Odd number of tailing backslashes, add some padding to
414                         # avoid escaping the closing string quote.
415                         docstring += " "
416                         has_trailing_backslash = True
417             elif not docstring_started_empty:
418                 docstring = " "
419
420             # We could enforce triple quotes at this point.
421             quote = quote_char * quote_len
422
423             # It's invalid to put closing single-character quotes on a new line.
424             if self.mode and quote_len == 3:
425                 # We need to find the length of the last line of the docstring
426                 # to find if we can add the closing quotes to the line without
427                 # exceeding the maximum line length.
428                 # If docstring is one line, we don't put the closing quotes on a
429                 # separate line because it looks ugly (#3320).
430                 lines = docstring.splitlines()
431                 last_line_length = len(lines[-1]) if docstring else 0
432
433                 # If adding closing quotes would cause the last line to exceed
434                 # the maximum line length then put a line break before the
435                 # closing quotes
436                 if (
437                     len(lines) > 1
438                     and last_line_length + quote_len > self.mode.line_length
439                     and len(indent) + quote_len <= self.mode.line_length
440                     and not has_trailing_backslash
441                 ):
442                     leaf.value = prefix + quote + docstring + "\n" + indent + quote
443                 else:
444                     leaf.value = prefix + quote + docstring + quote
445             else:
446                 leaf.value = prefix + quote + docstring + quote
447
448         yield from self.visit_default(leaf)
449
450     def __post_init__(self) -> None:
451         """You are in a twisty little maze of passages."""
452         self.current_line = Line(mode=self.mode)
453
454         v = self.visit_stmt
455         Ø: Set[str] = set()
456         self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
457         self.visit_if_stmt = partial(
458             v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
459         )
460         self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
461         self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
462         self.visit_try_stmt = partial(
463             v, keywords={"try", "except", "else", "finally"}, parens=Ø
464         )
465         self.visit_except_clause = partial(v, keywords={"except"}, parens={"except"})
466         self.visit_with_stmt = partial(v, keywords={"with"}, parens={"with"})
467         self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
468         self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
469         self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
470         self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
471         self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
472         self.visit_async_funcdef = self.visit_async_stmt
473         self.visit_decorated = self.visit_decorators
474
475         # PEP 634
476         self.visit_match_stmt = self.visit_match_case
477         self.visit_case_block = self.visit_match_case
478
479
480 def transform_line(
481     line: Line, mode: Mode, features: Collection[Feature] = ()
482 ) -> Iterator[Line]:
483     """Transform a `line`, potentially splitting it into many lines.
484
485     They should fit in the allotted `line_length` but might not be able to.
486
487     `features` are syntactical features that may be used in the output.
488     """
489     if line.is_comment:
490         yield line
491         return
492
493     line_str = line_to_string(line)
494
495     ll = mode.line_length
496     sn = mode.string_normalization
497     string_merge = StringMerger(ll, sn)
498     string_paren_strip = StringParenStripper(ll, sn)
499     string_split = StringSplitter(ll, sn)
500     string_paren_wrap = StringParenWrapper(ll, sn)
501
502     transformers: List[Transformer]
503     if (
504         not line.contains_uncollapsable_type_comments()
505         and not line.should_split_rhs
506         and not line.magic_trailing_comma
507         and (
508             is_line_short_enough(line, mode=mode, line_str=line_str)
509             or line.contains_unsplittable_type_ignore()
510         )
511         and not (line.inside_brackets and line.contains_standalone_comments())
512     ):
513         # Only apply basic string preprocessing, since lines shouldn't be split here.
514         if Preview.string_processing in mode:
515             transformers = [string_merge, string_paren_strip]
516         else:
517             transformers = []
518     elif line.is_def:
519         transformers = [left_hand_split]
520     else:
521
522         def _rhs(
523             self: object, line: Line, features: Collection[Feature], mode: Mode
524         ) -> Iterator[Line]:
525             """Wraps calls to `right_hand_split`.
526
527             The calls increasingly `omit` right-hand trailers (bracket pairs with
528             content), meaning the trailers get glued together to split on another
529             bracket pair instead.
530             """
531             for omit in generate_trailers_to_omit(line, mode.line_length):
532                 lines = list(right_hand_split(line, mode, features, omit=omit))
533                 # Note: this check is only able to figure out if the first line of the
534                 # *current* transformation fits in the line length.  This is true only
535                 # for simple cases.  All others require running more transforms via
536                 # `transform_line()`.  This check doesn't know if those would succeed.
537                 if is_line_short_enough(lines[0], mode=mode):
538                     yield from lines
539                     return
540
541             # All splits failed, best effort split with no omits.
542             # This mostly happens to multiline strings that are by definition
543             # reported as not fitting a single line, as well as lines that contain
544             # trailing commas (those have to be exploded).
545             yield from right_hand_split(line, mode, features=features)
546
547         # HACK: nested functions (like _rhs) compiled by mypyc don't retain their
548         # __name__ attribute which is needed in `run_transformer` further down.
549         # Unfortunately a nested class breaks mypyc too. So a class must be created
550         # via type ... https://github.com/mypyc/mypyc/issues/884
551         rhs = type("rhs", (), {"__call__": _rhs})()
552
553         if Preview.string_processing in mode:
554             if line.inside_brackets:
555                 transformers = [
556                     string_merge,
557                     string_paren_strip,
558                     string_split,
559                     delimiter_split,
560                     standalone_comment_split,
561                     string_paren_wrap,
562                     rhs,
563                 ]
564             else:
565                 transformers = [
566                     string_merge,
567                     string_paren_strip,
568                     string_split,
569                     string_paren_wrap,
570                     rhs,
571                 ]
572         else:
573             if line.inside_brackets:
574                 transformers = [delimiter_split, standalone_comment_split, rhs]
575             else:
576                 transformers = [rhs]
577     # It's always safe to attempt hugging of power operations and pretty much every line
578     # could match.
579     transformers.append(hug_power_op)
580
581     for transform in transformers:
582         # We are accumulating lines in `result` because we might want to abort
583         # mission and return the original line in the end, or attempt a different
584         # split altogether.
585         try:
586             result = run_transformer(line, transform, mode, features, line_str=line_str)
587         except CannotTransform:
588             continue
589         else:
590             yield from result
591             break
592
593     else:
594         yield line
595
596
597 class _BracketSplitComponent(Enum):
598     head = auto()
599     body = auto()
600     tail = auto()
601
602
603 def left_hand_split(
604     line: Line, _features: Collection[Feature], mode: Mode
605 ) -> Iterator[Line]:
606     """Split line into many lines, starting with the first matching bracket pair.
607
608     Note: this usually looks weird, only use this for function definitions.
609     Prefer RHS otherwise.  This is why this function is not symmetrical with
610     :func:`right_hand_split` which also handles optional parentheses.
611     """
612     tail_leaves: List[Leaf] = []
613     body_leaves: List[Leaf] = []
614     head_leaves: List[Leaf] = []
615     current_leaves = head_leaves
616     matching_bracket: Optional[Leaf] = None
617     for leaf in line.leaves:
618         if (
619             current_leaves is body_leaves
620             and leaf.type in CLOSING_BRACKETS
621             and leaf.opening_bracket is matching_bracket
622             and isinstance(matching_bracket, Leaf)
623         ):
624             ensure_visible(leaf)
625             ensure_visible(matching_bracket)
626             current_leaves = tail_leaves if body_leaves else head_leaves
627         current_leaves.append(leaf)
628         if current_leaves is head_leaves:
629             if leaf.type in OPENING_BRACKETS:
630                 matching_bracket = leaf
631                 current_leaves = body_leaves
632     if not matching_bracket:
633         raise CannotSplit("No brackets found")
634
635     head = bracket_split_build_line(
636         head_leaves, line, matching_bracket, component=_BracketSplitComponent.head
637     )
638     body = bracket_split_build_line(
639         body_leaves, line, matching_bracket, component=_BracketSplitComponent.body
640     )
641     tail = bracket_split_build_line(
642         tail_leaves, line, matching_bracket, component=_BracketSplitComponent.tail
643     )
644     bracket_split_succeeded_or_raise(head, body, tail)
645     for result in (head, body, tail):
646         if result:
647             yield result
648
649
650 @dataclass
651 class _RHSResult:
652     """Intermediate split result from a right hand split."""
653
654     head: Line
655     body: Line
656     tail: Line
657     opening_bracket: Leaf
658     closing_bracket: Leaf
659
660
661 def right_hand_split(
662     line: Line,
663     mode: Mode,
664     features: Collection[Feature] = (),
665     omit: Collection[LeafID] = (),
666 ) -> Iterator[Line]:
667     """Split line into many lines, starting with the last matching bracket pair.
668
669     If the split was by optional parentheses, attempt splitting without them, too.
670     `omit` is a collection of closing bracket IDs that shouldn't be considered for
671     this split.
672
673     Note: running this function modifies `bracket_depth` on the leaves of `line`.
674     """
675     rhs_result = _first_right_hand_split(line, omit=omit)
676     yield from _maybe_split_omitting_optional_parens(
677         rhs_result, line, mode, features=features, omit=omit
678     )
679
680
681 def _first_right_hand_split(
682     line: Line,
683     omit: Collection[LeafID] = (),
684 ) -> _RHSResult:
685     """Split the line into head, body, tail starting with the last bracket pair.
686
687     Note: this function should not have side effects. It's relied upon by
688     _maybe_split_omitting_optional_parens to get an opinion whether to prefer
689     splitting on the right side of an assignment statement.
690     """
691     tail_leaves: List[Leaf] = []
692     body_leaves: List[Leaf] = []
693     head_leaves: List[Leaf] = []
694     current_leaves = tail_leaves
695     opening_bracket: Optional[Leaf] = None
696     closing_bracket: Optional[Leaf] = None
697     for leaf in reversed(line.leaves):
698         if current_leaves is body_leaves:
699             if leaf is opening_bracket:
700                 current_leaves = head_leaves if body_leaves else tail_leaves
701         current_leaves.append(leaf)
702         if current_leaves is tail_leaves:
703             if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
704                 opening_bracket = leaf.opening_bracket
705                 closing_bracket = leaf
706                 current_leaves = body_leaves
707     if not (opening_bracket and closing_bracket and head_leaves):
708         # If there is no opening or closing_bracket that means the split failed and
709         # all content is in the tail.  Otherwise, if `head_leaves` are empty, it means
710         # the matching `opening_bracket` wasn't available on `line` anymore.
711         raise CannotSplit("No brackets found")
712
713     tail_leaves.reverse()
714     body_leaves.reverse()
715     head_leaves.reverse()
716     head = bracket_split_build_line(
717         head_leaves, line, opening_bracket, component=_BracketSplitComponent.head
718     )
719     body = bracket_split_build_line(
720         body_leaves, line, opening_bracket, component=_BracketSplitComponent.body
721     )
722     tail = bracket_split_build_line(
723         tail_leaves, line, opening_bracket, component=_BracketSplitComponent.tail
724     )
725     bracket_split_succeeded_or_raise(head, body, tail)
726     return _RHSResult(head, body, tail, opening_bracket, closing_bracket)
727
728
729 def _maybe_split_omitting_optional_parens(
730     rhs: _RHSResult,
731     line: Line,
732     mode: Mode,
733     features: Collection[Feature] = (),
734     omit: Collection[LeafID] = (),
735 ) -> Iterator[Line]:
736     if (
737         Feature.FORCE_OPTIONAL_PARENTHESES not in features
738         # the opening bracket is an optional paren
739         and rhs.opening_bracket.type == token.LPAR
740         and not rhs.opening_bracket.value
741         # the closing bracket is an optional paren
742         and rhs.closing_bracket.type == token.RPAR
743         and not rhs.closing_bracket.value
744         # it's not an import (optional parens are the only thing we can split on
745         # in this case; attempting a split without them is a waste of time)
746         and not line.is_import
747         # there are no standalone comments in the body
748         and not rhs.body.contains_standalone_comments(0)
749         # and we can actually remove the parens
750         and can_omit_invisible_parens(rhs.body, mode.line_length)
751     ):
752         omit = {id(rhs.closing_bracket), *omit}
753         try:
754             # The _RHSResult Omitting Optional Parens.
755             rhs_oop = _first_right_hand_split(line, omit=omit)
756             if not (
757                 Preview.prefer_splitting_right_hand_side_of_assignments in line.mode
758                 # the split is right after `=`
759                 and len(rhs.head.leaves) >= 2
760                 and rhs.head.leaves[-2].type == token.EQUAL
761                 # the left side of assignment contains brackets
762                 and any(leaf.type in BRACKETS for leaf in rhs.head.leaves[:-1])
763                 # the left side of assignment is short enough (the -1 is for the ending
764                 # optional paren)
765                 and is_line_short_enough(
766                     rhs.head, mode=replace(mode, line_length=mode.line_length - 1)
767                 )
768                 # the left side of assignment won't explode further because of magic
769                 # trailing comma
770                 and rhs.head.magic_trailing_comma is None
771                 # the split by omitting optional parens isn't preferred by some other
772                 # reason
773                 and not _prefer_split_rhs_oop(rhs_oop, mode)
774             ):
775                 yield from _maybe_split_omitting_optional_parens(
776                     rhs_oop, line, mode, features=features, omit=omit
777                 )
778                 return
779
780         except CannotSplit as e:
781             if not (
782                 can_be_split(rhs.body) or is_line_short_enough(rhs.body, mode=mode)
783             ):
784                 raise CannotSplit(
785                     "Splitting failed, body is still too long and can't be split."
786                 ) from e
787
788             elif (
789                 rhs.head.contains_multiline_strings()
790                 or rhs.tail.contains_multiline_strings()
791             ):
792                 raise CannotSplit(
793                     "The current optional pair of parentheses is bound to fail to"
794                     " satisfy the splitting algorithm because the head or the tail"
795                     " contains multiline strings which by definition never fit one"
796                     " line."
797                 ) from e
798
799     ensure_visible(rhs.opening_bracket)
800     ensure_visible(rhs.closing_bracket)
801     for result in (rhs.head, rhs.body, rhs.tail):
802         if result:
803             yield result
804
805
806 def _prefer_split_rhs_oop(rhs_oop: _RHSResult, mode: Mode) -> bool:
807     """
808     Returns whether we should prefer the result from a split omitting optional parens.
809     """
810     has_closing_bracket_after_assign = False
811     for leaf in reversed(rhs_oop.head.leaves):
812         if leaf.type == token.EQUAL:
813             break
814         if leaf.type in CLOSING_BRACKETS:
815             has_closing_bracket_after_assign = True
816             break
817     return (
818         # contains matching brackets after the `=` (done by checking there is a
819         # closing bracket)
820         has_closing_bracket_after_assign
821         or (
822             # the split is actually from inside the optional parens (done by checking
823             # the first line still contains the `=`)
824             any(leaf.type == token.EQUAL for leaf in rhs_oop.head.leaves)
825             # the first line is short enough
826             and is_line_short_enough(rhs_oop.head, mode=mode)
827         )
828         # contains unsplittable type ignore
829         or rhs_oop.head.contains_unsplittable_type_ignore()
830         or rhs_oop.body.contains_unsplittable_type_ignore()
831         or rhs_oop.tail.contains_unsplittable_type_ignore()
832     )
833
834
835 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
836     """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
837
838     Do nothing otherwise.
839
840     A left- or right-hand split is based on a pair of brackets. Content before
841     (and including) the opening bracket is left on one line, content inside the
842     brackets is put on a separate line, and finally content starting with and
843     following the closing bracket is put on a separate line.
844
845     Those are called `head`, `body`, and `tail`, respectively. If the split
846     produced the same line (all content in `head`) or ended up with an empty `body`
847     and the `tail` is just the closing bracket, then it's considered failed.
848     """
849     tail_len = len(str(tail).strip())
850     if not body:
851         if tail_len == 0:
852             raise CannotSplit("Splitting brackets produced the same line")
853
854         elif tail_len < 3:
855             raise CannotSplit(
856                 f"Splitting brackets on an empty body to save {tail_len} characters is"
857                 " not worth it"
858             )
859
860
861 def bracket_split_build_line(
862     leaves: List[Leaf],
863     original: Line,
864     opening_bracket: Leaf,
865     *,
866     component: _BracketSplitComponent,
867 ) -> Line:
868     """Return a new line with given `leaves` and respective comments from `original`.
869
870     If it's the head component, brackets will be tracked so trailing commas are
871     respected.
872
873     If it's the body component, the result line is one-indented inside brackets and as
874     such has its first leaf's prefix normalized and a trailing comma added when
875     expected.
876     """
877     result = Line(mode=original.mode, depth=original.depth)
878     if component is _BracketSplitComponent.body:
879         result.inside_brackets = True
880         result.depth += 1
881         if leaves:
882             # Since body is a new indent level, remove spurious leading whitespace.
883             normalize_prefix(leaves[0], inside_brackets=True)
884             # Ensure a trailing comma for imports and standalone function arguments, but
885             # be careful not to add one after any comments or within type annotations.
886             no_commas = (
887                 original.is_def
888                 and opening_bracket.value == "("
889                 and not any(leaf.type == token.COMMA for leaf in leaves)
890                 # In particular, don't add one within a parenthesized return annotation.
891                 # Unfortunately the indicator we're in a return annotation (RARROW) may
892                 # be defined directly in the parent node, the parent of the parent ...
893                 # and so on depending on how complex the return annotation is.
894                 # This isn't perfect and there's some false negatives but they are in
895                 # contexts were a comma is actually fine.
896                 and not any(
897                     node.prev_sibling.type == RARROW
898                     for node in (
899                         leaves[0].parent,
900                         getattr(leaves[0].parent, "parent", None),
901                     )
902                     if isinstance(node, Node) and isinstance(node.prev_sibling, Leaf)
903                 )
904             )
905
906             if original.is_import or no_commas:
907                 for i in range(len(leaves) - 1, -1, -1):
908                     if leaves[i].type == STANDALONE_COMMENT:
909                         continue
910
911                     if leaves[i].type != token.COMMA:
912                         new_comma = Leaf(token.COMMA, ",")
913                         leaves.insert(i + 1, new_comma)
914                     break
915
916     leaves_to_track: Set[LeafID] = set()
917     if component is _BracketSplitComponent.head:
918         leaves_to_track = get_leaves_inside_matching_brackets(leaves)
919     # Populate the line
920     for leaf in leaves:
921         result.append(
922             leaf,
923             preformatted=True,
924             track_bracket=id(leaf) in leaves_to_track,
925         )
926         for comment_after in original.comments_after(leaf):
927             result.append(comment_after, preformatted=True)
928     if component is _BracketSplitComponent.body and should_split_line(
929         result, opening_bracket
930     ):
931         result.should_split_rhs = True
932     return result
933
934
935 def dont_increase_indentation(split_func: Transformer) -> Transformer:
936     """Normalize prefix of the first leaf in every line returned by `split_func`.
937
938     This is a decorator over relevant split functions.
939     """
940
941     @wraps(split_func)
942     def split_wrapper(
943         line: Line, features: Collection[Feature], mode: Mode
944     ) -> Iterator[Line]:
945         for split_line in split_func(line, features, mode):
946             normalize_prefix(split_line.leaves[0], inside_brackets=True)
947             yield split_line
948
949     return split_wrapper
950
951
952 def _get_last_non_comment_leaf(line: Line) -> Optional[int]:
953     for leaf_idx in range(len(line.leaves) - 1, 0, -1):
954         if line.leaves[leaf_idx].type != STANDALONE_COMMENT:
955             return leaf_idx
956     return None
957
958
959 def _safe_add_trailing_comma(safe: bool, delimiter_priority: int, line: Line) -> Line:
960     if (
961         safe
962         and delimiter_priority == COMMA_PRIORITY
963         and line.leaves[-1].type != token.COMMA
964         and line.leaves[-1].type != STANDALONE_COMMENT
965     ):
966         new_comma = Leaf(token.COMMA, ",")
967         line.append(new_comma)
968     return line
969
970
971 @dont_increase_indentation
972 def delimiter_split(
973     line: Line, features: Collection[Feature], mode: Mode
974 ) -> Iterator[Line]:
975     """Split according to delimiters of the highest priority.
976
977     If the appropriate Features are given, the split will add trailing commas
978     also in function signatures and calls that contain `*` and `**`.
979     """
980     try:
981         last_leaf = line.leaves[-1]
982     except IndexError:
983         raise CannotSplit("Line empty") from None
984
985     bt = line.bracket_tracker
986     try:
987         delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
988     except ValueError:
989         raise CannotSplit("No delimiters found") from None
990
991     if delimiter_priority == DOT_PRIORITY:
992         if bt.delimiter_count_with_priority(delimiter_priority) == 1:
993             raise CannotSplit("Splitting a single attribute from its owner looks wrong")
994
995     current_line = Line(
996         mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
997     )
998     lowest_depth = sys.maxsize
999     trailing_comma_safe = True
1000
1001     def append_to_line(leaf: Leaf) -> Iterator[Line]:
1002         """Append `leaf` to current line or to new line if appending impossible."""
1003         nonlocal current_line
1004         try:
1005             current_line.append_safe(leaf, preformatted=True)
1006         except ValueError:
1007             yield current_line
1008
1009             current_line = Line(
1010                 mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
1011             )
1012             current_line.append(leaf)
1013
1014     last_non_comment_leaf = _get_last_non_comment_leaf(line)
1015     for leaf_idx, leaf in enumerate(line.leaves):
1016         yield from append_to_line(leaf)
1017
1018         for comment_after in line.comments_after(leaf):
1019             yield from append_to_line(comment_after)
1020
1021         lowest_depth = min(lowest_depth, leaf.bracket_depth)
1022         if leaf.bracket_depth == lowest_depth:
1023             if is_vararg(leaf, within={syms.typedargslist}):
1024                 trailing_comma_safe = (
1025                     trailing_comma_safe and Feature.TRAILING_COMMA_IN_DEF in features
1026                 )
1027             elif is_vararg(leaf, within={syms.arglist, syms.argument}):
1028                 trailing_comma_safe = (
1029                     trailing_comma_safe and Feature.TRAILING_COMMA_IN_CALL in features
1030                 )
1031
1032         if (
1033             Preview.add_trailing_comma_consistently in mode
1034             and last_leaf.type == STANDALONE_COMMENT
1035             and leaf_idx == last_non_comment_leaf
1036         ):
1037             current_line = _safe_add_trailing_comma(
1038                 trailing_comma_safe, delimiter_priority, current_line
1039             )
1040
1041         leaf_priority = bt.delimiters.get(id(leaf))
1042         if leaf_priority == delimiter_priority:
1043             yield current_line
1044
1045             current_line = Line(
1046                 mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
1047             )
1048     if current_line:
1049         current_line = _safe_add_trailing_comma(
1050             trailing_comma_safe, delimiter_priority, current_line
1051         )
1052         yield current_line
1053
1054
1055 @dont_increase_indentation
1056 def standalone_comment_split(
1057     line: Line, features: Collection[Feature], mode: Mode
1058 ) -> Iterator[Line]:
1059     """Split standalone comments from the rest of the line."""
1060     if not line.contains_standalone_comments(0):
1061         raise CannotSplit("Line does not have any standalone comments")
1062
1063     current_line = Line(
1064         mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
1065     )
1066
1067     def append_to_line(leaf: Leaf) -> Iterator[Line]:
1068         """Append `leaf` to current line or to new line if appending impossible."""
1069         nonlocal current_line
1070         try:
1071             current_line.append_safe(leaf, preformatted=True)
1072         except ValueError:
1073             yield current_line
1074
1075             current_line = Line(
1076                 line.mode, depth=line.depth, inside_brackets=line.inside_brackets
1077             )
1078             current_line.append(leaf)
1079
1080     for leaf in line.leaves:
1081         yield from append_to_line(leaf)
1082
1083         for comment_after in line.comments_after(leaf):
1084             yield from append_to_line(comment_after)
1085
1086     if current_line:
1087         yield current_line
1088
1089
1090 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
1091     """Leave existing extra newlines if not `inside_brackets`. Remove everything
1092     else.
1093
1094     Note: don't use backslashes for formatting or you'll lose your voting rights.
1095     """
1096     if not inside_brackets:
1097         spl = leaf.prefix.split("#")
1098         if "\\" not in spl[0]:
1099             nl_count = spl[-1].count("\n")
1100             if len(spl) > 1:
1101                 nl_count -= 1
1102             leaf.prefix = "\n" * nl_count
1103             return
1104
1105     leaf.prefix = ""
1106
1107
1108 def normalize_invisible_parens(
1109     node: Node, parens_after: Set[str], *, mode: Mode, features: Collection[Feature]
1110 ) -> None:
1111     """Make existing optional parentheses invisible or create new ones.
1112
1113     `parens_after` is a set of string leaf values immediately after which parens
1114     should be put.
1115
1116     Standardizes on visible parentheses for single-element tuples, and keeps
1117     existing visible parentheses for other tuples and generator expressions.
1118     """
1119     for pc in list_comments(node.prefix, is_endmarker=False):
1120         if pc.value in FMT_OFF:
1121             # This `node` has a prefix with `# fmt: off`, don't mess with parens.
1122             return
1123
1124     # The multiple context managers grammar has a different pattern, thus this is
1125     # separate from the for-loop below. This possibly wraps them in invisible parens,
1126     # and later will be removed in remove_with_parens when needed.
1127     if node.type == syms.with_stmt:
1128         _maybe_wrap_cms_in_parens(node, mode, features)
1129
1130     check_lpar = False
1131     for index, child in enumerate(list(node.children)):
1132         # Fixes a bug where invisible parens are not properly stripped from
1133         # assignment statements that contain type annotations.
1134         if isinstance(child, Node) and child.type == syms.annassign:
1135             normalize_invisible_parens(
1136                 child, parens_after=parens_after, mode=mode, features=features
1137             )
1138
1139         # Add parentheses around long tuple unpacking in assignments.
1140         if (
1141             index == 0
1142             and isinstance(child, Node)
1143             and child.type == syms.testlist_star_expr
1144         ):
1145             check_lpar = True
1146
1147         if check_lpar:
1148             if (
1149                 child.type == syms.atom
1150                 and node.type == syms.for_stmt
1151                 and isinstance(child.prev_sibling, Leaf)
1152                 and child.prev_sibling.type == token.NAME
1153                 and child.prev_sibling.value == "for"
1154             ):
1155                 if maybe_make_parens_invisible_in_atom(
1156                     child,
1157                     parent=node,
1158                     remove_brackets_around_comma=True,
1159                 ):
1160                     wrap_in_parentheses(node, child, visible=False)
1161             elif isinstance(child, Node) and node.type == syms.with_stmt:
1162                 remove_with_parens(child, node)
1163             elif child.type == syms.atom:
1164                 if maybe_make_parens_invisible_in_atom(
1165                     child,
1166                     parent=node,
1167                 ):
1168                     wrap_in_parentheses(node, child, visible=False)
1169             elif is_one_tuple(child):
1170                 wrap_in_parentheses(node, child, visible=True)
1171             elif node.type == syms.import_from:
1172                 _normalize_import_from(node, child, index)
1173                 break
1174             elif (
1175                 index == 1
1176                 and child.type == token.STAR
1177                 and node.type == syms.except_clause
1178             ):
1179                 # In except* (PEP 654), the star is actually part of
1180                 # of the keyword. So we need to skip the insertion of
1181                 # invisible parentheses to work more precisely.
1182                 continue
1183
1184             elif not (isinstance(child, Leaf) and is_multiline_string(child)):
1185                 wrap_in_parentheses(node, child, visible=False)
1186
1187         comma_check = child.type == token.COMMA
1188
1189         check_lpar = isinstance(child, Leaf) and (
1190             child.value in parens_after or comma_check
1191         )
1192
1193
1194 def _normalize_import_from(parent: Node, child: LN, index: int) -> None:
1195     # "import from" nodes store parentheses directly as part of
1196     # the statement
1197     if is_lpar_token(child):
1198         assert is_rpar_token(parent.children[-1])
1199         # make parentheses invisible
1200         child.value = ""
1201         parent.children[-1].value = ""
1202     elif child.type != token.STAR:
1203         # insert invisible parentheses
1204         parent.insert_child(index, Leaf(token.LPAR, ""))
1205         parent.append_child(Leaf(token.RPAR, ""))
1206
1207
1208 def remove_await_parens(node: Node) -> None:
1209     if node.children[0].type == token.AWAIT and len(node.children) > 1:
1210         if (
1211             node.children[1].type == syms.atom
1212             and node.children[1].children[0].type == token.LPAR
1213         ):
1214             if maybe_make_parens_invisible_in_atom(
1215                 node.children[1],
1216                 parent=node,
1217                 remove_brackets_around_comma=True,
1218             ):
1219                 wrap_in_parentheses(node, node.children[1], visible=False)
1220
1221             # Since await is an expression we shouldn't remove
1222             # brackets in cases where this would change
1223             # the AST due to operator precedence.
1224             # Therefore we only aim to remove brackets around
1225             # power nodes that aren't also await expressions themselves.
1226             # https://peps.python.org/pep-0492/#updated-operator-precedence-table
1227             # N.B. We've still removed any redundant nested brackets though :)
1228             opening_bracket = cast(Leaf, node.children[1].children[0])
1229             closing_bracket = cast(Leaf, node.children[1].children[-1])
1230             bracket_contents = node.children[1].children[1]
1231             if isinstance(bracket_contents, Node):
1232                 if bracket_contents.type != syms.power:
1233                     ensure_visible(opening_bracket)
1234                     ensure_visible(closing_bracket)
1235                 elif (
1236                     bracket_contents.type == syms.power
1237                     and bracket_contents.children[0].type == token.AWAIT
1238                 ):
1239                     ensure_visible(opening_bracket)
1240                     ensure_visible(closing_bracket)
1241                     # If we are in a nested await then recurse down.
1242                     remove_await_parens(bracket_contents)
1243
1244
1245 def _maybe_wrap_cms_in_parens(
1246     node: Node, mode: Mode, features: Collection[Feature]
1247 ) -> None:
1248     """When enabled and safe, wrap the multiple context managers in invisible parens.
1249
1250     It is only safe when `features` contain Feature.PARENTHESIZED_CONTEXT_MANAGERS.
1251     """
1252     if (
1253         Feature.PARENTHESIZED_CONTEXT_MANAGERS not in features
1254         or Preview.wrap_multiple_context_managers_in_parens not in mode
1255         or len(node.children) <= 2
1256         # If it's an atom, it's already wrapped in parens.
1257         or node.children[1].type == syms.atom
1258     ):
1259         return
1260     colon_index: Optional[int] = None
1261     for i in range(2, len(node.children)):
1262         if node.children[i].type == token.COLON:
1263             colon_index = i
1264             break
1265     if colon_index is not None:
1266         lpar = Leaf(token.LPAR, "")
1267         rpar = Leaf(token.RPAR, "")
1268         context_managers = node.children[1:colon_index]
1269         for child in context_managers:
1270             child.remove()
1271         # After wrapping, the with_stmt will look like this:
1272         #   with_stmt
1273         #     NAME 'with'
1274         #     atom
1275         #       LPAR ''
1276         #       testlist_gexp
1277         #         ... <-- context_managers
1278         #       /testlist_gexp
1279         #       RPAR ''
1280         #     /atom
1281         #     COLON ':'
1282         new_child = Node(
1283             syms.atom, [lpar, Node(syms.testlist_gexp, context_managers), rpar]
1284         )
1285         node.insert_child(1, new_child)
1286
1287
1288 def remove_with_parens(node: Node, parent: Node) -> None:
1289     """Recursively hide optional parens in `with` statements."""
1290     # Removing all unnecessary parentheses in with statements in one pass is a tad
1291     # complex as different variations of bracketed statements result in pretty
1292     # different parse trees:
1293     #
1294     # with (open("file")) as f:                       # this is an asexpr_test
1295     #     ...
1296     #
1297     # with (open("file") as f):                       # this is an atom containing an
1298     #     ...                                         # asexpr_test
1299     #
1300     # with (open("file")) as f, (open("file")) as f:  # this is asexpr_test, COMMA,
1301     #     ...                                         # asexpr_test
1302     #
1303     # with (open("file") as f, open("file") as f):    # an atom containing a
1304     #     ...                                         # testlist_gexp which then
1305     #                                                 # contains multiple asexpr_test(s)
1306     if node.type == syms.atom:
1307         if maybe_make_parens_invisible_in_atom(
1308             node,
1309             parent=parent,
1310             remove_brackets_around_comma=True,
1311         ):
1312             wrap_in_parentheses(parent, node, visible=False)
1313         if isinstance(node.children[1], Node):
1314             remove_with_parens(node.children[1], node)
1315     elif node.type == syms.testlist_gexp:
1316         for child in node.children:
1317             if isinstance(child, Node):
1318                 remove_with_parens(child, node)
1319     elif node.type == syms.asexpr_test and not any(
1320         leaf.type == token.COLONEQUAL for leaf in node.leaves()
1321     ):
1322         if maybe_make_parens_invisible_in_atom(
1323             node.children[0],
1324             parent=node,
1325             remove_brackets_around_comma=True,
1326         ):
1327             wrap_in_parentheses(node, node.children[0], visible=False)
1328
1329
1330 def maybe_make_parens_invisible_in_atom(
1331     node: LN,
1332     parent: LN,
1333     remove_brackets_around_comma: bool = False,
1334 ) -> bool:
1335     """If it's safe, make the parens in the atom `node` invisible, recursively.
1336     Additionally, remove repeated, adjacent invisible parens from the atom `node`
1337     as they are redundant.
1338
1339     Returns whether the node should itself be wrapped in invisible parentheses.
1340     """
1341     if (
1342         node.type != syms.atom
1343         or is_empty_tuple(node)
1344         or is_one_tuple(node)
1345         or (is_yield(node) and parent.type != syms.expr_stmt)
1346         or (
1347             # This condition tries to prevent removing non-optional brackets
1348             # around a tuple, however, can be a bit overzealous so we provide
1349             # and option to skip this check for `for` and `with` statements.
1350             not remove_brackets_around_comma
1351             and max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
1352         )
1353         or is_tuple_containing_walrus(node)
1354     ):
1355         return False
1356
1357     if is_walrus_assignment(node):
1358         if parent.type in [
1359             syms.annassign,
1360             syms.expr_stmt,
1361             syms.assert_stmt,
1362             syms.return_stmt,
1363             syms.except_clause,
1364             syms.funcdef,
1365             syms.with_stmt,
1366             # these ones aren't useful to end users, but they do please fuzzers
1367             syms.for_stmt,
1368             syms.del_stmt,
1369             syms.for_stmt,
1370         ]:
1371             return False
1372
1373     first = node.children[0]
1374     last = node.children[-1]
1375     if is_lpar_token(first) and is_rpar_token(last):
1376         middle = node.children[1]
1377         # make parentheses invisible
1378         first.value = ""
1379         last.value = ""
1380         maybe_make_parens_invisible_in_atom(
1381             middle,
1382             parent=parent,
1383             remove_brackets_around_comma=remove_brackets_around_comma,
1384         )
1385
1386         if is_atom_with_invisible_parens(middle):
1387             # Strip the invisible parens from `middle` by replacing
1388             # it with the child in-between the invisible parens
1389             middle.replace(middle.children[1])
1390
1391         return False
1392
1393     return True
1394
1395
1396 def should_split_line(line: Line, opening_bracket: Leaf) -> bool:
1397     """Should `line` be immediately split with `delimiter_split()` after RHS?"""
1398
1399     if not (opening_bracket.parent and opening_bracket.value in "[{("):
1400         return False
1401
1402     # We're essentially checking if the body is delimited by commas and there's more
1403     # than one of them (we're excluding the trailing comma and if the delimiter priority
1404     # is still commas, that means there's more).
1405     exclude = set()
1406     trailing_comma = False
1407     try:
1408         last_leaf = line.leaves[-1]
1409         if last_leaf.type == token.COMMA:
1410             trailing_comma = True
1411             exclude.add(id(last_leaf))
1412         max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
1413     except (IndexError, ValueError):
1414         return False
1415
1416     return max_priority == COMMA_PRIORITY and (
1417         (line.mode.magic_trailing_comma and trailing_comma)
1418         # always explode imports
1419         or opening_bracket.parent.type in {syms.atom, syms.import_from}
1420     )
1421
1422
1423 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
1424     """Generate sets of closing bracket IDs that should be omitted in a RHS.
1425
1426     Brackets can be omitted if the entire trailer up to and including
1427     a preceding closing bracket fits in one line.
1428
1429     Yielded sets are cumulative (contain results of previous yields, too).  First
1430     set is empty, unless the line should explode, in which case bracket pairs until
1431     the one that needs to explode are omitted.
1432     """
1433
1434     omit: Set[LeafID] = set()
1435     if not line.magic_trailing_comma:
1436         yield omit
1437
1438     length = 4 * line.depth
1439     opening_bracket: Optional[Leaf] = None
1440     closing_bracket: Optional[Leaf] = None
1441     inner_brackets: Set[LeafID] = set()
1442     for index, leaf, leaf_length in line.enumerate_with_length(reversed=True):
1443         length += leaf_length
1444         if length > line_length:
1445             break
1446
1447         has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
1448         if leaf.type == STANDALONE_COMMENT or has_inline_comment:
1449             break
1450
1451         if opening_bracket:
1452             if leaf is opening_bracket:
1453                 opening_bracket = None
1454             elif leaf.type in CLOSING_BRACKETS:
1455                 prev = line.leaves[index - 1] if index > 0 else None
1456                 if (
1457                     prev
1458                     and prev.type == token.COMMA
1459                     and leaf.opening_bracket is not None
1460                     and not is_one_sequence_between(
1461                         leaf.opening_bracket, leaf, line.leaves
1462                     )
1463                 ):
1464                     # Never omit bracket pairs with trailing commas.
1465                     # We need to explode on those.
1466                     break
1467
1468                 inner_brackets.add(id(leaf))
1469         elif leaf.type in CLOSING_BRACKETS:
1470             prev = line.leaves[index - 1] if index > 0 else None
1471             if prev and prev.type in OPENING_BRACKETS:
1472                 # Empty brackets would fail a split so treat them as "inner"
1473                 # brackets (e.g. only add them to the `omit` set if another
1474                 # pair of brackets was good enough.
1475                 inner_brackets.add(id(leaf))
1476                 continue
1477
1478             if closing_bracket:
1479                 omit.add(id(closing_bracket))
1480                 omit.update(inner_brackets)
1481                 inner_brackets.clear()
1482                 yield omit
1483
1484             if (
1485                 prev
1486                 and prev.type == token.COMMA
1487                 and leaf.opening_bracket is not None
1488                 and not is_one_sequence_between(leaf.opening_bracket, leaf, line.leaves)
1489             ):
1490                 # Never omit bracket pairs with trailing commas.
1491                 # We need to explode on those.
1492                 break
1493
1494             if leaf.value:
1495                 opening_bracket = leaf.opening_bracket
1496                 closing_bracket = leaf
1497
1498
1499 def run_transformer(
1500     line: Line,
1501     transform: Transformer,
1502     mode: Mode,
1503     features: Collection[Feature],
1504     *,
1505     line_str: str = "",
1506 ) -> List[Line]:
1507     if not line_str:
1508         line_str = line_to_string(line)
1509     result: List[Line] = []
1510     for transformed_line in transform(line, features, mode):
1511         if str(transformed_line).strip("\n") == line_str:
1512             raise CannotTransform("Line transformer returned an unchanged result")
1513
1514         result.extend(transform_line(transformed_line, mode=mode, features=features))
1515
1516     features_set = set(features)
1517     if (
1518         Feature.FORCE_OPTIONAL_PARENTHESES in features_set
1519         or transform.__class__.__name__ != "rhs"
1520         or not line.bracket_tracker.invisible
1521         or any(bracket.value for bracket in line.bracket_tracker.invisible)
1522         or line.contains_multiline_strings()
1523         or result[0].contains_uncollapsable_type_comments()
1524         or result[0].contains_unsplittable_type_ignore()
1525         or is_line_short_enough(result[0], mode=mode)
1526         # If any leaves have no parents (which _can_ occur since
1527         # `transform(line)` potentially destroys the line's underlying node
1528         # structure), then we can't proceed. Doing so would cause the below
1529         # call to `append_leaves()` to fail.
1530         or any(leaf.parent is None for leaf in line.leaves)
1531     ):
1532         return result
1533
1534     line_copy = line.clone()
1535     append_leaves(line_copy, line, line.leaves)
1536     features_fop = features_set | {Feature.FORCE_OPTIONAL_PARENTHESES}
1537     second_opinion = run_transformer(
1538         line_copy, transform, mode, features_fop, line_str=line_str
1539     )
1540     if all(is_line_short_enough(ln, mode=mode) for ln in second_opinion):
1541         result = second_opinion
1542     return result