/
visp.py
195 lines (164 loc) · 6.1 KB
/
visp.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
import collections
import functools
import itertools
import operator
from datatypes import (cons, from_cons, to_cons, ignore, nil, true, false,
Cons, Exact, Inexact, Symbol, Boolean, String)
from lex import lex
from reader import read, read_many
from env import BaseEnv
from util import accumulate, constructor, last
from collections import namedtuple
class Env(BaseEnv):
def __init__(self, bindings={}):
super().__init__(collections.ChainMap(bindings, {
# syntactic forms
'let': syntaxLet,
'lambda': syntaxLambda,
'quote': syntaxQuote,
'exact-number': syntaxExact,
'inexact-number': syntaxInexact,
'set!': syntaxSetBang,
'if': syntaxIf,
'define': syntaxDefine,
'defmacro': syntaxDefmacro,
'macroexpand': syntaxMacroexpand,
# primitive functions
'list': primList,
'cons': primCons,
'+': primPlus,
'-': primMinus,
'*': primTimes,
'/': primDivide,
'print': primPrint,
'null?': primNullQ,
}).new_child())
def load_file(filename, env):
with open(filename) as f:
for expr in read_many(f.read()):
evaluate(expr, env)
def load_prelude(env):
load_file('prelude.visp', env)
def evaluate(form, env):
if isinstance(form, Cons):
return apply(evaluate(form.car, env), form.cdr, env)
return form.eval(env)
@accumulate(last)
def evaluate_many(forms, env):
for form in forms:
yield evaluate(form, env)
def evaluate_seq(body, env):
return evaluate_many(from_cons(body), env)
@accumulate(lambda bs: sum(bs, BaseEnv()))
def match_let(ptrees, args_lists):
for ptree, args in zip(ptrees, args_lists):
yield match(ptree, args)
def match(ptree, args):
if ptree == nil or ptree == ignore:
return BaseEnv()
if isinstance(ptree, Symbol):
return BaseEnv({ ptree.name: args })
if isinstance(ptree, Cons):
return match(ptree.car, args.car) + match(ptree.cdr, args.cdr)
raise NotImplementedError( # pragma: no cover
'Matching against tree not supported: {!r}'.format(ptree))
def apply(combiner, operands, env):
if isinstance(combiner, Macro):
return combiner.apply(operands, env)
return combiner(operands, env)
class Macro(namedtuple('Macro', 'ptree, body, env')):
def apply(self, operands, env):
return evaluate(self.expand(operands), env)
def expand(self, operands):
bindings = match(self.ptree, operands) + self.env
return evaluate_seq(self.body, bindings)
@accumulate('\n'.join)
def to_string(self): # pragma: no cover
for name in ['ptree', 'body', 'env']:
yield '{} == {}'.format(name, getattr(self, name))
class Procedure:
@constructor
def __init__(self, ptree, body, env):
pass
def apply(self, operands, env):
args = to_cons(evaluate(form, env) for form in from_cons(operands))
bindings = match(self.ptree, args) + self.env
return evaluate_seq(self.body, bindings)
def syntaxSetBang(operands, env):
var, form = tuple(from_cons(operands))
result = evaluate(form, env)
var.set(env, result)
return result
def syntaxDefine(operands, env):
var, form = tuple(from_cons(operands))
result = evaluate(form, env)
var.add(env, result)
return result
def syntaxDefmacro(operands, env):
var, ptree, *body = tuple(from_cons(operands))
macro = Macro(ptree, to_cons(body), env)
env.add(var.name, macro)
return macro
def syntaxMacroexpand(operands, env):
macro_name = operands.car.car
macro_args = operands.car.cdr
return macro_name.eval(env).expand(macro_args)
def syntaxLambda(operands, env):
ptree, body = operands.car, operands.cdr
return Procedure(ptree, body, env).apply
def syntaxQuote(operands, env):
return operands.car
def syntaxExact(operands, env):
return operands.car
def syntaxInexact(operands, env):
return Inexact(operands.car.value)
def syntaxLet(operands, env):
binding_pairs = operands.car
body = operands.cdr
ptrees = (x.car for x in from_cons(binding_pairs))
forms = (x.cdr.car for x in from_cons(binding_pairs))
args_lists = [evaluate(form, env) for form in forms]
bindings = match_let(ptrees, args_lists)
return evaluate_seq(body, bindings + env)
def syntaxIf(operands, env):
condform = operands.car
trueform = operands.cdr.car
falseform = operands.cdr.cdr.car
result = evaluate(condform, env)
if result is true:
return evaluate(trueform, env)
else:
return evaluate(falseform, env)
def primArithmetic(operands, env, arith, start):
args = list(evaluate(form, env) for form in from_cons(operands))
values = (arg.value for arg in args)
result = functools.reduce(arith, values, start)
if all(isinstance(arg, Exact) for arg in args):
return Exact(result)
else:
return Inexact(result)
def primArithmetic1(operands, env, arith):
first, *args = list(evaluate(form, env) for form in from_cons(operands))
values = (arg.value for arg in args)
result = functools.reduce(arith, values, first.value)
if all(isinstance(arg, Exact) for arg in itertools.chain((first,), args)):
return Exact(result)
else:
return Inexact(result)
def primPlus(operands, env):
return primArithmetic(operands, env, operator.add, 0)
def primMinus(operands, env):
return primArithmetic1(operands, env, operator.sub)
def primTimes(operands, env):
return primArithmetic(operands, env, operator.mul, 1)
def primDivide(operands, env):
return primArithmetic1(operands, env, operator.truediv)
def primList(operands, env):
return to_cons(evaluate(form, env) for form in from_cons(operands))
# can't unit test I/O
def primPrint(operands, env): # pragma: no cover
print(*(evaluate(form, env) for form in from_cons(operands)))
def primNullQ(operands, env):
return true if evaluate(operands.car, env) == nil else false
def primCons(operands, env):
return Cons(evaluate(operands.car, env), evaluate(operands.cdr.car, env))