1 import rdstdin, tables, sequtils, os, types, reader, printer, env, core
3 proc read(str: string): MalType = str.read_str
5 proc is_pair(x: MalType): bool =
6 x.kind in {List, Vector} and x.list.len > 0
8 proc quasiquote(ast: MalType): MalType =
10 return list(symbol "quote", ast)
11 elif ast.list[0] == symbol "unquote":
13 elif ast.list[0].is_pair and ast.list[0].list[0] == symbol "splice-unquote":
14 return list(symbol "concat", ast.list[0].list[1],
15 quasiquote(list ast.list[1 .. ^1]))
17 return list(symbol "cons", quasiquote(ast.list[0]), quasiquote(list(ast.list[1 .. ^1])))
19 proc eval(ast: MalType, env: Env): MalType
21 proc eval_ast(ast: MalType, env: var Env): MalType =
24 result = env.get(ast.str)
26 result = list ast.list.mapIt(MalType, it.eval(env))
28 result = vector ast.list.mapIt(MalType, it.eval(env))
31 for k, v in ast.hash_map.pairs:
32 result.hash_map[k] = v.eval(env)
36 proc eval(ast: MalType, env: Env): MalType =
40 template defaultApply =
41 let el = ast.eval_ast(env)
46 env = initEnv(f.malfun.env, f.malfun.params, list(el.list[1 .. ^1]))
48 return f.fun(el.list[1 .. ^1])
51 if ast.kind != List: return ast.eval_ast(env)
52 if ast.list.len == 0: return ast
62 return env.set(a1.str, a2.eval(env))
68 var let_env = initEnv(env)
71 for i in countup(0, a1.list.high, 2):
72 let_env.set(a1.list[i].str, a1.list[i+1].eval(let_env))
73 else: raise newException(ValueError, "Illegal kind in let*")
82 ast = ast.list[1].quasiquote
86 let last = ast.list.high
87 discard (list ast.list[1 .. <last]).eval_ast(env)
97 if cond.kind in {Nil, False}:
98 if ast.list.len > 3: ast = ast.list[3]
107 let fn = proc(a: varargs[MalType]): MalType =
108 var newEnv = initEnv(env2, a1, list(a))
110 return malfun(fn, a2, a1, env)
118 proc print(exp: MalType): string = exp.pr_str
120 var repl_env = initEnv()
122 for k, v in ns.items:
124 repl_env.set("eval", fun(proc(xs: varargs[MalType]): MalType = eval(xs[0], repl_env)))
125 var ps = commandLineParams()
126 repl_env.set("*ARGV*", list((if paramCount() > 1: ps[1..ps.high] else: @[]).map(str)))
129 # core.nim: defined using nim
130 proc rep(str: string): string {.discardable.} =
131 str.read.eval(repl_env).print
133 # core.mal: defined using mal itself
134 rep "(def! not (fn* (a) (if a false true)))"
135 rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))"
137 if paramCount() >= 1:
138 rep "(load-file \"" & paramStr(1) & "\")"
143 let line = readLineFromStdin("user> ")
145 except Blank: discard
147 echo getCurrentExceptionMsg()
148 echo getCurrentException().getStackTrace()