summary refs log tree commit diff
path: root/the_e_programming_language/ast.ts
blob: 80210d834edbaec81205632bfe3634ebda6b7f12 (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import { Token, TokenType } from "./tokenizer.ts";

export interface ASTNode {
    type: string;
}

export interface VariableDeclarationNode extends ASTNode {
    type: "VariableDeclaration";
    identifier: string;
    value: ASTNode;
    vtype: string;
    length: number;
}

export interface FunctionDeclarationNode extends ASTNode {
    type: "FunctionDeclaration";
    name: string;
    // params: string[];
    body: ASTNode[];
}

export interface AssignmentNode extends ASTNode {
    type: "Assignment";
    identifier: IdentifierNode;
    value: ASTNode;
}

export interface BinaryExpressionNode extends ASTNode {
    type: "BinaryExpression";
    operator: string;
    left: ASTNode;
    right: ASTNode;
}

export interface LiteralNode extends ASTNode {
    type: "Literal";
    value: string;
}

export interface NumberNode extends ASTNode {
    type: "Number";
    value: number;
}

export interface IdentifierNode extends ASTNode {
    type: "Identifier";
    name: string;
    offset?: ASTNode;
}

export interface FunctionCallNode extends ASTNode {
    type: "FunctionCall";
    identifier: string;
    args: ASTNode[];
}

// export interface BranchFunctionCallNode extends ASTNode {
//     type: "BranchFunctionCall";
//     identifier: string;
//     args: ASTNode[];
//     branches: ASTNode[][];
// }

// export interface StartBlockNode extends ASTNode {
//     type: "StartBlock";
//     body: ASTNode[];
// }

export interface IfNode extends ASTNode {
    type: "If";
    condition: ASTNode;
    thenBranch: ASTNode[];
    elseBranch?: ASTNode[];
}

export interface WhileNode extends ASTNode {
    type: "While";
    condition: ASTNode;
    branch: ASTNode[];
}

// export interface ForNode extends ASTNode {
//     type: "For";
//     times: ASTNode;
//     varname: ASTNode;
//     branch: ASTNode[];
// }

// export interface GreenFlagNode extends ASTNode {
//     type: "GreenFlag";
//     branch: ASTNode[];
// }

// use 1 or 0 for boolean
// export interface BooleanNode extends ASTNode {
//     type: "Boolean";
//     value: boolean;
// }

// export interface IncludeNode extends ASTNode {
//     type: "Include";
//     itype: string;
//     path: string;
// }

// export interface ListDeclarationNode extends ASTNode {
//     type: "ListDeclaration";
//     identifier: string;
//     value: ASTNode[];
//     vtype: 'list' | 'global'
// }

export default class AST {
    private tokens: Token[];
    position: number = 0;

    constructor(tokens: Token[]) {
        this.tokens = tokens;
    }

    private peek(ahead = 0): Token {
        return this.tokens[this.position + ahead];
    }

    private advance(): Token {
        return this.tokens[this.position++];
    }

    private match(...types: TokenType[]): boolean {
        if (types.includes(this.peek().type)) {
            this.advance();
            return true;
        }
        return false;
    }

    private matchTk(types: TokenType[], token = this.peek()): boolean {
        if (types.includes(token.type)) {
            return true;
        }
        return false;
    }

    private expect(type: TokenType, errorMessage: string): Token {
        if (this.peek().type === type) {
            return this.advance();
        }
        console.error('trace: tokens', this.tokens, '\nIDX:', this.position);
        throw new Error(errorMessage);
    }

    parse(): ASTNode[] {
        const nodes: ASTNode[] = [];
        while (this.peek().type !== TokenType.EOF) {
            nodes.push(this.parseStatement());
        }
        return nodes;
    }

    private parseStatement(): ASTNode {
        if (this.matchTk([TokenType.TYPE])) {
            const type = this.advance().value
            let len = 1;
            if (this.match(TokenType.LBRACKET)) {
                len = Number(this.expect(TokenType.NUMBER, 'expected number after [').value);
                this.expect(TokenType.RBRACKET, 'expected ] after length')
            }
            const identifier = this.expect(TokenType.IDENTIFIER, "expected var name after type (hint: functions dont have return types yet").value;
            this.expect(TokenType.ASSIGN, "expected = after var name");
            const value = this.parseAssignment(false);
            return { type: "VariableDeclaration", identifier, value, vtype: type, length: len } as VariableDeclarationNode;
        }

        if (this.match(TokenType.FN_DECL)) {
            const name = this.expect(TokenType.IDENTIFIER, "expected function name after fn").value;
            // this.expect(TokenType.LPAREN, "Expected '(' after function name");
            // const params: string[] = [];
            // if (!this.match(TokenType.RPAREN)) {
            //     do {
            //         params.push(this.expect(TokenType.IDENTIFIER, "Expected parameter name").value);
            //     } while (this.match(TokenType.COMMA));
            //     this.expect(TokenType.RPAREN, "Expected ')' after parameters");
            // }
            this.expect(TokenType.LBRACE, "expected '{' before function body");
            const body = this.parseBlock();
            return { type: "FunctionDeclaration", name, body } as FunctionDeclarationNode;
        }

        if (this.match(TokenType.IF)) {
            this.expect(TokenType.LPAREN, "Expected '(' after 'if'");
            const condition = this.parseAssignment();
            this.expect(TokenType.RPAREN, "Expected ')' after if condition");
            this.expect(TokenType.LBRACE, "Expected '{' after if condition");
            const thenBranch = this.parseBlock();
            let elseBranch: ASTNode[] | undefined;
            if (this.match(TokenType.ELSE)) {
                this.expect(TokenType.LBRACE, "Expected '{' after 'else'");
                elseBranch = this.parseBlock();
            }
            return { type: "If", condition, thenBranch, elseBranch } as IfNode;
        }

        if (this.match(TokenType.WHILE)) {
            this.expect(TokenType.LPAREN, "Expected '(' after 'while'");
            const condition = this.parseAssignment();
            this.expect(TokenType.RPAREN, "Expected ')' after while condition");
            this.expect(TokenType.LBRACE, "Expected '{' after while condition");
            const branch = this.parseBlock();
            return { type: "While", condition, branch } as WhileNode;
        }

        // if (this.match(TokenType.FOR)) {
        //     this.expect(TokenType.LPAREN, "Expected '(' after 'for'");
        //     const varname = this.parseAssignment();
        //     const of = this.expect(TokenType.IDENTIFIER, 'expected of');
        //     if (of.value !== 'of') throw new Error('expected of');
        //     const times = this.parseAssignment();
        //     this.expect(TokenType.RPAREN, "Expected ')' after for");
        //     this.expect(TokenType.LBRACE, "Expected '{' after for");
        //     const branch = this.parseBlock();

        //     return { type: "For", varname, times, branch } as ForNode;
        // }

        // if (this.match(TokenType.GREENFLAG)) {
        //     this.expect(TokenType.LBRACE, "Expected '{' after greenflag");
        //     const branch = this.parseBlock();

        //     return { type: "GreenFlag", branch } as GreenFlagNode;
        // }

        return this.parseAssignment();
    }

    private parseBlock(): ASTNode[] {
        const nodes: ASTNode[] = [];

        while (!this.match(TokenType.RBRACE)) {
            nodes.push(this.parseStatement());
        }

        return nodes;
    }

    private parseAssignment(allowStuff = true): ASTNode {

        const expr = this.parseBinaryExpression(allowStuff);
        if (this.match(TokenType.ASSIGN)) {
            if (expr.type !== "Identifier")
                throw new Error("invalid assignment target; expected an identifier");
            const value = allowStuff ? this.parseAssignment() : this.parsePrimary(false);
            // let offset = undefined;
            // if (this.match(TokenType.LBRACKET)) {
            //     offset = this.parseAssignment();
            //     this.expect(TokenType.RBRACKET, 'expected ]')
            // }
            return { type: "Assignment", identifier: (expr as IdentifierNode), value } as AssignmentNode;
        }
        return expr;
    }

    private parseBinaryExpression(allowStuff = false): ASTNode {
        let left = this.parseCall(allowStuff);

        while (this.peek().type === TokenType.BINOP) {
            const operator = this.advance().value;
            const right = this.parseCall();
            left = { type: "BinaryExpression", operator, left, right } as BinaryExpressionNode;
        }
        return left;
    }

    private parseCall(allowStuff = false): ASTNode {
        let expr = this.parsePrimary(allowStuff);

        while (this.peek().type === TokenType.LPAREN) {
            expr = this.finishCall(expr);
        }
        return expr;
    }

    private finishCall(callee: ASTNode): ASTNode {
        this.expect(TokenType.LPAREN, "Expected '(' after function name");
        //TODO - arguments
        // const args: ASTNode[] = [];
        // if (this.peek().type !== TokenType.RPAREN) {
        //     do {
        //         args.push(this.parseAssignment());
        //     } while (this.match(TokenType.COMMA));
        // }
        this.expect(TokenType.RPAREN, "Expected ')' after arguments");


        // if (this.peek().type === TokenType.LBRACE) {
        //     const branches: ASTNode[][] = [];
        //     do {
        //         this.expect(TokenType.LBRACE, "Expected '{' for branch block");
        //         branches.push(this.parseBlock());
        //     } while (this.peek().type === TokenType.LBRACE);

        //     if (callee.type !== "Identifier")
        //         throw new Error("Branch function call expects an identifier");
        //     return {
        //         type: "BranchFunctionCall",
        //         identifier: (callee as IdentifierNode).name,
        //         args,
        //         branches,
        //     } as BranchFunctionCallNode;
        // }


        if (callee.type !== "Identifier")
            throw new Error("Function call expects an identifier");
        return {
            type: "FunctionCall",
            identifier: (callee as IdentifierNode).name,
            // args,
        } as FunctionCallNode;
    }

    private parsePrimary(allowOther = true): ASTNode {
        const token = this.peek();

        if (this.match(TokenType.NUMBER)) {
            return { type: "Number", value: Number(token.value) } as NumberNode;
        }

        if (this.match(TokenType.LITERAL)) {
            return { type: "Literal", value: token.value } as LiteralNode;
        }

        if (this.match(TokenType.IDENTIFIER) && allowOther) {

            // if (["True", "true", "False", "false"].includes(token.value)) {
            //     return {
            //         type: "Boolean",
            //         value: token.value === "True" || token.value === "true"
            //     } as BooleanNode;
            // }
            let offset = undefined;
            if (this.match(TokenType.LBRACKET)) {
                offset = this.parseAssignment();
                this.expect(TokenType.RBRACKET, 'expected ]')
            }
            return { type: "Identifier", name: token.value, offset } as IdentifierNode;
        }

        if (this.match(TokenType.LPAREN) && allowOther) {
            const expr = this.parseAssignment();
            this.expect(TokenType.RPAREN, "Expected ')' after expression");
            return expr;
        }

        throw new Error(`Unexpected token: ${token.type}`);
    }

}