forked from amitsaha/PythonCompilerWorkbench
-
Notifications
You must be signed in to change notification settings - Fork 1
/
backend.py
executable file
·63 lines (48 loc) · 1.61 KB
/
backend.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
# Created by Philip Guo on 2013-12-03, with help from Kyle Murray
# to invoke, run 'python backend.py'
# and visit http://localhost:8080/index.html
#
# external dependencies: bottle, pydot, GraphViz executable
#
# easy_install pip
# pip install bottle
# pip install pydot
import ast
import byteplay
import json
from bottle import route, get, request, run, template, static_file
from bottle import default_app, redirect
from pg_astmonkey import PGGraphvizCreator
from ast_extents import CodeAst
app = default_app()
@route('/')
def main():
redirect('/index.html')
@route('/<filepath:path>')
def index(filepath):
return static_file(filepath, root='.')
@get('/compile')
def get_compile():
source_code = request.query.program
# empty
if not source_code.strip():
return json.dumps({'status': 'success',
'ast_svg': '',
'bytecode_str': ''})
try:
obj = CodeAst(source_code)
node = obj.get_ast()
g = PGGraphvizCreator(node)
ast_svg = g.graph.create_svg()
codeobject = compile(node, '<string>', 'exec')
c = byteplay.Code.from_code(codeobject)
bytecode_str = str(c.code)
ast_json = obj.to_renderable_json()
return json.dumps({'status': 'success',
'ast_svg': ast_svg,
'ast_json': ast_json,
'bytecode_str': bytecode_str})
except SyntaxError:
return json.dumps({'status': 'error', 'data': 'SyntaxError'})
if __name__ == "__main__":
run(host='localhost', port=8080, reloader=True, debug=True)