-
Notifications
You must be signed in to change notification settings - Fork 4
/
parser.ts
60 lines (45 loc) · 1.3 KB
/
parser.ts
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
import {
createRootNode,
createStringLiteralNode,
createNumberLiteralNode,
createCallExpression,
} from "./ast";
import { Token, TokenTypes } from "./tokenizer";
export function parser(tokens: Token[]) {
const root = createRootNode();
let current = 0;
function walk() {
let token = tokens[current];
if (token.type === TokenTypes.Number) {
current++;
return createNumberLiteralNode(token.value);
}
if (token.type === TokenTypes.String) {
current++;
return createStringLiteralNode(token.value);
}
if (token.type === TokenTypes.Paren && token.value === "(") {
token = tokens[++current];
let node = createCallExpression(token.value);
// 上一个 token 已经使用完了 所以我们还需要在移动下位置
token = tokens[++current];
// params
while (
// token.type !== TokenType.paren ||
// (token.type === TokenType.paren && token.value !== ")")
!(token.type === TokenTypes.Paren && token.value === ")")
) {
node.params.push(walk());
token = tokens[current];
}
// 跳过 )
current++;
return node;
}
throw new Error(`识别不了的 token: ${token}`);
}
while (current < tokens.length) {
root.body.push(walk());
}
return root;
}