-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathast-rewrite.py
70 lines (53 loc) · 1.48 KB
/
ast-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
import inspect
import compiler
import astor
import ast
from astor.codegen import to_source
import lfs
def foo(disk):
print 'test'
disk.write()
disk.flush()
disk.write()
disk.flush()
disk.write()
disk.flush()
class RemoveFlush(ast.NodeTransformer):
def __init__(self, root, *args, **kwargs):
self.__root = root
self.__objs = []
super(RemoveFlush, self).__init__(*args, **kwargs)
def get_all(self):
return self.__objs
def visit_Call(self, node):
# from ipdb import set_trace; set_trace()
# print to_source(node, add_line_information=False)
if not hasattr(node, 'func'):
return node
if not hasattr(node.func, 'attr'):
return node
if not node.func.attr == 'flush':
return node
l = {}
g = {}
s = to_source(self.__root, add_line_information=False)
eval(compile(ast.parse(s), '<string>', 'exec'), l, g)
g['__source'] = s
self.__objs.append(g)
def remove_flush_opt(obj):
code = inspect.getsource(obj)
cnode = ast.parse(code)
rf = RemoveFlush(cnode)
cnode = rf.visit(cnode)
s = to_source(cnode, add_line_information=False)
l = {}
g = {}
eval(compile(ast.parse(s), '<string>', 'exec'), l, g)
g['__source'] = s
objs = rf.get_all()
objs.append(g)
return objs
print remove_flush_opt(lfs.LFS)
for k in remove_flush_opt(lfs.LFS):
print k['__source']
print ""