1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-21 10:37:58 +03:00
mal/crystal/step2_eval.cr

96 lines
2.0 KiB
Crystal
Raw Normal View History

#! /usr/bin/env crystal run
2018-10-27 23:20:36 +03:00
require "readline"
require "./reader"
require "./printer"
require "./types"
# Note:
# Employed downcase names because Crystal prohibits uppercase names for methods
2015-06-03 19:59:10 +03:00
module Mal
extend self
2015-06-03 19:59:10 +03:00
def eval_error(msg)
raise Mal::EvalException.new msg
end
2015-06-03 19:59:10 +03:00
def num_func(func)
2018-10-27 23:20:36 +03:00
->(args : Array(Mal::Type)) {
2015-06-03 19:59:10 +03:00
x, y = args[0].unwrap, args[1].unwrap
eval_error "invalid arguments" unless x.is_a?(Int64) && y.is_a?(Int64)
2015-06-03 19:59:10 +03:00
Mal::Type.new func.call(x, y)
}
end
2015-06-03 19:59:10 +03:00
def eval_ast(a, env)
2018-10-27 23:20:36 +03:00
return a.map { |n| eval(n, env).as(Mal::Type) } if a.is_a? Mal::List
2015-06-03 19:59:10 +03:00
return a unless a
2015-06-03 19:59:10 +03:00
ast = a.unwrap
case ast
when Mal::Symbol
if env.has_key? ast.str
env[ast.str]
else
eval_error "'#{ast.str}' not found"
end
when Mal::List
2018-10-27 23:20:36 +03:00
ast.each_with_object(Mal::List.new) { |n, l| l << eval(n, env) }
2015-06-03 19:59:10 +03:00
when Mal::Vector
2018-10-27 23:20:36 +03:00
ast.each_with_object(Mal::Vector.new) { |n, l| l << eval(n, env) }
2015-06-03 19:59:10 +03:00
when Mal::HashMap
2018-10-27 23:20:36 +03:00
ast.each { |k, v| ast[k] = eval(v, env) }
ast
else
2015-06-03 19:59:10 +03:00
ast
end
end
2015-06-03 19:59:10 +03:00
def read(str)
read_str str
end
2015-06-03 19:59:10 +03:00
def eval(t, env)
Mal::Type.new case ast = t.unwrap
when Mal::List
return gen_type Mal::List if ast.empty?
2015-06-03 19:59:10 +03:00
f = eval_ast(ast.first, env)
ast.shift(1)
args = eval_ast(ast, env)
2015-06-03 19:59:10 +03:00
if f.is_a?(Mal::Func)
f.call(args)
else
eval_error "expected function symbol as the first symbol of list"
end
else
2015-06-03 19:59:10 +03:00
eval_ast(t, env)
end
end
2015-06-03 19:59:10 +03:00
def print(result)
pr_str(result, true)
end
2015-06-03 19:59:10 +03:00
def rep(str)
2018-10-27 23:20:36 +03:00
print(eval(read(str), REPL_ENV))
2015-06-03 19:59:10 +03:00
end
end
2018-10-27 23:20:36 +03:00
REPL_ENV = {
"+" => Mal.num_func(->(x : Int64, y : Int64) { x + y }),
"-" => Mal.num_func(->(x : Int64, y : Int64) { x - y }),
"*" => Mal.num_func(->(x : Int64, y : Int64) { x * y }),
"/" => Mal.num_func(->(x : Int64, y : Int64) { x / y }),
2015-06-03 19:59:10 +03:00
} of String => Mal::Func
2018-10-27 23:20:36 +03:00
while line = Readline.readline("user> ", true)
begin
2015-06-03 19:59:10 +03:00
puts Mal.rep(line)
rescue e
STDERR.puts e
end
end