]> 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:

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