-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
78 lines (63 loc) · 1.41 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* 解析器(语法分析初步生成ast)
* @param {*} tokens
*/
const parser = (tokens) => {
// 记录位置
let current = 0
// 声明语法树
let ast = {
type: 'Program',
body: [],
}
// ast.body记录语法树
while (current < tokens.length) {
ast.body.push(walk())
}
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,
}
}
// 括号处理
if (token.type === 'operator' && token.value === '(') {
// 跳过括号
token = tokens[++current]
// 括号为调用表达式
let node = {
type: 'CallExpression',
name: token.value,
params: [],
}
// 跳过方法名
token = tokens[++current]
// 遍历括号内(参数)
while (
token.type !== 'operator' ||
(token.type === 'operator' && token.value !== ')')
) {
// 记录改节点参数 (参数存在调用表达式此处递归)
node.params.push(walk())
token = tokens[current]
}
current++
return node
}
throw new TypeError(token.type)
}
return ast
}
module.exports = parser