-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.py
More file actions
266 lines (208 loc) · 5.18 KB
/
interpreter.py
File metadata and controls
266 lines (208 loc) · 5.18 KB
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
import re
import sys
from decimal import Decimal
from inspect import isfunction
from lex import tokenize
from parse import parse
class Symbol(str): pass
class Namespace(dict):
'''
A namespace is a dictionary of (symbol, definition) pairs,
with an optional parent namespace.
'''
def __init__(self, d, p=None):
self.p = p
self.update(d)
def find(self, s):
'''
Find the innermost namespace in which a given symbol
is defined.
'''
if s in self: return self
elif self.p is None: raise LookupError(s)
else: return self.p.find(s)
class Procedure(object):
'''
An instance of a Tali procedure, consisting of
parameters, expression, and namespace.
'''
def __init__(self, ks, e, n):
self.ks, self.e, self.n = ks, e, n
def __call__(self, *vs):
return eval(self.e, Namespace(ks, vs, self.n))
namespaces = {}
current = 'core'
# TODO: finish
def define(n, p, f, ns=current, nss=namespaces):
'''
Given a function name, parameters, and body, as well
as a namespace and a namespace collection, define
the respective function within the namespace within
the collection.
'''
nss[ns][n] = {
'p': p,
'f': f
}
def bind(k, v, ns=current, nss=namespaces):
nss[ns][k] = v
return v
def index(k, ns=current, nss=namespaces):
return nss[ns][k]
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def floordiv(a, b):
return a // b
def truediv(a, b):
return a / b
def gt(a, b):
return a > b
def lt(a, b):
return a < b
def gte(a, b):
return a >= b
def lte(a, b):
return a <= b
def eq(a, b):
return a == b
# TODO: Want to be able to declare some namespaces immutable
# TODO: Want to return this value as a function
core = Namespace({
'def': {
'p': ['n', 'p', 'f'],
'f': define
},
'bnd': {
'p': ['k', 'p', 'f'],
'f': bind
},
'idx': {
'p': ['n', 'p', 'f'],
'f': bind
},
'+': {
'p': ['a', 'b'],
'f': add
},
'-': {
'p': ['a', 'b'],
'f': sub
},
'*': {
'p': ['a', 'b'],
'f': mul
},
'//': {
'p': ['a', 'b'],
'f': floordiv
},
'/': {
'p': ['a', 'b'],
'f': truediv
},
'>': {
'p': ['a', 'b'],
'f': gt
},
'<': {
'p': ['a', 'b'],
'f': lt
},
'>=': {
'p': ['a', 'b'],
'f': gte
},
'<=': {
'p': ['a', 'b'],
'f': lte
},
'=': {
'p': ['a', 'b'],
'f': eq
}
})
# TODO: This construction should be returned via a function
# rather than sitting here, so that I can grab them and
# call eval in other contexts as well
namespaces['core'] = core
isa = isinstance
# TODO: Make tail-recursive
def eval(t, ns=current, nss=namespaces):
'''
Tail-recursive evaluation of an parse tree in a given
environment.
'''
while True:
# atom
if not isa(t, dict):
if re.match('[0-9]+', t):
return int(t)
elif re.match('[0-9]+\.[0-9]+', t):
return Decimal(t)
elif re.match('\"\S\"', t):
return str(t[1:-1])
else:
return nss[ns].find(t)[t]
# Auto-quoted dictionary
elif '@' not in t:
return t
# TODO: if q is an atom, then this is really
# returning a string. The distinction should be
# enforced more strongly to prevent this being
# abused.
elif t['@'] == 'quote':
return t['q']
# (@: if
# p: ...
# t: ...
# f: ...)
elif t['@'] == 'if':
pre = t['p']
con = t['t']
alt = t['f']
t = con if eval(pre, ns, nss) else alt
# (@: ...)
else:
d = nss[ns][t['@']]
args = {}
for p in d['p']:
print(p) # n
print(t[p]) # add3
args[p] = eval(t[p])
ctx = Namespace(d=args, p=ns)
if callable(d['f']):
return d['f'](**args)
return eval(d['f'], ctx, nss)
def shortform(t):
'''
Given a parse tree, return its canonical stringified
short-form
'''
pass
def longform(t):
'''
Given a parse tree, return its canonical stringified
long-form
'''
pass
# TODO: Arrow through REPL history. Requires intercepting
# arrow keys from stdin.
def repl(p='\n> ', i=sys.stdin, o=sys.stdout):
'''
Given a stream of parse trees, evaluate each,
and return the result.
'''
sys.stderr.write('(…) Tali (α) ')
ts=parse(tokenize(i))
while True:
if p: print(p, end='', flush=True)
t = next(ts)
r = eval(t)
print(t, flush=True)
print(r, flush=True)
if __name__ == '__main__':
repl(i=sys.stdin)