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.
1 from dataclasses import dataclass, field
17 from blib2to3.pytree import Node, Leaf
18 from blib2to3.pgen2 import token
20 from black.brackets import BracketTracker, DOT_PRIORITY
21 from black.mode import Mode
22 from black.nodes import STANDALONE_COMMENT, TEST_DESCENDANTS
23 from black.nodes import BRACKETS, OPENING_BRACKETS, CLOSING_BRACKETS
24 from black.nodes import syms, whitespace, replace_child, child_towards
25 from black.nodes import is_multiline_string, is_import, is_type_comment, last_two_except
26 from black.nodes import is_one_tuple_between
36 """Holds leaves and comments. Can be printed with `str(line)`."""
40 leaves: List[Leaf] = field(default_factory=list)
41 # keys ordered like `leaves`
42 comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
43 bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
44 inside_brackets: bool = False
45 should_split_rhs: bool = False
46 magic_trailing_comma: Optional[Leaf] = None
48 def append(self, leaf: Leaf, preformatted: bool = False) -> None:
49 """Add a new `leaf` to the end of the line.
51 Unless `preformatted` is True, the `leaf` will receive a new consistent
52 whitespace prefix and metadata applied by :class:`BracketTracker`.
53 Trailing commas are maybe removed, unpacked for loop variables are
54 demoted from being delimiters.
56 Inline comments are put aside.
58 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
62 if token.COLON == leaf.type and self.is_class_paren_empty:
64 if self.leaves and not preformatted:
65 # Note: at this point leaf.prefix should be empty except for
66 # imports, for which we only preserve newlines.
67 leaf.prefix += whitespace(
68 leaf, complex_subscript=self.is_complex_subscript(leaf)
70 if self.inside_brackets or not preformatted:
71 self.bracket_tracker.mark(leaf)
72 if self.mode.magic_trailing_comma:
73 if self.has_magic_trailing_comma(leaf):
74 self.magic_trailing_comma = leaf
75 elif self.has_magic_trailing_comma(leaf, ensure_removable=True):
76 self.remove_trailing_comma()
77 if not self.append_comment(leaf):
78 self.leaves.append(leaf)
80 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
81 """Like :func:`append()` but disallow invalid standalone comment structure.
83 Raises ValueError when any `leaf` is appended after a standalone comment
84 or when a standalone comment is not the first leaf on the line.
86 if self.bracket_tracker.depth == 0:
88 raise ValueError("cannot append to standalone comments")
90 if self.leaves and leaf.type == STANDALONE_COMMENT:
92 "cannot append standalone comments to a populated line"
95 self.append(leaf, preformatted=preformatted)
98 def is_comment(self) -> bool:
99 """Is this line a standalone comment?"""
100 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
103 def is_decorator(self) -> bool:
104 """Is this line a decorator?"""
105 return bool(self) and self.leaves[0].type == token.AT
108 def is_import(self) -> bool:
109 """Is this an import line?"""
110 return bool(self) and is_import(self.leaves[0])
113 def is_class(self) -> bool:
114 """Is this line a class definition?"""
117 and self.leaves[0].type == token.NAME
118 and self.leaves[0].value == "class"
122 def is_stub_class(self) -> bool:
123 """Is this line a class definition with a body consisting only of "..."?"""
124 return self.is_class and self.leaves[-3:] == [
125 Leaf(token.DOT, ".") for _ in range(3)
129 def is_def(self) -> bool:
130 """Is this a function definition? (Also returns True for async defs.)"""
132 first_leaf = self.leaves[0]
137 second_leaf: Optional[Leaf] = self.leaves[1]
140 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
141 first_leaf.type == token.ASYNC
142 and second_leaf is not None
143 and second_leaf.type == token.NAME
144 and second_leaf.value == "def"
148 def is_class_paren_empty(self) -> bool:
149 """Is this a class with no base classes but using parentheses?
151 Those are unnecessary and should be removed.
155 and len(self.leaves) == 4
157 and self.leaves[2].type == token.LPAR
158 and self.leaves[2].value == "("
159 and self.leaves[3].type == token.RPAR
160 and self.leaves[3].value == ")"
164 def is_triple_quoted_string(self) -> bool:
165 """Is the line a triple quoted string?"""
168 and self.leaves[0].type == token.STRING
169 and self.leaves[0].value.startswith(('"""', "'''"))
172 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
173 """If so, needs to be split before emitting."""
174 for leaf in self.leaves:
175 if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit:
180 def contains_uncollapsable_type_comments(self) -> bool:
183 last_leaf = self.leaves[-1]
184 ignored_ids.add(id(last_leaf))
185 if last_leaf.type == token.COMMA or (
186 last_leaf.type == token.RPAR and not last_leaf.value
188 # When trailing commas or optional parens are inserted by Black for
189 # consistency, comments after the previous last element are not moved
190 # (they don't have to, rendering will still be correct). So we ignore
191 # trailing commas and invisible.
192 last_leaf = self.leaves[-2]
193 ignored_ids.add(id(last_leaf))
197 # A type comment is uncollapsable if it is attached to a leaf
198 # that isn't at the end of the line (since that could cause it
199 # to get associated to a different argument) or if there are
200 # comments before it (since that could cause it to get hidden
203 for leaf_id, comments in self.comments.items():
204 for comment in comments:
205 if is_type_comment(comment):
207 not is_type_comment(comment, " ignore")
208 and leaf_id not in ignored_ids
216 def contains_unsplittable_type_ignore(self) -> bool:
220 # If a 'type: ignore' is attached to the end of a line, we
221 # can't split the line, because we can't know which of the
222 # subexpressions the ignore was meant to apply to.
224 # We only want this to apply to actual physical lines from the
225 # original source, though: we don't want the presence of a
226 # 'type: ignore' at the end of a multiline expression to
227 # justify pushing it all onto one line. Thus we
228 # (unfortunately) need to check the actual source lines and
229 # only report an unsplittable 'type: ignore' if this line was
230 # one line in the original code.
232 # Grab the first and last line numbers, skipping generated leaves
233 first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
235 (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
238 if first_line == last_line:
239 # We look at the last two leaves since a comma or an
240 # invisible paren could have been added at the end of the
242 for node in self.leaves[-2:]:
243 for comment in self.comments.get(id(node), []):
244 if is_type_comment(comment, " ignore"):
249 def contains_multiline_strings(self) -> bool:
250 return any(is_multiline_string(leaf) for leaf in self.leaves)
252 def has_magic_trailing_comma(
253 self, closing: Leaf, ensure_removable: bool = False
255 """Return True if we have a magic trailing comma, that is when:
256 - there's a trailing comma here
257 - it's not a one-tuple
258 Additionally, if ensure_removable:
259 - it's not from square bracket indexing
262 closing.type in CLOSING_BRACKETS
264 and self.leaves[-1].type == token.COMMA
268 if closing.type == token.RBRACE:
271 if closing.type == token.RSQB:
272 if not ensure_removable:
274 comma = self.leaves[-1]
275 return bool(comma.parent and comma.parent.type == syms.listmaker)
280 if closing.opening_bracket is not None and not is_one_tuple_between(
281 closing.opening_bracket, closing, self.leaves
287 def append_comment(self, comment: Leaf) -> bool:
288 """Add an inline or standalone comment to the line."""
290 comment.type == STANDALONE_COMMENT
291 and self.bracket_tracker.any_open_brackets()
296 if comment.type != token.COMMENT:
300 comment.type = STANDALONE_COMMENT
304 last_leaf = self.leaves[-1]
306 last_leaf.type == token.RPAR
307 and not last_leaf.value
309 and len(list(last_leaf.parent.leaves())) <= 3
310 and not is_type_comment(comment)
312 # Comments on an optional parens wrapping a single leaf should belong to
313 # the wrapped node except if it's a type comment. Pinning the comment like
314 # this avoids unstable formatting caused by comment migration.
315 if len(self.leaves) < 2:
316 comment.type = STANDALONE_COMMENT
320 last_leaf = self.leaves[-2]
321 self.comments.setdefault(id(last_leaf), []).append(comment)
324 def comments_after(self, leaf: Leaf) -> List[Leaf]:
325 """Generate comments that should appear directly after `leaf`."""
326 return self.comments.get(id(leaf), [])
328 def remove_trailing_comma(self) -> None:
329 """Remove the trailing comma and moves the comments attached to it."""
330 trailing_comma = self.leaves.pop()
331 trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
332 self.comments.setdefault(id(self.leaves[-1]), []).extend(
333 trailing_comma_comments
336 def is_complex_subscript(self, leaf: Leaf) -> bool:
337 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
338 open_lsqb = self.bracket_tracker.get_open_lsqb()
339 if open_lsqb is None:
342 subscript_start = open_lsqb.next_sibling
344 if isinstance(subscript_start, Node):
345 if subscript_start.type == syms.listmaker:
348 if subscript_start.type == syms.subscriptlist:
349 subscript_start = child_towards(subscript_start, leaf)
350 return subscript_start is not None and any(
351 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
354 def enumerate_with_length(
355 self, reversed: bool = False
356 ) -> Iterator[Tuple[Index, Leaf, int]]:
357 """Return an enumeration of leaves with their length.
359 Stops prematurely on multiline strings and standalone comments.
362 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
363 enumerate_reversed if reversed else enumerate,
365 for index, leaf in op(self.leaves):
366 length = len(leaf.prefix) + len(leaf.value)
367 if "\n" in leaf.value:
368 return # Multiline strings, we can't continue.
370 for comment in self.comments_after(leaf):
371 length += len(comment.value)
373 yield index, leaf, length
375 def clone(self) -> "Line":
379 inside_brackets=self.inside_brackets,
380 should_split_rhs=self.should_split_rhs,
381 magic_trailing_comma=self.magic_trailing_comma,
384 def __str__(self) -> str:
385 """Render the line."""
389 indent = " " * self.depth
390 leaves = iter(self.leaves)
392 res = f"{first.prefix}{indent}{first.value}"
395 for comment in itertools.chain.from_iterable(self.comments.values()):
400 def __bool__(self) -> bool:
401 """Return True if the line has leaves or comments."""
402 return bool(self.leaves or self.comments)
406 class EmptyLineTracker:
407 """Provides a stateful method that returns the number of potential extra
408 empty lines needed before and after the currently processed line.
410 Note: this tracker works on lines that haven't been split yet. It assumes
411 the prefix of the first leaf consists of optional newlines. Those newlines
412 are consumed by `maybe_empty_lines()` and included in the computation.
416 previous_line: Optional[Line] = None
417 previous_after: int = 0
418 previous_defs: List[int] = field(default_factory=list)
420 def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
421 """Return the number of extra empty lines before and after the `current_line`.
423 This is for separating `def`, `async def` and `class` with extra empty
424 lines (two on module-level).
426 before, after = self._maybe_empty_lines(current_line)
428 # Black should not insert empty lines at the beginning
431 if self.previous_line is None
432 else before - self.previous_after
434 self.previous_after = after
435 self.previous_line = current_line
438 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
440 if current_line.depth == 0:
441 max_allowed = 1 if self.is_pyi else 2
442 if current_line.leaves:
443 # Consume the first leaf's extra newlines.
444 first_leaf = current_line.leaves[0]
445 before = first_leaf.prefix.count("\n")
446 before = min(before, max_allowed)
447 first_leaf.prefix = ""
450 depth = current_line.depth
451 while self.previous_defs and self.previous_defs[-1] >= depth:
453 assert self.previous_line is not None
454 if depth and not current_line.is_def and self.previous_line.is_def:
455 # Empty lines between attributes and methods should be preserved.
456 before = min(1, before)
466 and self.previous_defs[-1]
467 and current_line.leaves[-1].type == token.COLON
469 current_line.leaves[0].value
470 not in ("with", "try", "for", "while", "if", "match")
473 # We shouldn't add two newlines between an indented function and
474 # a dependent non-indented clause. This is to avoid issues with
475 # conditional function definitions that are technically top-level
476 # and therefore get two trailing newlines, but look weird and
477 # inconsistent when they're followed by elif, else, etc. This is
478 # worse because these functions only get *one* preceding newline
483 self.previous_defs.pop()
484 if current_line.is_decorator or current_line.is_def or current_line.is_class:
485 return self._maybe_empty_lines_for_class_or_def(current_line, before)
489 and self.previous_line.is_import
490 and not current_line.is_import
491 and depth == self.previous_line.depth
493 return (before or 1), 0
497 and self.previous_line.is_class
498 and current_line.is_triple_quoted_string
504 def _maybe_empty_lines_for_class_or_def(
505 self, current_line: Line, before: int
506 ) -> Tuple[int, int]:
507 if not current_line.is_decorator:
508 self.previous_defs.append(current_line.depth)
509 if self.previous_line is None:
510 # Don't insert empty lines before the first line in the file.
513 if self.previous_line.is_decorator:
514 if self.is_pyi and current_line.is_stub_class:
515 # Insert an empty line after a decorated stub class
520 if self.previous_line.depth < current_line.depth and (
521 self.previous_line.is_class or self.previous_line.is_def
526 self.previous_line.is_comment
527 and self.previous_line.depth == current_line.depth
533 if self.previous_line.depth > current_line.depth:
534 newlines = 0 if current_line.depth else 1
535 elif current_line.is_class or self.previous_line.is_class:
536 if current_line.depth:
538 elif current_line.is_stub_class and self.previous_line.is_stub_class:
539 # No blank line between classes with an empty body
544 current_line.is_def or current_line.is_decorator
545 ) and not self.previous_line.is_def:
546 if current_line.depth:
547 # In classes empty lines between attributes and methods should
549 newlines = min(1, before)
551 # Blank line between a block of functions (maybe with preceding
552 # decorators) and a block of non-functions
557 newlines = 1 if current_line.depth else 2
561 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
562 """Like `reversed(enumerate(sequence))` if that were possible."""
563 index = len(sequence) - 1
564 for element in reversed(sequence):
565 yield (index, element)
570 new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
573 Append leaves (taken from @old_line) to @new_line, making sure to fix the
574 underlying Node structure where appropriate.
576 All of the leaves in @leaves are duplicated. The duplicates are then
577 appended to @new_line and used to replace their originals in the underlying
578 Node structure. Any comments attached to the old leaves are reattached to
582 set(@leaves) is a subset of set(@old_line.leaves).
584 for old_leaf in leaves:
585 new_leaf = Leaf(old_leaf.type, old_leaf.value)
586 replace_child(old_leaf, new_leaf)
587 new_line.append(new_leaf, preformatted=preformatted)
589 for comment_leaf in old_line.comments_after(old_leaf):
590 new_line.append(comment_leaf, preformatted=True)
593 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
594 """Return True if `line` is no longer than `line_length`.
596 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
599 line_str = line_to_string(line)
601 len(line_str) <= line_length
602 and "\n" not in line_str # multiline strings
603 and not line.contains_standalone_comments()
607 def can_be_split(line: Line) -> bool:
608 """Return False if the line cannot be split *for sure*.
610 This is not an exhaustive search but a cheap heuristic that we can use to
611 avoid some unfortunate formattings (mostly around wrapping unsplittable code
612 in unnecessary parentheses).
618 if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
622 for leaf in leaves[-2::-1]:
623 if leaf.type in OPENING_BRACKETS:
624 if next.type not in CLOSING_BRACKETS:
628 elif leaf.type == token.DOT:
630 elif leaf.type == token.NAME:
631 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
634 elif leaf.type not in CLOSING_BRACKETS:
637 if dot_count > 1 and call_count > 1:
643 def can_omit_invisible_parens(
646 omit_on_explode: Collection[LeafID] = (),
648 """Does `line` have a shape safe to reformat without optional parens around it?
650 Returns True for only a subset of potentially nice looking formattings but
651 the point is to not return false positives that end up producing lines that
654 bt = line.bracket_tracker
655 if not bt.delimiters:
656 # Without delimiters the optional parentheses are useless.
659 max_priority = bt.max_delimiter_priority()
660 if bt.delimiter_count_with_priority(max_priority) > 1:
661 # With more than one delimiter of a kind the optional parentheses read better.
664 if max_priority == DOT_PRIORITY:
665 # A single stranded method call doesn't require optional parentheses.
668 assert len(line.leaves) >= 2, "Stranded delimiter"
670 # With a single delimiter, omit if the expression starts or ends with
672 first = line.leaves[0]
673 second = line.leaves[1]
674 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
675 if _can_omit_opening_paren(line, first=first, line_length=line_length):
678 # Note: we are not returning False here because a line might have *both*
679 # a leading opening bracket and a trailing closing bracket. If the
680 # opening bracket doesn't match our rule, maybe the closing will.
682 penultimate = line.leaves[-2]
683 last = line.leaves[-1]
684 if line.magic_trailing_comma:
686 penultimate, last = last_two_except(line.leaves, omit=omit_on_explode)
688 # Turns out we'd omit everything. We cannot skip the optional parentheses.
692 last.type == token.RPAR
693 or last.type == token.RBRACE
695 # don't use indexing for omitting optional parentheses;
697 last.type == token.RSQB
699 and last.parent.type != syms.trailer
702 if penultimate.type in OPENING_BRACKETS:
703 # Empty brackets don't help.
706 if is_multiline_string(first):
707 # Additional wrapping of a multiline string in this situation is
711 if line.magic_trailing_comma and penultimate.type == token.COMMA:
712 # The rightmost non-omitted bracket pair is the one we want to explode on.
715 if _can_omit_closing_paren(line, last=last, line_length=line_length):
721 def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
722 """See `can_omit_invisible_parens`."""
724 length = 4 * line.depth
726 for _index, leaf, leaf_length in line.enumerate_with_length():
727 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
730 length += leaf_length
731 if length > line_length:
734 if leaf.type in OPENING_BRACKETS:
735 # There are brackets we can further split on.
739 # checked the entire string and line length wasn't exceeded
740 if len(line.leaves) == _index + 1:
746 def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
747 """See `can_omit_invisible_parens`."""
748 length = 4 * line.depth
749 seen_other_brackets = False
750 for _index, leaf, leaf_length in line.enumerate_with_length():
751 length += leaf_length
752 if leaf is last.opening_bracket:
753 if seen_other_brackets or length <= line_length:
756 elif leaf.type in OPENING_BRACKETS:
757 # There are brackets we can further split on.
758 seen_other_brackets = True
763 def line_to_string(line: Line) -> str:
764 """Returns the string representation of @line.
766 WARNING: This is known to be computationally expensive.
768 return str(line).strip("\n")