-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsinterp.py
274 lines (255 loc) · 7.99 KB
/
jsinterp.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
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
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: TRINITI
#
# Created: 17-08-2014
# Copyright: (c) TRINITI 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ply.lex as lex
import ply.yacc as yacc
import jstokens
import jsgrammar
def optimize(tree): # Expression trees only
etype = tree[0]
if etype == "binop":
# Fix this code so that it handles a + ( 5 * 0 )
# recursively! QUIZ!
a = optimize(tree[1])
op = tree[2]
b = optimize(tree[3])
if (op == "*" and b == ("number","1")) or (op == "+" and b == ("number","0")):
return a
if (op == "*" and a == ("number","1")) or (op == "+" and a == ("number","0")):
return b
elif op == "*" and (a == ("number","0") or b == ("number","0")):
return ("number","0")
elif op == '-' and a == b:
return ("number", '0')
elif a[0] == 'number' and b[0] == 'number':
if op == "+":
return ("number", str(float(a[1])+float(b[1])))
if op == "-":
return ("number", str(float(a[1])-float(b[1])))
if op == "*":
return ("number", str(float(a[1])*float(b[1])))
return tree
return tree
##
##print optimize(("binop",("number","5"),"*",("number","1"))) == ("number","5")
##print optimize(("binop",("number","5"),"+",("number","1")))
##print optimize(("binop",("number","5"),"*",("number","0"))) == ("number","0")
##print optimize(("binop",("number","5"),"+",("number","0"))) == ("number","5")
##print optimize(("binop",("number","5"),"+",("binop",("number","5"),"*",("number","0")))) == ("number","5")
def interpret(trees):
global_env = (None, {"javascript output":''})
for elt in trees:
eval_elt(elt, global_env)
return (global_env[1])["javascript output"]
def eval_stmts(stmts,env):
for stmt in stmts:
#print stmts[0]
eval_stmt(stmt,env)
def eval_stmt(tree, environment):
stmttype = tree[0]
#print 'stmt:', stmttype
if stmttype == 'return':
return_exp = tree[1]
retval = eval_exp(return_exp, environment)
raise Exception(retval)
elif stmttype == 'while':
while eval_exp(tree[1], environment):
eval_stmts(tree[2], environment)
elif stmttype == "exp":
eval_exp(tree[1],environment)
elif stmttype == "assign":
# ("assign", "x", ("binop", ..., "+", ...)) <=== x = ... + ...
variable_name = tree[1]
right_child = tree[2]
new_value = eval_exp(right_child, environment)
env_update(environment, variable_name, new_value)
elif stmttype == 'var':
vname = tree[1]
rhs = tree[2]
environment[1][vname] = eval_exp(rhs, environment)
elif stmttype == "if-then-else": # if x < 5 then A;B; else C;D;
conditional_exp = tree[1] # x < 5
then_stmts = tree[2] # A;B;
else_stmts = tree[3] # C;D;
if eval_exp(conditional_exp, environment):
eval_stmts(then_stmts, environment)
else:
eval_stmts(else_stmts, environment)
#add_to_env(environment, fname, fvalue)
elif stmttype == "if-then": # if x < 5 then A;B; else C;D;
conditional_exp = tree[1] # x < 5
then_stmts = tree[2] # A;B;
if eval_exp(conditional_exp, environment):
eval_stmts(then_stmts, environment)
else:
print "ERROR: unknown statement type ",
print stmttype
def eval_elt(tree, env):
elttype = tree[0]
#print 'elt: ', elttype
if elttype == 'function':
fname = tree[1]
fparams = tree[2]
fbody = tree[3]
fvalue = ('function', fparams, fbody, env)
env[1][fname] = fvalue
elif elttype == 'stmt':
eval_stmt(tree[1], env)
else:
print 'ERROR: eval_elt: unkown element ' + elt
def eval_exp(exp, env):
etype = exp[0]
#print 'exp:', etype
if etype == "number":
return float(exp[1])
elif etype == "string":
return exp[1]
elif etype == "true":
return True
elif etype == "false":
return False
elif etype == "not":
return not(eval_exp(exp[1], env))
elif etype == 'function':
fparams = exp[1]
fbody = exp[2]
return ("function", fparams, fbody, env)
elif etype == "binop":
a = eval_exp(exp[1], env)
op = exp[2]
b = eval_exp(exp[3], env)
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == "%":
return a%b
elif op == "==":
return a==b
elif op == "<=":
return a<=b
elif op == "<":
return a<b
elif op == ">=":
return a>=b
elif op == ">":
return a>b
elif op == "&&":
return a and b
elif op == "||":
return a or b
else:
print "ERROR: unknown binary operator ",
print op
exit(1)
elif etype == 'identifier':
vname = exp[1]
value = env_lookup(vname,env)
if value == None:
print "ERROR: unbound variable " + vname
else:
return value
elif etype == 'call':
fname = exp[1]
args = exp[2]
if fname == 'write':
#print 'met write'
argval = eval_exp(args[0], env)
output_sofar = env_lookup("javascript output", env)
env_update(env, "javascript output", output_sofar + '\n'+str(argval))
return None
fvalue = env_lookup(fname, env)
if fvalue[0] == "function":
# ("function", params, body, env)
fparams = fvalue[1]
fbody = fvalue[2]
fenv = fvalue[3]
if len(fparams) != len(args):
print "ERROR: wrong number of args", fname
else:
#QUIZ: Make a new environment frame
new_env = (fenv, {})
for i in range(len(fparams)):
new_env[1][fparams[i]] = eval_exp(args[i], env)
try:
eval_stmts(fbody, new_env)
# QUIZ : Evaluate the body
return None
except Exception as return_value:
return return_value
else:
print "ERROR: call to non-function"
else:
print 'ERROR: unknown expression type ',
print etype
return None
def env_lookup(vname, env):
if vname in env[1]:
return (env[1])[vname]
elif env[0] == None:
return None
else:
return env_lookup(vname, env[0])
def env_update(env, vname, value):
if vname in env[1]:
env[1][vname] = value
elif not env[0] == None:
env_update(vname, value, env[0])
def make_exception():
try:
print "joseph"
y = 1/0
raise Exception(22)
print 'heller'
except Exception as problem:
print "didn't work: we caught"
print problem
##sqrt = ("function",("x"),(("return",("binop",("identifier","x"),"*",("identifier","x"))),),{})
##environment = (None,{"sqrt":sqrt})
##print eval_stmt(("call","sqrt",[("number","2")]),environment)
def get_tree(jstext):
jslexer = lex.lex(module = jstokens)
jsparser = yacc.yacc(module=jsgrammar)
jstree = jsparser.parse(jstext, lexer=jslexer)
return jstree
jslexer = lex.lex(module=jstokens)
def test_lexer(input_string):
jslexer.input(input_string)
result = [ ]
while True:
tok = jslexer.token()
if not tok: break
result = result + [tok.type]
return result
jstext1 = """
function sqrt(x){
return x*x;
}
write(sqrt(2));
"""
jstext2 = """
var x = 2;
x = 5;
write(x+3);
var y = function(q){return(q*q);};
write(y(x));
"""
jstext = """
var x = 5;
while (x > 0){
write(x);
x = x - 1;
};
"""
jstree = get_tree(jstext)
print jstree
print interpret(jstree)