Update Crystal implementation
[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 # Already checked in macro_call?
105 list = ast.unwrap.as(Mal::List)
106 func_sym = list[0].unwrap.as(Mal::Symbol)
107 func = env.get(func_sym.str).unwrap
108
109 case func
110 when Mal::Func
111 ast = func.call(list[1..-1])
112 when Mal::Closure
113 ast = func.fn.call(list[1..-1])
114 else
115 eval_error "macro '#{func_sym.str}' must be function: #{ast}"
116 end
117 end
118
119 ast
120 end
121
122 macro invoke_list(l, env)
123 f = eval({{l}}.first, {{env}}).unwrap
124 args = eval_ast({{l}}[1..-1], {{env}}).as(Array)
125
126 case f
127 when Mal::Closure
128 ast = f.ast
129 {{env}} = Mal::Env.new(f.env, f.params, args)
130 next # TCO
131 when Mal::Func
132 return f.call args
133 else
134 eval_error "expected function as the first argument: #{f}"
135 end
136 end
137
138 def debug(ast)
139 puts print(ast).colorize.red
140 end
141
142 def eval(ast, env)
143 # 'next' in 'do...end' has a bug in crystal 0.7.1
144 # https://github.com/manastech/crystal/issues/659
145 while true
146 return eval_ast(ast, env) unless ast.unwrap.is_a? Mal::List
147
148 ast = macroexpand(ast, env)
149
150 list = ast.unwrap
151
152 return eval_ast(ast, env) unless list.is_a? Mal::List
153 return ast if list.empty?
154
155 head = list.first.unwrap
156
157 return invoke_list(list, env) unless head.is_a? Mal::Symbol
158
159 return Mal::Type.new case head.str
160 when "def!"
161 eval_error "wrong number of argument for 'def!'" unless list.size == 3
162 a1 = list[1].unwrap
163 eval_error "1st argument of 'def!' must be symbol: #{a1}" unless a1.is_a? Mal::Symbol
164 env.set(a1.str, eval(list[2], env))
165 when "let*"
166 eval_error "wrong number of argument for 'def!'" unless list.size == 3
167
168 bindings = list[1].unwrap
169 eval_error "1st argument of 'let*' must be list or vector" unless bindings.is_a? Array
170 eval_error "size of binding list must be even" unless bindings.size.even?
171
172 new_env = Mal::Env.new env
173 bindings.each_slice(2) do |binding|
174 key, value = binding
175 name = key.unwrap
176 eval_error "name of binding must be specified as symbol #{name}" unless name.is_a? Mal::Symbol
177 new_env.set(name.str, eval(value, new_env))
178 end
179
180 ast, env = list[2], new_env
181 next # TCO
182 when "do"
183 if list.empty?
184 ast = Mal::Type.new nil
185 next
186 end
187
188 eval_ast(list[1..-2].to_mal, env)
189 ast = list.last
190 next # TCO
191 when "if"
192 ast = unless eval(list[1], env).unwrap
193 list.size >= 4 ? list[3] : Mal::Type.new(nil)
194 else
195 list[2]
196 end
197 next # TCO
198 when "fn*"
199 params = list[1].unwrap
200 unless params.is_a? Array
201 eval_error "'fn*' parameters must be list or vector: #{params}"
202 end
203 Mal::Closure.new(list[2], params, env, func_of(env, params, list[2]))
204 when "quote"
205 list[1]
206 when "quasiquote"
207 ast = quasiquote list[1]
208 next # TCO
209 when "defmacro!"
210 eval_error "wrong number of argument for 'defmacro!'" unless list.size == 3
211 a1 = list[1].unwrap
212 eval_error "1st argument of 'defmacro!' must be symbol: #{a1}" unless a1.is_a? Mal::Symbol
213 env.set(a1.str, eval(list[2], env).tap { |n| n.is_macro = true })
214 when "macroexpand"
215 macroexpand(list[1], env)
216 when "try*"
217 catch_list = list[2].unwrap
218 return eval(list[1], env) unless catch_list.is_a? Mal::List
219
220 catch_head = catch_list.first.unwrap
221 return eval(list[1], env) unless catch_head.is_a? Mal::Symbol
222 return eval(list[1], env) unless catch_head.str == "catch*"
223
224 begin
225 eval(list[1], env)
226 rescue e : Mal::RuntimeException
227 new_env = Mal::Env.new(env, [catch_list[1]], [e.thrown])
228 eval(catch_list[2], new_env)
229 rescue e
230 new_env = Mal::Env.new(env, [catch_list[1]], [Mal::Type.new e.message])
231 eval(catch_list[2], new_env)
232 end
233 else
234 invoke_list(list, env)
235 end
236 end
237 end
238
239 def print(result)
240 pr_str(result, true)
241 end
242
243 def rep(str)
244 print(eval(read(str), REPL_ENV))
245 end
246 end
247
248 REPL_ENV = Mal::Env.new nil
249 Mal::NS.each { |k, v| REPL_ENV.set(k, Mal::Type.new(v)) }
250 REPL_ENV.set("eval", Mal::Type.new ->(args : Array(Mal::Type)) { Mal.eval(args[0], REPL_ENV) })
251 Mal.rep "(def! not (fn* (a) (if a false true)))"
252 Mal.rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))"
253 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)))))))"
254 Mal.rep "(def! *gensym-counter* (atom 0))"
255 Mal.rep "(def! gensym (fn* [] (symbol (str \"G__\" (swap! *gensym-counter* (fn* [x] (+ 1 x)))))))"
256 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)))))))))"
257 Mal.rep("(def! *host-language* \"crystal\")")
258
259 argv = Mal::List.new
260 REPL_ENV.set("*ARGV*", Mal::Type.new argv)
261
262 unless ARGV.empty?
263 if ARGV.size > 1
264 ARGV[1..-1].each do |a|
265 argv << Mal::Type.new(a)
266 end
267 end
268
269 begin
270 Mal.rep "(load-file \"#{ARGV[0]}\")"
271 rescue e
272 STDERR.puts e
273 end
274 exit
275 end
276
277 Mal.rep("(println (str \"Mal [\" *host-language* \"]\"))")
278
279 while line = Readline.readline("user> ", true)
280 begin
281 puts Mal.rep(line)
282 rescue e
283 STDERR.puts e
284 end
285 end