-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsexp.py
434 lines (318 loc) · 10.3 KB
/
sexp.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
from __future__ import annotations
from abc import abstractmethod
from dataclasses import dataclass, field
from typing import (TYPE_CHECKING, Counter, Dict, Iterator, List, Optional,
Sequence, Tuple, Union, cast)
import bytecode
if TYPE_CHECKING:
import bytecode
from scheme_types import TypeTuple
class SExp:
"""An s-expression base class"""
...
class Value(SExp):
"""An s-expression that's a valid run-time object."""
@abstractmethod
def type_name(self) -> SSym:
...
@abstractmethod
def address(self) -> int:
...
@abstractmethod
def to_param(self) -> Optional[bytecode.Parameter]:
...
@dataclass(frozen=True, order=True)
class SNum(Value):
"""A lisp number"""
value: int
def type_name(self) -> SSym:
return SSym('number')
def __str__(self) -> str:
return str(self.value)
def __hash__(self) -> int:
return hash(self.value)
def address(self) -> int:
return self.value
def to_param(self) -> bytecode.NumLit:
return bytecode.NumLit(self)
@dataclass(frozen=True)
class SBool(Value):
"""A lisp boolean"""
value: bool
def type_name(self) -> SSym:
return SSym('bool')
def __str__(self) -> str:
return str(self.value)
def address(self) -> int:
return id(self.value)
def to_param(self) -> bytecode.BoolLit:
return bytecode.BoolLit(self)
@dataclass(frozen=True)
class SSym(Value):
"""A lisp symbol"""
name: str
def type_name(self) -> SSym:
return SSym('symbol')
def __str__(self) -> str:
return self.name
def __hash__(self) -> int:
return hash(self.name)
def address(self) -> int:
return id(self.name)
def to_param(self) -> bytecode.SymLit:
return bytecode.SymLit(self)
@dataclass(frozen=True)
class SVect(Value):
"""An n element vector
>>> vect = SVect([
... SNum(42), SSym('spam'),
... SVect([SNum(43), SNum(44)])
... ])
>>> str(vect)
'[42 spam [43 44]]'
>>>
>>> str(SVect([]))
'[]'
"""
items: List[SExp]
def type_name(self) -> SSym:
return SSym('vector')
def __str__(self) -> str:
return f"[{' '.join(str(i) for i in self.items)}]"
def address(self) -> int:
return id(self.items)
def to_param(self) -> Optional[bytecode.Parameter]:
return None
@dataclass(frozen=True)
class SPair(SExp):
"""A scheme pair.
>>> single_pair = SPair(SNum(42), SSym('spam'))
>>> str(single_pair)
'(42 . spam)'
>>> list(single_pair)
[SNum(value=42), SSym(name='spam')]
>>> nested_pair = SPair(SNum(42), SPair(SSym('egg'), SSym('spam')))
>>> str(nested_pair)
'(42 . (egg . spam))'
>>> list(nested_pair)
[SNum(value=42), SSym(name='egg'), SSym(name='spam')]
>>> s_list = SPair(SNum(42), SPair(SSym('egg'), Nil))
>>> str(s_list)
'(42 egg)'
>>> list(s_list)
[SNum(value=42), SSym(name='egg')]
"""
first: SExp
second: SExp
def is_list(self) -> bool:
if self.second is Nil:
return True
if not isinstance(self.second, SPair):
return False
return self.second.is_list()
def __iter__(self) -> PairIterator:
return PairIterator(self)
def __str__(self) -> str:
if self.is_list():
return f"({' '.join((str(item) for item in self))})"
return f"({str(self.first)} . {str(self.second)})"
@dataclass(frozen=True)
class Quote(SExp):
"""A quoted expression"""
expr: SExp
def __str__(self) -> str:
return f"'{str(self.expr)}"
class PairIterator:
def __init__(self, pair: SPair):
self._expr: SExp = pair
def __next__(self) -> SExp:
if self._expr is Nil:
raise StopIteration
if not isinstance(self._expr, SPair):
val = self._expr
self._expr = Nil
return val
val = self._expr.first
self._expr = self._expr.second
return val
def __iter__(self) -> PairIterator:
return self
class NilType(SExp):
def __iter__(self) -> NilIterator:
return self.NilIterator()
class NilIterator:
def __next__(self) -> SExp:
raise StopIteration
def __iter__(self) -> NilType.NilIterator:
return self
def __str__(self) -> str:
return 'Nil'
Nil = NilType()
SList = Union[SPair, NilType]
def to_slist(x: Sequence[SExp]) -> SList:
acc: SList = Nil
for item in reversed(x):
acc = SPair(item, acc)
return acc
def make_bool(x: bool) -> SSym:
"""
Returns a scheme boolean.
>>> make_bool(True)
SSym(name='true')
>>> make_bool(False)
SSym(name='false')
"""
if x:
return SSym('true')
return SSym('false')
@dataclass
class SFunction(Value):
name: SSym
params: List[SSym]
body: SList
code: Optional[bytecode.Function] = None
is_lambda: bool = False
calls: Counter[TypeTuple] = field(default_factory=Counter)
specializations: Dict[TypeTuple, bytecode.Function] = \
field(default_factory=dict)
def type_name(self) -> SSym:
return SSym('function')
def address(self) -> int:
return id(self.code)
def __str__(self) -> str:
params = ''.join(' ' + p.name for p in self.params)
return f"<function ({self.name}{params}) at {id(self):x}>"
def get_specialized(self, types: Optional[TypeTuple]) -> bytecode.Function:
assert self.code
if types is None:
return self.code
return self.specializations.get(types, self.code)
def to_param(self) -> None:
return None
@dataclass(frozen=True)
class SCall(SExp):
func: SExp
args: List[SExp]
@dataclass(frozen=True)
class SConditional(SExp):
test: SExp
then_expr: SExp
else_expr: SExp
@dataclass(frozen=True)
class SBegin(SExp):
exprs: List[SExp]
def parse(x: str) -> List[SExp]:
# Remove line comments. Since we don't have string literals,
# we don't need fancier than this!
x = '\n'.join(l.split(';')[0] for l in x.split('\n'))
tokens = (
x
.replace('(', ' ( ')
.replace(')', ' ) ')
.replace('[', ' [ ')
.replace(']', ' ] ')
.replace("'", " ' ")
.split()
)
lambda_names = lambda_name_generator()
def is_number(x: str) -> bool:
return x.isdecimal() or (x.startswith('-') and x[1:].isdecimal())
def parse(tokens: List[str],
quoted: bool = False) -> Tuple[SExp, List[str]]:
if not tokens:
raise Exception("Parse Error")
elif tokens[0] == "'":
return parse_quote(tokens[1:])
elif tokens[0] == '[':
vector = []
tokens = tokens[1:]
while tokens[0] != ']':
item, tokens = parse(tokens)
vector.append(item)
return SVect(vector), tokens[1:]
elif tokens[0] == '(':
tokens = tokens[1:]
if tokens[0] == ')':
return Nil, tokens[1:]
if quoted:
list_tail, tokens = read_list_tail(tokens)
return to_slist(list_tail), tokens[1:]
parsed_first, tokens = parse(tokens)
if parsed_first == SSym('if'):
return parse_conditional(tokens)
if parsed_first == SSym('begin'):
body, tokens = read_list_tail(tokens)
return SBegin(list(body)), tokens[1:]
if parsed_first == SSym('define'):
return parse_define(tokens)
if parsed_first == SSym('lambda'):
return parse_lambda(tokens)
if parsed_first == SSym('quote'):
quote, tokens = parse_quote(tokens)
return quote, tokens[1:]
return parse_call(parsed_first, tokens)
elif is_number(tokens[0]):
return SNum(int(tokens[0])), tokens[1:]
elif tokens[0] in ('true', 'false'):
return SBool(tokens[0] == 'true'), tokens[1:]
else:
return SSym(tokens[0]), tokens[1:]
def parse_conditional(tokens: List[str]) -> Tuple[SExp, List[str]]:
items, tokens = read_list_tail(tokens)
assert len(items) == 3, 'Missing parts of conditional'
return SConditional(
items[0],
items[1],
items[2]
), tokens[1:]
def parse_define(tokens: List[str]) -> Tuple[SExp, List[str]]:
params, tokens = parse_function_params(tokens)
assert len(params) >= 1, 'Missing function name'
body, tokens = read_list_tail(tokens)
return SFunction(
params[0],
params[1:],
to_slist(body)
), tokens[1:]
def parse_lambda(tokens: List[str]) -> Tuple[SExp, List[str]]:
params, tokens = parse_function_params(tokens)
body, tokens = read_list_tail(tokens)
return SFunction(
SSym(next(lambda_names)),
params,
to_slist(body),
is_lambda=True
), tokens[1:]
def parse_function_params(
tokens: List[str]) -> Tuple[List[SSym], List[str]]:
formals: List[SSym] = []
assert tokens[0] == '(', 'Expected parameter list'
tokens = tokens[1:]
expr_list, tokens = read_list_tail(tokens)
for item in expr_list:
assert isinstance(item, SSym), 'Expected a symbol'
formals.append(item)
return formals, tokens[1:]
def parse_call(func: SExp,
tokens: List[str]) -> Tuple[SExp, List[str]]:
args, tokens = read_list_tail(tokens)
return SCall(func, args), tokens[1:]
def parse_quote(tokens: List[str]) -> Tuple[SExp, List[str]]:
quoted, tokens = parse(tokens, quoted=True)
return Quote(quoted), tokens
def read_list_tail(tokens: List[str]) -> Tuple[List[SExp], List[str]]:
items = []
while tokens[0] != ')':
item, tokens = parse(tokens)
items.append(item)
return items, tokens
results = []
while tokens:
result, tokens = parse(tokens)
results.append(result)
return results
def lambda_name_generator() -> Iterator[str]:
n = 0
while True:
yield f'__lambda{n}'
n += 1