-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_ast.py
93 lines (75 loc) · 1.87 KB
/
test_ast.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
import ast
from io import BytesIO
from shlex import split
from tokenize import COMMENT
from tokenize import tokenize
from astpretty import pprint
code1 = """
print(2)
print(2)
"""
code2 = """
async def f(request):
print(2)
"""
class NumberChanger(ast.NodeTransformer):
"""Changes all number literals to 42."""
def visit_Module(self, node):
super().generic_visit(node)
if isinstance(node, ast.Module):
wrapper = ast.AsyncFunctionDef(
name="do_request",
decorator_list=[],
args=ast.arguments(
posonlyargs=[],
kwonlyargs=[],
defaults=[],
kw_defaults=[],
args=[ast.arg(arg="request")],
),
)
wrapper.body = node.body
node.body = [wrapper]
return node
if not isinstance(node, ast.Constant) or not isinstance(node.value, int):
return node
return ast.Constant(value=42)
# pprint(ast.parse(code1))
# pprint(ast.parse(code2))
# pprint(a)
modded1 = ast.fix_missing_locations(NumberChanger().visit(ast.parse(code1)))
# pprint(modded1)
modded2 = ast.parse(code2)
# pprint(modded2)
# print(modded1 == modded2)
# print("--------------")
# print(ast.unparse(modded1))
# print(ast.unparse(modded2))
# pprint(
# ast.parse(
# """
# return dark_star_templates.TemplateResponse("{template_path}", locals())
# """
# )
# )
# code = '''
# print('')
# """adfa
# fadf
# a
# fadf
# ad
# """
# '''
# pprint(ast.parse(code))
code = """
# methods="GET, POST" name="this is my name"
r = request
"""
g = tokenize(BytesIO(code.strip().encode("utf-8")).readline)
for toknum, tokval, (srow, scol), *_ in g:
if toknum == COMMENT:
print(tokval, srow)
for s in split(tokval):
print(s)
pprint(ast.parse(code))