1 import rdstdin, tables, sequtils, os, types, reader, printer, env, core
3 proc read(str: string): MalType = str.read_str
5 proc eval(ast: MalType, env: var Env): MalType
7 proc eval_ast(ast: MalType, env: var Env): MalType =
10 result = env.get(ast.str)
12 result = list ast.list.mapIt(MalType, it.eval(env))
14 result = vector ast.list.mapIt(MalType, it.eval(env))
17 for k, v in ast.hash_map.pairs:
18 result.hash_map[k] = v.eval(env)
22 proc eval(ast: MalType, env: var Env): MalType =
25 template defaultApply =
26 let el = ast.eval_ast(env)
31 env = initEnv(f.malfun.env, f.malfun.params, list(el.list[1 .. -1]))
33 return f.fun(el.list[1 .. -1])
36 if ast.kind != List: return ast.eval_ast(env)
46 return env.set(a1.str, a2.eval(env))
52 var let_env = Env(env)
55 for i in countup(0, a1.list.high, 2):
56 let_env.set(a1.list[i].str, a1.list[i+1].eval(let_env))
57 else: raise newException(ValueError, "Illegal kind in let*")
63 let last = ast.list.high
64 let el = (list ast.list[1 .. <last]).eval_ast(env)
74 if cond.kind in {Nil, False}:
75 if ast.list.len > 3: ast = ast.list[3]
84 let fn = proc(a: varargs[MalType]): MalType =
85 var newEnv = initEnv(env2, a1, list(a))
87 return malfun(fn, a2, a1, env)
95 proc print(exp: MalType): string = exp.pr_str
97 var repl_env = initEnv()
101 repl_env.set("eval", fun(proc(xs: varargs[MalType]): MalType = eval(xs[0], repl_env)))
102 var ps = commandLineParams()
103 repl_env.set("*ARGV*", list((if paramCount() > 1: ps[1..ps.high] else: @[]).map(str)))
106 # core.nim: defined using nim
107 proc rep(str: string): string {.discardable.} =
108 str.read.eval(repl_env).print
110 # core.mal: defined using mal itself
111 rep "(def! not (fn* (a) (if a false true)))"
112 rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))"
114 if paramCount() >= 1:
115 rep "(load-file \"" & paramStr(1) & "\")"
120 let line = readLineFromStdin("user> ")
122 except Blank: discard
124 echo getCurrentExceptionMsg()
125 echo getCurrentException().getStackTrace()