-
Notifications
You must be signed in to change notification settings - Fork 2
/
12_language.js
264 lines (225 loc) · 6.74 KB
/
12_language.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
264
function parseExpression(program) {
program = skipSpace(program);
let match, expr;
if (match = /^"([^"]*)"/.exec(program)) {
expr = {type: "value", value: match[1]};
} else if (match = /^\d+\b/.exec(program)) {
expr = {type: "value", value: Number(match[0])};
} else if (match = /^[^\s(),#"]+/.exec(program)) {
expr = {type: "word", name: match[0]};
} else {
throw new SyntaxError("Unexpected syntax: " + program);
}
return parseApply(expr, program.slice(match[0].length));
}
function skipSpace(string) {
let first = string.search(/\S/);
if (first == -1) return "";
return string.slice(first);
}
function parseApply(expr, program) {
program = skipSpace(program);
if (program[0] != "(") {
return {expr: expr, rest: program};
}
program = skipSpace(program.slice(1));
expr = {type: "apply", operator: expr, args: []};
while (program[0] != ")") {
let arg = parseExpression(program);
expr.args.push(arg.expr);
program = skipSpace(arg.rest);
if (program[0] == ",") {
program = skipSpace(program.slice(1));
} else if (program[0] != ")") {
throw new SyntaxError("Expected ',' or ')'");
}
}
return parseApply(expr, program.slice(1));
}
function parse(program) {
let {expr, rest} = parseExpression(program);
if (skipSpace(rest).length > 0) {
throw new SyntaxError("Unexpected text after program");
}
return expr;
}
// operator: {type: "word", name: "+"},
// args: [{type: "word", name: "a"},
// {type: "value", value: 10}]}
var specialForms = Object.create(null);
function evaluate(expr, scope) {
if (expr.type == "value") {
return expr.value;
} else if (expr.type == "word") {
if (expr.name in scope) {
return scope[expr.name];
} else {
throw new ReferenceError(
`Undefined binding: ${expr.name}`);
}
} else if (expr.type == "apply") {
let {operator, args} = expr;
if (operator.type == "word" &&
operator.name in specialForms) {
return specialForms[operator.name](expr.args, scope);
} else {
let op = evaluate(operator, scope);
if (typeof op == "function") {
return op(...args.map(arg => evaluate(arg, scope)));
} else {
throw new TypeError("Applying a non-function.");
}
}
}
}
specialForms.if = (args, scope) => {
if (args.length != 3) {
throw new SyntaxError("Wrong number of args to if");
} else if (evaluate(args[0], scope) !== false) {
return evaluate(args[1], scope);
} else {
return evaluate(args[2], scope);
}
};
specialForms.while = (args, scope) => {
if (args.length != 2) {
throw new SyntaxError("Wrong number of args to while");
}
while (evaluate(args[0], scope) !== false) {
evaluate(args[1], scope);
}
// Since undefined does not exist in Egg, we return false,
// for lack of a meaningful result.
return false;
};
specialForms.do = (args, scope) => {
let value = false;
for (let arg of args) {
value = evaluate(arg, scope);
}
return value;
};
specialForms.define = (args, scope) => {
if (args.length != 2 || args[0].type != "word") {
throw new SyntaxError("Incorrect use of define");
}
let value = evaluate(args[1], scope);
scope[args[0].name] = value;
return value;
};
var topScope = Object.create(null);
topScope.true = true;
topScope.false = false;
for (let op of ["+", "-", "*", "/", "==", "<", ">"]) {
topScope[op] = Function("a, b", `return a ${op} b;`);
}
topScope.print = value => {
console.log(value);
return value;
};
function run(program) {
return evaluate(parse(program), Object.create(topScope));
}
specialForms.fun = (args, scope) => {
if (!args.length) {
throw new SyntaxError("Functions need a body");
}
let body = args[args.length - 1];
let params = args.slice(0, args.length - 1).map(expr => {
if (expr.type != "word") {
throw new SyntaxError("Parameter names must be words");
}
return expr.name;
});
return function() {
if (arguments.length != params.length) {
throw new TypeError("Wrong number of arguments");
}
let localScope = Object.create(scope);
for (let i = 0; i < arguments.length; i++) {
localScope[params[i]] = arguments[i];
}
return evaluate(body, localScope);
};
};
// // Modify these definitions...
topScope.array = (...args) => args;
topScope.length = array => array.length;
topScope.element = (array, i) => array[i];
// run(`
// do(define(sum, fun(array,
// do(define(i, 0),
// define(sum, 0),
// while(<(i, length(array)),
// do(define(sum, +(sum, element(array, i))),
// define(i, +(i, 1)))),
// sum))),
// print(sum(array(1, 2, 3))))
// `);
// // → 6
// This is the old skipSpace. Modify it...
function skipSpace(string) {
// My solution
// let first = string.search(/\S/);
// if (first == -1) return "";
// let nstring = string.slice(first);
// const regex = /#.*\n/g;
// nstring = nstring.replace(regex,'');
// return nstring;
// Their solution
let skippable = string.match(/^(\s|#.*)*/g);
return string.slice(skippable[0].length);
}
// console.log(parse(" a"));
// console.log(parse("# hello\nx"));
// // → {type: "word", name: "x"}
// console.log(parse("a # one\n # two\n()"));
// // → {type: "apply",
// // operator: {type: "word", name: "a"},
// // args: []}
// specialForms.set = (args, scope) => {
// Your code here.
////////////////
//My solution //
////////////////
// const outerScope = Object.getPrototypeOf(scope);
// const innerScopeBinding = Object.prototype.hasOwnProperty.call(scope, args[0].name);
// const outerScopeBinding = Object.prototype.hasOwnProperty.call(outerScope, args[0].name);
// if (innerScopeBinding) {
// return specialForms.define(args, scope)
// }
// else if (outerScopeBinding)
// {
// return specialForms.define([args[0], parse(scope.val.toString())], outerScope)
// }
// else {
// throw new ReferenceError(
// `Undefined binding: ${args[0].name}`);
// }
// };
/////////////////////////////
// Their (better) solution //
/////////////////////////////
specialForms.set = (args, scope) => {
if (args.length != 2 || args[0].type != "word") {
throw new SyntaxError("Bad use of Set")
}
let varName = args[0].name;
let varValue = evaluate(args[1], scope);
for (let currentScope = scope; currentScope; currentScope = Object.getPrototypeOf(currentScope)) {
if (Object.prototype.hasOwnProperty.call(currentScope, varName)) {
currentScope[varName] = varValue;
return varValue;
}
}
throw new ReferenceError(`Setting undefined binding: ${varName}`)
};
run(`
do(define(x, 4),
define(setx, fun(val, set(x, val))),
setx(50),
print(x))
`);
// → 50
run(`set(quux, true)`);
// → Some kind of ReferenceError