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.
4 from dataclasses import dataclass, field
18 from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker
19 from black.mode import Mode, Preview
20 from black.nodes import (
29 is_one_sequence_between,
31 is_with_or_async_with_stmt,
36 from blib2to3.pgen2 import token
37 from blib2to3.pytree import Leaf, Node
43 LN = Union[Leaf, Node]
48 """Holds leaves and comments. Can be printed with `str(line)`."""
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
61 self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False
63 """Add a new `leaf` to the end of the line.
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.
70 Inline comments are put aside.
72 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
76 if token.COLON == leaf.type and self.is_class_paren_empty:
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)
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)
94 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
95 """Like :func:`append()` but disallow invalid standalone comment structure.
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.
100 if self.bracket_tracker.depth == 0:
102 raise ValueError("cannot append to standalone comments")
104 if self.leaves and leaf.type == STANDALONE_COMMENT:
106 "cannot append standalone comments to a populated line"
109 self.append(leaf, preformatted=preformatted)
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
117 def is_decorator(self) -> bool:
118 """Is this line a decorator?"""
119 return bool(self) and self.leaves[0].type == token.AT
122 def is_import(self) -> bool:
123 """Is this an import line?"""
124 return bool(self) and is_import(self.leaves[0])
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])
132 def is_class(self) -> bool:
133 """Is this line a class definition?"""
136 and self.leaves[0].type == token.NAME
137 and self.leaves[0].value == "class"
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)
148 def is_def(self) -> bool:
149 """Is this a function definition? (Also returns True for async defs.)"""
151 first_leaf = self.leaves[0]
156 second_leaf: Optional[Leaf] = self.leaves[1]
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"
167 def is_class_paren_empty(self) -> bool:
168 """Is this a class with no base classes but using parentheses?
170 Those are unnecessary and should be removed.
174 and len(self.leaves) == 4
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 == ")"
183 def is_triple_quoted_string(self) -> bool:
184 """Is the line a triple quoted string?"""
187 and self.leaves[0].type == token.STRING
188 and self.leaves[0].value.startswith(('"""', "'''"))
192 def opens_block(self) -> bool:
193 """Does this line open a new level of indentation."""
194 if len(self.leaves) == 0:
196 return self.leaves[-1].type == token.COLON
198 def is_fmt_pass_converted(
199 self, *, first_leaf_matches: Optional[Callable[[Leaf], bool]] = None
201 """Is this line converted from fmt off/skip code?
203 If first_leaf_matches is not None, it only returns True if the first
204 leaf of converted code matches.
206 if len(self.leaves) != 1:
208 leaf = self.leaves[0]
210 leaf.type != STANDALONE_COMMENT
211 or leaf.fmt_pass_converted_first_leaf is None
214 return first_leaf_matches is None or first_leaf_matches(
215 leaf.fmt_pass_converted_first_leaf
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:
226 def contains_uncollapsable_type_comments(self) -> bool:
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
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))
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
249 for leaf_id, comments in self.comments.items():
250 for comment in comments:
251 if is_type_comment(comment):
253 not is_type_comment(comment, " ignore")
254 and leaf_id not in ignored_ids
262 def contains_unsplittable_type_ignore(self) -> bool:
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.
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.
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)
281 (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
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
288 for node in self.leaves[-2:]:
289 for comment in self.comments.get(id(node), []):
290 if is_type_comment(comment, " ignore"):
295 def contains_multiline_strings(self) -> bool:
296 return any(is_multiline_string(leaf) for leaf in self.leaves)
298 def has_magic_trailing_comma(
299 self, closing: Leaf, ensure_removable: bool = False
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)
310 closing.type in CLOSING_BRACKETS
312 and self.leaves[-1].type == token.COMMA
316 if closing.type == token.RBRACE:
319 if closing.type == token.RSQB:
322 and closing.parent.type == syms.trailer
323 and closing.opening_bracket
324 and is_one_sequence_between(
325 closing.opening_bracket,
328 brackets=(token.LSQB, token.RSQB),
333 if not ensure_removable:
336 comma = self.leaves[-1]
337 if comma.parent is None:
340 comma.parent.type != syms.subscriptlist
341 or closing.opening_bracket is None
342 or not is_one_sequence_between(
343 closing.opening_bracket,
346 brackets=(token.LSQB, token.RSQB),
353 if closing.opening_bracket is not None and not is_one_sequence_between(
354 closing.opening_bracket, closing, self.leaves
360 def append_comment(self, comment: Leaf) -> bool:
361 """Add an inline or standalone comment to the line."""
363 comment.type == STANDALONE_COMMENT
364 and self.bracket_tracker.any_open_brackets()
369 if comment.type != token.COMMENT:
373 comment.type = STANDALONE_COMMENT
377 last_leaf = self.leaves[-1]
379 last_leaf.type == token.RPAR
380 and not last_leaf.value
382 and len(list(last_leaf.parent.leaves())) <= 3
383 and not is_type_comment(comment)
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
393 last_leaf = self.leaves[-2]
394 self.comments.setdefault(id(last_leaf), []).append(comment)
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), [])
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
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:
415 subscript_start = open_lsqb.next_sibling
417 if isinstance(subscript_start, Node):
418 if subscript_start.type == syms.listmaker:
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()
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.
432 Stops prematurely on multiline strings and standalone comments.
435 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
436 enumerate_reversed if reversed else enumerate,
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.
443 for comment in self.comments_after(leaf):
444 length += len(comment.value)
446 yield index, leaf, length
448 def clone(self) -> "Line":
452 inside_brackets=self.inside_brackets,
453 should_split_rhs=self.should_split_rhs,
454 magic_trailing_comma=self.magic_trailing_comma,
457 def __str__(self) -> str:
458 """Render the line."""
462 indent = " " * self.depth
463 leaves = iter(self.leaves)
465 res = f"{first.prefix}{indent}{first.value}"
468 for comment in itertools.chain.from_iterable(self.comments.values()):
473 def __bool__(self) -> bool:
474 """Return True if the line has leaves or comments."""
475 return bool(self.leaves or self.comments)
480 """Intermediate split result from a right hand split."""
485 opening_bracket: Leaf
486 closing_bracket: Leaf
491 """Class that holds information about a block of formatted lines.
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.
498 previous_block: Optional["LinesBlock"]
501 content_lines: List[str] = field(default_factory=list)
504 def all_lines(self) -> List[str]:
505 empty_line = str(Line(mode=self.mode))
507 [empty_line * self.before] + self.content_lines + [empty_line * self.after]
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.
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.
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
527 def maybe_empty_lines(self, current_line: Line) -> LinesBlock:
528 """Return the number of extra empty lines before and after the `current_line`.
530 This is for separating `def`, `async def` and `class` with extra empty
531 lines (two on module-level).
533 before, after = self._maybe_empty_lines(current_line)
534 previous_after = self.previous_block.after if self.previous_block else 0
536 # Black should not insert empty lines at the beginning
539 if self.previous_line is None
540 else before - previous_after
544 previous_block=self.previous_block,
545 original_line=current_line,
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)
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
563 self.previous_line = current_line
564 self.previous_block = block
567 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
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 = ""
579 depth = current_line.depth
580 while self.previous_defs and self.previous_defs[-1] >= depth:
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)
595 and self.previous_defs[-1]
596 and current_line.leaves[-1].type == token.COLON
598 current_line.leaves[0].value
599 not in ("with", "try", "for", "while", "if", "match")
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
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)
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
623 return (before or 1), 0
627 and self.previous_line.is_class
628 and current_line.is_triple_quoted_string
632 if self.previous_line and self.previous_line.opens_block:
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.
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
652 if self.previous_line.depth < current_line.depth and (
653 self.previous_line.is_class or self.previous_line.is_def
657 comment_to_add_newlines: Optional[LinesBlock] = None
659 self.previous_line.is_comment
660 and self.previous_line.depth == current_line.depth
663 slc = self.semantic_leading_comment
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
671 comment_to_add_newlines = slc
676 if current_line.is_class or self.previous_line.is_class:
677 if self.previous_line.depth < current_line.depth:
679 elif self.previous_line.depth > current_line.depth:
681 elif current_line.is_stub_class and self.previous_line.is_stub_class:
682 # No blank line between classes with an empty body
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
692 newlines = min(1, before)
694 # Blank line between a block of functions (maybe with preceding
695 # decorators) and a block of non-functions
697 elif self.previous_line.depth > current_line.depth:
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
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)
722 new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
725 Append leaves (taken from @old_line) to @new_line, making sure to fix the
726 underlying Node structure where appropriate.
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
734 set(@leaves) is a subset of set(@old_line.leaves).
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)
741 for comment_leaf in old_line.comments_after(old_leaf):
742 new_line.append(comment_leaf, preformatted=True)
745 def is_line_short_enough( # noqa: C901
746 line: Line, *, mode: Mode, line_str: str = ""
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.
754 line_str = line_to_string(line)
756 if Preview.multiline_string_handling not in mode:
758 len(line_str) <= mode.line_length
759 and "\n" not in line_str # multiline strings
760 and not line.contains_standalone_comments()
763 if line.contains_standalone_comments():
765 if "\n" not in line_str:
766 # No multiline strings (MLS) present
767 return len(line_str) <= mode.line_length
769 first, *_, last = line_str.split("\n")
770 if len(first) > mode.line_length or len(last) > mode.line_length:
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] = []
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):
790 elif leaf.bracket_depth + 1 < len(commas):
791 had_comma = commas.pop()
793 had_comma is not None
794 and multiline_string is not None
795 and multiline_string.bracket_depth == leaf.bracket_depth + 1
797 # Have left the level with the MLS, stop tracking commas
798 max_level_to_update = leaf.bracket_depth
800 # MLS was in parens with at least one comma - force split
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)
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
817 multiline_string = 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:
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:
831 return all(val == 0 for val in commas)
834 def can_be_split(line: Line) -> bool:
835 """Return False if the line cannot be split *for sure*.
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).
845 if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
849 for leaf in leaves[-2::-1]:
850 if leaf.type in OPENING_BRACKETS:
851 if next.type not in CLOSING_BRACKETS:
855 elif leaf.type == token.DOT:
857 elif leaf.type == token.NAME:
858 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
861 elif leaf.type not in CLOSING_BRACKETS:
864 if dot_count > 1 and call_count > 1:
870 def can_omit_invisible_parens(
874 """Does `rhs.body` have a shape safe to reformat without optional parens around it?
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
881 bt = line.bracket_tracker
882 if not bt.delimiters:
883 # Without delimiters the optional parentheses are useless.
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.
892 if delimiter_count == 1:
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
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
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.
907 if max_priority == DOT_PRIORITY:
908 # A single stranded method call doesn't require optional parentheses.
911 assert len(line.leaves) >= 2, "Stranded delimiter"
913 # With a single delimiter, omit if the expression starts or ends with
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):
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.
925 penultimate = line.leaves[-2]
926 last = line.leaves[-1]
929 last.type == token.RPAR
930 or last.type == token.RBRACE
932 # don't use indexing for omitting optional parentheses;
934 last.type == token.RSQB
936 and last.parent.type != syms.trailer
939 if penultimate.type in OPENING_BRACKETS:
940 # Empty brackets don't help.
943 if is_multiline_string(first):
944 # Additional wrapping of a multiline string in this situation is
948 if _can_omit_closing_paren(line, last=last, line_length=line_length):
954 def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
955 """See `can_omit_invisible_parens`."""
957 length = 4 * line.depth
959 for _index, leaf, leaf_length in line.enumerate_with_length():
960 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
963 length += leaf_length
964 if length > line_length:
967 if leaf.type in OPENING_BRACKETS:
968 # There are brackets we can further split on.
972 # checked the entire string and line length wasn't exceeded
973 if len(line.leaves) == _index + 1:
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:
989 elif leaf.type in OPENING_BRACKETS:
990 # There are brackets we can further split on.
991 seen_other_brackets = True
996 def line_to_string(line: Line) -> str:
997 """Returns the string representation of @line.
999 WARNING: This is known to be computationally expensive.
1001 return str(line).strip("\n")