crystal: add seq and string?
[jackhill/mal.git] / es6 / step4_if_fn_do.js
CommitLineData
4f8c7db9
JM
1import { readline } from './node_readline'
2import { _symbol, _symbol_Q, _list_Q, _vector, _vector_Q,
3 _hash_map_Q } from './types'
4import { BlankException, read_str } from './reader'
5import { pr_str } from './printer'
6import { new_env, env_set, env_get } from './env'
7import { core_ns } from './core'
5024b694
JM
8
9// read
4f8c7db9 10const READ = (str) => read_str(str)
5024b694
JM
11
12// eval
13const eval_ast = (ast, env) => {
4f8c7db9 14 if (_symbol_Q(ast)) {
5024b694
JM
15 return env_get(env, ast)
16 } else if (_list_Q(ast)) {
4f8c7db9 17 return ast.map((x) => EVAL(x, env))
afa79313 18 } else if (_vector_Q(ast)) {
4f8c7db9 19 return _vector(...ast.map((x) => EVAL(x, env)))
afa79313 20 } else if (_hash_map_Q(ast)) {
4f8c7db9 21 let new_hm = new Map()
afa79313 22 for (let [k, v] of ast) {
4f8c7db9 23 new_hm.set(EVAL(k, env), EVAL(v, env))
afa79313 24 }
4f8c7db9 25 return new_hm
5024b694 26 } else {
4f8c7db9 27 return ast
5024b694
JM
28 }
29}
30
31const EVAL = (ast, env) => {
4f8c7db9 32 //console.log('EVAL:', pr_str(ast, true))
5024b694
JM
33 if (!_list_Q(ast)) { return eval_ast(ast, env) }
34
4f8c7db9
JM
35 const [a0, a1, a2, a3] = ast
36 const a0sym = _symbol_Q(a0) ? Symbol.keyFor(a0) : Symbol(':default')
5024b694
JM
37 switch (a0sym) {
38 case 'def!':
4f8c7db9 39 return env_set(env, a1, EVAL(a2, env))
5024b694 40 case 'let*':
4f8c7db9 41 let let_env = new_env(env)
5024b694 42 for (let i=0; i < a1.length; i+=2) {
4f8c7db9 43 env_set(let_env, a1[i], EVAL(a1[i+1], let_env))
5024b694 44 }
4f8c7db9
JM
45 return EVAL(a2, let_env)
46 case 'do':
47 return eval_ast(ast.slice(1), env)[ast.length-2]
48 case 'if':
49 let cond = EVAL(a1, env)
5024b694 50 if (cond === null || cond === false) {
4f8c7db9 51 return typeof a3 !== 'undefined' ? EVAL(a3, env) : null
5024b694 52 } else {
4f8c7db9 53 return EVAL(a2, env)
5024b694 54 }
4f8c7db9
JM
55 case 'fn*':
56 return (...args) => EVAL(a2, new_env(env, a1, args))
5024b694 57 default:
4f8c7db9
JM
58 let [f, ...args] = eval_ast(ast, env)
59 return f(...args)
5024b694
JM
60 }
61}
62
63// print
4f8c7db9 64const PRINT = (exp) => pr_str(exp, true)
5024b694
JM
65
66// repl
4f8c7db9
JM
67let repl_env = new_env()
68const REP = (str) => PRINT(EVAL(READ(str), repl_env))
5024b694
JM
69
70// core.EXT: defined using ES6
4f8c7db9 71for (let [k, v] of core_ns) { env_set(repl_env, _symbol(k), v) }
5024b694
JM
72
73// core.mal: defined using language itself
4f8c7db9 74REP('(def! not (fn* (a) (if a false true)))')
5024b694
JM
75
76while (true) {
4f8c7db9
JM
77 let line = readline('user> ')
78 if (line == null) break
5024b694
JM
79 try {
80 if (line) { console.log(REP(line)); }
81 } catch (exc) {
82 if (exc instanceof BlankException) { continue; }
83 if (exc.stack) { console.log(exc.stack); }
4f8c7db9 84 else { console.log(`Error: ${exc}`); }
5024b694
JM
85 }
86}