process: Add literal empty list check to step3-stepA
[jackhill/mal.git] / coffee / step4_if_fn_do.coffee
CommitLineData
891c3f3b
JM
1readline = require "./node_readline.coffee"
2types = require "./types.coffee"
3reader = require "./reader.coffee"
4printer = require "./printer.coffee"
5Env = require("./env.coffee").Env
6core = require("./core.coffee")
7
8# read
9READ = (str) -> reader.read_str str
10
11# eval
12eval_ast = (ast, env) ->
b8ee29b2 13 if types._symbol_Q(ast) then env.get ast
891c3f3b
JM
14 else if types._list_Q(ast) then ast.map((a) -> EVAL(a, env))
15 else if types._vector_Q(ast)
16 types._vector(ast.map((a) -> EVAL(a, env))...)
17 else if types._hash_map_Q(ast)
18 new_hm = {}
19 new_hm[k] = EVAL(ast[k],env) for k,v of ast
20 new_hm
21 else ast
22
23EVAL = (ast, env) ->
24 #console.log "EVAL:", printer._pr_str ast
25 if !types._list_Q ast then return eval_ast ast, env
26
27 # apply list
28 [a0, a1, a2, a3] = ast
29 switch a0.name
30 when "def!"
b8ee29b2 31 env.set(a1, EVAL(a2, env))
891c3f3b
JM
32 when "let*"
33 let_env = new Env(env)
34 for k,i in a1 when i %% 2 == 0
b8ee29b2 35 let_env.set(a1[i], EVAL(a1[i+1], let_env))
891c3f3b
JM
36 EVAL(a2, let_env)
37 when "do"
38 el = eval_ast(ast[1..], env)
39 el[el.length-1]
40 when "if"
41 cond = EVAL(a1, env)
42 if cond == null or cond == false
43 if a3? then EVAL(a3, env) else null
44 else
45 EVAL(a2, env)
46 when "fn*"
47 (args...) -> EVAL(a2, new Env(env, a1, args))
48 else
49 [f, args...] = eval_ast ast, env
50 f(args...)
51
52
53# print
54PRINT = (exp) -> printer._pr_str exp, true
55
56# repl
57repl_env = new Env()
58rep = (str) -> PRINT(EVAL(READ(str), repl_env))
59
60# core.coffee: defined using CoffeeScript
b8ee29b2 61repl_env.set types._symbol(k), v for k,v of core.ns
891c3f3b
JM
62
63# core.mal: defined using the language itself
64rep("(def! not (fn* (a) (if a false true)))");
65
66# repl loop
67while (line = readline.readline("user> ")) != null
68 continue if line == ""
69 try
70 console.log rep line
71 catch exc
72 continue if exc instanceof reader.BlankException
4ed89670
JM
73 if exc.stack? and exc.stack.length > 2000
74 console.log exc.stack.slice(0,1000) + "\n ..." + exc.stack.slice(-1000)
75 else if exc.stack? console.log exc.stack
76 else console.log exc
891c3f3b
JM
77
78# vim: ts=2:sw=2