-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
79 lines (58 loc) · 1.91 KB
/
parser.js
File metadata and controls
79 lines (58 loc) · 1.91 KB
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
/*
// [
// { type: 'paren', value: '(' },
// { type: 'symbol', value: 'add' },
// { type: 'number', value: '2' },
// { type: 'paren', value: '(' },
// { type: 'symbol', value: 'subtract' },
// { type: 'number', value: '4' },
// { type: 'number', value: '2' },
// { type: 'paren', value: ')' }, <<< 右圆括号
// { type: 'paren', value: ')' } <<< 右圆括号
// ]
*/
/*
当 ( 开始新的函数
symbol 函数名
取得value.. while...循环
直到 ) 结束退出.
*/
function parser(tokens) {
let index = 0
function walk() {
const token = tokens[index++]
let node = {}
if (token.type === 'number') {
node = {
type: 'NumberLiteral',
value: token.value
}
} else if (token.type === 'paren' && token.value === '(') {
let token = tokens[index++]
if (token.type === 'symbol') {
node = {
type: 'CallExpression',
name: token.value,
params: []
}
const context = node.params
while(!(token.type === 'paren' && token.value === ')')) {
context.push(walk())
token = tokens[index]
}
} else {
throw new TypeError(token.type)
}
} else if (token && token.type){ // 最外层
throw new TypeError(token.type)
} else {
// !node
}
return node
}
return {
type: 'Program',
body: [walk()]
}
}
module.exports = parser