-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-parser.js
78 lines (63 loc) · 1.66 KB
/
2-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
// 2-parser.js
// tokenを受け取り、ASTにする
export function parser(tokens) {
let current = 0; //現在位置
function walk () {
let token = tokens[current];
// numberがあるとき
if (token.type === 'number') {
current++;
//NumberLiteral nodeを作成
return {
type: 'NumberLiteral',
value: token.value,
};
}
// stringがあるとき
if (token.type === 'string') {
current++;
//StringLiteral nodeを作成
return {
type: 'StringLiteral',
value: token.value,
};
}
// parenと 「 ( 」のときはASTに必要ないので次に
if (token.type === 'paren' && token.value === '(') {
token = tokens[++current];
let node = {
type: 'CallExpression',
name: token.value,
params:[],
}
token = tokens[++current];
//「 ) 」まで callExpression のparamsとなる各tokenをwhile文でループ
while (
(token.type !== 'paren') ||
(token.type === 'paren' && token.value !== ')')
) {
node.params.push(walk());
token = tokens[current];
if (token === undefined) {
alert('正しい構文を入力してください');
}
}
// 「 ) 」のときskip
current++;
return node;
}
//例外処理
alert('正しい構文を入力してください');
throw new TypeError(token.type);
}
// rootのASTを作成
let ast = {
type: 'Program',
body: [],
};
//ループ内でast.body.push(walk())を行う;
while (current < tokens.length) {
ast.body.push(walk());
}
return ast;
}