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.
18 if sys.version_info >= (3, 8):
19 from typing import Final
21 from typing_extensions import Final
23 from mypy_extensions import mypyc_attr
26 from blib2to3.pytree import Node, Leaf, type_repr
27 from blib2to3 import pygram
28 from blib2to3.pgen2 import token
30 from black.cache import CACHE_DIR
31 from black.strings import has_triple_quotes
34 pygram.initialize(CACHE_DIR)
35 syms: Final = pygram.python_symbols
40 LN = Union[Leaf, Node]
45 WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE}
56 STANDALONE_COMMENT: Final = 153
57 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
58 LOGIC_OPERATORS: Final = {"and", "or"}
59 COMPARATORS: Final = {
67 MATH_OPERATORS: Final = {
83 STARS: Final = {token.STAR, token.DOUBLESTAR}
84 VARARGS_SPECIALS: Final = STARS | {token.SLASH}
85 VARARGS_PARENTS: Final = {
87 syms.argument, # double star in arglist
88 syms.trailer, # single argument to call
90 syms.varargslist, # lambdas
92 UNPACKING_PARENTS: Final = {
93 syms.atom, # single element of a list or set literal
97 syms.testlist_star_expr,
99 TEST_DESCENDANTS: Final = {
116 ASSIGNMENTS: Final = {
133 IMPLICIT_TUPLE: Final = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
135 token.LPAR: token.RPAR,
136 token.LSQB: token.RSQB,
137 token.LBRACE: token.RBRACE,
139 OPENING_BRACKETS: Final = set(BRACKET.keys())
140 CLOSING_BRACKETS: Final = set(BRACKET.values())
141 BRACKETS: Final = OPENING_BRACKETS | CLOSING_BRACKETS
142 ALWAYS_NO_SPACE: Final = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
147 @mypyc_attr(allow_interpreted_subclasses=True)
148 class Visitor(Generic[T]):
149 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
151 def visit(self, node: LN) -> Iterator[T]:
152 """Main method to visit `node` and its children.
154 It tries to find a `visit_*()` method for the given `node.type`, like
155 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
156 If no dedicated `visit_*()` method is found, chooses `visit_default()`
159 Then yields objects of type `T` from the selected visitor.
162 name = token.tok_name[node.type]
164 name = str(type_repr(node.type))
165 # We explicitly branch on whether a visitor exists (instead of
166 # using self.visit_default as the default arg to getattr) in order
167 # to save needing to create a bound method object and so mypyc can
168 # generate a native call to visit_default.
169 visitf = getattr(self, f"visit_{name}", None)
171 yield from visitf(node)
173 yield from self.visit_default(node)
175 def visit_default(self, node: LN) -> Iterator[T]:
176 """Default `visit_*()` implementation. Recurses to children of `node`."""
177 if isinstance(node, Node):
178 for child in node.children:
179 yield from self.visit(child)
182 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
183 """Return whitespace prefix if needed for the given `leaf`.
185 `complex_subscript` signals whether the given leaf is part of a subscription
186 which has non-trivial arguments, like arithmetic expressions or function calls.
190 DOUBLESPACE: Final = " "
194 if t in ALWAYS_NO_SPACE:
197 if t == token.COMMENT:
200 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
201 if t == token.COLON and p.type not in {
208 prev = leaf.prev_sibling
210 prevp = preceding_leaf(p)
211 if not prevp or prevp.type in OPENING_BRACKETS:
215 if prevp.type == token.COLON:
218 elif prevp.type != token.COMMA and not complex_subscript:
223 if prevp.type == token.EQUAL:
225 if prevp.parent.type in {
233 elif prevp.parent.type == syms.typedargslist:
234 # A bit hacky: if the equal sign has whitespace, it means we
235 # previously found it's a typed argument. So, we're using
239 elif prevp.type in VARARGS_SPECIALS:
240 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
243 elif prevp.type == token.COLON:
244 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
245 return SPACE if complex_subscript else NO
249 and prevp.parent.type == syms.factor
250 and prevp.type in MATH_OPERATORS
255 prevp.type == token.RIGHTSHIFT
257 and prevp.parent.type == syms.shift_expr
258 and prevp.prev_sibling
259 and prevp.prev_sibling.type == token.NAME
260 and prevp.prev_sibling.value == "print" # type: ignore
262 # Python 2 print chevron
264 elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator:
265 # no space in decorators
268 elif prev.type in OPENING_BRACKETS:
271 if p.type in {syms.parameters, syms.arglist}:
272 # untyped function signatures or calls
273 if not prev or prev.type != token.COMMA:
276 elif p.type == syms.varargslist:
278 if prev and prev.type != token.COMMA:
281 elif p.type == syms.typedargslist:
282 # typed function signatures
287 if prev.type != syms.tname:
290 elif prev.type == token.EQUAL:
291 # A bit hacky: if the equal sign has whitespace, it means we
292 # previously found it's a typed argument. So, we're using that, too.
295 elif prev.type != token.COMMA:
298 elif p.type == syms.tname:
301 prevp = preceding_leaf(p)
302 if not prevp or prevp.type != token.COMMA:
305 elif p.type == syms.trailer:
306 # attributes and calls
307 if t == token.LPAR or t == token.RPAR:
312 prevp = preceding_leaf(p)
313 if not prevp or prevp.type != token.NUMBER:
316 elif t == token.LSQB:
319 elif prev.type != token.COMMA:
322 elif p.type == syms.argument:
328 prevp = preceding_leaf(p)
329 if not prevp or prevp.type == token.LPAR:
332 elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
335 elif p.type == syms.decorator:
339 elif p.type == syms.dotted_name:
343 prevp = preceding_leaf(p)
344 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
347 elif p.type == syms.classdef:
351 if prev and prev.type == token.LPAR:
354 elif p.type in {syms.subscript, syms.sliceop}:
357 assert p.parent is not None, "subscripts are always parented"
358 if p.parent.type == syms.subscriptlist:
363 elif not complex_subscript:
366 elif p.type == syms.atom:
367 if prev and t == token.DOT:
368 # dots, but not the first one.
371 elif p.type == syms.dictsetmaker:
373 if prev and prev.type == token.DOUBLESTAR:
376 elif p.type in {syms.factor, syms.star_expr}:
379 prevp = preceding_leaf(p)
380 if not prevp or prevp.type in OPENING_BRACKETS:
383 prevp_parent = prevp.parent
384 assert prevp_parent is not None
385 if prevp.type == token.COLON and prevp_parent.type in {
391 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
394 elif t in {token.NAME, token.NUMBER, token.STRING}:
397 elif p.type == syms.import_from:
399 if prev and prev.type == token.DOT:
402 elif t == token.NAME:
406 if prev and prev.type == token.DOT:
409 elif p.type == syms.sliceop:
415 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
416 """Return the first leaf that precedes `node`, if any."""
418 res = node.prev_sibling
420 if isinstance(res, Leaf):
424 return list(res.leaves())[-1]
433 def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
434 """Return if the `node` and its previous siblings match types against the provided
435 list of tokens; the provided `node`has its type matched against the last element in
436 the list. `None` can be used as the first element to declare that the start of the
437 list is anchored at the start of its parent's children."""
440 if tokens[-1] is None:
444 if node.type != tokens[-1]:
446 return prev_siblings_are(node.prev_sibling, tokens[:-1])
449 def last_two_except(leaves: List[Leaf], omit: Collection[LeafID]) -> Tuple[Leaf, Leaf]:
450 """Return (penultimate, last) leaves skipping brackets in `omit` and contents."""
451 stop_after: Optional[Leaf] = None
452 last: Optional[Leaf] = None
453 for leaf in reversed(leaves):
455 if leaf is stop_after:
463 stop_after = leaf.opening_bracket
467 raise LookupError("Last two leaves were also skipped")
470 def parent_type(node: Optional[LN]) -> Optional[NodeType]:
473 @node.parent.type, if @node is not None and has a parent.
477 if node is None or node.parent is None:
480 return node.parent.type
483 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
484 """Return the child of `ancestor` that contains `descendant`."""
485 node: Optional[LN] = descendant
486 while node and node.parent != ancestor:
491 def replace_child(old_child: LN, new_child: LN) -> None:
494 * If @old_child.parent is set, replace @old_child with @new_child in
495 @old_child's underlying Node structure.
497 * Otherwise, this function does nothing.
499 parent = old_child.parent
503 child_idx = old_child.remove()
504 if child_idx is not None:
505 parent.insert_child(child_idx, new_child)
508 def container_of(leaf: Leaf) -> LN:
509 """Return `leaf` or one of its ancestors that is the topmost container of it.
511 By "container" we mean a node where `leaf` is the very first child.
513 same_prefix = leaf.prefix
516 parent = container.parent
520 if parent.children[0].prefix != same_prefix:
523 if parent.type == syms.file_input:
526 if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
533 def first_leaf_column(node: Node) -> Optional[int]:
534 """Returns the column of the first leaf child of a node."""
535 for child in node.children:
536 if isinstance(child, Leaf):
541 def first_child_is_arith(node: Node) -> bool:
542 """Whether first child is an arithmetic or a binary arithmetic expression"""
549 return bool(node.children and node.children[0].type in expr_types)
552 def is_docstring(leaf: Leaf) -> bool:
553 if prev_siblings_are(
554 leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
558 # Multiline docstring on the same line as the `def`.
559 if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
560 # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
561 # grammar. We're safe to return True without further checks.
567 def is_empty_tuple(node: LN) -> bool:
568 """Return True if `node` holds an empty tuple."""
570 node.type == syms.atom
571 and len(node.children) == 2
572 and node.children[0].type == token.LPAR
573 and node.children[1].type == token.RPAR
577 def is_one_tuple(node: LN) -> bool:
578 """Return True if `node` holds a tuple with one element, with or without parens."""
579 if node.type == syms.atom:
580 gexp = unwrap_singleton_parenthesis(node)
581 if gexp is None or gexp.type != syms.testlist_gexp:
584 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
587 node.type in IMPLICIT_TUPLE
588 and len(node.children) == 2
589 and node.children[1].type == token.COMMA
593 def is_one_tuple_between(opening: Leaf, closing: Leaf, leaves: List[Leaf]) -> bool:
594 """Return True if content between `opening` and `closing` looks like a one-tuple."""
595 if opening.type != token.LPAR and closing.type != token.RPAR:
598 depth = closing.bracket_depth + 1
599 for _opening_index, leaf in enumerate(leaves):
604 raise LookupError("Opening paren not found in `leaves`")
608 for leaf in leaves[_opening_index:]:
612 bracket_depth = leaf.bracket_depth
613 if bracket_depth == depth and leaf.type == token.COMMA:
615 if leaf.parent and leaf.parent.type in {
625 def is_walrus_assignment(node: LN) -> bool:
626 """Return True iff `node` is of the shape ( test := test )"""
627 inner = unwrap_singleton_parenthesis(node)
628 return inner is not None and inner.type == syms.namedexpr_test
631 def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool:
632 """Return True iff `node` is a trailer valid in a simple decorator"""
633 return node.type == syms.trailer and (
635 len(node.children) == 2
636 and node.children[0].type == token.DOT
637 and node.children[1].type == token.NAME
639 # last trailer can be an argument-less parentheses pair
642 and len(node.children) == 2
643 and node.children[0].type == token.LPAR
644 and node.children[1].type == token.RPAR
646 # last trailer can be arguments
649 and len(node.children) == 3
650 and node.children[0].type == token.LPAR
651 # and node.children[1].type == syms.argument
652 and node.children[2].type == token.RPAR
657 def is_simple_decorator_expression(node: LN) -> bool:
658 """Return True iff `node` could be a 'dotted name' decorator
660 This function takes the node of the 'namedexpr_test' of the new decorator
661 grammar and test if it would be valid under the old decorator grammar.
663 The old grammar was: decorator: @ dotted_name [arguments] NEWLINE
664 The new grammar is : decorator: @ namedexpr_test NEWLINE
666 if node.type == token.NAME:
668 if node.type == syms.power:
671 node.children[0].type == token.NAME
672 and all(map(is_simple_decorator_trailer, node.children[1:-1]))
674 len(node.children) < 2
675 or is_simple_decorator_trailer(node.children[-1], last=True)
681 def is_yield(node: LN) -> bool:
682 """Return True if `node` holds a `yield` or `yield from` expression."""
683 if node.type == syms.yield_expr:
686 if node.type == token.NAME and node.value == "yield": # type: ignore
689 if node.type != syms.atom:
692 if len(node.children) != 3:
695 lpar, expr, rpar = node.children
696 if lpar.type == token.LPAR and rpar.type == token.RPAR:
697 return is_yield(expr)
702 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
703 """Return True if `leaf` is a star or double star in a vararg or kwarg.
705 If `within` includes VARARGS_PARENTS, this applies to function signatures.
706 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
707 extended iterable unpacking (PEP 3132) and additional unpacking
708 generalizations (PEP 448).
710 if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
714 if p.type == syms.star_expr:
715 # Star expressions are also used as assignment targets in extended
716 # iterable unpacking (PEP 3132). See what its parent is instead.
722 return p.type in within
725 def is_multiline_string(leaf: Leaf) -> bool:
726 """Return True if `leaf` is a multiline string that actually spans many lines."""
727 return has_triple_quotes(leaf.value) and "\n" in leaf.value
730 def is_stub_suite(node: Node) -> bool:
731 """Return True if `node` is a suite with a stub body."""
733 len(node.children) != 4
734 or node.children[0].type != token.NEWLINE
735 or node.children[1].type != token.INDENT
736 or node.children[3].type != token.DEDENT
740 return is_stub_body(node.children[2])
743 def is_stub_body(node: LN) -> bool:
744 """Return True if `node` is a simple statement containing an ellipsis."""
745 if not isinstance(node, Node) or node.type != syms.simple_stmt:
748 if len(node.children) != 2:
751 child = node.children[0]
753 child.type == syms.atom
754 and len(child.children) == 3
755 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
759 def is_atom_with_invisible_parens(node: LN) -> bool:
760 """Given a `LN`, determines whether it's an atom `node` with invisible
761 parens. Useful in dedupe-ing and normalizing parens.
763 if isinstance(node, Leaf) or node.type != syms.atom:
766 first, last = node.children[0], node.children[-1]
768 isinstance(first, Leaf)
769 and first.type == token.LPAR
770 and first.value == ""
771 and isinstance(last, Leaf)
772 and last.type == token.RPAR
777 def is_empty_par(leaf: Leaf) -> bool:
778 return is_empty_lpar(leaf) or is_empty_rpar(leaf)
781 def is_empty_lpar(leaf: Leaf) -> bool:
782 return leaf.type == token.LPAR and leaf.value == ""
785 def is_empty_rpar(leaf: Leaf) -> bool:
786 return leaf.type == token.RPAR and leaf.value == ""
789 def is_import(leaf: Leaf) -> bool:
790 """Return True if the given leaf starts an import statement."""
797 (v == "import" and p and p.type == syms.import_name)
798 or (v == "from" and p and p.type == syms.import_from)
803 def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
804 """Return True if the given leaf is a special comment.
805 Only returns true for type comments for now."""
808 return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
811 def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
812 """Wrap `child` in parentheses.
814 This replaces `child` with an atom holding the parentheses and the old
815 child. That requires moving the prefix.
817 If `visible` is False, the leaves will be valueless (and thus invisible).
819 lpar = Leaf(token.LPAR, "(" if visible else "")
820 rpar = Leaf(token.RPAR, ")" if visible else "")
821 prefix = child.prefix
823 index = child.remove() or 0
824 new_child = Node(syms.atom, [lpar, child, rpar])
825 new_child.prefix = prefix
826 parent.insert_child(index, new_child)
829 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
830 """Returns `wrapped` if `node` is of the shape ( wrapped ).
832 Parenthesis can be optional. Returns None otherwise"""
833 if len(node.children) != 3:
836 lpar, wrapped, rpar = node.children
837 if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
843 def ensure_visible(leaf: Leaf) -> None:
844 """Make sure parentheses are visible.
846 They could be invisible as part of some statements (see
847 :func:`normalize_invisible_parens` and :func:`visit_import_from`).
849 if leaf.type == token.LPAR:
851 elif leaf.type == token.RPAR: