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
|
from parser import Expr
class Function:
def __init__(self, name, params, body, *arities):
self.name = name
self.params = params
self.body = body
if len(arities) == 0:
self.arities = None
else:
self.arities = arities
def call(self, expr, env):
pass
class Builtin(Function):
def __init__(self, callable_, *arities):
super().__init__("<builtin>", None, callable_, *arities)
def call(self, expr, env):
if self.arities is not None and len(expr.args[1:]) not in self.arities:
#if self.arity >= 0 and len(args) != self.arity:
fmt = f"[{self.arities[0]}"
for arity in self.arities[1:]:
fmt += f", {arity}"
fmt += "]"
raise Exception(f"expected {fmt} arguments, received {len(expr.args)}")
return self.body(expr.args[0], expr.args[1:], env)
class UserFunction(Function):
def __init__(self, name, params, body):
super().__init__(name, params, body, len(params))
def call(self, expr, env):
this_env = Environment(env)
for idx, param in enumerate(self.params):
# TODO this is wrong!!! this won't always be a literal
this_env.register(param.name, Expr.Literal(evaluate(expr.args[idx+1],env)))
return interpret(self.body, this_env)
class Environment:
def __init__(self, parent=None):
self.parent = parent
self.environment = {}
def register(self, key, value):
self.environment[key] = value
def contains(self, key):
if key in self.environment:
return True
elif self.parent is not None:
return self.parent.contains(key)
else:
return False
def get(self, key):
if not self.contains(key):
raise Exception(f"undefined symbol: '{key}")
if key in self.environment:
return self.environment[key]
else:
return self.parent.get(key)
def __str__(self):
out = ""
for k, v in self.environment.items():
out += f"{k}: {v}, "
return out
GLOBALS = Environment()
def interpret(exprs, env=GLOBALS):
ret = None
for expr in exprs:
ret = evaluate(expr, env)
return ret
def evaluate(expr, env):
if isinstance(expr, Expr.Literal):
return expr.value
elif isinstance(expr, Expr.Symbol):
if not env.contains(expr.name):
raise Exception(f"no such symbol: {expr}")
return evaluate(env.get(expr.name), env)
#name = expr.symbol.name
if not isinstance(expr.args[0], Expr.Symbol):
raise Exception("can't evaluate without a symbol")
name = expr.args[0].name
if name == "def":
return interpretDef(expr.args[0], expr.args[1:], env)
elif env.contains(name):
return env.get(name).call(expr, env)
else:
raise Exception(f"unable to evaluate: {expr}")
def interpretOr(symbol, args, env):
# or returns true for the first expression that returns true
if len(args) < 2:
raise Exception("'or' has at least two operands")
for arg in args:
ev = evaluate(arg, env)
if ev not in (True, False):
raise Exception("'or' needs boolean arguments")
if ev == True:
return True
return False
GLOBALS.register("or", Builtin(interpretOr))
def interpretAnd(symbol, args, env):
# and returns false for the first expression that returns false
if len(args) < 2:
raise Exception("'and' has at least two operands")
for arg in args:
ev = evaluate(arg, env)
if ev not in (True, False):
raise Exception("'and' needs boolean arguments")
if ev == False:
return False
return True
GLOBALS.register("and", Builtin(interpretAnd))
def interpretEq(symbol, args, env):
# equal
first = evaluate(args[0], env)
second = evaluate(args[1], env)
return first == second
GLOBALS.register("eq?", Builtin(interpretEq, 2))
def interpretComparison(symbol, args, env):
left = evaluate(args[0], env)
if type(left) not in (int, float):
raise Exception("'left' must be a number")
right = evaluate(args[1], env)
if type(right) not in (int, float):
raise Exception("'right' must be a number")
if symbol.name == ">":
return left > right
elif symbol.name == ">=":
return left >= right
elif symbol.name == "<":
return left < right
elif symbol.name == "<=":
return left <= right
GLOBALS.register(">", Builtin(interpretComparison, 2))
GLOBALS.register(">=", Builtin(interpretComparison, 2))
GLOBALS.register("<", Builtin(interpretComparison, 2))
GLOBALS.register("<=", Builtin(interpretComparison, 2))
def interpretTerm(symbol, args, env):
if len(args) < 1:
raise Exception("term has at least one operand")
res = None
for arg in args:
ev = evaluate(arg, env)
if type(ev) not in (int, float):
raise Exception("term must be a number")
if res is None:
res = ev
elif symbol.name == "+":
res += ev
elif symbol.name == "-":
res -= ev
return res
GLOBALS.register("+", Builtin(interpretTerm))
GLOBALS.register("-", Builtin(interpretTerm))
def interpretFactor(symbol, args, env):
if symbol.name == "/":
num = evaluate(args[0], env)
if type(num) not in (int, float):
raise Exception("numerator must be a number")
denom = evaluate(args[1], env)
if type(denom) not in (int, float):
raise Exception("denominator must be a number")
return num / denom # TODO floats and ints
else:
if len(args) < 2:
raise Exception("'*' requires at least two operands")
first = evaluate(args[0], env)
if type(first) not in (int, float):
raise Exception("'*' operand must be a number")
res = first
for arg in args[1:]:
tmp = evaluate(arg, env)
if type(tmp) not in (int, float):
raise Exception("'*' operand must be a number")
res = res * tmp
return res
GLOBALS.register("*", Builtin(interpretFactor))
GLOBALS.register("/", Builtin(interpretFactor, 2))
def interpretNot(symbol, args, env):
res = evaluate(args[0], env)
if res not in (True, False):
raise Exception("'not' only works on booleans")
return not res
GLOBALS.register("not", Builtin(interpretNot, 1))
def interpretIf(symbol, args, env):
# if cond t-branch [f-branch]
cond = evaluate(args[0], env)
if cond not in (True, False):
raise Exception("'if' condition must be boolean")
if cond:
return evaluate(args[1], env)
elif len(args) == 3:
return evaluate(args[2], env)
return None # this shouldn't be reached
GLOBALS.register("if", Builtin(interpretIf, 2, 3))
def interpretPrint(symbol, args, env):
ev = evaluate(args[0], env)
if not isinstance(ev, str):
raise Exception("can only 'print' strings")
print(ev)
return None # print returns nothing
GLOBALS.register("print", Builtin(interpretPrint, 1))
def interpretDef(symbol, args, env):
if not isinstance(args[0], Expr.Symbol):
raise Exception("'def' requires a string literal as a name")
name = args[0].name # NOTE: we are not evaluating the name!!
if not isinstance(name, str):
raise Exception("'def' requires a string literal as a name")
ev = evaluate(args[1], env)
if isinstance(ev, UserFunction):
env.register(name, ev)
else:
env.register(name, args[1])
return None
GLOBALS.register("def", Builtin(interpretDef, 2))
def interpretLambda(symbol, args, env):
if args[0].args[0] != None:
func = UserFunction("<lambda>", args[0].args, args[1:])
else:
func = UserFunction("<lambda>", [], args[1:])
return func
GLOBALS.register("lambda", Builtin(interpretLambda))
def interpretToString(symbol, args, env):
return str(evaluate(args[0], env))
GLOBALS.register("->string", Builtin(interpretToString, 1))
def interpretConcat(symbol, args, env):
# concat str1 str2...strN
if len(args) < 2:
raise Exception("'concat' takes at least two arguments")
out = ""
for arg in args:
tmp = evaluate(arg, env)
if not isinstance(tmp, str):
raise Exception("'concat' arguments must be strings")
out += tmp
return out
GLOBALS.register("concat", Builtin(interpretConcat))
def interpretForCount(symbol, args, env):
# for-count int exprs
num = evaluate(args[0], env)
if type(num) is not int:
raise Exception("'for-count' count must be an integer")
new_env = Environment(env)
ret = None
for idx in range(0, num):
new_env.register("idx", Expr.Literal(idx + 1))
for arg in args[1:]:
ret = evaluate(arg, new_env)
return ret
GLOBALS.register("for-count", Builtin(interpretForCount))
def interpretPipe(symbol, args, env):
if len(args) < 2:
raise Exception("'|' takes at least two expressions")
new_env = Environment(env)
pipe = None
for arg in args:
if pipe is not None:
new_env.register("items", pipe)
pipe = Expr.Literal(evaluate(arg, new_env))
return pipe
GLOBALS.register("|", Builtin(interpretPipe))
def interpretBranch(symbol, args, env):
if len(args) == 0:
raise Exception("'branch' takes at least one expression")
for arg in args:
if len(arg.args) != 2:
raise Exception("'branch' branches have two expressions")
cond = evaluate(arg.args[0], env) # this is the condition
if cond:
return evaluate(arg.args[1], env)
return None
GLOBALS.register("branch", Builtin(interpretBranch))
def interpretFunc(symbol, args, env):
# func <name> (args) (exprs)
if len(args) < 3:
raise Exception("'func' takes a name, arguments, and at least one expression")
if not isinstance(args[0], Expr.Symbol):
raise Exception("'func' requires a string literal as a name")
name = args[0].name # NOTE: we are not evaluating the name!!
# compose a lambda
func = interpretLambda(None, args[1:], env)
env.register(name, func)
return None
GLOBALS.register("func", Builtin(interpretFunc))
|