DISABLE FDs (REMOVE ME).
[jackhill/mal.git] / js / step2_eval.js
CommitLineData
31690700 1if (typeof module !== 'undefined') {
31b44161 2 var types = require('./types');
31690700 3 var readline = require('./node_readline');
31b44161
JM
4 var reader = require('./reader');
5 var printer = require('./printer');
31690700
JM
6}
7
8// read
9function READ(str) {
10 return reader.read_str(str);
11}
12
13// eval
14function eval_ast(ast, env) {
ea81a808 15 if (types._symbol_Q(ast)) {
970935da
JM
16 if (ast in env) {
17 return env[ast];
18 } else {
19 throw new Error("'" + ast.value + "' not found");
20 }
ea81a808 21 } else if (types._list_Q(ast)) {
31690700 22 return ast.map(function(a) { return EVAL(a, env); });
ea81a808 23 } else if (types._vector_Q(ast)) {
31690700
JM
24 var v = ast.map(function(a) { return EVAL(a, env); });
25 v.__isvector__ = true;
26 return v;
ea81a808 27 } else if (types._hash_map_Q(ast)) {
31690700
JM
28 var new_hm = {};
29 for (k in ast) {
30 new_hm[EVAL(k, env)] = EVAL(ast[k], env);
31 }
32 return new_hm;
33 } else {
34 return ast;
35 }
36}
37
38function _EVAL(ast, env) {
86b689f3 39 //printer.println("EVAL:", printer._pr_str(ast, true));
ea81a808 40 if (!types._list_Q(ast)) {
31690700
JM
41 return eval_ast(ast, env);
42 }
efa2daef
JM
43 if (ast.length === 0) {
44 return ast;
45 }
31690700
JM
46
47 // apply list
48 var el = eval_ast(ast, env), f = el[0];
49 return f.apply(f, el.slice(1));
50}
51
52function EVAL(ast, env) {
53 var result = _EVAL(ast, env);
54 return (typeof result !== "undefined") ? result : null;
55}
56
57// print
58function PRINT(exp) {
ea81a808 59 return printer._pr_str(exp, true);
31690700
JM
60}
61
62// repl
63repl_env = {};
64var rep = function(str) { return PRINT(EVAL(READ(str), repl_env)); };
65
66repl_env['+'] = function(a,b){return a+b;};
67repl_env['-'] = function(a,b){return a-b;};
68repl_env['*'] = function(a,b){return a*b;};
69repl_env['/'] = function(a,b){return a/b;};
70
86b689f3 71// repl loop
e4393504 72if (typeof require !== 'undefined' && require.main === module) {
31690700
JM
73 // Synchronous node.js commandline mode
74 while (true) {
75 var line = readline.readline("user> ");
76 if (line === null) { break; }
77 try {
31b44161 78 if (line) { printer.println(rep(line)); }
31690700 79 } catch (exc) {
dd7a4f55
JM
80 if (exc instanceof reader.BlankException) { continue }
81 if (exc instanceof Error) { console.warn(exc.stack) }
82 else { console.warn("Error: " + printer._pr_str(exc, true)) }
31690700
JM
83 }
84 }
31690700 85}