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}
58 STANDALONE_COMMENT: Final = 153
59 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
60 LOGIC_OPERATORS: Final = {"and", "or"}
61 COMPARATORS: Final = {
69 MATH_OPERATORS: Final = {
85 STARS: Final = {token.STAR, token.DOUBLESTAR}
86 VARARGS_SPECIALS: Final = STARS | {token.SLASH}
87 VARARGS_PARENTS: Final = {
89 syms.argument, # double star in arglist
90 syms.trailer, # single argument to call
92 syms.varargslist, # lambdas
94 UNPACKING_PARENTS: Final = {
95 syms.atom, # single element of a list or set literal
99 syms.testlist_star_expr,
103 TEST_DESCENDANTS: Final = {
120 ASSIGNMENTS: Final = {
137 IMPLICIT_TUPLE: Final = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
139 token.LPAR: token.RPAR,
140 token.LSQB: token.RSQB,
141 token.LBRACE: token.RBRACE,
143 OPENING_BRACKETS: Final = set(BRACKET.keys())
144 CLOSING_BRACKETS: Final = set(BRACKET.values())
145 BRACKETS: Final = OPENING_BRACKETS | CLOSING_BRACKETS
146 ALWAYS_NO_SPACE: Final = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
151 @mypyc_attr(allow_interpreted_subclasses=True)
152 class Visitor(Generic[T]):
153 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
155 def visit(self, node: LN) -> Iterator[T]:
156 """Main method to visit `node` and its children.
158 It tries to find a `visit_*()` method for the given `node.type`, like
159 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
160 If no dedicated `visit_*()` method is found, chooses `visit_default()`
163 Then yields objects of type `T` from the selected visitor.
166 name = token.tok_name[node.type]
168 name = str(type_repr(node.type))
169 # We explicitly branch on whether a visitor exists (instead of
170 # using self.visit_default as the default arg to getattr) in order
171 # to save needing to create a bound method object and so mypyc can
172 # generate a native call to visit_default.
173 visitf = getattr(self, f"visit_{name}", None)
175 yield from visitf(node)
177 yield from self.visit_default(node)
179 def visit_default(self, node: LN) -> Iterator[T]:
180 """Default `visit_*()` implementation. Recurses to children of `node`."""
181 if isinstance(node, Node):
182 for child in node.children:
183 yield from self.visit(child)
186 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
187 """Return whitespace prefix if needed for the given `leaf`.
189 `complex_subscript` signals whether the given leaf is part of a subscription
190 which has non-trivial arguments, like arithmetic expressions or function calls.
194 DOUBLESPACE: Final = " "
198 if t in ALWAYS_NO_SPACE:
201 if t == token.COMMENT:
204 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
205 if t == token.COLON and p.type not in {
212 prev = leaf.prev_sibling
214 prevp = preceding_leaf(p)
215 if not prevp or prevp.type in OPENING_BRACKETS:
219 if prevp.type == token.COLON:
222 elif prevp.type != token.COMMA and not complex_subscript:
227 if prevp.type == token.EQUAL:
229 if prevp.parent.type in {
237 elif prevp.parent.type == syms.typedargslist:
238 # A bit hacky: if the equal sign has whitespace, it means we
239 # previously found it's a typed argument. So, we're using
243 elif prevp.type in VARARGS_SPECIALS:
244 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
247 elif prevp.type == token.COLON:
248 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
249 return SPACE if complex_subscript else NO
253 and prevp.parent.type == syms.factor
254 and prevp.type in MATH_OPERATORS
259 prevp.type == token.RIGHTSHIFT
261 and prevp.parent.type == syms.shift_expr
262 and prevp.prev_sibling
263 and prevp.prev_sibling.type == token.NAME
264 and prevp.prev_sibling.value == "print" # type: ignore
266 # Python 2 print chevron
268 elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator:
269 # no space in decorators
272 elif prev.type in OPENING_BRACKETS:
275 if p.type in {syms.parameters, syms.arglist}:
276 # untyped function signatures or calls
277 if not prev or prev.type != token.COMMA:
280 elif p.type == syms.varargslist:
282 if prev and prev.type != token.COMMA:
285 elif p.type == syms.typedargslist:
286 # typed function signatures
291 if prev.type != syms.tname:
294 elif prev.type == token.EQUAL:
295 # A bit hacky: if the equal sign has whitespace, it means we
296 # previously found it's a typed argument. So, we're using that, too.
299 elif prev.type != token.COMMA:
302 elif p.type == syms.tname:
305 prevp = preceding_leaf(p)
306 if not prevp or prevp.type != token.COMMA:
309 elif p.type == syms.trailer:
310 # attributes and calls
311 if t == token.LPAR or t == token.RPAR:
316 prevp = preceding_leaf(p)
317 if not prevp or prevp.type != token.NUMBER:
320 elif t == token.LSQB:
323 elif prev.type != token.COMMA:
326 elif p.type == syms.argument:
332 prevp = preceding_leaf(p)
333 if not prevp or prevp.type == token.LPAR:
336 elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
339 elif p.type == syms.decorator:
343 elif p.type == syms.dotted_name:
347 prevp = preceding_leaf(p)
348 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
351 elif p.type == syms.classdef:
355 if prev and prev.type == token.LPAR:
358 elif p.type in {syms.subscript, syms.sliceop}:
361 assert p.parent is not None, "subscripts are always parented"
362 if p.parent.type == syms.subscriptlist:
367 elif not complex_subscript:
370 elif p.type == syms.atom:
371 if prev and t == token.DOT:
372 # dots, but not the first one.
375 elif p.type == syms.dictsetmaker:
377 if prev and prev.type == token.DOUBLESTAR:
380 elif p.type in {syms.factor, syms.star_expr}:
383 prevp = preceding_leaf(p)
384 if not prevp or prevp.type in OPENING_BRACKETS:
387 prevp_parent = prevp.parent
388 assert prevp_parent is not None
389 if prevp.type == token.COLON and prevp_parent.type in {
395 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
398 elif t in {token.NAME, token.NUMBER, token.STRING}:
401 elif p.type == syms.import_from:
403 if prev and prev.type == token.DOT:
406 elif t == token.NAME:
410 if prev and prev.type == token.DOT:
413 elif p.type == syms.sliceop:
419 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
420 """Return the first leaf that precedes `node`, if any."""
422 res = node.prev_sibling
424 if isinstance(res, Leaf):
428 return list(res.leaves())[-1]
437 def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
438 """Return if the `node` and its previous siblings match types against the provided
439 list of tokens; the provided `node`has its type matched against the last element in
440 the list. `None` can be used as the first element to declare that the start of the
441 list is anchored at the start of its parent's children."""
444 if tokens[-1] is None:
448 if node.type != tokens[-1]:
450 return prev_siblings_are(node.prev_sibling, tokens[:-1])
453 def last_two_except(leaves: List[Leaf], omit: Collection[LeafID]) -> Tuple[Leaf, Leaf]:
454 """Return (penultimate, last) leaves skipping brackets in `omit` and contents."""
455 stop_after: Optional[Leaf] = None
456 last: Optional[Leaf] = None
457 for leaf in reversed(leaves):
459 if leaf is stop_after:
467 stop_after = leaf.opening_bracket
471 raise LookupError("Last two leaves were also skipped")
474 def parent_type(node: Optional[LN]) -> Optional[NodeType]:
477 @node.parent.type, if @node is not None and has a parent.
481 if node is None or node.parent is None:
484 return node.parent.type
487 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
488 """Return the child of `ancestor` that contains `descendant`."""
489 node: Optional[LN] = descendant
490 while node and node.parent != ancestor:
495 def replace_child(old_child: LN, new_child: LN) -> None:
498 * If @old_child.parent is set, replace @old_child with @new_child in
499 @old_child's underlying Node structure.
501 * Otherwise, this function does nothing.
503 parent = old_child.parent
507 child_idx = old_child.remove()
508 if child_idx is not None:
509 parent.insert_child(child_idx, new_child)
512 def container_of(leaf: Leaf) -> LN:
513 """Return `leaf` or one of its ancestors that is the topmost container of it.
515 By "container" we mean a node where `leaf` is the very first child.
517 same_prefix = leaf.prefix
520 parent = container.parent
524 if parent.children[0].prefix != same_prefix:
527 if parent.type == syms.file_input:
530 if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
537 def first_leaf_column(node: Node) -> Optional[int]:
538 """Returns the column of the first leaf child of a node."""
539 for child in node.children:
540 if isinstance(child, Leaf):
545 def first_child_is_arith(node: Node) -> bool:
546 """Whether first child is an arithmetic or a binary arithmetic expression"""
553 return bool(node.children and node.children[0].type in expr_types)
556 def is_docstring(leaf: Leaf) -> bool:
557 if prev_siblings_are(
558 leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
562 # Multiline docstring on the same line as the `def`.
563 if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
564 # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
565 # grammar. We're safe to return True without further checks.
571 def is_empty_tuple(node: LN) -> bool:
572 """Return True if `node` holds an empty tuple."""
574 node.type == syms.atom
575 and len(node.children) == 2
576 and node.children[0].type == token.LPAR
577 and node.children[1].type == token.RPAR
581 def is_one_tuple(node: LN) -> bool:
582 """Return True if `node` holds a tuple with one element, with or without parens."""
583 if node.type == syms.atom:
584 gexp = unwrap_singleton_parenthesis(node)
585 if gexp is None or gexp.type != syms.testlist_gexp:
588 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
591 node.type in IMPLICIT_TUPLE
592 and len(node.children) == 2
593 and node.children[1].type == token.COMMA
597 def is_one_tuple_between(opening: Leaf, closing: Leaf, leaves: List[Leaf]) -> bool:
598 """Return True if content between `opening` and `closing` looks like a one-tuple."""
599 if opening.type != token.LPAR and closing.type != token.RPAR:
602 depth = closing.bracket_depth + 1
603 for _opening_index, leaf in enumerate(leaves):
608 raise LookupError("Opening paren not found in `leaves`")
612 for leaf in leaves[_opening_index:]:
616 bracket_depth = leaf.bracket_depth
617 if bracket_depth == depth and leaf.type == token.COMMA:
619 if leaf.parent and leaf.parent.type in {
629 def is_walrus_assignment(node: LN) -> bool:
630 """Return True iff `node` is of the shape ( test := test )"""
631 inner = unwrap_singleton_parenthesis(node)
632 return inner is not None and inner.type == syms.namedexpr_test
635 def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool:
636 """Return True iff `node` is a trailer valid in a simple decorator"""
637 return node.type == syms.trailer and (
639 len(node.children) == 2
640 and node.children[0].type == token.DOT
641 and node.children[1].type == token.NAME
643 # last trailer can be an argument-less parentheses pair
646 and len(node.children) == 2
647 and node.children[0].type == token.LPAR
648 and node.children[1].type == token.RPAR
650 # last trailer can be arguments
653 and len(node.children) == 3
654 and node.children[0].type == token.LPAR
655 # and node.children[1].type == syms.argument
656 and node.children[2].type == token.RPAR
661 def is_simple_decorator_expression(node: LN) -> bool:
662 """Return True iff `node` could be a 'dotted name' decorator
664 This function takes the node of the 'namedexpr_test' of the new decorator
665 grammar and test if it would be valid under the old decorator grammar.
667 The old grammar was: decorator: @ dotted_name [arguments] NEWLINE
668 The new grammar is : decorator: @ namedexpr_test NEWLINE
670 if node.type == token.NAME:
672 if node.type == syms.power:
675 node.children[0].type == token.NAME
676 and all(map(is_simple_decorator_trailer, node.children[1:-1]))
678 len(node.children) < 2
679 or is_simple_decorator_trailer(node.children[-1], last=True)
685 def is_yield(node: LN) -> bool:
686 """Return True if `node` holds a `yield` or `yield from` expression."""
687 if node.type == syms.yield_expr:
690 if node.type == token.NAME and node.value == "yield": # type: ignore
693 if node.type != syms.atom:
696 if len(node.children) != 3:
699 lpar, expr, rpar = node.children
700 if lpar.type == token.LPAR and rpar.type == token.RPAR:
701 return is_yield(expr)
706 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
707 """Return True if `leaf` is a star or double star in a vararg or kwarg.
709 If `within` includes VARARGS_PARENTS, this applies to function signatures.
710 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
711 extended iterable unpacking (PEP 3132) and additional unpacking
712 generalizations (PEP 448).
714 if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
718 if p.type == syms.star_expr:
719 # Star expressions are also used as assignment targets in extended
720 # iterable unpacking (PEP 3132). See what its parent is instead.
726 return p.type in within
729 def is_multiline_string(leaf: Leaf) -> bool:
730 """Return True if `leaf` is a multiline string that actually spans many lines."""
731 return has_triple_quotes(leaf.value) and "\n" in leaf.value
734 def is_stub_suite(node: Node) -> bool:
735 """Return True if `node` is a suite with a stub body."""
737 len(node.children) != 4
738 or node.children[0].type != token.NEWLINE
739 or node.children[1].type != token.INDENT
740 or node.children[3].type != token.DEDENT
744 return is_stub_body(node.children[2])
747 def is_stub_body(node: LN) -> bool:
748 """Return True if `node` is a simple statement containing an ellipsis."""
749 if not isinstance(node, Node) or node.type != syms.simple_stmt:
752 if len(node.children) != 2:
755 child = node.children[0]
757 child.type == syms.atom
758 and len(child.children) == 3
759 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
763 def is_atom_with_invisible_parens(node: LN) -> bool:
764 """Given a `LN`, determines whether it's an atom `node` with invisible
765 parens. Useful in dedupe-ing and normalizing parens.
767 if isinstance(node, Leaf) or node.type != syms.atom:
770 first, last = node.children[0], node.children[-1]
772 isinstance(first, Leaf)
773 and first.type == token.LPAR
774 and first.value == ""
775 and isinstance(last, Leaf)
776 and last.type == token.RPAR
781 def is_empty_par(leaf: Leaf) -> bool:
782 return is_empty_lpar(leaf) or is_empty_rpar(leaf)
785 def is_empty_lpar(leaf: Leaf) -> bool:
786 return leaf.type == token.LPAR and leaf.value == ""
789 def is_empty_rpar(leaf: Leaf) -> bool:
790 return leaf.type == token.RPAR and leaf.value == ""
793 def is_import(leaf: Leaf) -> bool:
794 """Return True if the given leaf starts an import statement."""
801 (v == "import" and p and p.type == syms.import_name)
802 or (v == "from" and p and p.type == syms.import_from)
807 def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
808 """Return True if the given leaf is a special comment.
809 Only returns true for type comments for now."""
812 return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
815 def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
816 """Wrap `child` in parentheses.
818 This replaces `child` with an atom holding the parentheses and the old
819 child. That requires moving the prefix.
821 If `visible` is False, the leaves will be valueless (and thus invisible).
823 lpar = Leaf(token.LPAR, "(" if visible else "")
824 rpar = Leaf(token.RPAR, ")" if visible else "")
825 prefix = child.prefix
827 index = child.remove() or 0
828 new_child = Node(syms.atom, [lpar, child, rpar])
829 new_child.prefix = prefix
830 parent.insert_child(index, new_child)
833 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
834 """Returns `wrapped` if `node` is of the shape ( wrapped ).
836 Parenthesis can be optional. Returns None otherwise"""
837 if len(node.children) != 3:
840 lpar, wrapped, rpar = node.children
841 if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
847 def ensure_visible(leaf: Leaf) -> None:
848 """Make sure parentheses are visible.
850 They could be invisible as part of some statements (see
851 :func:`normalize_invisible_parens` and :func:`visit_import_from`).
853 if leaf.type == token.LPAR:
855 elif leaf.type == token.RPAR: