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.
2 blib2to3 Node/Leaf transformation-related utility functions.
16 if sys.version_info >= (3, 8):
17 from typing import Final
19 from typing_extensions import Final
20 if sys.version_info >= (3, 10):
21 from typing import TypeGuard
23 from typing_extensions import TypeGuard
25 from mypy_extensions import mypyc_attr
28 from blib2to3.pytree import Node, Leaf, type_repr, NL
29 from blib2to3 import pygram
30 from blib2to3.pgen2 import token
32 from black.cache import CACHE_DIR
33 from black.strings import has_triple_quotes
36 pygram.initialize(CACHE_DIR)
37 syms: Final = pygram.python_symbols
42 LN = Union[Leaf, Node]
47 WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE}
60 STANDALONE_COMMENT: Final = 153
61 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
62 LOGIC_OPERATORS: Final = {"and", "or"}
63 COMPARATORS: Final = {
71 MATH_OPERATORS: Final = {
87 STARS: Final = {token.STAR, token.DOUBLESTAR}
88 VARARGS_SPECIALS: Final = STARS | {token.SLASH}
89 VARARGS_PARENTS: Final = {
91 syms.argument, # double star in arglist
92 syms.trailer, # single argument to call
94 syms.varargslist, # lambdas
96 UNPACKING_PARENTS: Final = {
97 syms.atom, # single element of a list or set literal
101 syms.testlist_star_expr,
105 TEST_DESCENDANTS: Final = {
122 ASSIGNMENTS: Final = {
139 IMPLICIT_TUPLE: Final = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
141 token.LPAR: token.RPAR,
142 token.LSQB: token.RSQB,
143 token.LBRACE: token.RBRACE,
145 OPENING_BRACKETS: Final = set(BRACKET.keys())
146 CLOSING_BRACKETS: Final = set(BRACKET.values())
147 BRACKETS: Final = OPENING_BRACKETS | CLOSING_BRACKETS
148 ALWAYS_NO_SPACE: Final = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
153 @mypyc_attr(allow_interpreted_subclasses=True)
154 class Visitor(Generic[T]):
155 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
157 def visit(self, node: LN) -> Iterator[T]:
158 """Main method to visit `node` and its children.
160 It tries to find a `visit_*()` method for the given `node.type`, like
161 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
162 If no dedicated `visit_*()` method is found, chooses `visit_default()`
165 Then yields objects of type `T` from the selected visitor.
168 name = token.tok_name[node.type]
170 name = str(type_repr(node.type))
171 # We explicitly branch on whether a visitor exists (instead of
172 # using self.visit_default as the default arg to getattr) in order
173 # to save needing to create a bound method object and so mypyc can
174 # generate a native call to visit_default.
175 visitf = getattr(self, f"visit_{name}", None)
177 yield from visitf(node)
179 yield from self.visit_default(node)
181 def visit_default(self, node: LN) -> Iterator[T]:
182 """Default `visit_*()` implementation. Recurses to children of `node`."""
183 if isinstance(node, Node):
184 for child in node.children:
185 yield from self.visit(child)
188 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
189 """Return whitespace prefix if needed for the given `leaf`.
191 `complex_subscript` signals whether the given leaf is part of a subscription
192 which has non-trivial arguments, like arithmetic expressions or function calls.
196 DOUBLESPACE: Final = " "
200 if t in ALWAYS_NO_SPACE:
203 if t == token.COMMENT:
206 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
207 if t == token.COLON and p.type not in {
214 prev = leaf.prev_sibling
216 prevp = preceding_leaf(p)
217 if not prevp or prevp.type in OPENING_BRACKETS:
221 if prevp.type == token.COLON:
224 elif prevp.type != token.COMMA and not complex_subscript:
229 if prevp.type == token.EQUAL:
231 if prevp.parent.type in {
239 elif prevp.parent.type == syms.typedargslist:
240 # A bit hacky: if the equal sign has whitespace, it means we
241 # previously found it's a typed argument. So, we're using
245 elif prevp.type in VARARGS_SPECIALS:
246 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
249 elif prevp.type == token.COLON:
250 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
251 return SPACE if complex_subscript else NO
255 and prevp.parent.type == syms.factor
256 and prevp.type in MATH_OPERATORS
260 elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator:
261 # no space in decorators
264 elif prev.type in OPENING_BRACKETS:
267 if p.type in {syms.parameters, syms.arglist}:
268 # untyped function signatures or calls
269 if not prev or prev.type != token.COMMA:
272 elif p.type == syms.varargslist:
274 if prev and prev.type != token.COMMA:
277 elif p.type == syms.typedargslist:
278 # typed function signatures
283 if prev.type != syms.tname:
286 elif prev.type == token.EQUAL:
287 # A bit hacky: if the equal sign has whitespace, it means we
288 # previously found it's a typed argument. So, we're using that, too.
291 elif prev.type != token.COMMA:
294 elif p.type == syms.tname:
297 prevp = preceding_leaf(p)
298 if not prevp or prevp.type != token.COMMA:
301 elif p.type == syms.trailer:
302 # attributes and calls
303 if t == token.LPAR or t == token.RPAR:
307 if t == token.DOT or t == token.LSQB:
310 elif prev.type != token.COMMA:
313 elif p.type == syms.argument:
319 prevp = preceding_leaf(p)
320 if not prevp or prevp.type == token.LPAR:
323 elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
326 elif p.type == syms.decorator:
330 elif p.type == syms.dotted_name:
334 prevp = preceding_leaf(p)
335 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
338 elif p.type == syms.classdef:
342 if prev and prev.type == token.LPAR:
345 elif p.type in {syms.subscript, syms.sliceop}:
348 assert p.parent is not None, "subscripts are always parented"
349 if p.parent.type == syms.subscriptlist:
354 elif not complex_subscript:
357 elif p.type == syms.atom:
358 if prev and t == token.DOT:
359 # dots, but not the first one.
362 elif p.type == syms.dictsetmaker:
364 if prev and prev.type == token.DOUBLESTAR:
367 elif p.type in {syms.factor, syms.star_expr}:
370 prevp = preceding_leaf(p)
371 if not prevp or prevp.type in OPENING_BRACKETS:
374 prevp_parent = prevp.parent
375 assert prevp_parent is not None
376 if prevp.type == token.COLON and prevp_parent.type in {
382 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
385 elif t in {token.NAME, token.NUMBER, token.STRING}:
388 elif p.type == syms.import_from:
390 if prev and prev.type == token.DOT:
393 elif t == token.NAME:
397 if prev and prev.type == token.DOT:
400 elif p.type == syms.sliceop:
406 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
407 """Return the first leaf that precedes `node`, if any."""
409 res = node.prev_sibling
411 if isinstance(res, Leaf):
415 return list(res.leaves())[-1]
424 def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
425 """Return if the `node` and its previous siblings match types against the provided
426 list of tokens; the provided `node`has its type matched against the last element in
427 the list. `None` can be used as the first element to declare that the start of the
428 list is anchored at the start of its parent's children."""
431 if tokens[-1] is None:
435 if node.type != tokens[-1]:
437 return prev_siblings_are(node.prev_sibling, tokens[:-1])
440 def parent_type(node: Optional[LN]) -> Optional[NodeType]:
443 @node.parent.type, if @node is not None and has a parent.
447 if node is None or node.parent is None:
450 return node.parent.type
453 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
454 """Return the child of `ancestor` that contains `descendant`."""
455 node: Optional[LN] = descendant
456 while node and node.parent != ancestor:
461 def replace_child(old_child: LN, new_child: LN) -> None:
464 * If @old_child.parent is set, replace @old_child with @new_child in
465 @old_child's underlying Node structure.
467 * Otherwise, this function does nothing.
469 parent = old_child.parent
473 child_idx = old_child.remove()
474 if child_idx is not None:
475 parent.insert_child(child_idx, new_child)
478 def container_of(leaf: Leaf) -> LN:
479 """Return `leaf` or one of its ancestors that is the topmost container of it.
481 By "container" we mean a node where `leaf` is the very first child.
483 same_prefix = leaf.prefix
486 parent = container.parent
490 if parent.children[0].prefix != same_prefix:
493 if parent.type == syms.file_input:
496 if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
503 def first_leaf_column(node: Node) -> Optional[int]:
504 """Returns the column of the first leaf child of a node."""
505 for child in node.children:
506 if isinstance(child, Leaf):
511 def is_arith_like(node: LN) -> bool:
512 """Whether node is an arithmetic or a binary arithmetic expression"""
513 return node.type in {
521 def is_docstring(leaf: Leaf) -> bool:
522 if prev_siblings_are(
523 leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
527 # Multiline docstring on the same line as the `def`.
528 if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
529 # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
530 # grammar. We're safe to return True without further checks.
536 def is_empty_tuple(node: LN) -> bool:
537 """Return True if `node` holds an empty tuple."""
539 node.type == syms.atom
540 and len(node.children) == 2
541 and node.children[0].type == token.LPAR
542 and node.children[1].type == token.RPAR
546 def is_one_tuple(node: LN) -> bool:
547 """Return True if `node` holds a tuple with one element, with or without parens."""
548 if node.type == syms.atom:
549 gexp = unwrap_singleton_parenthesis(node)
550 if gexp is None or gexp.type != syms.testlist_gexp:
553 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
556 node.type in IMPLICIT_TUPLE
557 and len(node.children) == 2
558 and node.children[1].type == token.COMMA
562 def is_one_tuple_between(opening: Leaf, closing: Leaf, leaves: List[Leaf]) -> bool:
563 """Return True if content between `opening` and `closing` looks like a one-tuple."""
564 if opening.type != token.LPAR and closing.type != token.RPAR:
567 depth = closing.bracket_depth + 1
568 for _opening_index, leaf in enumerate(leaves):
573 raise LookupError("Opening paren not found in `leaves`")
577 for leaf in leaves[_opening_index:]:
581 bracket_depth = leaf.bracket_depth
582 if bracket_depth == depth and leaf.type == token.COMMA:
584 if leaf.parent and leaf.parent.type in {
594 def is_walrus_assignment(node: LN) -> bool:
595 """Return True iff `node` is of the shape ( test := test )"""
596 inner = unwrap_singleton_parenthesis(node)
597 return inner is not None and inner.type == syms.namedexpr_test
600 def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool:
601 """Return True iff `node` is a trailer valid in a simple decorator"""
602 return node.type == syms.trailer and (
604 len(node.children) == 2
605 and node.children[0].type == token.DOT
606 and node.children[1].type == token.NAME
608 # last trailer can be an argument-less parentheses pair
611 and len(node.children) == 2
612 and node.children[0].type == token.LPAR
613 and node.children[1].type == token.RPAR
615 # last trailer can be arguments
618 and len(node.children) == 3
619 and node.children[0].type == token.LPAR
620 # and node.children[1].type == syms.argument
621 and node.children[2].type == token.RPAR
626 def is_simple_decorator_expression(node: LN) -> bool:
627 """Return True iff `node` could be a 'dotted name' decorator
629 This function takes the node of the 'namedexpr_test' of the new decorator
630 grammar and test if it would be valid under the old decorator grammar.
632 The old grammar was: decorator: @ dotted_name [arguments] NEWLINE
633 The new grammar is : decorator: @ namedexpr_test NEWLINE
635 if node.type == token.NAME:
637 if node.type == syms.power:
640 node.children[0].type == token.NAME
641 and all(map(is_simple_decorator_trailer, node.children[1:-1]))
643 len(node.children) < 2
644 or is_simple_decorator_trailer(node.children[-1], last=True)
650 def is_yield(node: LN) -> bool:
651 """Return True if `node` holds a `yield` or `yield from` expression."""
652 if node.type == syms.yield_expr:
655 if is_name_token(node) and node.value == "yield":
658 if node.type != syms.atom:
661 if len(node.children) != 3:
664 lpar, expr, rpar = node.children
665 if lpar.type == token.LPAR and rpar.type == token.RPAR:
666 return is_yield(expr)
671 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
672 """Return True if `leaf` is a star or double star in a vararg or kwarg.
674 If `within` includes VARARGS_PARENTS, this applies to function signatures.
675 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
676 extended iterable unpacking (PEP 3132) and additional unpacking
677 generalizations (PEP 448).
679 if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
683 if p.type == syms.star_expr:
684 # Star expressions are also used as assignment targets in extended
685 # iterable unpacking (PEP 3132). See what its parent is instead.
691 return p.type in within
694 def is_multiline_string(leaf: Leaf) -> bool:
695 """Return True if `leaf` is a multiline string that actually spans many lines."""
696 return has_triple_quotes(leaf.value) and "\n" in leaf.value
699 def is_stub_suite(node: Node) -> bool:
700 """Return True if `node` is a suite with a stub body."""
702 len(node.children) != 4
703 or node.children[0].type != token.NEWLINE
704 or node.children[1].type != token.INDENT
705 or node.children[3].type != token.DEDENT
709 return is_stub_body(node.children[2])
712 def is_stub_body(node: LN) -> bool:
713 """Return True if `node` is a simple statement containing an ellipsis."""
714 if not isinstance(node, Node) or node.type != syms.simple_stmt:
717 if len(node.children) != 2:
720 child = node.children[0]
722 child.type == syms.atom
723 and len(child.children) == 3
724 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
728 def is_atom_with_invisible_parens(node: LN) -> bool:
729 """Given a `LN`, determines whether it's an atom `node` with invisible
730 parens. Useful in dedupe-ing and normalizing parens.
732 if isinstance(node, Leaf) or node.type != syms.atom:
735 first, last = node.children[0], node.children[-1]
737 isinstance(first, Leaf)
738 and first.type == token.LPAR
739 and first.value == ""
740 and isinstance(last, Leaf)
741 and last.type == token.RPAR
746 def is_empty_par(leaf: Leaf) -> bool:
747 return is_empty_lpar(leaf) or is_empty_rpar(leaf)
750 def is_empty_lpar(leaf: Leaf) -> bool:
751 return leaf.type == token.LPAR and leaf.value == ""
754 def is_empty_rpar(leaf: Leaf) -> bool:
755 return leaf.type == token.RPAR and leaf.value == ""
758 def is_import(leaf: Leaf) -> bool:
759 """Return True if the given leaf starts an import statement."""
766 (v == "import" and p and p.type == syms.import_name)
767 or (v == "from" and p and p.type == syms.import_from)
772 def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
773 """Return True if the given leaf is a special comment.
774 Only returns true for type comments for now."""
777 return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
780 def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
781 """Wrap `child` in parentheses.
783 This replaces `child` with an atom holding the parentheses and the old
784 child. That requires moving the prefix.
786 If `visible` is False, the leaves will be valueless (and thus invisible).
788 lpar = Leaf(token.LPAR, "(" if visible else "")
789 rpar = Leaf(token.RPAR, ")" if visible else "")
790 prefix = child.prefix
792 index = child.remove() or 0
793 new_child = Node(syms.atom, [lpar, child, rpar])
794 new_child.prefix = prefix
795 parent.insert_child(index, new_child)
798 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
799 """Returns `wrapped` if `node` is of the shape ( wrapped ).
801 Parenthesis can be optional. Returns None otherwise"""
802 if len(node.children) != 3:
805 lpar, wrapped, rpar = node.children
806 if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
812 def ensure_visible(leaf: Leaf) -> None:
813 """Make sure parentheses are visible.
815 They could be invisible as part of some statements (see
816 :func:`normalize_invisible_parens` and :func:`visit_import_from`).
818 if leaf.type == token.LPAR:
820 elif leaf.type == token.RPAR:
824 def is_name_token(nl: NL) -> TypeGuard[Leaf]:
825 return nl.type == token.NAME
828 def is_lpar_token(nl: NL) -> TypeGuard[Leaf]:
829 return nl.type == token.LPAR
832 def is_rpar_token(nl: NL) -> TypeGuard[Leaf]:
833 return nl.type == token.RPAR
836 def is_string_token(nl: NL) -> TypeGuard[Leaf]:
837 return nl.type == token.STRING