ts: defmacro! doesn't modify existing functions
[jackhill/mal.git] / impls / ts / step9_try.ts
1 import { readline } from "./node_readline";
2
3 import { Node, MalType, MalString, MalNil, MalList, MalVector, MalHashMap, MalSymbol, MalFunction, isAST, isSeq } from "./types";
4 import { Env } from "./env";
5 import * as core from "./core";
6 import { readStr } from "./reader";
7 import { prStr } from "./printer";
8
9 // READ
10 function read(str: string): MalType {
11 return readStr(str);
12 }
13
14 function starts_with(lst: MalType[], sym: string): boolean {
15 if (lst.length == 2) {
16 let a0 = lst[0]
17 switch (a0.type) {
18 case Node.Symbol:
19 return a0.v === sym;
20 }
21 }
22 return false;
23 }
24
25 function qq_loop(elt: MalType, acc: MalList): MalList {
26 if (elt.type == Node.List && starts_with(elt.list, "splice-unquote")) {
27 return new MalList([MalSymbol.get("concat"), elt.list[1], acc]);
28 } else {
29 return new MalList([MalSymbol.get("cons"), quasiquote(elt), acc]);
30 }
31 }
32
33 function qq_foldr(xs : MalType[]): MalList {
34 let acc = new MalList([])
35 for (let i=xs.length-1; 0<=i; i-=1) {
36 acc = qq_loop(xs[i], acc)
37 }
38 return acc;
39 }
40
41 function quasiquote(ast: MalType): MalType {
42 switch (ast.type) {
43 case Node.Symbol:
44 return new MalList([MalSymbol.get("quote"), ast]);
45 case Node.HashMap:
46 return new MalList([MalSymbol.get("quote"), ast]);
47 case Node.List:
48 if (starts_with(ast.list, "unquote")) {
49 return ast.list[1];
50 } else {
51 return qq_foldr(ast.list);
52 }
53 case Node.Vector:
54 return new MalList([MalSymbol.get("vec"), qq_foldr(ast.list)]);
55 default:
56 return ast;
57 }
58 }
59
60 function isMacro(ast: MalType, env: Env): boolean {
61 if (!isSeq(ast)) {
62 return false;
63 }
64 const s = ast.list[0];
65 if (s.type !== Node.Symbol) {
66 return false;
67 }
68 const foundEnv = env.find(s);
69 if (!foundEnv) {
70 return false;
71 }
72
73 const f = foundEnv.get(s);
74 if (f.type !== Node.Function) {
75 return false;
76 }
77
78 return f.isMacro;
79 }
80
81 function macroexpand(ast: MalType, env: Env): MalType {
82 while (isMacro(ast, env)) {
83 if (!isSeq(ast)) {
84 throw new Error(`unexpected token type: ${ast.type}, expected: list or vector`);
85 }
86 const s = ast.list[0];
87 if (s.type !== Node.Symbol) {
88 throw new Error(`unexpected token type: ${s.type}, expected: symbol`);
89 }
90 const f = env.get(s);
91 if (f.type !== Node.Function) {
92 throw new Error(`unexpected token type: ${f.type}, expected: function`);
93 }
94 ast = f.func(...ast.list.slice(1));
95 }
96
97 return ast;
98 }
99
100 function evalAST(ast: MalType, env: Env): MalType {
101 switch (ast.type) {
102 case Node.Symbol:
103 const f = env.get(ast);
104 if (!f) {
105 throw new Error(`unknown symbol: ${ast.v}`);
106 }
107 return f;
108 case Node.List:
109 return new MalList(ast.list.map(ast => evalMal(ast, env)));
110 case Node.Vector:
111 return new MalVector(ast.list.map(ast => evalMal(ast, env)));
112 case Node.HashMap:
113 const list: MalType[] = [];
114 for (const [key, value] of ast.entries()) {
115 list.push(key);
116 list.push(evalMal(value, env));
117 }
118 return new MalHashMap(list);
119 default:
120 return ast;
121 }
122 }
123
124 // EVAL
125 function evalMal(ast: MalType, env: Env): MalType {
126 loop: while (true) {
127 if (ast.type !== Node.List) {
128 return evalAST(ast, env);
129 }
130 if (ast.list.length === 0) {
131 return ast;
132 }
133
134 ast = macroexpand(ast, env);
135 if (!isSeq(ast)) {
136 return evalAST(ast, env);
137 }
138
139 if (ast.list.length === 0) {
140 return ast;
141 }
142 const first = ast.list[0];
143 switch (first.type) {
144 case Node.Symbol:
145 switch (first.v) {
146 case "def!": {
147 const [, key, value] = ast.list;
148 if (key.type !== Node.Symbol) {
149 throw new Error(`unexpected token type: ${key.type}, expected: symbol`);
150 }
151 if (!value) {
152 throw new Error(`unexpected syntax`);
153 }
154 return env.set(key, evalMal(value, env));
155 }
156 case "let*": {
157 env = new Env(env);
158 const pairs = ast.list[1];
159 if (!isSeq(pairs)) {
160 throw new Error(`unexpected token type: ${pairs.type}, expected: list or vector`);
161 }
162 for (let i = 0; i < pairs.list.length; i += 2) {
163 const key = pairs.list[i];
164 const value = pairs.list[i + 1];
165 if (key.type !== Node.Symbol) {
166 throw new Error(`unexpected token type: ${key.type}, expected: symbol`);
167 }
168 if (!key || !value) {
169 throw new Error(`unexpected syntax`);
170 }
171
172 env.set(key, evalMal(value, env));
173 }
174 ast = ast.list[2];
175 continue loop;
176 }
177 case "quote": {
178 return ast.list[1];
179 }
180 case "quasiquoteexpand": {
181 return quasiquote(ast.list[1]);
182 }
183 case "quasiquote": {
184 ast = quasiquote(ast.list[1]);
185 continue loop;
186 }
187 case "defmacro!": {
188 const [, key, value] = ast.list;
189 if (key.type !== Node.Symbol) {
190 throw new Error(`unexpected token type: ${key.type}, expected: symbol`);
191 }
192 if (!value) {
193 throw new Error(`unexpected syntax`);
194 }
195 const f = evalMal(value, env);
196 if (f.type !== Node.Function) {
197 throw new Error(`unexpected token type: ${f.type}, expected: function`);
198 }
199 return env.set(key, f.toMacro());
200 }
201 case "macroexpand": {
202 return macroexpand(ast.list[1], env);
203 }
204 case "try*": {
205 try {
206 return evalMal(ast.list[1], env);
207 } catch (e) {
208 if (ast.list.length < 3) {
209 throw e;
210 }
211 const catchBody = ast.list[2];
212 if (!isSeq(catchBody)) {
213 throw new Error(`unexpected return type: ${catchBody.type}, expected: list or vector`);
214 }
215 const catchSymbol = catchBody.list[0];
216 if (catchSymbol.type === Node.Symbol && catchSymbol.v === "catch*") {
217 const errorSymbol = catchBody.list[1];
218 if (errorSymbol.type !== Node.Symbol) {
219 throw new Error(`unexpected return type: ${errorSymbol.type}, expected: symbol`);
220 }
221 if (!isAST(e)) {
222 e = new MalString((e as Error).message);
223 }
224 return evalMal(catchBody.list[2], new Env(env, [errorSymbol], [e]));
225 }
226 throw e;
227 }
228 }
229 case "do": {
230 const list = ast.list.slice(1, -1);
231 evalAST(new MalList(list), env);
232 ast = ast.list[ast.list.length - 1];
233 continue loop;
234 }
235 case "if": {
236 const [, cond, thenExpr, elseExrp] = ast.list;
237 const ret = evalMal(cond, env);
238 let b = true;
239 if (ret.type === Node.Boolean && !ret.v) {
240 b = false;
241 } else if (ret.type === Node.Nil) {
242 b = false;
243 }
244 if (b) {
245 ast = thenExpr;
246 } else if (elseExrp) {
247 ast = elseExrp;
248 } else {
249 ast = MalNil.instance;
250 }
251 continue loop;
252 }
253 case "fn*": {
254 const [, params, bodyAst] = ast.list;
255 if (!isSeq(params)) {
256 throw new Error(`unexpected return type: ${params.type}, expected: list or vector`);
257 }
258 const symbols = params.list.map(param => {
259 if (param.type !== Node.Symbol) {
260 throw new Error(`unexpected return type: ${param.type}, expected: symbol`);
261 }
262 return param;
263 });
264 return MalFunction.fromLisp(evalMal, env, symbols, bodyAst);
265 }
266 }
267 }
268 const result = evalAST(ast, env);
269 if (!isSeq(result)) {
270 throw new Error(`unexpected return type: ${result.type}, expected: list or vector`);
271 }
272 const [f, ...args] = result.list;
273 if (f.type !== Node.Function) {
274 throw new Error(`unexpected token: ${f.type}, expected: function`);
275 }
276 if (f.ast) {
277 ast = f.ast;
278 env = f.newEnv(args);
279 continue loop;
280 }
281
282 return f.func(...args);
283 }
284 }
285
286 // PRINT
287 function print(exp: MalType): string {
288 return prStr(exp);
289 }
290
291 const replEnv = new Env();
292 function rep(str: string): string {
293 return print(evalMal(read(str), replEnv));
294 }
295
296 // core.EXT: defined using Racket
297 core.ns.forEach((value, key) => {
298 replEnv.set(key, value);
299 });
300 replEnv.set(MalSymbol.get("eval"), MalFunction.fromBootstrap(ast => {
301 if (!ast) {
302 throw new Error(`undefined argument`);
303 }
304 return evalMal(ast, replEnv);
305 }));
306 replEnv.set(MalSymbol.get("*ARGV*"), new MalList([]));
307
308 // core.mal: defined using the language itself
309 rep("(def! not (fn* (a) (if a false true)))");
310 rep(`(def! load-file (fn* (f) (eval (read-string (str "(do " (slurp f) "\nnil)")))))`);
311 rep(`(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw "odd number of forms to cond")) (cons 'cond (rest (rest xs)))))))`);
312
313 if (typeof process !== "undefined" && 2 < process.argv.length) {
314 replEnv.set(MalSymbol.get("*ARGV*"), new MalList(process.argv.slice(3).map(s => new MalString(s))));
315 rep(`(load-file "${process.argv[2]}")`);
316 process.exit(0);
317 }
318
319 while (true) {
320 const line = readline("user> ");
321 if (line == null) {
322 break;
323 }
324 if (line === "") {
325 continue;
326 }
327 try {
328 console.log(rep(line));
329 } catch (e) {
330 if (isAST(e)) {
331 console.error("Error:", prStr(e));
332 } else {
333 const err: Error = e;
334 console.error("Error:", err.message);
335 }
336 }
337 }