-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (36 loc) · 936 Bytes
/
index.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
const { Parser } = require("acorn");
const NodeIterator = require("./iterator");
const Scope = require("./scope");
class Interpreter {
constructor(code = "", preDeclaration = {}) {
this.code = code;
//preDeclaration 是预先定义的变量
this.preDeclaration = preDeclaration;
this.ast = Parser.parse(code);
this.nodeIterator = null;
this.init();
}
//init方法来预先定义变量
init() {
const globalScope = new Scope("function");
//遍历传入的对象
Object.keys(this.preDeclaration).forEach((key) => {
globalScope.addDeclaration(key, this.preDeclaration[key]);
});
//把全局作用域和null节点传入节点遍历器
this.nodeIterator = new NodeIterator(null, globalScope);
}
run() {
return this.nodeIterator.traverse(this.ast);
}
}
module.exports = Interpreter;
new Interpreter(
`
const a = 2;
console.log(a);
`,
{
b: 2,
}
).run();