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: Env): MalType
7 proc eval_ast(ast: MalType, env: var Env): MalType =
10 result = env.get(ast.str)
12 result = list ast.list.mapIt(it.eval(env))
14 result = vector ast.list.mapIt(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: Env): MalType =
26 template defaultApply =
27 let el = ast.eval_ast(env)
32 env = initEnv(f.malfun.env, f.malfun.params, list(el.list[1 .. ^1]))
34 return f.fun(el.list[1 .. ^1])
37 if ast.kind != List: return ast.eval_ast(env)
38 if ast.list.len == 0: return ast
48 return env.set(a1.str, a2.eval(env))
54 var let_env = initEnv(env)
57 for i in countup(0, a1.list.high, 2):
58 let_env.set(a1.list[i].str, a1.list[i+1].eval(let_env))
59 else: raise newException(ValueError, "Illegal kind in let*")
65 let last = ast.list.high
66 discard (list ast.list[1 ..< last]).eval_ast(env)
76 if cond.kind in {Nil, False}:
77 if ast.list.len > 3: ast = ast.list[3]
86 let fn = proc(a: varargs[MalType]): MalType =
87 var newEnv = initEnv(env2, a1, list(a))
89 return malfun(fn, a2, a1, env)
97 proc print(exp: MalType): string = exp.pr_str
99 var repl_env = initEnv()
101 for k, v in ns.items:
103 repl_env.set("eval", fun(proc(xs: varargs[MalType]): MalType = eval(xs[0], repl_env)))
104 var ps = commandLineParams()
105 repl_env.set("*ARGV*", list((if paramCount() > 1: ps[1..ps.high] else: @[]).map(str)))
108 # core.nim: defined using nim
109 proc rep(str: string): string {.discardable.} =
110 str.read.eval(repl_env).print
112 # core.mal: defined using mal itself
113 rep "(def! not (fn* (a) (if a false true)))"
114 rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))"
116 if paramCount() >= 1:
117 rep "(load-file \"" & paramStr(1) & "\")"
122 let line = readLineFromStdin("user> ")
124 except Blank: discard
126 echo getCurrentExceptionMsg()
127 echo getCurrentException().getStackTrace()