forked from PythonJS/PythonJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_to_visjs.py
More file actions
433 lines (337 loc) · 9.97 KB
/
python_to_visjs.py
File metadata and controls
433 lines (337 loc) · 9.97 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import ast
#from cStringIO import StringIO as StringIO
from StringIO import StringIO as StringIO
head = """
<div id="mygraph"></div>
<script type="text/javascript">
nodes = [];
edges = [];
stack = [];
"""
tail = """
con = document.getElementById('mygraph');
data = {
nodes: nodes,
edges: edges
}
options = { stabilize: false, clustering: false, hierarchicalLayout:false };
graph = new vis.Graph(con, data, options);
</script>
"""
def main(script):
PythonToVisJS( source=script )
return head + writer.getvalue() + tail
class Writer(object):
def __init__(self):
self.level = 0
self.buffer = list()
self.output = StringIO()
self.nodes = []
self.ids = 0
self.title_blocks = False
self.use_indent = False
self.classes = {} ## name : id
def push_block(self, s='', shape="box", size=1, font_size=13, color=None):
id = self.ids
self.ids += 1
class_name = None
if s.startswith('class '):
x = s.split()
class_name = x[1]
if len(x)==3:
class_parents = x[2].split(',')
else:
class_parents = []
self.classes[ class_name ] = id
for pname in class_parents:
if pname in self.classes:
pid = self.classes[ pname ]
self.output.write('edges.push({from:%s, to:%s, length:200, style:"arrow"})\n' %(pid,id))
s = 'class \\n\\n'+class_name
if self.nodes:
if self.level <= 1 and s.startswith( 'def' ) or class_name:
pass
else:
if self.title_blocks:
self.output.write('stack[stack.length-1].label += "--block%s-->\\n"\n' %id)
else:
self.output.write('stack[stack.length-1].label += ""\n')
prev = self.nodes[-1]
style = 'dash-line'
width = 1
length = 100
if prev.startswith('if '):
style = 'arrow'
elif prev.startswith('for '):
style = 'arrow-center'
length = 150
self.output.write('edges.push({from:%s, to:stack[stack.length-1].id, style: "%s", width: 1, length: %s})\n' %(id, style, length))
elif prev.startswith('class '):
style = 'line'
width = 3
length = 200
self.output.write('edges.push({to:%s, from:stack[stack.length-1].id, style: "%s", width: %s, length: %s})\n' %(id, style, width, length))
if s:
s += '\\n'
if self.title_blocks:
s = ('BLOCK-%s\\n'%id) + s
if color is None:
color = 'undefined'
else:
if type(color) is tuple:
color = '{background:"%s", border:"%s"}'%color
else:
color = '{background:"%s"}'%color
self.output.write('var block = {id:%s, label:"%s", shape:"%s", value:%s, fontSize:%s, color:%s};\n' %(id, s, shape, size, font_size, color))
self.output.write('nodes.push( block );')
self.output.write('stack.push( block );\n')
self.nodes.append( s )
self.level += 1
def pull_block(self):
self.level -= 1
self.nodes.pop()
self.output.write('block = stack.pop();\n')
def push(self):
self.push_block()
def pull(self):
self.pull_block()
def append(self, code):
self.buffer.append(code)
def write(self, code):
for content in self.buffer:
self._write(content)
self.buffer = list()
self._write(code)
def _write(self, code):
if self.use_indent:
indentation = self.level * 4 * ' '
else:
indentation = ''
if code.startswith('if '):
s = '"%s%s";' % (indentation, code)
else:
s = '"%s%s\\n";' % (indentation, code)
self.output.write('stack[stack.length-1].label += %s\n' %s)
def getvalue(self):
s = self.output.getvalue()
self.output = StringIO()
return s
writer = Writer()
class PythonToVisJS(ast.NodeVisitor):
def __init__(self, source=None):
super(PythonToVisJS, self).__init__()
tree = ast.parse( source )
writer.push_block('#module#', shape='circle', color=('lightyellow', 'red'))
self.visit( tree )
writer.pull_block()
def visit_Print(self, node):
return 'print %s' % ', '.join(map(self.visit, node.values))
def visit_Expr(self, node):
return self.visit(node.value)
def visit_If(self, node):
#writer.write('if %s:' %self.visit(node.test))
writer.push_block('if \\n%s' %self.visit(node.test), color=('lightgreen', 'green'), size=5, font_size=16)
writer.push()
for n in node.body:
res = self.visit(n)
if res: writer.write(res)
writer.pull()
if node.orelse:
writer.push_block('else:', color=('pink', 'red'), size=5, font_size=16)
writer.push()
for n in node.orelse:
res = self.visit(n)
if res: writer.write(res)
writer.pull()
writer.pull_block()
writer.pull_block()
def visit_Compare(self, node):
left = self.visit(node.left)
comp = [ left ]
for i in range( len(node.ops) ):
comp.append( self.visit(node.ops[i]) )
comp.append( self.visit(node.comparators[i]) )
return ' '.join( comp )
def visit_For(self, node):
a = 'for \\n%s in %s' %(self.visit(node.target), self.visit(node.iter))
writer.push_block(a, color=('cyan', 'orange'), size=5, font_size=16)
writer.push()
for n in node.body:
res = self.visit(n)
if res: writer.write( res )
writer.pull()
writer.pull_block()
def visit_While(self, node):
writer.push_block('while \\n%s' % self.visit(node.test))
writer.push()
for n in node.body:
res = self.visit(n)
if res: writer.write( res )
writer.pull()
writer.pull_block()
def visit_Call(self, node):
args = [self.visit(arg) for arg in node.args]
if node.keywords:
args.extend( [self.visit(x.value) for x in node.keywords] )
return '%s(%s)' %( self.visit(node.func), ','.join(args) )
else:
return '%s(%s)' %( self.visit(node.func), ','.join(args) )
def visit_ClassDef(self, node):
bases = []
for base in node.bases:
bases.append( self.visit(base) )
if bases:
a = 'class %s %s'%(node.name, ','.join(bases))
else:
a = 'class %s' %node.name
writer.push_block(a, color=('orange', 'black'), font_size=16, shape='database')
for n in node.body:
if isinstance(n, ast.FunctionDef):
self.visit(n)
writer.pull_block()
def visit_FunctionDef(self, node):
args = []
offset = len(node.args.args) - len(node.args.defaults)
for i, arg in enumerate(node.args.args):
a = arg.id
dindex = i - offset
if dindex >= 0 and node.args.defaults:
default_value = self.visit( node.args.defaults[dindex] )
args.append( '%s=%s' %(a, default_value) )
else:
args.append( a )
if node.args.vararg:
args.append('*%s' %node.args.vararg)
if node.args.kwarg:
args.append('**%s' %node.args.kwarg)
a = 'def %s\\n%s' % (node.name, ',\\n'.join(args))
writer.push_block( a, color=('yellow', 'orange'), font_size=16 )
writer.push()
for n in node.body:
res = self.visit(n)
if res: writer.write(res)
writer.pull()
writer.pull_block()
def visit_Return(self, node):
if node.value:
writer.write('return %s' % self.visit(node.value))
return ''
def visit_Attribute(self, node):
node_value = self.visit(node.value)
return '%s.%s' %(node_value, node.attr)
def visit_Pass(self, node):
return 'pass'
def visit_Str(self, node):
return '`%s`' %node.s.replace('"','"').replace('\n', '\\n').replace('&', '&').replace('<','<').replace('>','>')
def visit_Name(self, node):
return node.id
def visit_Num(self, node):
return str(node.n)
def visit_Eq(self, node):
return '=='
def visit_NotEq(self, node):
return '!='
def visit_Is(self, node):
return 'is'
def visit_Pow(self, node):
return '**'
def visit_Mult(self, node):
return '*'
def visit_Add(self, node):
return '+'
def visit_Sub(self, node):
return '-'
def visit_And(self, node):
return ' and '
def visit_Or(self, node):
return ' or '
def visit_FloorDiv(self, node):
return '//'
def visit_Div(self, node):
return '/'
def visit_Mod(self, node):
return '%'
def visit_LShift(self, node):
return '<<'
def visit_RShift(self, node):
return '>>'
def visit_BitXor(self, node):
return '^'
def visit_BitOr(self, node):
return '|'
def visit_BitAnd(self, node):
return '&'
def visit_Lt(self, node):
return '<'
def visit_Gt(self, node):
return '>'
def visit_GtE(self, node):
return '>='
def visit_LtE(self, node):
return '<='
def visit_In(self, node):
return ' in '
def visit_NotIn(self, node):
return ' not in '
def visit_Not(self, node):
return ' not '
def visit_IsNot(self, node):
return ' is not '
def visit_UnaryOp(self, node):
op = self.visit(node.op)
if op is None: raise RuntimeError( node.op )
operand = self.visit(node.operand)
if operand is None: raise RuntimeError( node.operand )
return op + operand
def visit_USub(self, node):
return '-'
def visit_BoolOp(self, node):
op = self.visit(node.op)
return op.join( [self.visit(v) for v in node.values] )
def visit_BinOp(self, node):
left = self.visit(node.left)
op = self.visit(node.op)
right = self.visit(node.right)
return '(%s %s %s)' % (left, op, right)
def visit_Subscript(self, node):
name = self.visit(node.value)
return '%s[ %s ]' %(name, self.visit(node.slice))
def visit_Assign(self, node):
#assert len(node.targets) == 1
target = node.targets[0]
if isinstance(target, ast.Tuple):
elts = [self.visit(e) for e in target.elts]
code = '%s = %s' % (','.join(elts), self.visit(node.value))
else:
target = self.visit(target)
value = self.visit(node.value)
code = '%s = %s' % (target, value)
writer.write(code)
def visit_AugAssign(self, node):
target = self.visit( node.target )
op = '%s=' %self.visit( node.op )
a = '%s %s %s' %(target, op, self.visit(node.value))
writer.write(a)
def visit_Assert(self, node):
writer.write('assert %s'%self.visit(node.test))
def visit_TryExcept(self, node):
writer.push_block('try')
for n in node.body:
res = self.visit(n)
if res: writer.write( res )
#map(self.visit, node.handlers)
writer.pull_block()
def visit_Raise(self, node):
writer.write('raise %s' % self.visit(node.type))
def visit_Tuple(self, node):
return '(%s)' % ', '.join(map(self.visit, node.elts))
def visit_List(self, node):
return '[%s]' % ', '.join(map(self.visit, node.elts))
def visit_Dict(self, node):
a = []
for i in range( len(node.keys) ):
k = self.visit( node.keys[ i ] )
v = self.visit( node.values[i] )
a.append( '%s:%s'%(k,v) )
b = ','.join( a )
return '{%s}' %b