-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.ts
52 lines (46 loc) · 1.1 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
import {
Token,
TokenTypes,
NodeTypes,
RootNode,
NumberNode,
CallExpressionNode,
} from "../type/ast";
export function parser(tokens: Token[]) {
const rootNode: RootNode = {
type: NodeTypes.Program,
body: [],
};
let current = 0;
function walk() {
let token = tokens[current];
if (token.type === TokenTypes.number) {
current++;
const numberNode: NumberNode = {
type: NodeTypes.NumberLiteral,
value: token.value,
};
return numberNode;
}
if (token.type === TokenTypes.paren && token.value === "(") {
token = tokens[++current];
const node: CallExpressionNode = {
type: NodeTypes.CallExpression,
name: token.value,
params: [],
};
token = tokens[++current];
while (!(token.type === TokenTypes.paren && token.value === ")")) {
node.params.push(walk());
token = tokens[current];
}
current++;
return node;
}
throw new Error(`do not recognize${token}`);
}
while (current < tokens.length) {
rootNode.body.push(walk());
}
return rootNode;
}