3 local table = require('table')
5 local readline
= require('readline')
6 local utils
= require('utils')
7 local types
= require('types')
8 local reader
= require('reader')
9 local printer
= require('printer')
10 local Env
= require('env')
11 local core
= require('core')
12 local List
, Vector
, HashMap
= types
.List
, types
.Vector
, types
.HashMap
16 return reader
.read_str(str
)
20 function eval_ast(ast
, env
)
21 if types
._symbol_Q(ast
) then
23 elseif types
._list_Q(ast
) then
24 return List
:new(utils
.map(function(x
) return EVAL(x
,env
) end,ast
))
25 elseif types
._vector_Q(ast
) then
26 return Vector
:new(utils
.map(function(x
) return EVAL(x
,env
) end,ast
))
27 elseif types
._hash_map_Q(ast
) then
29 for k
,v
in pairs(ast
) do
30 new_hm
[EVAL(k
, env
)] = EVAL(v
, env
)
32 return HashMap
:new(new_hm
)
38 function EVAL(ast
, env
)
39 --print("EVAL: "..printer._pr_str(ast,true))
40 if not types
._list_Q(ast
) then return eval_ast(ast
, env
) end
42 local a0
,a1
,a2
,a3
= ast
[1], ast
[2],ast
[3],ast
[4]
43 local a0sym
= types
._symbol_Q(a0
) and a0
.val
or ""
44 if 'def!' == a0sym
then
45 return env
:set(a1
, EVAL(a2
, env
))
46 elseif 'let*' == a0sym
then
47 local let_env
= Env
:new(env
)
49 let_env
:set(a1
[i
], EVAL(a1
[i
+1], let_env
))
51 return EVAL(a2
, let_env
)
52 elseif 'do' == a0sym
then
53 local el
= eval_ast(ast
:slice(2,#ast
), env
)
55 elseif 'if' == a0sym
then
56 local cond
= EVAL(a1
, env
)
57 if cond
== types
.Nil
or cond
== false then
58 if a3
then return EVAL(a3
, env
) else return types
.Nil
end
62 elseif 'fn*' == a0sym
then
64 return EVAL(a2
, Env
:new(env
, a1
, arg
))
67 local args
= eval_ast(ast
, env
)
68 local f
= table.remove(args
, 1)
69 return f(unpack(args
))
75 return printer
._pr_str(exp, true)
79 local repl_env
= Env
:new()
81 return PRINT(EVAL(READ(str
),repl_env
))
84 -- core.lua: defined using Lua
85 for k
,v
in pairs(core
.ns
) do
86 repl_env
:set(types
.Symbol
:new(k
), v
)
89 -- core.mal: defined using mal
90 rep("(def! not (fn* (a) (if a false true)))")
93 line
= readline
.readline("user> ")
94 if not line
then break end
99 if types
._malexception_Q(exc
) then
100 exc
= printer
._pr_str(exc
.val
, true)
102 print("Error: " .. exc
)
103 print(debug
.traceback())