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 | TOKENS = {
"left": "(",
"right": ")",
"comment": ";",
"left_comment": "/*",
"right_comment": "*/"
}
class Procedure(object):
def __init__(self, params, body, envi):
for elem in params:
require(isinstance(elem, list), SyntaxError, "Missing brace arround argument '%s'" % elem)
self.params, self.body, self.env = params, body, envi
def __call__(self, *args):
return eval_code(self.body, Env(self.params, args, self.env))
class Env(dict):
def __init__(self, parms=(), args=(), outer=None):
super().__init__(self)
self.outer = outer
try:
self.update(dict(parms))
parms_keys = tuple(dict(parms).keys())
except ValueError:
parms_keys = tuple([i[0] for i in parms])
self.update(zip(parms_keys, args))
def __xor__(self, other):
new = Env()
for key in other:
if key not in self:
new[key] = other[key]
return new
def __and__(self, other):
new = Env()
for key in other:
if key in self and key in other:
new[key] = self[key]
return new
def __getitem__(self, var):
return dict.__getitem__(self, var) if (var in self) else None
def find(self, var):
require(var in self or self.outer is not None, KeyError, "'%s' does not exist (with type : %s)" % (var, type(var).__name__))
if var in self:
return self[var]
elif self.outer is not None:
return self.outer.find(var)
def op(_op, *x):
require(bool(x), ArithmeticError, "Missing arguments")
require(_op in ("div", "mul", "xor", "or", "and", "mod"), ValueError, "Operation is not listed")
tot = x[0]
for i in x[1:]:
if _op == "div":
tot /= i
elif _op == "mul":
tot *= i
elif _op == "xor":
tot ^= i
elif _op == "or":
tot |= i
elif _op == "and":
tot &= i
elif _op == "mod":
tot %= i
return tot
def create_env():
_env = Env()
_env.update({
"+": lambda *x: sum(x), "-": lambda *x: sum(-i for i in x),
"/": lambda *x: op("div", *x), "*": lambda *x: op("mul", *x),
"%": lambda *x: op("mod", *x), "pow": lambda x, p: x ** p,
"^": lambda *x: op("xor", *x), "|": lambda *x: op("or", *x),
"&": lambda *x: op("and", *x), "~": lambda x: ~x,
">>": lambda x, dc: x >> dc, "<<": lambda x, dc: x << dc,
"symbol": lambda *x: " ".join(x)
})
return _env
def read_from_tokens(tokens):
require(bool(tokens), SyntaxError, "Unexpected EOF while reading")
token = tokens.pop(0)
require(token != TOKENS["right"], SyntaxError, "Unexpected '%s'" % token)
if token == TOKENS["left_comment"]:
while tokens[0] != TOKENS["right_comment"]:
tokens.pop(0)
tokens.pop(0)
token = tokens.pop(0)
if token == TOKENS["left"]:
ast = []
while tokens[0] != end_token:
ast.append(read_from_tokens(tokens))
tokens.pop(0)
return ast
elif token == TOKENS["comment"]:
pass
else:
return atom(token)
def atom(token):
if token == '#t':
return True
elif token == '#f':
return False
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
try:
return complex(token.replace('i', 'j', 1))
except ValueError:
return str(token)
def to_string(x):
if x is True:
return "#t"
elif x is False:
return "#f"
elif isinstance(x, str):
return x
elif isinstance(x, str):
return '"%s"' % x.replace('"', r'\"')
elif isinstance(x, list):
return '(' + ' '.join(map(to_string, x)) + ')'
elif isinstance(x, complex):
return str(x).replace('j', 'i')
else:
return str(x)
def print_schemestr(expr):
if expr:
print(to_string(expr))
def require(expr, err_kind, err_msg):
if not expr:
raise err_kind(err_msg)
def tokenize(code):
for tok in TOKENS.values():
code = code.replace(tok, " %s " % tok)
return code.split(" ")
def parse(code):
tokens = tokenize(code)
parsed = None
if '(' in tokens and ')' in tokens:
parsed = read_from_tokens(tokens)
require(parsed is not None, SyntaxError, "Missing brackets")
return parsed
def evaluate(source, environment):
while True:
if isinstance(x, str):
return env.find(x)
elif not isinstance(x, list):
return x
elif x[0] == "quote":
require(len(x) >= 2, ValueError, "Missing arguments")
(_, *exp) = x
return ' '.join(x)
elif x[0] == "match":
require(len(x) >= 3, ValueError, "Missing arguments")
(_, cond, *patterns) = x
val = evaluate(cond, environment)
for (pattern, new_code) in patterns:
if val == evaluate(pattern, environment):
return evaluate(new_code, environment)
return None
elif x[0] == "lambda":
require(len(x) == 3, ValueError, "Missing arguments")
(_, params, body) = x
return Procedure(params, body, environment)
elif x[0] == "if":
require(3 <= len(x) <= 4, ValueError, "Missing arguments")
if len(x) == 4:
(_, test, conseq, alt) = x
x = conseq if evaluate(test, environment) else alt
elif len(x) == 3:
(_, test, conseq) = x
if evaluate(test, environment):
x = conseq
elif x[0] == "define":
require(len(x) == 3, ValueError, "Missing arguments")
(_, var, *exp) = x
require(var not in environment.keys(), RuntimeError, "Can not overwrite existing variable, use set! instead")
tmp = evaluate(exp, environment)
require(tmp, RuntimeError, "Impossible to create the value")
environment[var] = tmp
return None
elif x[0] == "set!":
require(len(x) == 3, ValueError, "Missing arguments")
(_, var, *exp) = x
require(var in environment.keys(), RuntimeError, "Can not overwrite non existing variable, use define instead")
tmp = evaluate(exp, environment)
require(tmp, RuntimeError, "Impossible to create the value")
environment[var] = tmp
return None
elif x[0] == "begin":
for exp in x[1:]:
evaluate(exp, environment)
x = x[-1]
else:
if not isinstance(environment.find(x[0]), str):
exps = [evaluate(exp, environment) for exp in x]
proc = exps.pop(0)
if isinstance(proc, Procedure):
x = proc.body
env = Env(proc.params, exps, proc.env)
else:
return proc(*exps)
def loop(prompt="ZLang"):
p2_entire_line = "> "
p2_unfinished_line = "' "
code = ""
env = create_env()
while True:
if code.count(TOKENS["left"]) == code.count(TOKENS["right"]):
if not code:
code = input(prompt + p2_entire_line)
try:
print_schemestr(evaluate(parse(code)))
except Exception as exc:
print(type(exc).__name__, ":", exc)
else:
code += "\n" + input(prompt + p2_unfinished_line)
if __name__ == '__main__':
loop()
|