]> 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:

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