forked from hackyourlife/orakel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lisp.py
520 lines (451 loc) · 11.9 KB
/
lisp.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# -*- coding: utf-8 -*-
# vim:set ts=8 sts=8 sw=8 tw=80 noet cc=80:
import re
WHITESPACE = [' ', '\r', '\n', '\t']
class Identifier(object):
def __init__(self, name):
self.name = name
def __call__(self):
return self.name
def __str__(self):
return self.name
def __repr__(self):
return self.name
class Function(object):
def __init__(self, name, args, code):
self.name = name
self.args = args
self.code = code
def __str__(self):
def fmt(x, top=True):
if type(x) == str:
return '"%s"' % x
if type(x) == list:
if top:
return " ".join([ fmt(c, False) for c in x ])
return "(%s)" % " ".join([ fmt(c, False) for c in x ])
return str(x)
prefix = "defun %s" % self.name if not self.name is None \
else "lambda"
return "(%s (%s) %s)" % (prefix, \
" ".join([ str(a) for a in self.args]),
fmt(self.code))
def __repr__(self):
return self.__str__()
class Context(object):
def __init__(self, parent={}):
self.parent = parent
self.overlay = {}
def __getitem__(self, key):
if key in self.overlay:
return self.overlay[key]
return self.parent[key]
def __setitem__(self, key, value):
self.parent[key] = value
def __contains__(self, key):
return key in self.overlay or key in self.parent
def __iter__(self):
merged = self.concat()
return merged.__iter__()
def set(self, key, value):
self.overlay[key] = value
def concat(self):
v = { key: self.parent[key] for key in self.parent }
for key in self.overlay:
v[key] = self.overlay[key]
return v
def __str__(self):
return str(self.concat())
def __repr__(self):
return self.__str__()
def print_stdout(x):
print(x)
def set_print_function(x):
global print_stdout
print_stdout = x
def parse(text):
ast = []
i = 0
l = len(text)
def is_float(x):
try:
float(x)
return True
except ValueError:
return False
def is_integer(x):
try:
int(x)
return True
except ValueError:
return False
def parse_lisp_internal(text):
global WHITESPACE
v = []
isstr = False
bol = True
escape = False
l = len(text)
txt = []
def append():
nonlocal v, txt
if len(txt) > 0:
t = "".join(txt)
if is_integer(t):
v += [ int(t) ]
elif is_float(t):
v += [ float(t) ]
else:
v += [ Identifier(t) ]
txt = []
i = 0
while True:
c = text[i]
if bol:
if c == '(':
bol = False
elif isstr:
if c == '\\':
escape = True
elif (c == '"') and (not escape):
isstr = False
v += [ "".join(txt) ]
txt = []
else:
escape = False
txt += [ c ]
elif c in WHITESPACE:
append()
elif c == '"':
isstr = True
elif c == '(':
append()
z, d = parse_lisp_internal(text[i:])
v += [ z ]
i += d
elif c == ')':
append()
return v, i
else:
txt += [ c ]
i += 1
if i >= l:
raise SyntaxError("missing ')'")
while True:
code = text[i:]
if not '(' in code: # no more expressions
for c in code:
if not c in WHITESPACE:
raise SyntaxError("unexpected '%c'" % c)
return ast
tree, end = parse_lisp_internal(code)
ast += [ tree ]
i += end + 1
if i >= l:
return ast
def do_add(context, *args):
v = lisp_eval(context, args[0])
for arg in args[1:]:
v += lisp_eval(context, arg)
return v
def do_sub(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a - b
def do_mul(context, *args):
p = lisp_eval(context, args[0])
for arg in args[1:]:
p *= lisp_eval(context, arg)
return p
def do_div(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a / b
def do_mod(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a % b
def do_inc(context, x):
return lisp_eval(context, x) + 1
def do_dec(context, x):
return lisp_eval(context, x) - 1
def do_lt(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a < b
def do_gt(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a > b
def do_le(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a <= b
def do_ge(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a >= b
def do_eq(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a == b
def do_not(context, x):
return not lisp_eval(context, x)
def do_and(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a and b
def do_or(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a or b
def do_xor(context, a, b):
a = lisp_eval(context, a)
b = lisp_eval(context, b)
return a ^ b
def do_if(context, test, when, otherwise):
c = lisp_eval(context, test)
if c:
return lisp_eval(context, when)
else:
return lisp_eval(context, otherwise)
def do_when(context, test, when):
c = lisp_eval(context, test)
if c:
return lisp_eval(context, when)
return None
def do_let(context, variables, *methods):
ctx = Context(context)
overlay = {}
for var in variables:
if type(var) != list:
raise SyntaxError("list expected")
if len(var) != 2:
raise SyntaxError("exactly two token required")
if type(var[0]) != Identifier:
raise SyntaxError("identifier expected")
overlay[var[0].name] = lisp_eval(ctx, var[1])
ctx.overlay = overlay
return lisp_run(ctx, methods)
def do_defun(context, name, args, *content):
if type(name) != Identifier:
raise SyntaxError("identifier expected")
context[name.name] = Function(name, args, list(content))
def do_defconstant(context, name, value):
if type(name) != Identifier:
raise SyntaxError("identifier expected")
context[name.name] = lisp_eval(context, value)
def do_set(context, name, value):
if type(name) != Identifier:
raise SyntaxError("identifier expected")
context[name.name] = lisp_eval(context, value)
def do_lambda(context, args, *content):
return Function(None, args, list(content))
def do_funcall(context, function, *args):
function = lisp_eval(context, function)
a = [ lisp_eval(context, x) for x in args ]
return lisp_run_function(context, function, *a)
def do_list(context, *values):
return [ lisp_eval(context, value) for value in values ]
def do_dict(context, *values):
v = {}
for entry in values:
if type(entry) != list:
raise SyntaxError("list expected")
if len(entry) != 2:
raise SyntaxError("exactly two token required")
v[lisp_eval(context, entry[0])] = lisp_eval(context, entry[1])
return v
def do_put(context, data, key, value):
d = lisp_eval(context, data)
k = lisp_eval(context, key)
v = lisp_eval(context, value)
d[k] = v
return d
def do_get(context, string, index):
s = lisp_eval(context, string)
i = lisp_eval(context, index)
return s[i]
def do_regex(context, regex):
return re.compile(lisp_eval(context, regex))
def do_search(context, regex, text):
return re.search(lisp_eval(context, regex), lisp_eval(context, text))
def do_method(context, method, obj, *args):
method = lisp_eval(context, method)
if type(method) != str:
raise SyntaxError("need string for method name")
obj = lisp_eval(context, obj)
a = [ lisp_eval(context, arg) for arg in args ]
return getattr(obj, method)(*a)
def do_progn(context, *expressions):
r = None
for expression in expressions:
r = lisp_eval(context, expression)
return r
def do_substr(context, string, start, stop=None):
s = lisp_eval(context, string)
if stop == None:
return s[start:]
return s[start:stop]
def do_sprintf(context, *args):
if len(args) > 1:
values = [ lisp_eval(context, arg) for arg in args ]
return values[0] % tuple(values[1:])
else:
return args[0]
def do_print(context, *args):
print_stdout(*[ lisp_eval(context, arg) for arg in args ])
def do_printf(context, *args):
if len(args) > 1:
values = [ lisp_eval(context, arg) for arg in args ]
print_stdout(values[0] % tuple(values[1:]))
else:
print_stdout(*args)
def lisp_run_function(context, function, *args):
signature = function.args
replacements = { signature[i].name: lisp_eval(context, args[i]) \
for i in range(len(signature)) }
ctx = Context(context)
ctx.overlay = replacements
return lisp_run(ctx, function.code)
methods = {
'+': do_add,
'-': do_sub,
'*': do_mul,
'/': do_div,
'mod': do_mod,
'1+': do_inc,
'1-': do_dec,
'<': do_lt,
'>': do_gt,
'=': do_eq,
'<=': do_le,
'>=': do_ge,
'not': do_not,
'and': do_and,
'or': do_or,
'xor': do_xor,
'&': do_and,
'|': do_or,
'^': do_xor,
'if': do_if,
'when': do_when,
'let': do_let,
'defun': do_defun,
'defconstant': do_defconstant,
'set': do_set,
'lambda': do_lambda,
'funcall': do_funcall,
'list': do_list,
'dict': do_dict,
'put': do_put,
'get': do_get,
'regex': do_regex,
'search': do_search,
'method': do_method,
'progn': do_progn,
'substr': do_substr,
'sprintf': do_sprintf,
'print': do_print,
'printf': do_printf
}
default_variables = {
'true': True,
'false': False,
'nil': None
}
def create_default_context():
global default_variables
return Context({ key: default_variables[key] \
for key in default_variables })
def lisp_call(context, method, *args):
global methods
if type(method) == Function:
return lisp_run_function(context, method, *args)
elif method in context:
return lisp_run_function(context, context[method], *args)
elif method in methods:
return methods[method](context, *args)
raise NameError("undefined method '%s'" % method)
def lisp_run_expr(context, expression):
#print("EXEC[%s]" % expression)
if type(expression) != list:
raise SyntaxError("can only execute list")
if len(expression) < 1:
raise SyntaxError("non empty list expected")
if type(expression[0]) != Identifier:
raise SyntaxError("identifier expected")
method = expression[0].name
args = [ context, method ]
if len(expression) > 1:
args += expression[1:]
return lisp_call(*args)
def lisp_eval(context, expression):
if type(expression) == list:
return lisp_run_expr(context, expression)
elif type(expression) == int or type(expression) == float \
or type(expression) == str:
return expression
elif type(expression) == Identifier:
return context[expression.name]
elif type(expression) == Function:
return lisp_call(context, *expression)
raise SyntaxError("unexpected token type")
def lisp_run(context, ast):
rv = None
for expression in ast:
rv = lisp_eval(context, expression)
return rv
execute = lisp_run
if __name__ == "__main__":
context = create_default_context()
code = r"""
(print "hello, world")
(defun f (x) (printf "hi %s" x))
(defun wtf () (print "wtf?!"))
(wtf)
(f "tester")
(printf "Value: %s" (+ 1 2 0.5))
(printf "%d" (1+ 5))
(let ((x 7) (y 8)) (printf "x = %d" x) (printf "y = %d" y))
(defconstant +year-size+ 365)
(defun birthday-paradox (probability number-of-people)
(let ((new-probability (* (/ (- +year-size+ number-of-people)
+year-size+)
probability)))
(if (< new-probability 0.5)
(1+ number-of-people)
(birthday-paradox new-probability (1+ number-of-people)))))
(printf "birthday-paradox = %s" (birthday-paradox 1.0 1))
(printf "progn = %s" (progn (print "hello, world") (print "it works") 5 (+ 1 2)))
(printf "%s" (lambda (x y) (+ x y)))
(funcall (lambda (x y) (printf "%d + %d = %d" x y (+ x y))) 2 3)
(printf "%d" (funcall (lambda (x y) (* x y) (+ x y)) 2 3))
(printf "[3] = '%c'" (get "hello" 3))
(printf "a \"quote\"")
(printf "sprintf says: '%s'" (sprintf "x = %d" 7))
(let ((x (dict
("abc" 21)
("def" 13))))
(progn
(put x "a" "b")
(put (put x "x" "y") "r" 7)
(print x)))
(let ((x (list 19 43 2))) (printf "x[1] = %d" (get x 1)))
(let ((x "Hello, World!") (r (regex "([A-Za-z][a-z]*)")))
(let ((match (method "match" r x)))
(printf "does it match? %s" (if match "yes" "no"))
(when match
(printf "the match: %s" (method "group" match 1))))
)
"""
ast = parse(code)
execute(context, ast)
try:
ast = parse("((bla)")
except SyntaxError as e:
print("Error 1: %s" % e)
try:
ast = parse("(bla))")
except SyntaxError as e:
print("Error 2: %s" % e)