File: visitor.py

package info (click to toggle)
firefox-esr 115.14.0esr-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,659,200 kB
  • sloc: cpp: 6,676,648; javascript: 5,690,850; ansic: 3,328,545; python: 1,120,605; asm: 397,163; xml: 180,531; java: 178,838; sh: 68,930; makefile: 20,999; perl: 12,595; objc: 12,561; yacc: 4,583; cs: 3,846; pascal: 2,840; lex: 1,720; ruby: 1,079; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10
file content (65 lines) | stat: -rw-r--r-- 2,164 bytes parent folder | download | duplicates (22)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from typing import Any, List
from .ast import BaseNode, Node


class Visitor:
    '''Read-only visitor pattern.

    Subclass this to gather information from an AST.
    To generally define which nodes not to descend in to, overload
    `generic_visit`.
    To handle specific node types, add methods like `visit_Pattern`.
    If you want to still descend into the children of the node, call
    `generic_visit` of the superclass.
    '''

    def visit(self, node: Any) -> None:
        if isinstance(node, list):
            for child in node:
                self.visit(child)
            return
        if not isinstance(node, BaseNode):
            return
        nodename = type(node).__name__
        visit = getattr(self, f'visit_{nodename}', self.generic_visit)
        visit(node)

    def generic_visit(self, node: BaseNode) -> None:
        for propvalue in vars(node).values():
            self.visit(propvalue)


class Transformer(Visitor):
    '''In-place AST Transformer pattern.

    Subclass this to create an in-place modified variant
    of the given AST.
    If you need to keep the original AST around, pass
    a `node.clone()` to the transformer.
    '''

    def visit(self, node: Any) -> Any:
        if not isinstance(node, BaseNode):
            return node

        nodename = type(node).__name__
        visit = getattr(self, f'visit_{nodename}', self.generic_visit)
        return visit(node)

    def generic_visit(self, node: Node) -> Node:  # type: ignore
        for propname, propvalue in vars(node).items():
            if isinstance(propvalue, list):
                new_vals: List[Any] = []
                for child in propvalue:
                    new_val = self.visit(child)
                    if new_val is not None:
                        new_vals.append(new_val)
                # in-place manipulation
                propvalue[:] = new_vals
            elif isinstance(propvalue, BaseNode):
                new_val = self.visit(propvalue)
                if new_val is None:
                    delattr(node, propname)
                else:
                    setattr(node, propname, new_val)
        return node