Implement step 9
[jackhill/mal.git] / crystal / stepA_mal.cr
1 #! /usr/bin/env crystal run
2
3 require "colorize"
4
5 require "./readline"
6 require "./reader"
7 require "./printer"
8 require "./types"
9 require "./env"
10 require "./core"
11 require "./error"
12
13 # Note:
14 # Employed downcase names because Crystal prohibits uppercase names for methods
15
16 module Mal
17 extend self
18
19 def func_of(env, binds, body)
20 -> (args : Array(Mal::Type)) {
21 new_env = Mal::Env.new(env, binds, args)
22 eval(body, new_env)
23 } as Mal::Func
24 end
25
26 def eval_ast(ast, env)
27 return ast.map{|n| eval(n, env) as Mal::Type} if ast.is_a? Array
28
29 val = ast.unwrap
30
31 Mal::Type.new case val
32 when Mal::Symbol
33 if e = env.get(val.str)
34 e
35 else
36 eval_error "'#{val.str}' not found"
37 end
38 when Mal::List
39 val.each_with_object(Mal::List.new){|n, l| l << eval(n, env)}
40 when Mal::Vector
41 val.each_with_object(Mal::Vector.new){|n, l| l << eval(n, env)}
42 when Mal::HashMap
43 new_map = Mal::HashMap.new
44 val.each{|k, v| new_map[k] = eval(v, env)}
45 new_map
46 else
47 val
48 end
49 end
50
51 def read(str)
52 read_str str
53 end
54
55 macro pair?(list)
56 {{list}}.is_a?(Array) && !{{list}}.empty?
57 end
58
59 def quasiquote(ast)
60 list = ast.unwrap
61
62 unless pair?(list)
63 return Mal::Type.new(
64 Mal::List.new << gen_type(Mal::Symbol, "quote") << ast
65 )
66 end
67
68 head = list.first.unwrap
69
70 case
71 # ("unquote" ...)
72 when head.is_a?(Mal::Symbol) && head.str == "unquote"
73 list[1]
74 # (("splice-unquote" ...) ...)
75 when pair?(head) && (arg0 = head.first.unwrap).is_a?(Mal::Symbol) && arg0.str == "splice-unquote"
76 tail = Mal::Type.new list[1..-1].to_mal
77 Mal::Type.new(
78 Mal::List.new << gen_type(Mal::Symbol, "concat") << head[1] << quasiquote(tail)
79 )
80 else
81 tail = Mal::Type.new list[1..-1].to_mal
82 Mal::Type.new(
83 Mal::List.new << gen_type(Mal::Symbol, "cons") << quasiquote(list.first) << quasiquote(tail)
84 )
85 end
86 end
87
88 def macro_call?(ast, env)
89 list = ast.unwrap
90 return false unless list.is_a? Mal::List
91 return false if list.empty?
92
93 sym = list.first.unwrap
94 return false unless sym.is_a? Mal::Symbol
95
96 func = env.find(sym.str).try(&.data[sym.str])
97 return false unless func && func.macro?
98
99 true
100 end
101
102 def macroexpand(ast, env)
103 while macro_call?(ast, env)
104
105 # Already checked in macro_call?
106 list = ast.unwrap as Mal::List
107 func_sym = list[0].unwrap as Mal::Symbol
108 func = env.get(func_sym.str).unwrap
109
110 case func
111 when Mal::Func
112 ast = func.call(list[1..-1])
113 when Mal::Closure
114 ast = func.fn.call(list[1..-1])
115 else
116 eval_error "macro '#{func_sym.str}' must be function: #{ast}"
117 end
118 end
119
120 ast
121 end
122
123 macro invoke_list(l, env)
124 f = eval({{l}}.first, {{env}}).unwrap
125 args = eval_ast({{l}}[1..-1], {{env}}) as Array
126
127 case f
128 when Mal::Closure
129 ast = f.ast
130 {{env}} = Mal::Env.new(f.env, f.params, args)
131 next # TCO
132 when Mal::Func
133 return f.call args
134 else
135 eval_error "expected function as the first argument: #{f}"
136 end
137 end
138
139 def debug(ast)
140 puts print(ast).colorize.red
141 end
142
143 def eval(ast, env)
144 # 'next' in 'do...end' has a bug in crystal 0.7.1
145 # https://github.com/manastech/crystal/issues/659
146 while true
147 return eval_ast(ast, env) unless ast.unwrap.is_a? Mal::List
148
149 ast = macroexpand(ast, env)
150
151 list = ast.unwrap
152
153 return eval_ast(ast, env) unless list.is_a? Mal::List
154 return ast if list.empty?
155
156 head = list.first.unwrap
157
158 return invoke_list(list, env) unless head.is_a? Mal::Symbol
159
160 return Mal::Type.new case head.str
161 when "def!"
162 eval_error "wrong number of argument for 'def!'" unless list.size == 3
163 a1 = list[1].unwrap
164 eval_error "1st argument of 'def!' must be symbol: #{a1}" unless a1.is_a? Mal::Symbol
165 env.set(a1.str, eval(list[2], env))
166 when "let*"
167 eval_error "wrong number of argument for 'def!'" unless list.size == 3
168
169 bindings = list[1].unwrap
170 eval_error "1st argument of 'let*' must be list or vector" unless bindings.is_a? Array
171 eval_error "size of binding list must be even" unless bindings.size.even?
172
173 new_env = Mal::Env.new env
174 bindings.each_slice(2) do |binding|
175 key, value = binding
176 name = key.unwrap
177 eval_error "name of binding must be specified as symbol #{name}" unless name.is_a? Mal::Symbol
178 new_env.set(name.str, eval(value, new_env))
179 end
180
181 ast, env = list[2], new_env
182 next # TCO
183 when "do"
184 if list.empty?
185 ast = Mal::Type.new nil
186 next
187 end
188
189 eval_ast(list[1..-2].to_mal, env)
190 ast = list.last
191 next # TCO
192 when "if"
193 ast = unless eval(list[1], env).unwrap
194 list.size >= 4 ? list[3] : Mal::Type.new(nil)
195 else
196 list[2]
197 end
198 next # TCO
199 when "fn*"
200 params = list[1].unwrap
201 unless params.is_a? Array
202 eval_error "'fn*' parameters must be list or vector: #{params}"
203 end
204 Mal::Closure.new(list[2], params, env, func_of(env, params, list[2]))
205 when "quote"
206 list[1]
207 when "quasiquote"
208 ast = quasiquote list[1]
209 next # TCO
210 when "defmacro!"
211 eval_error "wrong number of argument for 'defmacro!'" unless list.size == 3
212 a1 = list[1].unwrap
213 eval_error "1st argument of 'defmacro!' must be symbol: #{a1}" unless a1.is_a? Mal::Symbol
214 env.set(a1.str, eval(list[2], env).tap{|n| n.is_macro = true})
215 when "macroexpand"
216 macroexpand(list[1], env)
217 when "try*"
218 catch_list = list[2].unwrap
219 return eval(list[1], env) unless catch_list.is_a? Mal::List
220
221 catch_head = catch_list.first.unwrap
222 return eval(list[1], env) unless catch_head.is_a? Mal::Symbol
223 return eval(list[1], env) unless catch_head.str == "catch*"
224
225 begin
226 eval(list[1], env)
227 rescue e : Mal::RuntimeException
228 new_env = Mal::Env.new(env, [catch_list[1]], [e.thrown])
229 eval(catch_list[2], new_env)
230 rescue e
231 new_env = Mal::Env.new(env, [catch_list[1]], [Mal::Type.new e.message])
232 eval(catch_list[2], new_env)
233 end
234 else
235 invoke_list(list, env)
236 end
237 end
238 end
239
240 def print(result)
241 pr_str(result, true)
242 end
243
244 def rep(str)
245 print(eval(read(str), $repl_env))
246 end
247 end
248
249 $repl_env = Mal::Env.new nil
250 Mal::NS.each{|k,v| $repl_env.set(k, Mal::Type.new(v))}
251 $repl_env.set("eval", Mal::Type.new -> (args: Array(Mal::Type)){ Mal.eval(args[0], $repl_env) })
252 Mal.rep "(def! not (fn* (a) (if a false true)))"
253 Mal.rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))"
254 Mal.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)))))))"
255 Mal.rep "(def! *gensym-counter* (atom 0))"
256 Mal.rep "(def! gensym (fn* [] (symbol (str \"G__\" (swap! *gensym-counter* (fn* [x] (+ 1 x)))))))"
257 Mal.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)))))))))"
258 Mal.rep("(def! *host-language* \"crystal\")")
259
260 $argv = Mal::List.new
261 $repl_env.set("*ARGV*", Mal::Type.new $argv)
262
263 unless ARGV.empty?
264 if ARGV.size > 1
265 ARGV[1..-1].each do |a|
266 $argv << Mal::Type.new(a)
267 end
268 end
269
270 begin
271 Mal.rep "(load-file \"#{ARGV[0]}\")"
272 rescue e
273 STDERR.puts e
274 end
275 exit
276 end
277
278 Mal.rep("(println (str \"Mal [\" *host-language* \"]\"))")
279
280 while line = my_readline("user> ")
281 begin
282 puts Mal.rep(line)
283 rescue e
284 STDERR.puts e
285 end
286 end