1 #! /usr/bin/env crystal run
12 # Employed downcase names because Crystal prohibits uppercase names for methods
17 def func_of(env, binds, body)
18 ->(args : Array(Mal::Type)) {
19 new_env = Mal::Env.new(env, binds, args)
24 def eval_ast(ast, env)
25 return ast.map { |n| eval(n, env).as(Mal::Type) } if ast.is_a? Mal::List
29 Mal::Type.new case val
31 if e = env.get(val.str)
34 eval_error "'#{val.str}' not found"
37 val.each_with_object(Mal::List.new) { |n, l| l << eval(n, env) }
39 val.each_with_object(Mal::Vector.new) { |n, l| l << eval(n, env) }
41 val.each { |k, v| val[k] = eval(v, env) }
48 def eval_invocation(list, env)
49 f = eval(list.first, env).unwrap
50 eval_error "expected function symbol as the first symbol of list" unless f.is_a? Mal::Func
51 f.call eval_ast(list[1..-1].each_with_object(Mal::List.new) { |i, l| l << i }, env)
61 return eval_ast(ast, env) unless list.is_a? Mal::List
62 return gen_type Mal::List if list.empty?
64 head = list.first.unwrap
66 Mal::Type.new case head
70 eval_error "wrong number of argument for 'def!'" unless list.size == 3
72 eval_error "1st argument of 'def!' must be symbol" unless a1.is_a? Mal::Symbol
73 env.set(a1.str, eval(list[2], env))
75 eval_error "wrong number of argument for 'def!'" unless list.size == 3
77 bindings = list[1].unwrap
78 eval_error "1st argument of 'let*' must be list or vector" unless bindings.is_a? Array
79 eval_error "size of binding list must be even" unless bindings.size.even?
81 new_env = Mal::Env.new env
82 bindings.each_slice(2) do |binding|
85 eval_error "name of binding must be specified as symbol" unless name.is_a? Mal::Symbol
86 new_env.set(name.str, eval(value, new_env))
89 eval(list[2], new_env)
92 eval_ast(list, env).last
94 cond = eval(list[1], env).unwrap
97 list.size >= 4 ? eval(list[3], env) : nil
99 list.size >= 4 ? eval(list[3], env) : nil
105 # If writing lambda expression here directly, compiler will fail to infer type of 'list'. (Error 'Nil for empty?')
106 func_of(env, list[1].unwrap, list[2])
108 eval_invocation(list, env)
111 eval_invocation(list, env)
120 print(eval(read(str), REPL_ENV))
124 REPL_ENV = Mal::Env.new nil
125 Mal::NS.each { |k, v| REPL_ENV.set(k, Mal::Type.new(v)) }
126 Mal.rep "(def! not (fn* (a) (if a false true)))"
128 while line = Readline.readline("user> ")
131 rescue e : Mal::RuntimeException
132 STDERR.puts "Error: #{pr_str(e.thrown, true)}"
134 STDERR.puts "Error: #{e}"