plsql: add dockerfile. Lots of cleanup/renaming.
[jackhill/mal.git] / nim / step4_if_fn_do.nim
1 import rdstdin, tables, sequtils, types, reader, printer, env, core
2
3 proc read(str: string): MalType = str.read_str
4
5 proc eval(ast: MalType, env: var Env): MalType
6
7 proc eval_ast(ast: MalType, env: var Env): MalType =
8 case ast.kind
9 of Symbol:
10 result = env.get(ast.str)
11 of List:
12 result = list ast.list.mapIt(MalType, it.eval(env))
13 of Vector:
14 result = vector ast.list.mapIt(MalType, it.eval(env))
15 of HashMap:
16 result = hash_map()
17 for k, v in ast.hash_map.pairs:
18 result.hash_map[k] = v.eval(env)
19 else:
20 result = ast
21
22 proc eval(ast: MalType, env: var Env): MalType =
23 case ast.kind
24 of List:
25 if ast.list.len == 0: return ast
26 let a0 = ast.list[0]
27 case a0.kind
28 of Symbol:
29 case a0.str
30 of "def!":
31 let
32 a1 = ast.list[1]
33 a2 = ast.list[2]
34 result = env.set(a1.str, a2.eval(env))
35
36 of "let*":
37 let
38 a1 = ast.list[1]
39 a2 = ast.list[2]
40 var letEnv: Env
41 letEnv.deepCopy(env)
42
43 case a1.kind
44 of List, Vector:
45 for i in countup(0, a1.list.high, 2):
46 letEnv.set(a1.list[i].str, a1.list[i+1].eval(letEnv))
47 else: discard
48 result = a2.eval(letEnv)
49
50 of "do":
51 let el = (list ast.list[1 .. ^1]).eval_ast(env)
52 result = el.list[el.list.high]
53
54 of "if":
55 let
56 a1 = ast.list[1]
57 a2 = ast.list[2]
58 cond = a1.eval(env)
59
60 if cond.kind in {Nil, False}:
61 if ast.list.len > 3: result = ast.list[3].eval(env)
62 else: result = nilObj
63 else: result = a2.eval(env)
64
65 of "fn*":
66 let
67 a1 = ast.list[1]
68 a2 = ast.list[2]
69 var env2 = env
70 result = fun(proc(a: varargs[MalType]): MalType =
71 var newEnv = initEnv(env2, a1, list(a))
72 a2.eval(newEnv))
73
74 else:
75 let el = ast.eval_ast(env)
76 result = el.list[0].fun(el.list[1 .. ^1])
77
78 else:
79 let el = ast.eval_ast(env)
80 result = el.list[0].fun(el.list[1 .. ^1])
81
82 else:
83 result = ast.eval_ast(env)
84
85 proc print(exp: MalType): string = exp.pr_str
86
87 var repl_env = initEnv()
88
89 for k, v in ns.items:
90 repl_env.set(k, v)
91
92 # core.nim: defined using nim
93 proc rep(str: string): string =
94 str.read.eval(repl_env).print
95
96 # core.mal: defined using mal itself
97 discard rep "(def! not (fn* (a) (if a false true)))"
98
99 while true:
100 try:
101 let line = readLineFromStdin("user> ")
102 echo line.rep
103 except:
104 echo getCurrentExceptionMsg()
105 echo getCurrentException().getStackTrace()