]> git.madduck.net Git - etc/vim.git/blob - src/black/lines.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:

Do not add an extra blank line to an import line that has fmt disabled (#3610)
[etc/vim.git] / src / black / lines.py
1 import itertools
2 import math
3 import sys
4 from dataclasses import dataclass, field
5 from typing import (
6     Callable,
7     Dict,
8     Iterator,
9     List,
10     Optional,
11     Sequence,
12     Tuple,
13     TypeVar,
14     Union,
15     cast,
16 )
17
18 from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker
19 from black.mode import Mode, Preview
20 from black.nodes import (
21     BRACKETS,
22     CLOSING_BRACKETS,
23     OPENING_BRACKETS,
24     STANDALONE_COMMENT,
25     TEST_DESCENDANTS,
26     child_towards,
27     is_import,
28     is_multiline_string,
29     is_one_sequence_between,
30     is_type_comment,
31     is_with_or_async_with_stmt,
32     replace_child,
33     syms,
34     whitespace,
35 )
36 from blib2to3.pgen2 import token
37 from blib2to3.pytree import Leaf, Node
38
39 # types
40 T = TypeVar("T")
41 Index = int
42 LeafID = int
43 LN = Union[Leaf, Node]
44
45
46 @dataclass
47 class Line:
48     """Holds leaves and comments. Can be printed with `str(line)`."""
49
50     mode: Mode
51     depth: int = 0
52     leaves: List[Leaf] = field(default_factory=list)
53     # keys ordered like `leaves`
54     comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
55     bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
56     inside_brackets: bool = False
57     should_split_rhs: bool = False
58     magic_trailing_comma: Optional[Leaf] = None
59
60     def append(
61         self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False
62     ) -> None:
63         """Add a new `leaf` to the end of the line.
64
65         Unless `preformatted` is True, the `leaf` will receive a new consistent
66         whitespace prefix and metadata applied by :class:`BracketTracker`.
67         Trailing commas are maybe removed, unpacked for loop variables are
68         demoted from being delimiters.
69
70         Inline comments are put aside.
71         """
72         has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
73         if not has_value:
74             return
75
76         if token.COLON == leaf.type and self.is_class_paren_empty:
77             del self.leaves[-2:]
78         if self.leaves and not preformatted:
79             # Note: at this point leaf.prefix should be empty except for
80             # imports, for which we only preserve newlines.
81             leaf.prefix += whitespace(
82                 leaf, complex_subscript=self.is_complex_subscript(leaf)
83             )
84         if self.inside_brackets or not preformatted or track_bracket:
85             self.bracket_tracker.mark(leaf)
86             if self.mode.magic_trailing_comma:
87                 if self.has_magic_trailing_comma(leaf):
88                     self.magic_trailing_comma = leaf
89             elif self.has_magic_trailing_comma(leaf, ensure_removable=True):
90                 self.remove_trailing_comma()
91         if not self.append_comment(leaf):
92             self.leaves.append(leaf)
93
94     def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
95         """Like :func:`append()` but disallow invalid standalone comment structure.
96
97         Raises ValueError when any `leaf` is appended after a standalone comment
98         or when a standalone comment is not the first leaf on the line.
99         """
100         if self.bracket_tracker.depth == 0:
101             if self.is_comment:
102                 raise ValueError("cannot append to standalone comments")
103
104             if self.leaves and leaf.type == STANDALONE_COMMENT:
105                 raise ValueError(
106                     "cannot append standalone comments to a populated line"
107                 )
108
109         self.append(leaf, preformatted=preformatted)
110
111     @property
112     def is_comment(self) -> bool:
113         """Is this line a standalone comment?"""
114         return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
115
116     @property
117     def is_decorator(self) -> bool:
118         """Is this line a decorator?"""
119         return bool(self) and self.leaves[0].type == token.AT
120
121     @property
122     def is_import(self) -> bool:
123         """Is this an import line?"""
124         return bool(self) and is_import(self.leaves[0])
125
126     @property
127     def is_with_or_async_with_stmt(self) -> bool:
128         """Is this a with_stmt line?"""
129         return bool(self) and is_with_or_async_with_stmt(self.leaves[0])
130
131     @property
132     def is_class(self) -> bool:
133         """Is this line a class definition?"""
134         return (
135             bool(self)
136             and self.leaves[0].type == token.NAME
137             and self.leaves[0].value == "class"
138         )
139
140     @property
141     def is_stub_class(self) -> bool:
142         """Is this line a class definition with a body consisting only of "..."?"""
143         return self.is_class and self.leaves[-3:] == [
144             Leaf(token.DOT, ".") for _ in range(3)
145         ]
146
147     @property
148     def is_def(self) -> bool:
149         """Is this a function definition? (Also returns True for async defs.)"""
150         try:
151             first_leaf = self.leaves[0]
152         except IndexError:
153             return False
154
155         try:
156             second_leaf: Optional[Leaf] = self.leaves[1]
157         except IndexError:
158             second_leaf = None
159         return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
160             first_leaf.type == token.ASYNC
161             and second_leaf is not None
162             and second_leaf.type == token.NAME
163             and second_leaf.value == "def"
164         )
165
166     @property
167     def is_class_paren_empty(self) -> bool:
168         """Is this a class with no base classes but using parentheses?
169
170         Those are unnecessary and should be removed.
171         """
172         return (
173             bool(self)
174             and len(self.leaves) == 4
175             and self.is_class
176             and self.leaves[2].type == token.LPAR
177             and self.leaves[2].value == "("
178             and self.leaves[3].type == token.RPAR
179             and self.leaves[3].value == ")"
180         )
181
182     @property
183     def is_triple_quoted_string(self) -> bool:
184         """Is the line a triple quoted string?"""
185         return (
186             bool(self)
187             and self.leaves[0].type == token.STRING
188             and self.leaves[0].value.startswith(('"""', "'''"))
189         )
190
191     @property
192     def opens_block(self) -> bool:
193         """Does this line open a new level of indentation."""
194         if len(self.leaves) == 0:
195             return False
196         return self.leaves[-1].type == token.COLON
197
198     def is_fmt_pass_converted(
199         self, *, first_leaf_matches: Optional[Callable[[Leaf], bool]] = None
200     ) -> bool:
201         """Is this line converted from fmt off/skip code?
202
203         If first_leaf_matches is not None, it only returns True if the first
204         leaf of converted code matches.
205         """
206         if len(self.leaves) != 1:
207             return False
208         leaf = self.leaves[0]
209         if (
210             leaf.type != STANDALONE_COMMENT
211             or leaf.fmt_pass_converted_first_leaf is None
212         ):
213             return False
214         return first_leaf_matches is None or first_leaf_matches(
215             leaf.fmt_pass_converted_first_leaf
216         )
217
218     def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
219         """If so, needs to be split before emitting."""
220         for leaf in self.leaves:
221             if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit:
222                 return True
223
224         return False
225
226     def contains_uncollapsable_type_comments(self) -> bool:
227         ignored_ids = set()
228         try:
229             last_leaf = self.leaves[-1]
230             ignored_ids.add(id(last_leaf))
231             if last_leaf.type == token.COMMA or (
232                 last_leaf.type == token.RPAR and not last_leaf.value
233             ):
234                 # When trailing commas or optional parens are inserted by Black for
235                 # consistency, comments after the previous last element are not moved
236                 # (they don't have to, rendering will still be correct).  So we ignore
237                 # trailing commas and invisible.
238                 last_leaf = self.leaves[-2]
239                 ignored_ids.add(id(last_leaf))
240         except IndexError:
241             return False
242
243         # A type comment is uncollapsable if it is attached to a leaf
244         # that isn't at the end of the line (since that could cause it
245         # to get associated to a different argument) or if there are
246         # comments before it (since that could cause it to get hidden
247         # behind a comment.
248         comment_seen = False
249         for leaf_id, comments in self.comments.items():
250             for comment in comments:
251                 if is_type_comment(comment):
252                     if comment_seen or (
253                         not is_type_comment(comment, " ignore")
254                         and leaf_id not in ignored_ids
255                     ):
256                         return True
257
258                 comment_seen = True
259
260         return False
261
262     def contains_unsplittable_type_ignore(self) -> bool:
263         if not self.leaves:
264             return False
265
266         # If a 'type: ignore' is attached to the end of a line, we
267         # can't split the line, because we can't know which of the
268         # subexpressions the ignore was meant to apply to.
269         #
270         # We only want this to apply to actual physical lines from the
271         # original source, though: we don't want the presence of a
272         # 'type: ignore' at the end of a multiline expression to
273         # justify pushing it all onto one line. Thus we
274         # (unfortunately) need to check the actual source lines and
275         # only report an unsplittable 'type: ignore' if this line was
276         # one line in the original code.
277
278         # Grab the first and last line numbers, skipping generated leaves
279         first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
280         last_line = next(
281             (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
282         )
283
284         if first_line == last_line:
285             # We look at the last two leaves since a comma or an
286             # invisible paren could have been added at the end of the
287             # line.
288             for node in self.leaves[-2:]:
289                 for comment in self.comments.get(id(node), []):
290                     if is_type_comment(comment, " ignore"):
291                         return True
292
293         return False
294
295     def contains_multiline_strings(self) -> bool:
296         return any(is_multiline_string(leaf) for leaf in self.leaves)
297
298     def has_magic_trailing_comma(
299         self, closing: Leaf, ensure_removable: bool = False
300     ) -> bool:
301         """Return True if we have a magic trailing comma, that is when:
302         - there's a trailing comma here
303         - it's not a one-tuple
304         - it's not a single-element subscript
305         Additionally, if ensure_removable:
306         - it's not from square bracket indexing
307         (specifically, single-element square bracket indexing)
308         """
309         if not (
310             closing.type in CLOSING_BRACKETS
311             and self.leaves
312             and self.leaves[-1].type == token.COMMA
313         ):
314             return False
315
316         if closing.type == token.RBRACE:
317             return True
318
319         if closing.type == token.RSQB:
320             if (
321                 closing.parent
322                 and closing.parent.type == syms.trailer
323                 and closing.opening_bracket
324                 and is_one_sequence_between(
325                     closing.opening_bracket,
326                     closing,
327                     self.leaves,
328                     brackets=(token.LSQB, token.RSQB),
329                 )
330             ):
331                 return False
332
333             if not ensure_removable:
334                 return True
335
336             comma = self.leaves[-1]
337             if comma.parent is None:
338                 return False
339             return (
340                 comma.parent.type != syms.subscriptlist
341                 or closing.opening_bracket is None
342                 or not is_one_sequence_between(
343                     closing.opening_bracket,
344                     closing,
345                     self.leaves,
346                     brackets=(token.LSQB, token.RSQB),
347                 )
348             )
349
350         if self.is_import:
351             return True
352
353         if closing.opening_bracket is not None and not is_one_sequence_between(
354             closing.opening_bracket, closing, self.leaves
355         ):
356             return True
357
358         return False
359
360     def append_comment(self, comment: Leaf) -> bool:
361         """Add an inline or standalone comment to the line."""
362         if (
363             comment.type == STANDALONE_COMMENT
364             and self.bracket_tracker.any_open_brackets()
365         ):
366             comment.prefix = ""
367             return False
368
369         if comment.type != token.COMMENT:
370             return False
371
372         if not self.leaves:
373             comment.type = STANDALONE_COMMENT
374             comment.prefix = ""
375             return False
376
377         last_leaf = self.leaves[-1]
378         if (
379             last_leaf.type == token.RPAR
380             and not last_leaf.value
381             and last_leaf.parent
382             and len(list(last_leaf.parent.leaves())) <= 3
383             and not is_type_comment(comment)
384         ):
385             # Comments on an optional parens wrapping a single leaf should belong to
386             # the wrapped node except if it's a type comment. Pinning the comment like
387             # this avoids unstable formatting caused by comment migration.
388             if len(self.leaves) < 2:
389                 comment.type = STANDALONE_COMMENT
390                 comment.prefix = ""
391                 return False
392
393             last_leaf = self.leaves[-2]
394         self.comments.setdefault(id(last_leaf), []).append(comment)
395         return True
396
397     def comments_after(self, leaf: Leaf) -> List[Leaf]:
398         """Generate comments that should appear directly after `leaf`."""
399         return self.comments.get(id(leaf), [])
400
401     def remove_trailing_comma(self) -> None:
402         """Remove the trailing comma and moves the comments attached to it."""
403         trailing_comma = self.leaves.pop()
404         trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
405         self.comments.setdefault(id(self.leaves[-1]), []).extend(
406             trailing_comma_comments
407         )
408
409     def is_complex_subscript(self, leaf: Leaf) -> bool:
410         """Return True iff `leaf` is part of a slice with non-trivial exprs."""
411         open_lsqb = self.bracket_tracker.get_open_lsqb()
412         if open_lsqb is None:
413             return False
414
415         subscript_start = open_lsqb.next_sibling
416
417         if isinstance(subscript_start, Node):
418             if subscript_start.type == syms.listmaker:
419                 return False
420
421             if subscript_start.type == syms.subscriptlist:
422                 subscript_start = child_towards(subscript_start, leaf)
423         return subscript_start is not None and any(
424             n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
425         )
426
427     def enumerate_with_length(
428         self, reversed: bool = False
429     ) -> Iterator[Tuple[Index, Leaf, int]]:
430         """Return an enumeration of leaves with their length.
431
432         Stops prematurely on multiline strings and standalone comments.
433         """
434         op = cast(
435             Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
436             enumerate_reversed if reversed else enumerate,
437         )
438         for index, leaf in op(self.leaves):
439             length = len(leaf.prefix) + len(leaf.value)
440             if "\n" in leaf.value:
441                 return  # Multiline strings, we can't continue.
442
443             for comment in self.comments_after(leaf):
444                 length += len(comment.value)
445
446             yield index, leaf, length
447
448     def clone(self) -> "Line":
449         return Line(
450             mode=self.mode,
451             depth=self.depth,
452             inside_brackets=self.inside_brackets,
453             should_split_rhs=self.should_split_rhs,
454             magic_trailing_comma=self.magic_trailing_comma,
455         )
456
457     def __str__(self) -> str:
458         """Render the line."""
459         if not self:
460             return "\n"
461
462         indent = "    " * self.depth
463         leaves = iter(self.leaves)
464         first = next(leaves)
465         res = f"{first.prefix}{indent}{first.value}"
466         for leaf in leaves:
467             res += str(leaf)
468         for comment in itertools.chain.from_iterable(self.comments.values()):
469             res += str(comment)
470
471         return res + "\n"
472
473     def __bool__(self) -> bool:
474         """Return True if the line has leaves or comments."""
475         return bool(self.leaves or self.comments)
476
477
478 @dataclass
479 class RHSResult:
480     """Intermediate split result from a right hand split."""
481
482     head: Line
483     body: Line
484     tail: Line
485     opening_bracket: Leaf
486     closing_bracket: Leaf
487
488
489 @dataclass
490 class LinesBlock:
491     """Class that holds information about a block of formatted lines.
492
493     This is introduced so that the EmptyLineTracker can look behind the standalone
494     comments and adjust their empty lines for class or def lines.
495     """
496
497     mode: Mode
498     previous_block: Optional["LinesBlock"]
499     original_line: Line
500     before: int = 0
501     content_lines: List[str] = field(default_factory=list)
502     after: int = 0
503
504     def all_lines(self) -> List[str]:
505         empty_line = str(Line(mode=self.mode))
506         return (
507             [empty_line * self.before] + self.content_lines + [empty_line * self.after]
508         )
509
510
511 @dataclass
512 class EmptyLineTracker:
513     """Provides a stateful method that returns the number of potential extra
514     empty lines needed before and after the currently processed line.
515
516     Note: this tracker works on lines that haven't been split yet.  It assumes
517     the prefix of the first leaf consists of optional newlines.  Those newlines
518     are consumed by `maybe_empty_lines()` and included in the computation.
519     """
520
521     mode: Mode
522     previous_line: Optional[Line] = None
523     previous_block: Optional[LinesBlock] = None
524     previous_defs: List[int] = field(default_factory=list)
525     semantic_leading_comment: Optional[LinesBlock] = None
526
527     def maybe_empty_lines(self, current_line: Line) -> LinesBlock:
528         """Return the number of extra empty lines before and after the `current_line`.
529
530         This is for separating `def`, `async def` and `class` with extra empty
531         lines (two on module-level).
532         """
533         before, after = self._maybe_empty_lines(current_line)
534         previous_after = self.previous_block.after if self.previous_block else 0
535         before = (
536             # Black should not insert empty lines at the beginning
537             # of the file
538             0
539             if self.previous_line is None
540             else before - previous_after
541         )
542         block = LinesBlock(
543             mode=self.mode,
544             previous_block=self.previous_block,
545             original_line=current_line,
546             before=before,
547             after=after,
548         )
549
550         # Maintain the semantic_leading_comment state.
551         if current_line.is_comment:
552             if self.previous_line is None or (
553                 not self.previous_line.is_decorator
554                 # `or before` means this comment already has an empty line before
555                 and (not self.previous_line.is_comment or before)
556                 and (self.semantic_leading_comment is None or before)
557             ):
558                 self.semantic_leading_comment = block
559         # `or before` means this decorator already has an empty line before
560         elif not current_line.is_decorator or before:
561             self.semantic_leading_comment = None
562
563         self.previous_line = current_line
564         self.previous_block = block
565         return block
566
567     def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
568         max_allowed = 1
569         if current_line.depth == 0:
570             max_allowed = 1 if self.mode.is_pyi else 2
571         if current_line.leaves:
572             # Consume the first leaf's extra newlines.
573             first_leaf = current_line.leaves[0]
574             before = first_leaf.prefix.count("\n")
575             before = min(before, max_allowed)
576             first_leaf.prefix = ""
577         else:
578             before = 0
579         depth = current_line.depth
580         while self.previous_defs and self.previous_defs[-1] >= depth:
581             if self.mode.is_pyi:
582                 assert self.previous_line is not None
583                 if depth and not current_line.is_def and self.previous_line.is_def:
584                     # Empty lines between attributes and methods should be preserved.
585                     before = min(1, before)
586                 elif depth:
587                     before = 0
588                 else:
589                     before = 1
590             else:
591                 if depth:
592                     before = 1
593                 elif (
594                     not depth
595                     and self.previous_defs[-1]
596                     and current_line.leaves[-1].type == token.COLON
597                     and (
598                         current_line.leaves[0].value
599                         not in ("with", "try", "for", "while", "if", "match")
600                     )
601                 ):
602                     # We shouldn't add two newlines between an indented function and
603                     # a dependent non-indented clause. This is to avoid issues with
604                     # conditional function definitions that are technically top-level
605                     # and therefore get two trailing newlines, but look weird and
606                     # inconsistent when they're followed by elif, else, etc. This is
607                     # worse because these functions only get *one* preceding newline
608                     # already.
609                     before = 1
610                 else:
611                     before = 2
612             self.previous_defs.pop()
613         if current_line.is_decorator or current_line.is_def or current_line.is_class:
614             return self._maybe_empty_lines_for_class_or_def(current_line, before)
615
616         if (
617             self.previous_line
618             and self.previous_line.is_import
619             and not current_line.is_import
620             and not current_line.is_fmt_pass_converted(first_leaf_matches=is_import)
621             and depth == self.previous_line.depth
622         ):
623             return (before or 1), 0
624
625         if (
626             self.previous_line
627             and self.previous_line.is_class
628             and current_line.is_triple_quoted_string
629         ):
630             return before, 1
631
632         if self.previous_line and self.previous_line.opens_block:
633             return 0, 0
634         return before, 0
635
636     def _maybe_empty_lines_for_class_or_def(
637         self, current_line: Line, before: int
638     ) -> Tuple[int, int]:
639         if not current_line.is_decorator:
640             self.previous_defs.append(current_line.depth)
641         if self.previous_line is None:
642             # Don't insert empty lines before the first line in the file.
643             return 0, 0
644
645         if self.previous_line.is_decorator:
646             if self.mode.is_pyi and current_line.is_stub_class:
647                 # Insert an empty line after a decorated stub class
648                 return 0, 1
649
650             return 0, 0
651
652         if self.previous_line.depth < current_line.depth and (
653             self.previous_line.is_class or self.previous_line.is_def
654         ):
655             return 0, 0
656
657         comment_to_add_newlines: Optional[LinesBlock] = None
658         if (
659             self.previous_line.is_comment
660             and self.previous_line.depth == current_line.depth
661             and before == 0
662         ):
663             slc = self.semantic_leading_comment
664             if (
665                 slc is not None
666                 and slc.previous_block is not None
667                 and not slc.previous_block.original_line.is_class
668                 and not slc.previous_block.original_line.opens_block
669                 and slc.before <= 1
670             ):
671                 comment_to_add_newlines = slc
672             else:
673                 return 0, 0
674
675         if self.mode.is_pyi:
676             if current_line.is_class or self.previous_line.is_class:
677                 if self.previous_line.depth < current_line.depth:
678                     newlines = 0
679                 elif self.previous_line.depth > current_line.depth:
680                     newlines = 1
681                 elif current_line.is_stub_class and self.previous_line.is_stub_class:
682                     # No blank line between classes with an empty body
683                     newlines = 0
684                 else:
685                     newlines = 1
686             elif (
687                 current_line.is_def or current_line.is_decorator
688             ) and not self.previous_line.is_def:
689                 if current_line.depth:
690                     # In classes empty lines between attributes and methods should
691                     # be preserved.
692                     newlines = min(1, before)
693                 else:
694                     # Blank line between a block of functions (maybe with preceding
695                     # decorators) and a block of non-functions
696                     newlines = 1
697             elif self.previous_line.depth > current_line.depth:
698                 newlines = 1
699             else:
700                 newlines = 0
701         else:
702             newlines = 1 if current_line.depth else 2
703         if comment_to_add_newlines is not None:
704             previous_block = comment_to_add_newlines.previous_block
705             if previous_block is not None:
706                 comment_to_add_newlines.before = (
707                     max(comment_to_add_newlines.before, newlines) - previous_block.after
708                 )
709                 newlines = 0
710         return newlines, 0
711
712
713 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
714     """Like `reversed(enumerate(sequence))` if that were possible."""
715     index = len(sequence) - 1
716     for element in reversed(sequence):
717         yield (index, element)
718         index -= 1
719
720
721 def append_leaves(
722     new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
723 ) -> None:
724     """
725     Append leaves (taken from @old_line) to @new_line, making sure to fix the
726     underlying Node structure where appropriate.
727
728     All of the leaves in @leaves are duplicated. The duplicates are then
729     appended to @new_line and used to replace their originals in the underlying
730     Node structure. Any comments attached to the old leaves are reattached to
731     the new leaves.
732
733     Pre-conditions:
734         set(@leaves) is a subset of set(@old_line.leaves).
735     """
736     for old_leaf in leaves:
737         new_leaf = Leaf(old_leaf.type, old_leaf.value)
738         replace_child(old_leaf, new_leaf)
739         new_line.append(new_leaf, preformatted=preformatted)
740
741         for comment_leaf in old_line.comments_after(old_leaf):
742             new_line.append(comment_leaf, preformatted=True)
743
744
745 def is_line_short_enough(  # noqa: C901
746     line: Line, *, mode: Mode, line_str: str = ""
747 ) -> bool:
748     """For non-multiline strings, return True if `line` is no longer than `line_length`.
749     For multiline strings, looks at the context around `line` to determine
750     if it should be inlined or split up.
751     Uses the provided `line_str` rendering, if any, otherwise computes a new one.
752     """
753     if not line_str:
754         line_str = line_to_string(line)
755
756     if Preview.multiline_string_handling not in mode:
757         return (
758             len(line_str) <= mode.line_length
759             and "\n" not in line_str  # multiline strings
760             and not line.contains_standalone_comments()
761         )
762
763     if line.contains_standalone_comments():
764         return False
765     if "\n" not in line_str:
766         # No multiline strings (MLS) present
767         return len(line_str) <= mode.line_length
768
769     first, *_, last = line_str.split("\n")
770     if len(first) > mode.line_length or len(last) > mode.line_length:
771         return False
772
773     # Traverse the AST to examine the context of the multiline string (MLS),
774     # tracking aspects such as depth and comma existence,
775     # to determine whether to split the MLS or keep it together.
776     # Depth (which is based on the existing bracket_depth concept)
777     # is needed to determine nesting level of the MLS.
778     # Includes special case for trailing commas.
779     commas: List[int] = []  # tracks number of commas per depth level
780     multiline_string: Optional[Leaf] = None
781     # store the leaves that contain parts of the MLS
782     multiline_string_contexts: List[LN] = []
783
784     max_level_to_update = math.inf  # track the depth of the MLS
785     for i, leaf in enumerate(line.leaves):
786         if max_level_to_update == math.inf:
787             had_comma: Optional[int] = None
788             if leaf.bracket_depth + 1 > len(commas):
789                 commas.append(0)
790             elif leaf.bracket_depth + 1 < len(commas):
791                 had_comma = commas.pop()
792             if (
793                 had_comma is not None
794                 and multiline_string is not None
795                 and multiline_string.bracket_depth == leaf.bracket_depth + 1
796             ):
797                 # Have left the level with the MLS, stop tracking commas
798                 max_level_to_update = leaf.bracket_depth
799                 if had_comma > 0:
800                     # MLS was in parens with at least one comma - force split
801                     return False
802
803         if leaf.bracket_depth <= max_level_to_update and leaf.type == token.COMMA:
804             # Ignore non-nested trailing comma
805             # directly after MLS/MLS-containing expression
806             ignore_ctxs: List[Optional[LN]] = [None]
807             ignore_ctxs += multiline_string_contexts
808             if not (leaf.prev_sibling in ignore_ctxs and i == len(line.leaves) - 1):
809                 commas[leaf.bracket_depth] += 1
810         if max_level_to_update != math.inf:
811             max_level_to_update = min(max_level_to_update, leaf.bracket_depth)
812
813         if is_multiline_string(leaf):
814             if len(multiline_string_contexts) > 0:
815                 # >1 multiline string cannot fit on a single line - force split
816                 return False
817             multiline_string = leaf
818             ctx: LN = leaf
819             # fetch the leaf components of the MLS in the AST
820             while str(ctx) in line_str:
821                 multiline_string_contexts.append(ctx)
822                 if ctx.parent is None:
823                     break
824                 ctx = ctx.parent
825
826     # May not have a triple-quoted multiline string at all,
827     # in case of a regular string with embedded newlines and line continuations
828     if len(multiline_string_contexts) == 0:
829         return True
830
831     return all(val == 0 for val in commas)
832
833
834 def can_be_split(line: Line) -> bool:
835     """Return False if the line cannot be split *for sure*.
836
837     This is not an exhaustive search but a cheap heuristic that we can use to
838     avoid some unfortunate formattings (mostly around wrapping unsplittable code
839     in unnecessary parentheses).
840     """
841     leaves = line.leaves
842     if len(leaves) < 2:
843         return False
844
845     if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
846         call_count = 0
847         dot_count = 0
848         next = leaves[-1]
849         for leaf in leaves[-2::-1]:
850             if leaf.type in OPENING_BRACKETS:
851                 if next.type not in CLOSING_BRACKETS:
852                     return False
853
854                 call_count += 1
855             elif leaf.type == token.DOT:
856                 dot_count += 1
857             elif leaf.type == token.NAME:
858                 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
859                     return False
860
861             elif leaf.type not in CLOSING_BRACKETS:
862                 return False
863
864             if dot_count > 1 and call_count > 1:
865                 return False
866
867     return True
868
869
870 def can_omit_invisible_parens(
871     rhs: RHSResult,
872     line_length: int,
873 ) -> bool:
874     """Does `rhs.body` have a shape safe to reformat without optional parens around it?
875
876     Returns True for only a subset of potentially nice looking formattings but
877     the point is to not return false positives that end up producing lines that
878     are too long.
879     """
880     line = rhs.body
881     bt = line.bracket_tracker
882     if not bt.delimiters:
883         # Without delimiters the optional parentheses are useless.
884         return True
885
886     max_priority = bt.max_delimiter_priority()
887     delimiter_count = bt.delimiter_count_with_priority(max_priority)
888     if delimiter_count > 1:
889         # With more than one delimiter of a kind the optional parentheses read better.
890         return False
891
892     if delimiter_count == 1:
893         if (
894             Preview.wrap_multiple_context_managers_in_parens in line.mode
895             and max_priority == COMMA_PRIORITY
896             and rhs.head.is_with_or_async_with_stmt
897         ):
898             # For two context manager with statements, the optional parentheses read
899             # better. In this case, `rhs.body` is the context managers part of
900             # the with statement. `rhs.head` is the `with (` part on the previous
901             # line.
902             return False
903         # Otherwise it may also read better, but we don't do it today and requires
904         # careful considerations for all possible cases. See
905         # https://github.com/psf/black/issues/2156.
906
907     if max_priority == DOT_PRIORITY:
908         # A single stranded method call doesn't require optional parentheses.
909         return True
910
911     assert len(line.leaves) >= 2, "Stranded delimiter"
912
913     # With a single delimiter, omit if the expression starts or ends with
914     # a bracket.
915     first = line.leaves[0]
916     second = line.leaves[1]
917     if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
918         if _can_omit_opening_paren(line, first=first, line_length=line_length):
919             return True
920
921         # Note: we are not returning False here because a line might have *both*
922         # a leading opening bracket and a trailing closing bracket.  If the
923         # opening bracket doesn't match our rule, maybe the closing will.
924
925     penultimate = line.leaves[-2]
926     last = line.leaves[-1]
927
928     if (
929         last.type == token.RPAR
930         or last.type == token.RBRACE
931         or (
932             # don't use indexing for omitting optional parentheses;
933             # it looks weird
934             last.type == token.RSQB
935             and last.parent
936             and last.parent.type != syms.trailer
937         )
938     ):
939         if penultimate.type in OPENING_BRACKETS:
940             # Empty brackets don't help.
941             return False
942
943         if is_multiline_string(first):
944             # Additional wrapping of a multiline string in this situation is
945             # unnecessary.
946             return True
947
948         if _can_omit_closing_paren(line, last=last, line_length=line_length):
949             return True
950
951     return False
952
953
954 def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
955     """See `can_omit_invisible_parens`."""
956     remainder = False
957     length = 4 * line.depth
958     _index = -1
959     for _index, leaf, leaf_length in line.enumerate_with_length():
960         if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
961             remainder = True
962         if remainder:
963             length += leaf_length
964             if length > line_length:
965                 break
966
967             if leaf.type in OPENING_BRACKETS:
968                 # There are brackets we can further split on.
969                 remainder = False
970
971     else:
972         # checked the entire string and line length wasn't exceeded
973         if len(line.leaves) == _index + 1:
974             return True
975
976     return False
977
978
979 def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
980     """See `can_omit_invisible_parens`."""
981     length = 4 * line.depth
982     seen_other_brackets = False
983     for _index, leaf, leaf_length in line.enumerate_with_length():
984         length += leaf_length
985         if leaf is last.opening_bracket:
986             if seen_other_brackets or length <= line_length:
987                 return True
988
989         elif leaf.type in OPENING_BRACKETS:
990             # There are brackets we can further split on.
991             seen_other_brackets = True
992
993     return False
994
995
996 def line_to_string(line: Line) -> str:
997     """Returns the string representation of @line.
998
999     WARNING: This is known to be computationally expensive.
1000     """
1001     return str(line).strip("\n")