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: var 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: var Env): MalType =
39 template defaultApply =
40 let el = ast.eval_ast(env)
45 env = initEnv(f.malfun.env, f.malfun.params, list(el.list[1 .. -1]))
47 return f.fun(el.list[1 .. -1])
50 if ast.kind != List: return ast.eval_ast(env)
60 return env.set(a1.str, a2.eval(env))
66 var let_env = Env(env)
69 for i in countup(0, a1.list.high, 2):
70 let_env.set(a1.list[i].str, a1.list[i+1].eval(let_env))
71 else: raise newException(ValueError, "Illegal kind in let*")
80 ast = ast.list[1].quasiquote
84 let last = ast.list.high
85 let el = (list ast.list[1 .. <last]).eval_ast(env)
95 if cond.kind in {Nil, False}:
96 if ast.list.len > 3: ast = ast.list[3]
105 let fn = proc(a: varargs[MalType]): MalType =
106 var newEnv = initEnv(env2, a1, list(a))
108 return malfun(fn, a2, a1, env)
116 proc print(exp: MalType): string = exp.pr_str
118 var repl_env = initEnv()
120 for k, v in ns.items:
122 repl_env.set("eval", fun(proc(xs: varargs[MalType]): MalType = eval(xs[0], repl_env)))
123 var ps = commandLineParams()
124 repl_env.set("*ARGV*", list((if paramCount() > 1: ps[1..ps.high] else: @[]).map(str)))
127 # core.nim: defined using nim
128 proc rep(str: string): string {.discardable.} =
129 str.read.eval(repl_env).print
131 # core.mal: defined using mal itself
132 rep "(def! not (fn* (a) (if a false true)))"
133 rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))"
135 if paramCount() >= 1:
136 rep "(load-file \"" & paramStr(1) & "\")"
141 let line = readLineFromStdin("user> ")
143 except Blank: discard
145 echo getCurrentExceptionMsg()
146 echo getCurrentException().getStackTrace()