Merge pull request #256 from vvakame/impl-ts
[jackhill/mal.git] / coffee / step3_env.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
6
7# read
8READ = (str) -> reader.read_str str
9
10# eval
11eval_ast = (ast, env) ->
b8ee29b2 12 if types._symbol_Q(ast) then env.get ast
891c3f3b
JM
13 else if types._list_Q(ast) then ast.map((a) -> EVAL(a, env))
14 else if types._vector_Q(ast)
15 types._vector(ast.map((a) -> EVAL(a, env))...)
16 else if types._hash_map_Q(ast)
17 new_hm = {}
18 new_hm[k] = EVAL(ast[k],env) for k,v of ast
19 new_hm
20 else ast
21
22EVAL = (ast, env) ->
23 #console.log "EVAL:", printer._pr_str ast
24 if !types._list_Q ast then return eval_ast ast, env
903b669d 25 if ast.length == 0 then return ast
891c3f3b
JM
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 else
38 [f, args...] = eval_ast ast, env
39 f(args...)
40
41
42# print
43PRINT = (exp) -> printer._pr_str exp, true
44
45# repl
46repl_env = new Env()
47rep = (str) -> PRINT(EVAL(READ(str), repl_env))
48
b8ee29b2
JM
49repl_env.set types._symbol("+"), (a,b) -> a+b
50repl_env.set types._symbol("-"), (a,b) -> a-b
51repl_env.set types._symbol("*"), (a,b) -> a*b
52repl_env.set types._symbol("/"), (a,b) -> a/b
891c3f3b
JM
53
54# repl loop
55while (line = readline.readline("user> ")) != null
56 continue if line == ""
57 try
58 console.log rep line
59 catch exc
60 continue if exc instanceof reader.BlankException
4ed89670
JM
61 if exc.stack? and exc.stack.length > 2000
62 console.log exc.stack.slice(0,1000) + "\n ..." + exc.stack.slice(-1000)
63 else if exc.stack? console.log exc.stack
64 else console.log exc
891c3f3b
JM
65
66# vim: ts=2:sw=2