forked from vilterp/web-codeviz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecordexec.py
More file actions
149 lines (132 loc) · 4 KB
/
recordexec.py
File metadata and controls
149 lines (132 loc) · 4 KB
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
143
144
145
146
147
148
149
import sys, copy
EVENTS = []
OR = 0
# TODO: sandbox -- no IO, no imports
# TODO: line events -- local variable changes
# TODO: deal width lambdas, classes
RESTRICTED_BUILTINS = {}
blacklist = set(['open', 'input', 'raw_input', 'eval', 'quit', '__import__', 'SystemExit'])
import __builtin__
for item in dir(__builtin__):
if item not in blacklist:
RESTRICTED_BUILTINS[item] = getattr(__builtin__, item)
def recordexec(code):
global EVENTS, OR
EVENTS = []
OR = False
clean_globals = {
"__name__": "__main__",
"__file__": '<codeviz source>',
'__builtins__': RESTRICTED_BUILTINS
}
actual_stdout = sys.stdout
sys.stdout = OutputRecorder()
sys.settrace(tracefunc)
try:
exec code in clean_globals
except SyntaxError, e:
sys.settrace(None)
raise CompilationError(e)
except Exception, e:
sys.settrace(None)
EVENTS.append({
'type': 'exception',
'name': e.__class__.__name__,
'msg': str(e)
})
finally:
sys.settrace(None)
sys.stdout = actual_stdout
return build_call_objects(EVENTS)
def build_call_objects(events):
def bco(events, start_ind):
evt = events[start_ind]
call = {
'type': 'call',
'func': evt['func'],
'args': evt['args'],
'subevents': []
}
nextind = start_ind + 1
subevents = call['subevents']
while True:
nextevt = events[nextind]
if nextevt['type'] == 'print':
buf = ''
while nextevt['type'] == 'print':
buf += nextevt['output']
nextind += 1
nextevt = events[nextind]
subevents.append({
'type': 'print',
'output': buf
})
elif nextevt['type'] == 'call':
callobj, nextind = bco(events, nextind)
subevents.append(callobj)
elif nextevt['type'] == 'return':
call['retval'] = nextevt['val']
nextind += 1
break
else:
raise Exception('unknown event type', nextevt) # todo: handle exceptions...
return (call, nextind)
call, nextind = bco(events, 0)
if nextind == len(events):
return call
else:
raise Exception('events left over: ', events[nextind:])
class OutputRecorder:
def write(self, out):
global EVENTS
EVENTS.append({
'type': 'print',
'output': copy.deepcopy(out)
})
class CompilationError(Exception):
def __init__(self, e):
self.err = e
def __str__(self):
return str(self.err)
def tracefunc(frame, event, arg):
global EVENTS, OR
if event == 'return':
if OR > 0:
OR -= 1
else:
EVENTS.append({
'type': 'return',
'val': copy.deepcopy(arg)
})
elif event == 'call':
if OR > 0:
OR += 1
else:
codeobj = frame.f_code
numargs = codeobj.co_argcount
argnames = codeobj.co_varnames[:numargs]
argvals = [copy.deepcopy(frame.f_locals[name]) for name in argnames]
func_name = codeobj.co_name
if len(argvals) > 0 and isinstance(argvals[0], OutputRecorder):
OR += 1
else:
EVENTS.append({
'type': 'call',
'func': func_name,
'args': argvals
})
else:
pass
#print 'not doing', event, 'yet'
return tracefunc
def testonfile(fn):
source = open(fn).read()
return recordexec(source)
if __name__ == '__main__':
if len(sys.argv) == 2:
fn = sys.argv[1]
callobj = recordexec(open(fn).read())
import pprint
pprint.pprint(callobj)
else:
print 'supply file as arg'