-
Notifications
You must be signed in to change notification settings - Fork 7
/
rewrite.py
142 lines (104 loc) · 3.9 KB
/
rewrite.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from __future__ import annotations
import ast
import collections
import collections.abc
from typing import Any, Callable, NamedTuple, Sequence, Union
Node = Union[ast.AST, Sequence[ast.AST]]
class Replacement(NamedTuple):
old: str
new: str
def _is_iterable(value: Any) -> bool:
return not isinstance(value, str) and isinstance(value, collections.abc.Iterable)
def matches(value: Node, pattern: Node) -> bool:
"""Check whether `value` matches `pattern`.
Parameters
----------
value
Instance to match
pattern
Pattern to match against
"""
# types must match exactly
if type(value) != type(pattern):
return False
# recur into lists
if _is_iterable(value) and _is_iterable(pattern):
assert isinstance(
value, collections.abc.Iterable
), f"value is not a non-str iterable {type(value).__name__}"
assert isinstance(
pattern, collections.abc.Iterable
), f"pattern is not a non-str iterable {type(pattern).__name__}"
return all(map(matches, value, pattern))
# primitive value, such as None, True, False, etc.
if not isinstance(value, ast.AST) and not isinstance(pattern, ast.AST):
return value == pattern
assert isinstance(
value, ast.AST
), f"value is not an AST node: {type(value).__name__}"
assert isinstance(
pattern, ast.AST
), f"pattern is not an AST node: {type(pattern).__name__}"
fields = [
(field, getattr(pattern, field))
for field in pattern._fields
if hasattr(pattern, field)
]
for field_name, field_value in fields:
if not matches(getattr(value, field_name), field_value):
return False
return True
class Rewriter:
"""AST pattern matching to enable rewrite rules."""
def __init__(self) -> None:
self.funcs: list[tuple[ast.AST, Callable[[ast.AST], ast.AST]]] = []
def register(
self, pattern: ast.AST
) -> Callable[[Callable[[ast.AST], ast.AST]], Callable[[ast.AST], ast.AST]]:
def wrapper(f: Callable[[ast.AST], ast.AST]) -> Callable[[ast.AST], ast.AST]:
self.funcs.append((pattern, f))
return f
return wrapper
def __call__(self, node: ast.AST) -> ast.AST:
for pattern, func in self.funcs:
if matches(node, pattern):
return func(node)
return node
rewrite = Rewriter()
def build_import_rewrite(dep: str) -> Replacement:
"""Construct a replacement import for `dep`.
Parameters
----------
dep
The `name` field of a `FileDescriptorProto` message, stripped
of its ``.proto`` suffix.
Returns
-------
Replacement
A named tuple of the old import and its replacement
"""
parts = dep.split("/")
*import_parts, part = parts
if not import_parts:
old = f"import {part}_pb2 as {part}__pb2"
new = f"from . import {part}_pb2 as {part}__pb2"
else:
last_part = "__".join(f"{part}_pb2".split("_"))
from_ = ".".join(import_parts)
as_ = f"{'_dot_'.join(import_parts)}_dot_{last_part}"
old = f"from {from_} import {part}_pb2 as {as_}"
new = f"from .{from_} import {part}_pb2 as {as_}"
return Replacement(old=old, new=new)
def register_import_rewrite(replacement: Replacement) -> None:
"""Register a rewrite rule for turning `old` into `new`."""
(old_import,) = ast.parse(replacement.old).body
(new_import,) = ast.parse(replacement.new).body
def _rewrite(_: ast.AST, new_import: ast.AST = new_import) -> ast.AST:
return new_import
rewrite.register(old_import)(_rewrite)
class ImportRewriter(ast.NodeTransformer):
"""A NodeTransformer to apply rewrite rules."""
def visit_Import(self, node: ast.Import) -> ast.AST:
return rewrite(node)
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
return rewrite(node)