/
interpreter.ts
245 lines (235 loc) · 7.13 KB
/
interpreter.ts
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
import * as Node from "../parser/node";
// 作用域
class Scope {
private parent: Scope | null;
private declarations = new Map<string, any>();
constructor(parentScope: Scope | null) {
this.parent = parentScope;
}
set(name: string, value: any) {
this.declarations.set(name, value);
}
getLocal(name: string) {
return this.declarations.get(name);
}
// 模拟作用域链 向上查找
get(name: string) {
let res = this.getLocal(name);
if (!res && this.parent) {
res = this.parent.get(name);
}
return res;
}
has(name: string) {
return !!this.getLocal(name);
}
}
const getIdentifierValue = (node: any, scope: Scope) => {
if (node.type === "Identifier") {
return scope.get(node.name);
} else {
return evaluator(node, scope);
}
};
const astInterpreters = {
Program(node: Node.Script, scope: Scope) {
node.body.forEach((item) => {
evaluator(item, scope);
});
},
VariableDeclaration(node: Node.VariableDeclaration, scope: Scope) {
for (const declaration of node.declarations) {
scope.set(declaration.id.name, evaluator(declaration.init, scope));
}
},
FunctionDeclaration(node: Node.FunctionDeclaration, scope: Scope) {
// 函数名称
const declareName = evaluator(node.id, scope);
// 设置函数作用域
scope.set(declareName, function <
F extends (...arg: any[]) => any
>(this: ThisParameterType<F>, ...args: Parameters<F>) {
const funcScope = new Scope(scope);
node.params.forEach((item, index) => {
funcScope.set(item.name, args[index]);
});
funcScope.set("this", this);
return evaluator(node.body, funcScope);
});
},
WhileStatement(node: Node.WhileStatement, scope: Scope) {
scope.set("break", false);
// 如果测试条件一直成立
while (evaluator(node.test, scope)) {
evaluator(node.body, scope);
if (scope.get("break")) {
break;
}
}
},
BreakStatement(node: Node.BreakStatement, scope: Scope) {
scope.set("break", true);
},
ForStatement(node: Node.ForStatement, scope: Scope) {
scope.set("break", false);
const { init, test, update, body } = node;
evaluator(init, scope);
while (evaluator(test, scope)) {
evaluator(body, scope);
evaluator(update, scope);
if (scope.get("break")) {
break;
}
}
},
// 块语句中 我们需要检测所有的 return 语句
BlockStatement(node: Node.BlockStatement, scope: Scope) {
scope.set("return", false);
for (let i = 0; i < node.body.length; i++) {
// 如果有语句将 return 修改为 true 则终止
const v = evaluator(node.body[i], scope);
if (scope.get("return")) {
return v;
}
}
},
IfStatement(node: Node.IfStatement, scope: Scope) {
const test = evaluator(node.test, scope);
if (test) {
// 执行完块的语句后 返回块的值
const v = evaluator(node.consequent, scope);
return v;
} else if (node.alternate != null) {
const v = evaluator(node.alternate, scope);
return v;
}
},
ReturnStatement(node: Node.ReturnStatement, scope: Scope) {
scope.set("return", true);
return evaluator(node.argument, scope);
},
ExpressionStatement(node: Node.ExpressionStatement, scope: Scope) {
return evaluator(node.expression, scope);
},
CallExpression(node: Node.CallExpression, scope: Scope) {
const args = node.arguments.map((item: Node.Expression) => {
if (item.type === "Identifier") {
return scope.get((<Node.Identifier>item).name);
}
return evaluator(item, scope);
});
if (node.callee.type === "MemberExpression") {
const fn = evaluator(node.callee, scope);
const obj = evaluator((<Node.MemberExpression>node.callee).object, scope);
return fn.apply(obj, args);
} else {
const fn = scope.get(evaluator(node.callee, scope));
return fn.apply(null, args);
}
},
MemberExpression(node: Node.MemberExpression, scope: Scope) {
const obj = scope.get(evaluator(node.object, scope));
return obj[evaluator(node.property, scope)];
},
AssignmentExpression(node: Node.AssignmentExpression, scope: Scope) {
const left = (node.left as Node.Identifier).name;
const rightValue = getIdentifierValue(node.right, scope);
switch (node.operator) {
case "=":
scope.set(left, rightValue);
break;
}
},
BinaryExpression(node: Node.BinaryExpression, scope: Scope) {
const leftValue = getIdentifierValue(node.left, scope);
const rightValue = getIdentifierValue(node.right, scope);
switch (node.operator) {
case "+":
return leftValue + rightValue;
case "-":
return leftValue - rightValue;
case "*":
return leftValue * rightValue;
case "/":
return leftValue / rightValue;
case "==":
return leftValue == rightValue;
case "===":
return leftValue === rightValue;
case "!=":
return leftValue !== rightValue;
case "!==":
return leftValue !== rightValue;
case "<":
return leftValue < rightValue;
case ">":
return leftValue > rightValue;
case "<=":
return leftValue <= rightValue;
case ">=":
return leftValue >= rightValue;
default:
throw Error("upsupported operator:" + node.operator);
}
},
LogicalExpression(node: Node.BinaryExpression, scope: Scope) {
const leftValue = getIdentifierValue(node.left, scope);
const rightValue = getIdentifierValue(node.right, scope);
switch (node.operator) {
case "**":
return leftValue ** rightValue;
case "&&":
return leftValue && rightValue;
case "||":
return leftValue || rightValue;
default:
throw Error("upsupported operator:" + node.operator);
}
},
UpdateExpression(node: Node.UpdateExpression, scope: Scope) {
const argument = node.argument as Node.Identifier;
const identify = argument.name;
if (node.operator === "++") {
scope.set(identify, (getIdentifierValue(argument, scope) as number) + 1);
} else {
scope.set(identify, (getIdentifierValue(argument, scope) as number) - 1);
}
},
Identifier(node: Node.Identifier) {
return node.name;
},
Literal(node: Node.Literal) {
return node.value;
},
};
//解释器
const evaluator = (node: { type: string } | null, scope: Scope): any => {
if (!node) {
return undefined;
}
try {
return astInterpreters[node.type](node, scope);
} catch (e: unknown) {
console.error("unsupported ast type: " + node.type);
}
};
const evaluate = (node: Node.Script): any[][] => {
const globalScope = new Scope(null);
const output: any[][] = [];
globalScope.set("console", {
log: function (...args: any[]) {
output.push([...args]);
},
});
globalScope.set("parseInt", parseInt);
globalScope.set("Math", Math);
globalScope.set("String", String);
globalScope.set("Number", Number);
globalScope.set("Map", Map);
globalScope.set("Set", Set);
globalScope.set("Boolean", Boolean);
globalScope.set("Array", Array);
evaluator(node, globalScope);
return output;
};
export default evaluate;