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
2 from typing import Any, Iterator, List, TypeVar, Union
4 from black.nodes import Visitor
5 from black.output import out
6 from black.parsing import lib2to3_parse
7 from blib2to3.pgen2 import token
8 from blib2to3.pytree import Leaf, Node, type_repr
10 LN = Union[Leaf, Node]
15 class DebugVisitor(Visitor[T]):
17 list_output: List[str] = field(default_factory=list)
18 print_output: bool = True
20 def out(self, message: str, *args: Any, **kwargs: Any) -> None:
21 self.list_output.append(message)
23 out(message, *args, **kwargs)
25 def visit_default(self, node: LN) -> Iterator[T]:
26 indent = " " * (2 * self.tree_depth)
27 if isinstance(node, Node):
28 _type = type_repr(node.type)
29 self.out(f"{indent}{_type}", fg="yellow")
31 for child in node.children:
32 yield from self.visit(child)
35 self.out(f"{indent}/{_type}", fg="yellow", bold=False)
37 _type = token.tok_name.get(node.type, str(node.type))
38 self.out(f"{indent}{_type}", fg="blue", nl=False)
40 # We don't have to handle prefixes for `Node` objects since
41 # that delegates to the first child anyway.
42 self.out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
43 self.out(f" {node.value!r}", fg="blue", bold=False)
46 def show(cls, code: Union[str, Leaf, Node]) -> None:
47 """Pretty-print the lib2to3 AST of a given string of `code`.
49 Convenience method for debugging.
51 v: DebugVisitor[None] = DebugVisitor()
52 if isinstance(code, str):
53 code = lib2to3_parse(code)