]> git.madduck.net Git - etc/vim.git/blob - src/black/debug.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

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.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Improve & update release process to reflect recent changes (#3242)
[etc/vim.git] / src / black / debug.py
1 from dataclasses import dataclass
2 from typing import Iterator, TypeVar, Union
3
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
9
10 LN = Union[Leaf, Node]
11 T = TypeVar("T")
12
13
14 @dataclass
15 class DebugVisitor(Visitor[T]):
16     tree_depth: int = 0
17
18     def visit_default(self, node: LN) -> Iterator[T]:
19         indent = " " * (2 * self.tree_depth)
20         if isinstance(node, Node):
21             _type = type_repr(node.type)
22             out(f"{indent}{_type}", fg="yellow")
23             self.tree_depth += 1
24             for child in node.children:
25                 yield from self.visit(child)
26
27             self.tree_depth -= 1
28             out(f"{indent}/{_type}", fg="yellow", bold=False)
29         else:
30             _type = token.tok_name.get(node.type, str(node.type))
31             out(f"{indent}{_type}", fg="blue", nl=False)
32             if node.prefix:
33                 # We don't have to handle prefixes for `Node` objects since
34                 # that delegates to the first child anyway.
35                 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
36             out(f" {node.value!r}", fg="blue", bold=False)
37
38     @classmethod
39     def show(cls, code: Union[str, Leaf, Node]) -> None:
40         """Pretty-print the lib2to3 AST of a given string of `code`.
41
42         Convenience method for debugging.
43         """
44         v: DebugVisitor[None] = DebugVisitor()
45         if isinstance(code, str):
46             code = lib2to3_parse(code)
47         list(v.visit(code))