bash, c, clojure, coffee, es6, js: add seq/string?
[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)) {
31690700 16 return env[ast];
ea81a808 17 } else if (types._list_Q(ast)) {
31690700 18 return ast.map(function(a) { return EVAL(a, env); });
ea81a808 19 } else if (types._vector_Q(ast)) {
31690700
JM
20 var v = ast.map(function(a) { return EVAL(a, env); });
21 v.__isvector__ = true;
22 return v;
ea81a808 23 } else if (types._hash_map_Q(ast)) {
31690700
JM
24 var new_hm = {};
25 for (k in ast) {
26 new_hm[EVAL(k, env)] = EVAL(ast[k], env);
27 }
28 return new_hm;
29 } else {
30 return ast;
31 }
32}
33
34function _EVAL(ast, env) {
86b689f3 35 //printer.println("EVAL:", printer._pr_str(ast, true));
ea81a808 36 if (!types._list_Q(ast)) {
31690700
JM
37 return eval_ast(ast, env);
38 }
39
40 // apply list
41 var el = eval_ast(ast, env), f = el[0];
42 return f.apply(f, el.slice(1));
43}
44
45function EVAL(ast, env) {
46 var result = _EVAL(ast, env);
47 return (typeof result !== "undefined") ? result : null;
48}
49
50// print
51function PRINT(exp) {
ea81a808 52 return printer._pr_str(exp, true);
31690700
JM
53}
54
55// repl
56repl_env = {};
57var rep = function(str) { return PRINT(EVAL(READ(str), repl_env)); };
58
59repl_env['+'] = function(a,b){return a+b;};
60repl_env['-'] = function(a,b){return a-b;};
61repl_env['*'] = function(a,b){return a*b;};
62repl_env['/'] = function(a,b){return a/b;};
63
86b689f3 64// repl loop
e4393504 65if (typeof require !== 'undefined' && require.main === module) {
31690700
JM
66 // Synchronous node.js commandline mode
67 while (true) {
68 var line = readline.readline("user> ");
69 if (line === null) { break; }
70 try {
31b44161 71 if (line) { printer.println(rep(line)); }
31690700
JM
72 } catch (exc) {
73 if (exc instanceof reader.BlankException) { continue; }
31b44161
JM
74 if (exc.stack) { printer.println(exc.stack); }
75 else { printer.println(exc); }
31690700
JM
76 }
77 }
31690700 78}