-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlisp.js
242 lines (217 loc) · 5.7 KB
/
lisp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
var _text = null;
var _balanced = 0;
var _env = null;
function init() {
gui();
}
/////////////////
// Interpreter //
/////////////////
function read(text) {
try {
_balanced = 0;
_text = $.trim(text);
var code = ["list"];
while (_text.length)
code = code.concat(parser());
if (_balanced > 0)
throw "The expression is not balanced. Add " + _balanced + " parentheses.";
else if (_balanced < 0)
throw "The expression is not balanced. Remove " + Math.abs(_balanced) + " parentheses.";
if (!_env) _env = {};
return (eval_(code, _env)).pop();
} catch (e) {
return "Error: "+e;
}
}
function eval_(expr, env) {
// atoms
if (!isNaN(expr)) {
return Number(expr);
} else if (expr == "nil") {
return null;
} else if (expr[0] == '"') {
return expr.slice(1);
// list
} else if (expr[0] == "list") {
return $.map(expr.slice(1),
function(x) {
var v = eval_(x, env);
if ($.isArray(v))
return Array(v);
return v;
});
// variables
} else if (getenv(expr, env)) {
return getenv(expr, env);
} else if (expr[0] == "setq" || expr[0] == "set!") {
env[expr[1]] = eval_(expr[2], env);
return env[expr[1]];
// conditional
} else if (expr[0] == "if") {
if (eval_(expr[1], env))
return eval_(expr[2], env);
$.each(expr.slice(2, expr[expr.length - 2]),
function(i, x) { eval_(x, env); });
return eval_(expr[expr.length - 1], env);
// procedures
} else if (expr in operators) {
return operators[expr];
} else if (expr[0] == "lambda") {
return makeproc(expr[1], expr.slice(2), env);
} else if (expr[0] == "defun") {
env[expr[1]] = makeproc(expr[2], expr.slice(3), env);
return env[expr[1]];
} else if (expr[0] == "js") { // call a javascript function
return eval(expr[1]);
// apply
} else if ($.isArray(expr)) {
return apply_(
eval_(expr[0], env),
$.map(expr.slice(1), function(x, i) {
var v = eval_(x, env);
if ($.isArray(v))
return Array(v);
return v;
})
);
// error
} else {
throw expr+" is not defined"
}
}
function apply_(proc, args) {
if ($.isFunction(proc)) {
return proc.apply(this, args);
}
throw "Procedure "+proc+" is not defined";
}
function makeproc(args, body, env) {
return function() {
// extend the env
var arguments_ = arguments;
var newenv = {};
newenv["__up__"] = env;
$.each(args, function(i, x) { newenv[x] = arguments_[i]; });
$.each(body.slice(0, body.length - 1),
function(i, x) { eval_(x, newenv); });
return eval_(body[body.length - 1], newenv);
};
}
function getenv(expr, env) {
if (typeof expr != "string") return false;
if (expr in env) return env[expr];
if ("__up__" in env) return getenv(expr, env["__up__"]);
return false;
};
////////////////
// primitives //
////////////////
var operators = {
// list
"car":function() {
var l = arguments[0];
if (!l || !l.length) return null;
return l[0];
},
"cdr":function() {
var l = arguments[0];
if (!l || !l.length) return [];
return l.slice(1);
},
"cons":function() {
var a = arguments[1];
if (a == null) return [arguments[0]];
a.unshift(arguments[0])
return a;
},
// logical
"not":function() {
return !arguments[0];
},
"and":function() {
for (var i = 0; i < arguments.length; i++) {
if (!arguments[i]) return false;
}
return true;
},
"or":function() {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i]) return true;
}
return false;
},
// comparison
"<=":function(x, y) { return x <= y; },
"<":function(x, y) { return x < y; },
">=":function(x, y) { return x >= y; },
">":function(x, y) { return x > y; },
"=":function(x, y) { return x == y; },
"eq":function(x, y) { return x === y; },
// arithmetic
"+":function() {
var res = 0;
$.each(arguments, function(i, x) { res += x; });
return res;
},
"-":function() {
var res = arguments[0] * 2;
$.each(arguments, function(i, x) { res -= x; });
return res;
},
"*":function() {
var res = 1;
$.each(arguments, function(i, x) { res *= x; });
return res;
},
"/":function() {
var res = arguments[0] * arguments[0];
$.each(arguments, function(i, x) { res /= x; });
return res;
}
};
///////////////////////////
// Convert text to lists //
///////////////////////////
function scanner() {
if (!_text.length) return "";
var start = 0, index = 1;
if (_text.charAt(0) == "(" || _text.charAt(0) == ")") {
index = 1;
// check the text is balanced
_balanced += _text.charAt(0) == "(" ? 1 : -1;
} else if (_text.charAt(0) == '"') {
index = _text.search(/[^\\]"/) + 1;
} else
index = _text.search(/[ \n)]/);
if (index < 1) index = _text.length;
var t = _text.substring(start, index);
_text = $.trim(_text.substring(index));
return t;
}
function parser() {
var result = [];
var token = scanner();
while (token != ")" && token != "") {
var expr = null;
if (token == "(")
expr = parser();
else
expr = token;
result.push(expr);
token = scanner();
}
return result;
}
// Helpers
function trace(x) { console.log(x); }
////////////////////
// User interface //
////////////////////
function gui() {
$("#evaluate").click(function() {
var history = $("#history");
history.append("$ " + $("#input").val() + "\n" + read($("#input").val()) + "\n");
history.scrollTop(history[0].scrollHeight - history.height());
});
}