Merge branch 'master' into chuck-implementation
[jackhill/mal.git] / process / stepA_mal.txt
1 --- stepA_mal -------------------------------
2 import types, reader, printer, env, core
3
4 READ(str): return reader.read_str(str)
5
6 pair?(ast): return ... // true if non-empty sequence
7 quasiquote(ast): return ... // quasiquote
8
9 macro?(ast, env): return ... // true if macro call
10 macroexpand(ast, env): return ... // recursive macro expansion
11
12 eval_ast(ast,env):
13 switch type(ast):
14 symbol: return env.get(ast)
15 list,vector: return ast.map((x) -> EVAL(x,env))
16 hash: return ast.map((k,v) -> list(k, EVAL(v,env)))
17 _default_: return ast
18
19 EVAL(ast,env):
20 while true:
21 if not list?(ast): return eval_ast(ast, env)
22
23 ast = macroexpand(ast, env)
24 if not list?(ast): return eval_ast(ast, env)
25 if empty?(ast): return ast
26
27 switch ast[0]:
28 'def!: return env.set(ast[1], EVAL(ast[2], env))
29 'let*: env = ...; ast = ast[2] // TCO
30 'quote: return ast[1]
31 'quasiquote: ast = quasiquote(ast[1]) // TCO
32 'defmacro!: return ... // like def!, but set macro property
33 'macroexpand: return macroexpand(ast[1], env)
34 'try*: return ... // try/catch native and malval exceptions
35 'do: ast = eval_ast(ast[1..-1], env)[-1] // TCO
36 'if: EVAL(ast[1], env) ? ast = ast[2] : ast = ast[3] // TCO
37 'fn*: return new MalFunc(...)
38 _default_: f, args = eval_ast(ast, env)
39 if malfunc?(f): ast = f.fn; env = ... // TCO
40 else: return apply(f, args)
41
42 PRINT(exp): return printer.pr_str(exp)
43
44 repl_env = new Env()
45 rep(str): return PRINT(EVAL(READ(str),repl_env))
46
47 ;; core.EXT: defined using Racket
48 core.ns.map((k,v) -> (repl_env.set(k, v)))
49 repl_env.set('eval, (ast) -> EVAL(ast, repl-env))
50 repl_env.set('*ARGV*, cmdline_args[1..])
51
52 ;; core.mal: defined using the language itself
53 rep("(def! *host-language* \"racket\")")
54 rep("(def! not (fn* (a) (if a false true)))")
55 rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
56 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)))))))");
57 rep("(def! *gensym-counter* (atom 0))")
58 rep("(def! gensym (fn* [] (symbol (str \"G__\" (swap! *gensym-counter* (fn* [x] (+ 1 x)))))))")
59 rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) (let* (condvar (gensym)) `(let* (~condvar ~(first xs)) (if ~condvar ~condvar (or ~@(rest xs)))))))))")
60
61 if cmdline_args: rep("(load-file \"" + args[0] + "\")"); exit 0
62
63 rep("(println (str \"Mal [\" *host-language* \"]\"))")
64 main loop:
65 try: println(rep(readline("user> ")))
66 catch e: println("Error: ", e)
67
68 --- env module ----------------------------------
69 class Env (outer=null,binds=[],exprs=[])
70 data = hash_map()
71 foreach b, i in binds:
72 if binds[i] == '&: data[binds[i+1]] = exprs.drop(i); break
73 else: data[binds[i]] = exprs[i]
74 set(k,v): return data.set(k,v)
75 find(k): return data.has(k) ? this : (if outer ? find(outer) : null)
76 get(k): return data.find(k).get(k) OR raise "'" + k + "' not found"
77
78 --- core module ---------------------------------
79 ns = {'=: equal?,
80 'throw: throw,
81
82 'nil?: nil?,
83 'true?: true?,
84 'false?: false?,
85 'string?: string?,
86 'symbol: symbol,
87 'symbol?: symbol?,
88 'keyword: keyword,
89 'keyword?: keyword?,
90
91 'pr-str: (a) -> a.map(|s| pr_str(e,true)).join(" ")),
92 'str: (a) -> a.map(|s| pr_str(e,false)).join("")),
93 'prn: (a) -> println(a.map(|s| pr_str(e,true)).join(" ")),
94 'println: (a) -> println(a.map(|s| pr_str(e,false)).join(" ")),
95 'read-string: read_str,
96 'readline: readline,
97 'slurp read-file,
98
99 '<: lt,
100 '<=: lte,
101 '>: gt,
102 '>=: gte,
103 '+: add,
104 '-: sub,
105 '*: mult,
106 '/: div,
107 'time-ms cur-epoch-millis,
108
109 'list: list,
110 'list?: list?,
111 'vector: vector,
112 'vector?: vector?,
113 'hash-map: hash_map,
114 'map?: hash_map?,
115 'assoc: assoc,
116 'dissoc: dissoc,
117 'get: get,
118 'contains?: contains?,
119 'keys: keys,
120 'vals: vals,
121
122 'sequential? sequential?,
123 'cons: (a) -> concat([a[0]], a[1]),
124 'concat: (a) -> reduce(concat, [], a),
125 'nth: (a) -> a[0][a[1]] OR raise "nth: index out of range",
126 'first: (a) -> a[0][0] OR nil,
127 'rest: (a) -> a[0][1..] OR list(),
128 'empty?: empty?,
129 'count: count,
130 'apply: apply,
131 'map: map,
132
133 'conj: conj,
134 'seq: seq,
135
136 'meta: (a) -> a[0].meta,
137 'with-meta: (a) -> a[0].with_meta(a[1]),
138 'atom: (a) -> new Atom(a[0]),
139 'atom?: (a) -> type(a[0]) == "atom",
140 'deref: (a) -> a[0].val,
141 'reset!: (a) -> a[0].val = a[1],
142 'swap!: swap!}