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.
17 if sys.version_info >= (3, 8):
18 from typing import Final
20 from typing_extensions import Final
21 if sys.version_info >= (3, 10):
22 from typing import TypeGuard
24 from typing_extensions import TypeGuard
26 from mypy_extensions import mypyc_attr
29 from blib2to3.pytree import Node, Leaf, type_repr, NL
30 from blib2to3 import pygram
31 from blib2to3.pgen2 import token
33 from black.cache import CACHE_DIR
34 from black.strings import has_triple_quotes
37 pygram.initialize(CACHE_DIR)
38 syms: Final = pygram.python_symbols
43 LN = Union[Leaf, Node]
48 WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE}
61 STANDALONE_COMMENT: Final = 153
62 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
63 LOGIC_OPERATORS: Final = {"and", "or"}
64 COMPARATORS: Final = {
72 MATH_OPERATORS: Final = {
88 STARS: Final = {token.STAR, token.DOUBLESTAR}
89 VARARGS_SPECIALS: Final = STARS | {token.SLASH}
90 VARARGS_PARENTS: Final = {
92 syms.argument, # double star in arglist
93 syms.trailer, # single argument to call
95 syms.varargslist, # lambdas
97 UNPACKING_PARENTS: Final = {
98 syms.atom, # single element of a list or set literal
102 syms.testlist_star_expr,
106 TEST_DESCENDANTS: Final = {
123 ASSIGNMENTS: Final = {
140 IMPLICIT_TUPLE: Final = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
142 token.LPAR: token.RPAR,
143 token.LSQB: token.RSQB,
144 token.LBRACE: token.RBRACE,
146 OPENING_BRACKETS: Final = set(BRACKET.keys())
147 CLOSING_BRACKETS: Final = set(BRACKET.values())
148 BRACKETS: Final = OPENING_BRACKETS | CLOSING_BRACKETS
149 ALWAYS_NO_SPACE: Final = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
154 @mypyc_attr(allow_interpreted_subclasses=True)
155 class Visitor(Generic[T]):
156 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
158 def visit(self, node: LN) -> Iterator[T]:
159 """Main method to visit `node` and its children.
161 It tries to find a `visit_*()` method for the given `node.type`, like
162 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
163 If no dedicated `visit_*()` method is found, chooses `visit_default()`
166 Then yields objects of type `T` from the selected visitor.
169 name = token.tok_name[node.type]
171 name = str(type_repr(node.type))
172 # We explicitly branch on whether a visitor exists (instead of
173 # using self.visit_default as the default arg to getattr) in order
174 # to save needing to create a bound method object and so mypyc can
175 # generate a native call to visit_default.
176 visitf = getattr(self, f"visit_{name}", None)
178 yield from visitf(node)
180 yield from self.visit_default(node)
182 def visit_default(self, node: LN) -> Iterator[T]:
183 """Default `visit_*()` implementation. Recurses to children of `node`."""
184 if isinstance(node, Node):
185 for child in node.children:
186 yield from self.visit(child)
189 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
190 """Return whitespace prefix if needed for the given `leaf`.
192 `complex_subscript` signals whether the given leaf is part of a subscription
193 which has non-trivial arguments, like arithmetic expressions or function calls.
197 DOUBLESPACE: Final = " "
201 if t in ALWAYS_NO_SPACE:
204 if t == token.COMMENT:
207 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
208 if t == token.COLON and p.type not in {
215 prev = leaf.prev_sibling
217 prevp = preceding_leaf(p)
218 if not prevp or prevp.type in OPENING_BRACKETS:
222 if prevp.type == token.COLON:
225 elif prevp.type != token.COMMA and not complex_subscript:
230 if prevp.type == token.EQUAL:
232 if prevp.parent.type in {
240 elif prevp.parent.type == syms.typedargslist:
241 # A bit hacky: if the equal sign has whitespace, it means we
242 # previously found it's a typed argument. So, we're using
246 elif prevp.type in VARARGS_SPECIALS:
247 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
250 elif prevp.type == token.COLON:
251 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
252 return SPACE if complex_subscript else NO
256 and prevp.parent.type == syms.factor
257 and prevp.type in MATH_OPERATORS
261 elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator:
262 # no space in decorators
265 elif prev.type in OPENING_BRACKETS:
268 if p.type in {syms.parameters, syms.arglist}:
269 # untyped function signatures or calls
270 if not prev or prev.type != token.COMMA:
273 elif p.type == syms.varargslist:
275 if prev and prev.type != token.COMMA:
278 elif p.type == syms.typedargslist:
279 # typed function signatures
284 if prev.type != syms.tname:
287 elif prev.type == token.EQUAL:
288 # A bit hacky: if the equal sign has whitespace, it means we
289 # previously found it's a typed argument. So, we're using that, too.
292 elif prev.type != token.COMMA:
295 elif p.type == syms.tname:
298 prevp = preceding_leaf(p)
299 if not prevp or prevp.type != token.COMMA:
302 elif p.type == syms.trailer:
303 # attributes and calls
304 if t == token.LPAR or t == token.RPAR:
308 if t == token.DOT or t == token.LSQB:
311 elif prev.type != token.COMMA:
314 elif p.type == syms.argument:
320 prevp = preceding_leaf(p)
321 if not prevp or prevp.type == token.LPAR:
324 elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
327 elif p.type == syms.decorator:
331 elif p.type == syms.dotted_name:
335 prevp = preceding_leaf(p)
336 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
339 elif p.type == syms.classdef:
343 if prev and prev.type == token.LPAR:
346 elif p.type in {syms.subscript, syms.sliceop}:
349 assert p.parent is not None, "subscripts are always parented"
350 if p.parent.type == syms.subscriptlist:
355 elif not complex_subscript:
358 elif p.type == syms.atom:
359 if prev and t == token.DOT:
360 # dots, but not the first one.
363 elif p.type == syms.dictsetmaker:
365 if prev and prev.type == token.DOUBLESTAR:
368 elif p.type in {syms.factor, syms.star_expr}:
371 prevp = preceding_leaf(p)
372 if not prevp or prevp.type in OPENING_BRACKETS:
375 prevp_parent = prevp.parent
376 assert prevp_parent is not None
377 if prevp.type == token.COLON and prevp_parent.type in {
383 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
386 elif t in {token.NAME, token.NUMBER, token.STRING}:
389 elif p.type == syms.import_from:
391 if prev and prev.type == token.DOT:
394 elif t == token.NAME:
398 if prev and prev.type == token.DOT:
401 elif p.type == syms.sliceop:
407 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
408 """Return the first leaf that precedes `node`, if any."""
410 res = node.prev_sibling
412 if isinstance(res, Leaf):
416 return list(res.leaves())[-1]
425 def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
426 """Return if the `node` and its previous siblings match types against the provided
427 list of tokens; the provided `node`has its type matched against the last element in
428 the list. `None` can be used as the first element to declare that the start of the
429 list is anchored at the start of its parent's children."""
432 if tokens[-1] is None:
436 if node.type != tokens[-1]:
438 return prev_siblings_are(node.prev_sibling, tokens[:-1])
441 def parent_type(node: Optional[LN]) -> Optional[NodeType]:
444 @node.parent.type, if @node is not None and has a parent.
448 if node is None or node.parent is None:
451 return node.parent.type
454 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
455 """Return the child of `ancestor` that contains `descendant`."""
456 node: Optional[LN] = descendant
457 while node and node.parent != ancestor:
462 def replace_child(old_child: LN, new_child: LN) -> None:
465 * If @old_child.parent is set, replace @old_child with @new_child in
466 @old_child's underlying Node structure.
468 * Otherwise, this function does nothing.
470 parent = old_child.parent
474 child_idx = old_child.remove()
475 if child_idx is not None:
476 parent.insert_child(child_idx, new_child)
479 def container_of(leaf: Leaf) -> LN:
480 """Return `leaf` or one of its ancestors that is the topmost container of it.
482 By "container" we mean a node where `leaf` is the very first child.
484 same_prefix = leaf.prefix
487 parent = container.parent
491 if parent.children[0].prefix != same_prefix:
494 if parent.type == syms.file_input:
497 if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
504 def first_leaf_column(node: Node) -> Optional[int]:
505 """Returns the column of the first leaf child of a node."""
506 for child in node.children:
507 if isinstance(child, Leaf):
512 def is_arith_like(node: LN) -> bool:
513 """Whether node is an arithmetic or a binary arithmetic expression"""
514 return node.type in {
522 def is_docstring(leaf: Leaf) -> bool:
523 if prev_siblings_are(
524 leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
528 # Multiline docstring on the same line as the `def`.
529 if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
530 # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
531 # grammar. We're safe to return True without further checks.
537 def is_empty_tuple(node: LN) -> bool:
538 """Return True if `node` holds an empty tuple."""
540 node.type == syms.atom
541 and len(node.children) == 2
542 and node.children[0].type == token.LPAR
543 and node.children[1].type == token.RPAR
547 def is_one_tuple(node: LN) -> bool:
548 """Return True if `node` holds a tuple with one element, with or without parens."""
549 if node.type == syms.atom:
550 gexp = unwrap_singleton_parenthesis(node)
551 if gexp is None or gexp.type != syms.testlist_gexp:
554 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
557 node.type in IMPLICIT_TUPLE
558 and len(node.children) == 2
559 and node.children[1].type == token.COMMA
563 def is_one_sequence_between(
567 brackets: Tuple[int, int] = (token.LPAR, token.RPAR),
569 """Return True if content between `opening` and `closing` is a one-sequence."""
570 if (opening.type, closing.type) != brackets:
573 depth = closing.bracket_depth + 1
574 for _opening_index, leaf in enumerate(leaves):
579 raise LookupError("Opening paren not found in `leaves`")
583 for leaf in leaves[_opening_index:]:
587 bracket_depth = leaf.bracket_depth
588 if bracket_depth == depth and leaf.type == token.COMMA:
590 if leaf.parent and leaf.parent.type in {
600 def is_walrus_assignment(node: LN) -> bool:
601 """Return True iff `node` is of the shape ( test := test )"""
602 inner = unwrap_singleton_parenthesis(node)
603 return inner is not None and inner.type == syms.namedexpr_test
606 def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool:
607 """Return True iff `node` is a trailer valid in a simple decorator"""
608 return node.type == syms.trailer and (
610 len(node.children) == 2
611 and node.children[0].type == token.DOT
612 and node.children[1].type == token.NAME
614 # last trailer can be an argument-less parentheses pair
617 and len(node.children) == 2
618 and node.children[0].type == token.LPAR
619 and node.children[1].type == token.RPAR
621 # last trailer can be arguments
624 and len(node.children) == 3
625 and node.children[0].type == token.LPAR
626 # and node.children[1].type == syms.argument
627 and node.children[2].type == token.RPAR
632 def is_simple_decorator_expression(node: LN) -> bool:
633 """Return True iff `node` could be a 'dotted name' decorator
635 This function takes the node of the 'namedexpr_test' of the new decorator
636 grammar and test if it would be valid under the old decorator grammar.
638 The old grammar was: decorator: @ dotted_name [arguments] NEWLINE
639 The new grammar is : decorator: @ namedexpr_test NEWLINE
641 if node.type == token.NAME:
643 if node.type == syms.power:
646 node.children[0].type == token.NAME
647 and all(map(is_simple_decorator_trailer, node.children[1:-1]))
649 len(node.children) < 2
650 or is_simple_decorator_trailer(node.children[-1], last=True)
656 def is_yield(node: LN) -> bool:
657 """Return True if `node` holds a `yield` or `yield from` expression."""
658 if node.type == syms.yield_expr:
661 if is_name_token(node) and node.value == "yield":
664 if node.type != syms.atom:
667 if len(node.children) != 3:
670 lpar, expr, rpar = node.children
671 if lpar.type == token.LPAR and rpar.type == token.RPAR:
672 return is_yield(expr)
677 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
678 """Return True if `leaf` is a star or double star in a vararg or kwarg.
680 If `within` includes VARARGS_PARENTS, this applies to function signatures.
681 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
682 extended iterable unpacking (PEP 3132) and additional unpacking
683 generalizations (PEP 448).
685 if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
689 if p.type == syms.star_expr:
690 # Star expressions are also used as assignment targets in extended
691 # iterable unpacking (PEP 3132). See what its parent is instead.
697 return p.type in within
700 def is_multiline_string(leaf: Leaf) -> bool:
701 """Return True if `leaf` is a multiline string that actually spans many lines."""
702 return has_triple_quotes(leaf.value) and "\n" in leaf.value
705 def is_stub_suite(node: Node) -> bool:
706 """Return True if `node` is a suite with a stub body."""
708 len(node.children) != 4
709 or node.children[0].type != token.NEWLINE
710 or node.children[1].type != token.INDENT
711 or node.children[3].type != token.DEDENT
715 return is_stub_body(node.children[2])
718 def is_stub_body(node: LN) -> bool:
719 """Return True if `node` is a simple statement containing an ellipsis."""
720 if not isinstance(node, Node) or node.type != syms.simple_stmt:
723 if len(node.children) != 2:
726 child = node.children[0]
728 child.type == syms.atom
729 and len(child.children) == 3
730 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
734 def is_atom_with_invisible_parens(node: LN) -> bool:
735 """Given a `LN`, determines whether it's an atom `node` with invisible
736 parens. Useful in dedupe-ing and normalizing parens.
738 if isinstance(node, Leaf) or node.type != syms.atom:
741 first, last = node.children[0], node.children[-1]
743 isinstance(first, Leaf)
744 and first.type == token.LPAR
745 and first.value == ""
746 and isinstance(last, Leaf)
747 and last.type == token.RPAR
752 def is_empty_par(leaf: Leaf) -> bool:
753 return is_empty_lpar(leaf) or is_empty_rpar(leaf)
756 def is_empty_lpar(leaf: Leaf) -> bool:
757 return leaf.type == token.LPAR and leaf.value == ""
760 def is_empty_rpar(leaf: Leaf) -> bool:
761 return leaf.type == token.RPAR and leaf.value == ""
764 def is_import(leaf: Leaf) -> bool:
765 """Return True if the given leaf starts an import statement."""
772 (v == "import" and p and p.type == syms.import_name)
773 or (v == "from" and p and p.type == syms.import_from)
778 def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
779 """Return True if the given leaf is a special comment.
780 Only returns true for type comments for now."""
783 return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
786 def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
787 """Wrap `child` in parentheses.
789 This replaces `child` with an atom holding the parentheses and the old
790 child. That requires moving the prefix.
792 If `visible` is False, the leaves will be valueless (and thus invisible).
794 lpar = Leaf(token.LPAR, "(" if visible else "")
795 rpar = Leaf(token.RPAR, ")" if visible else "")
796 prefix = child.prefix
798 index = child.remove() or 0
799 new_child = Node(syms.atom, [lpar, child, rpar])
800 new_child.prefix = prefix
801 parent.insert_child(index, new_child)
804 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
805 """Returns `wrapped` if `node` is of the shape ( wrapped ).
807 Parenthesis can be optional. Returns None otherwise"""
808 if len(node.children) != 3:
811 lpar, wrapped, rpar = node.children
812 if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
818 def ensure_visible(leaf: Leaf) -> None:
819 """Make sure parentheses are visible.
821 They could be invisible as part of some statements (see
822 :func:`normalize_invisible_parens` and :func:`visit_import_from`).
824 if leaf.type == token.LPAR:
826 elif leaf.type == token.RPAR:
830 def is_name_token(nl: NL) -> TypeGuard[Leaf]:
831 return nl.type == token.NAME
834 def is_lpar_token(nl: NL) -> TypeGuard[Leaf]:
835 return nl.type == token.LPAR
838 def is_rpar_token(nl: NL) -> TypeGuard[Leaf]:
839 return nl.type == token.RPAR
842 def is_string_token(nl: NL) -> TypeGuard[Leaf]:
843 return nl.type == token.STRING