-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
63 lines (55 loc) · 1.13 KB
/
parser.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
/**
* 将tokens转成AST树
* @param {array} tokens
*/
function parser(tokens) {
let current = 0;
function walk() {
let token = tokens[current];
// 数字
if (token.type === 'number') {
current++;
return {
type: 'NumberLiteral',
value: token.value
};
}
// 字符串
if (token.type === 'string') {
current++;
return {
type: 'StringLiteral',
value: token.value
};
}
// callExpression
if (token.type === 'paren' && token.value === '(') {
token = tokens[++current];
let node = {
type: 'CallExpression',
name: token.value,
params: []
};
token = tokens[++current];
while (
token.type !== 'paren' ||
(token.type === 'paren' && token.value !== ')')
) {
node.params.push(walk());
token = tokens[current];
}
current++;
return node;
}
throw new TypeError(token.type);
}
let ast = {
type: 'Program',
body: []
};
while (current < tokens.length) {
ast.body.push(walk());
}
return ast;
}
module.exports = parser;