-
Notifications
You must be signed in to change notification settings - Fork 1
/
interp_Llambda.py
57 lines (50 loc) · 1.64 KB
/
interp_Llambda.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
from ast import *
from interp_Lfun import InterpLfun, Function
from utils import *
class ClosureTuple:
__match_args__ = ("args", "arity")
def __init__(self, args, arity):
self.args = args
self.arity = arity
def __repr__(self):
return 'ClosureTuple(' + repr(self.args) + ', ' + repr(self.arity) + ')'
def __getitem__(self, item):
return self.args[item]
def __setitem__(self, item, value):
self.args[item] = value
class InterpLlambda(InterpLfun):
def arity(self, v):
match v:
case Function(name, params, body, env):
return len(params)
case ClosureTuple(args, arity):
return arity
case _:
raise Exception('Llambda arity unexpected ' + repr(v))
def interp_exp(self, e, env):
match e:
case Call(Name('arity'), [fun]):
f = self.interp_exp(fun, env)
return self.arity(f)
case Uninitialized(ty):
return None
case FunRef(id, arity):
return env[id]
case Lambda(params, body):
return Function('lambda', params, [Return(body)], env)
case Closure(arity, args):
return ClosureTuple([self.interp_exp(arg, env) for arg in args], arity)
case AllocateClosure(length, typ, arity):
array = [None] * length
return ClosureTuple(array, arity)
case _:
return super().interp_exp(e, env)
def interp_stmts(self, ss, env):
if len(ss) == 0:
return
match ss[0]:
case AnnAssign(lhs, typ, value, simple):
env[lhs.id] = self.interp_exp(value, env)
return self.interp_stmts(ss[1:], env)
case _:
return super().interp_stmts(ss, env)