DISABLE FDs (REMOVE ME).
[jackhill/mal.git] / es6 / step9_try.mjs
1 import rl from './node_readline.js'
2 const readline = rl.readline
3 import { _clone, _list_Q, _malfunc, _malfunc_Q } from './types'
4 import { BlankException, read_str } from './reader'
5 import { pr_str } from './printer'
6 import { new_env, env_set, env_get } from './env'
7 import { core_ns } from './core'
8
9 // read
10 const READ = str => read_str(str)
11
12 // eval
13 const is_pair = x => Array.isArray(x) && x.length > 0
14
15 const quasiquote = ast => {
16 if (!is_pair(ast)) {
17 return [Symbol.for('quote'), ast]
18 } else if (ast[0] === Symbol.for('unquote')) {
19 return ast[1]
20 } else if (is_pair(ast[0]) && ast[0][0] === Symbol.for('splice-unquote')) {
21 return [Symbol.for('concat'),
22 ast[0][1],
23 quasiquote(ast.slice(1))]
24 } else {
25 return [Symbol.for('cons'),
26 quasiquote(ast[0]),
27 quasiquote(ast.slice(1))]
28 }
29 }
30
31 function macroexpand(ast, env) {
32 while (_list_Q(ast) && typeof ast[0] === 'symbol' && ast[0] in env) {
33 let f = env_get(env, ast[0])
34 if (!f.ismacro) { break }
35 ast = f(...ast.slice(1))
36 }
37 return ast
38 }
39
40
41 const eval_ast = (ast, env) => {
42 if (typeof ast === 'symbol') {
43 return env_get(env, ast)
44 } else if (ast instanceof Array) {
45 return ast.map(x => EVAL(x, env))
46 } else if (ast instanceof Map) {
47 let new_hm = new Map()
48 ast.forEach((v, k) => new_hm.set(EVAL(k, env), EVAL(v, env)))
49 return new_hm
50 } else {
51 return ast
52 }
53 }
54
55 const EVAL = (ast, env) => {
56 while (true) {
57 //console.log('EVAL:', pr_str(ast, true))
58 if (!_list_Q(ast)) { return eval_ast(ast, env) }
59
60 ast = macroexpand(ast, env)
61 if (!_list_Q(ast)) { return eval_ast(ast, env) }
62 if (ast.length === 0) { return ast }
63
64 const [a0, a1, a2, a3] = ast
65 switch (typeof a0 === 'symbol' ? Symbol.keyFor(a0) : Symbol(':default')) {
66 case 'def!':
67 return env_set(env, a1, EVAL(a2, env))
68 case 'let*':
69 let let_env = new_env(env)
70 for (let i=0; i < a1.length; i+=2) {
71 env_set(let_env, a1[i], EVAL(a1[i+1], let_env))
72 }
73 env = let_env
74 ast = a2
75 break // continue TCO loop
76 case 'quote':
77 return a1
78 case 'quasiquote':
79 ast = quasiquote(a1)
80 break // continue TCO loop
81 case 'defmacro!':
82 let func = _clone(EVAL(a2, env))
83 func.ismacro = true
84 return env_set(env, a1, func)
85 case 'macroexpand':
86 return macroexpand(a1, env)
87 case 'try*':
88 try {
89 return EVAL(a1, env)
90 } catch (exc) {
91 if (a2 && a2[0] === Symbol.for('catch*')) {
92 if (exc instanceof Error) { exc = exc.message }
93 return EVAL(a2[2], new_env(env, [a2[1]], [exc]))
94 } else {
95 throw exc
96 }
97 }
98 case 'do':
99 eval_ast(ast.slice(1,-1), env)
100 ast = ast[ast.length-1]
101 break // continue TCO loop
102 case 'if':
103 let cond = EVAL(a1, env)
104 if (cond === null || cond === false) {
105 ast = (typeof a3 !== 'undefined') ? a3 : null
106 } else {
107 ast = a2
108 }
109 break // continue TCO loop
110 case 'fn*':
111 return _malfunc((...args) => EVAL(a2, new_env(env, a1, args)),
112 a2, env, a1)
113 default:
114 let [f, ...args] = eval_ast(ast, env)
115 if (_malfunc_Q(f)) {
116 env = new_env(f.env, f.params, args)
117 ast = f.ast
118 break // continue TCO loop
119 } else {
120 return f(...args)
121 }
122 }
123 }
124 }
125
126 // print
127 const PRINT = exp => pr_str(exp, true)
128
129 // repl
130 let repl_env = new_env()
131 const REP = str => PRINT(EVAL(READ(str), repl_env))
132
133 // core.EXT: defined using ES6
134 for (let [k, v] of core_ns) { env_set(repl_env, Symbol.for(k), v) }
135 env_set(repl_env, Symbol.for('eval'), a => EVAL(a, repl_env))
136 env_set(repl_env, Symbol.for('*ARGV*'), [])
137
138 // core.mal: defined using language itself
139 REP('(def! not (fn* (a) (if a false true)))')
140 REP('(def! load-file (fn* (f) (eval (read-string (str "(do " (slurp f) "\nnil)")))))')
141 REP('(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list \'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw "odd number of forms to cond")) (cons \'cond (rest (rest xs)))))))')
142
143 if (process.argv.length > 2) {
144 env_set(repl_env, Symbol.for('*ARGV*'), process.argv.slice(3))
145 REP(`(load-file "${process.argv[2]}")`)
146 process.exit(0)
147 }
148
149
150 while (true) {
151 let line = readline('user> ')
152 if (line == null) break
153 try {
154 if (line) { console.log(REP(line)) }
155 } catch (exc) {
156 if (exc instanceof BlankException) { continue }
157 if (exc instanceof Error) { console.warn(exc.stack) }
158 else { console.warn(`Error: ${pr_str(exc, true)}`) }
159 }
160 }