-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.py
179 lines (134 loc) · 4.17 KB
/
interpreter.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
from compiler_studies.no_loop import scanner
from compiler_studies.no_loop import ast_parser as parser
def eval(ast, env):
if isinstance(ast, parser.Stmts):
for stmt in ast.stmts:
if isinstance(stmt, parser.Return):
return eval(stmt.expr, env)
# We can return from a if-else block
elif isinstance(stmt, parser.IfElse):
ret = eval(stmt, env)
if ret is not None:
return ret
else:
eval(stmt, env)
elif isinstance(ast, parser.ASTNode):
return eval_astnode(ast, env)
elif isinstance(ast, parser.VarLookup):
return env.lookup(ast.value)
elif isinstance(ast, parser.Num):
return int(ast.value)
elif isinstance(ast, parser.String):
return ast.value
elif isinstance(ast, parser.IfElse):
return eval(ast.cons, env) if eval(ast.cond, env) else eval(ast.alt, env)
elif isinstance(ast, parser.LambDef):
return Function(ast.args, ast.body, env)
elif isinstance(ast, parser.FunCall):
return apply(ast, env)
def eval_astnode(ast, env):
left, right = ast.children
if ast.type == '=':
env[left.value] = eval(right, env)
return env[left.value]
elif ast.type == '+':
return eval(left, env) + eval(right, env)
elif ast.type == '-':
return eval(left, env) - eval(right, env)
elif ast.type == '*':
return eval(left, env) * eval(right, env)
elif ast.type == '/':
return eval(left, env) / eval(right, env)
elif ast.type == '==':
return eval(left, env) == eval(right, env)
elif ast.type == '>=':
return eval(left, env) >= eval(right, env)
elif ast.type == '<=':
return eval(left, env) <= eval(right, env)
def apply(ast, env):
fun = eval(ast.expr, env)
args = [eval(a, env) for a in ast.args]
if isinstance(fun, NativeFunction):
return fun.callable(*args)
if len(fun.args) != len(ast.args):
raise RuntimeError('Wrong number of arguments for {}'.format(ast.name))
# Augment function environment with arguments
new_env = Env(fun.env, **{
name: value
for (name, value) in zip(fun.args, args)
})
ret = eval(fun.body, new_env)
if ret is None:
raise RuntimeError('Missing return statement in {}'.format(ast.name))
return ret
class Function:
def __init__(self, args, body, env):
self.args = args
self.body = body
self.env = env
def __repr__(self):
return '<Function>'
class NativeFunction:
def __init__(self, name, callable):
self.name = name
self.callable = callable
class Env(dict):
def __init__(self, parent=None, **kwargs):
super().__init__(**kwargs)
self.parent = parent
def lookup(self, name):
if name in self:
return self[name]
elif self.parent is not None:
return self.parent.lookup(name)
else:
raise Exception('{} is not defined'.format(name))
def __repr__(self):
has_parent = 'Yes' if self.parent is not None else 'No'
return '<Env has_parent={} {}>'.format(has_parent, super().__repr__())
def main():
global_env = Env(
print=NativeFunction('print', print),
)
prog = '''
fib = \(n) {
if n <= 1 {
return 1
} else {
return fib(n-1) + fib(n-2)
}
}
print('The result is:', fib(5))
'''
# Check that functions are really first class citizens
#prog = '''
# a = \() {
# b = 1
# return \() { return b + 2 }
# }
# print(a()())
#'''
#prog = '''
#inc = \(n) {
# next = n + 1
# return next
#}
#print(inc(1))
#'''
prog = '''
a = 1
make_inc = \(n) {
a = n
return \() {
return a + 1
}
}
print(make_inc(1)())
print(a)
'''
stream = parser.Stream(scanner.scan(prog))
ast = parser.parse(stream)
res = eval(ast, global_env)
print(global_env)
if __name__ == '__main__':
main()