-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
263 lines (252 loc) · 9.32 KB
/
app.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "_" }] */
/* eslint no-console: ["error", { allow: ["warn", "error"] }] */
/* global Vue */
(function() {
"use strict";
function tokenize(text) {
if (text.split("(").length !== text.split(")").length) {
throw SyntaxError("Parentheses missmatch.");
}
let line = 1, col = 1, result = [];
for (let token of text.split(/(\(|\)| |\n)/)) {
if (token === ""){
//nothing
} else if (token === " ") {
col += 1;
} else if (token === "\n") {
col = 1;
line += 1;
} else if (token[0] in "1234567890".split("")) {
let number = new Number(token);
if (Number.isNaN(number.valueOf())) {
throw new SyntaxError(`Not a number: ${token} (Line: ${line}, column: ${col})`);
}
number.line = line;
number.col = col;
number.length = token.length;
result.push(number);
col += token.length;
} else {
let str = new String(token);
str.line = line;
str.col = col;
result.push(str);
col += token.length;
}
}
return result;
}
function parse(tokens) {
var current = ["begin"];
const stack = [current];
for (let token of tokens) {
if (token.valueOf() === "(") {
let old = current;
current = [];
current.line = token.line;
current.col = token.col;
old.push(current);
stack.push(current);
} else if (token.valueOf() === ")") {
if (stack.length === 1) {
throw SyntaxError("Do not close the main 'begin' block.");
}
let old = stack.pop();
old.end_line = token.line;
old.end_col = token.col;
current = stack[stack.length - 1];
} else {
current.push(token);
}
}
if (stack.length > 1) {
throw SyntaxError("Program not finished."); // Should not happen
}
return stack[0];
}
const global_env = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
"=": (a, b) => a === b,
"!=": (a, b) => a !== b,
">": (a, b) => a > b,
">=": (a, b) => a >= b,
"<": (a, b) => a < b,
"<=": (a, b) => a <= b,
};
function evaluate(x, env) {
if (x instanceof String) {
const res = env[x.valueOf()];
if (typeof res === "undefined") {
throw Error("Variable '" + x + "' not found");
}
return env[x];
} else if (x instanceof Number) {
return x.valueOf();
} else if (x[0].valueOf() === "if") {
if (x.length != 4) {
throw Error("Wrong number of arguments for if: " +
(x.length - 1) + " != 3");
}
const [_, test, conseq, alt] = x;
const exp = evaluate(test, env) ? conseq : alt;
return evaluate(exp, env);
} else if (x[0].valueOf() === "define") {
if (x.length != 3) {
throw Error("Wrong number of arguments for define: " +
(x.length - 1) + " != 2");
}
const [_, name, exp] = x;
if (!(name instanceof String)){
throw Error("Name of a definition is not a string: " +
typeof name);
} else if ("begin define if lambda".split(" ").includes(name)) {
throw Error("Invalid name of a definition: " + name);
}
env[name.valueOf()] = evaluate(exp, env);
} else if (x[0].valueOf() === "begin") {
if (x.length < 2) {
throw Error("At least one expression required in begin block.");
}
const [_, ...exps] = x;
return exps.map(exp => evaluate(exp, env)).slice(-1)[0];
} else if (x[0].valueOf() === "lambda") {
if (x.length != 3) {
throw Error("Wrong number of arguments for lambda: " +
(x.length - 1) + " != 2");
}
const [_, arg_names, body] = x;
if (!(arg_names instanceof Array)) {
throw Error("Function arguments must be a list");
}
// Do nothing for now, except store the current environment
// together with the function definition.
return ["lambda", arg_names, body, env];
} else {
// Function call (no special form)
const func_name = typeof x[0] === "string" ? x[0] : "<anon>";
const [func, ...args] = x.map(exp => evaluate(exp, env));
if (typeof func === "function") {
// Native JavaScript function call
return func(...args);
} else if (func instanceof Array) {
// MiniScheme function call
const [_, arg_names, body, definition_env] = func;
if (arg_names.length !== args.length) {
throw Error("Wrong number of arguments for function " +
func_name + ". " + args.length + " supplied, " +
arg_names.length + " needed.");
}
// Create a new function calling environment with the supplied
// argument names and values. Link to the environment at
// function definition as outer environment.
const call_env = arg_names.reduce(function(env, name, i) {
env[name] = args[i];
return env;
}, Object.create(definition_env));
// Evaluate the function body with the newly created environment
return evaluate(body, call_env);
} else {
if (typeof func === "undefined") {
throw Error("No function supplied.");
} else {
throw Error("Invalid function: " + func_name);
}
}
}
}
Vue.component("item", {
template: "#item-template",
props: ["model", "index", "parentToggle", "parentModel"],
data: function() {
return {
collapsed: false,
};
},
computed: {
isList: function() {
return this.model instanceof Array;
},
isLambdaArgList: function() {
return this.isList
&& this.index === 1
&& this.parentModel[0].valueOf() === "lambda";
},
},
methods: {
click: function(event) {
if (!this.isList) { //
event.stopPropagation();
if (this.index === 0) {
this.parentToggle();
}
return false;
}
},
toggle: function() {
if (!this.isLambdaArgList) {
this.collapsed = !this.collapsed;
}
},
},
});
const vm = new Vue({
el: "#app",
data: {
input: "",
tokens: [],
ast: [],
env: {},
global_env: global_env,
result: undefined,
error: false,
debug: true
},
computed: {
parenBalance: function() {
return this.input.split("(").length -
this.input.split(")").length;
}
},
watch: {
input: function(val) {
this.ast = [];
this.result = undefined;
this.error = false;
try {
this.tokens = tokenize(val);
this.ast = parse(this.tokens.slice());
this.env = Object.create(this.global_env);
let result = evaluate(this.ast, this.env);
if (result instanceof Array) {
const pprint = tree => tree instanceof Array ?
"(" + tree.map(pprint).join(" ") + ")" : tree;
this.result = pprint(result.slice(0, -1));
} else if (typeof result === "function") {
this.result = "native function: " + result.name;
} else {
this.result = result;
}
} catch (error) {
this.error = error;
}
}
},
});
// Example input:
vm.input = `(define abs (lambda (a) (if (> a 0) a (- 0 a))))
(define avg (lambda (a b) (/ (+ a b) 2) ))
(define sqrt (lambda (x) (begin
(define start_guess 1)
(define tolerance 0.000001)
(define good_enough? (lambda (guess)
(<= (abs (- x (* guess guess))) tolerance)
))
(define sqrt_iter (lambda (guess)
(if (good_enough? guess) guess (sqrt_iter (avg guess (/ x guess))))
))
(sqrt_iter start_guess))))
(sqrt 2)`;
}());