aboutsummaryrefslogtreecommitdiff
path: root/src/ast/parser.rs
blob: 842ad092e048c20529e9e9237459c95a7c224217 (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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use super::{Expr, Stmt};
use crate::lexer::{Literal, Token, TokenType};

pub struct AstParser<'a> {
    tokens: Vec<Token<'a>>,
    index: usize,
}

/// Implementation containing utilities used by the parsers internal components
impl<'a> AstParser<'a> {
    pub fn new(tokens: Vec<Token<'a>>) -> Self {
        Self { tokens, index: 0 }
    }

    fn previous(&self) -> Option<&Token> {
        self.tokens.get(self.index - 1)
    }

    fn peek(&self) -> &Token {
        &self.tokens[self.index]
    }

    fn peek_nth(&self, nth: usize) -> Option<&Token> {
        self.tokens.get(self.index + nth)
    }

    fn advance(&mut self) -> Option<&Token> {
        if self.eof() {
            return None;
        }

        self.index += 1;
        Some(&self.tokens[self.index - 1])
    }

    fn advance_if(&mut self, next: impl FnOnce(&Token) -> bool) -> bool {
        if self.eof() {
            return false;
        }

        if next(self.peek()) {
            self.advance();
            return true;
        }

        false
    }

    fn advance_if_eq(&mut self, next: &TokenType) -> bool {
        self.advance_if(|it| it.tt == *next)
    }

    fn advance_seq(&mut self, seq: &[TokenType]) -> bool {
        for token in seq {
            if !self.advance_if_eq(token) {
                return false;
            }
        }

        true
    }

    fn consume(&mut self, next: TokenType, error: &str) {
        if std::mem::discriminant(&self.peek().tt) != std::mem::discriminant(&next) {
            panic!("{error}");
        }
        self.advance();
    }

    fn eof(&self) -> bool {
        self.index >= self.tokens.len()
    }
}

/// Implementation containing parsers internal components related to statements
impl<'a> AstParser<'a> {
    pub fn parse(&mut self) -> Vec<Stmt> {
        let mut statements = Vec::new();

        while !self.eof() {
            statements.push(self.statement());
        }

        statements
    }

    fn block(&mut self) -> Vec<Stmt> {
        self.consume(TokenType::LeftBrace, "Expected '{' at beggining of block");

        let mut statements = Vec::new();

        while !self.eof() && self.peek().tt != TokenType::RightBrace {
            statements.push(self.statement());
        }

        self.consume(TokenType::RightBrace, "Expected '}' at end of block");
        statements
    }

    fn statement(&mut self) -> Stmt {
        if self.peek().tt == TokenType::LeftBrace {
            return Stmt::Block(self.block());
        }

        if self.advance_if_eq(&TokenType::Var) {
            return self.var_statement();
        }

        if self.advance_if_eq(&TokenType::Val) {
            return self.val_statement();
        }

        if self.advance_if_eq(&TokenType::If) {
            return self.if_statement();
        }

        if self.advance_if_eq(&TokenType::For) {
            return self.for_statement();
        }

        // If we couldn't parse a statement return an expression statement
        self.expression_statement()
    }

    fn var_statement(&mut self) -> Stmt {
        let TokenType::Identifier(ident) = self.peek().tt.clone() else {
            panic!("Identifier expected after 'var'");
        };

        self.advance(); // Advancing from the identifier
        self.consume(TokenType::Eq, "Expected '=' after identifier");

        let value = self.expression();

        self.consume(TokenType::SemiColon, "Expected ';' at end of statement");

        Stmt::Var { ident, value }
    }

    fn val_statement(&mut self) -> Stmt {
        let TokenType::Identifier(ident) = self.peek().tt.clone() else {
            panic!("Identifier expected after 'val'");
        };

        self.advance(); // Advancing from the identifier
        self.consume(TokenType::Eq, "Expected '=' after identifier");

        let value = self.expression();

        self.consume(TokenType::SemiColon, "Expected ';' at end of statement");

        Stmt::Val { ident, value }
    }

    fn if_statement(&mut self) -> Stmt {
        let condition = self.expression();
        let body = self.block();

        Stmt::If { condition, body }
    }

    fn for_statement(&mut self) -> Stmt {
        let binding = self.expression();
        let Expr::Variable(binding) = binding else {
            panic!("Left side of for statement must be identifier");
        };

        self.consume(
            TokenType::In,
            "Expected 'in' in between identifier and range",
        );

        let range_start = self.expression();
        self.consume(
            TokenType::DotDot,
            "Expected '..' denoting min and max of range",
        );
        let range_end = self.expression();

        let body = self.block();

        Stmt::For {
            binding,
            range: (range_start, range_end),
            body,
        }
    }

    fn expression_statement(&mut self) -> Stmt {
        let expr = self.expression();

        // FIXME: Move assignment handling
        if self.advance_if_eq(&TokenType::Eq) {
            if let Expr::Variable(ident) = &expr {
                let value = self.expression();

                self.consume(TokenType::SemiColon, "Expected ';' at end of statement");
                return Stmt::Assignment {
                    ident: ident.clone(),
                    value,
                };
            }
        }

        self.consume(TokenType::SemiColon, "Expected ';' at end of statement");
        Stmt::Expr(expr)
    }
}

/// Implementation containing parsers internal components related to expressions
impl<'a> AstParser<'a> {
    // FIXME: Should probably avoid cloning token types

    fn expression(&mut self) -> Expr {
        self.logical_or()
    }

    fn unary(&mut self) -> Expr {
        if !self.eof()
            && matches!(
                self.peek().tt,
                TokenType::Bang | TokenType::Plus | TokenType::Minus
            )
        {
            let operator = self.advance().unwrap().tt.clone();
            let rhs = self.unary();
            return Expr::Unary {
                operator,
                expr: Box::new(rhs),
            };
        }

        self.call()
    }

    fn call(&mut self) -> Expr {
        let mut expr = self.primary();

        if self.advance_if_eq(&TokenType::LeftParen) {
            let mut arguments = Vec::<Expr>::new();

            if self.peek().tt != TokenType::RightParen {
                loop {
                    arguments.push(self.expression());
                    if !self.advance_if_eq(&TokenType::Comma) {
                        break;
                    }
                }
            }

            self.consume(
                TokenType::RightParen,
                "Expected ')' to close off function call",
            );

            let Expr::Variable(ident) = expr else { panic!("uh oh spaghettio"); };

            expr = Expr::Call { ident, arguments }
        }

        expr
    }

    fn primary(&mut self) -> Expr {
        match self.advance().unwrap().tt.clone() {
            TokenType::Literal(literal) => Expr::Literal(literal),
            TokenType::Identifier(ident) => Expr::Variable(ident),
            TokenType::LeftParen => {
                let expr = self.expression();
                self.consume(TokenType::RightParen, "Must end expression with ')'");
                Expr::Grouping(Box::new(expr))
            }
            _ => unimplemented!("{:?}", self.peek()),
        }
    }
}

// Macro to generate repetitive binary expressions. Things like addition,
// multiplication, exc.
macro_rules! binary_expr {
    ($name:ident, $parent:ident, $pattern:pat) => {
        fn $name(&mut self) -> Expr {
            let mut expr = self.$parent();

            while !self.eof() && matches!(self.peek().tt, $pattern) {
                let operator = self.advance().unwrap().tt.clone();
                let rhs = self.$parent();
                expr = Expr::Binary {
                    operator,
                    lhs: Box::new(expr),
                    rhs: Box::new(rhs),
                };
            }

            expr
        }
    };
}

#[rustfmt::skip]
impl<'a> AstParser<'a> {
    // Binary expressions in order of precedence from lowest to highest.
    binary_expr!(logical_or      , logical_and     , (TokenType::PipePipe));
    binary_expr!(logical_and     , equality        , (TokenType::AmpAmp));
    binary_expr!(equality        , comparison      , (TokenType::BangEq | TokenType::EqEq));
    binary_expr!(comparison      , bitwise_shifting, (TokenType::Lt     | TokenType::Gt    | TokenType::LtEq | TokenType::GtEq));
    binary_expr!(bitwise_shifting, additive        , (TokenType::LtLt   | TokenType::GtGt));
    binary_expr!(additive        , multiplicative  , (TokenType::Plus   | TokenType::Minus));
    binary_expr!(multiplicative  , unary           , (TokenType::Star   | TokenType::Slash | TokenType::Perc));
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;

    use super::AstParser;
    use crate::ast::Expr;
    use crate::lexer::{Lexer, Literal, TokenType};

    #[test]
    fn basic_expression_a() {
        let lexer = Lexer::new("3 + 5 * 4");
        let tokens = lexer.collect_vec();

        let expected_ast = Expr::Binary {
            operator: TokenType::Plus,
            lhs: Box::new(Expr::Literal(Literal::Number(3))),
            rhs: Box::new(Expr::Binary {
                operator: TokenType::Star,
                lhs: Box::new(Expr::Literal(Literal::Number(5))),
                rhs: Box::new(Expr::Literal(Literal::Number(4))),
            }),
        };

        let mut parser = AstParser::new(tokens);
        let generated_ast = parser.expression();

        println!("Expected AST:\n{expected_ast:#?}\n\n");
        println!("Generated AST:\n{generated_ast:#?}\n\n");

        assert_eq!(expected_ast, generated_ast);
    }

    #[test]
    fn basic_expression_b() {
        let lexer = Lexer::new("17 - (-5 + 5) / 6");
        let tokens = lexer.collect_vec();

        let expected_ast = Expr::Binary {
            operator: TokenType::Minus,
            lhs: Box::new(Expr::Literal(Literal::Number(17))),
            rhs: Box::new(Expr::Binary {
                operator: TokenType::Slash,
                lhs: Box::new(Expr::Grouping(Box::new(Expr::Binary {
                    operator: TokenType::Plus,
                    lhs: Box::new(Expr::Unary {
                        operator: TokenType::Minus,
                        expr: Box::new(Expr::Literal(Literal::Number(5))),
                    }),
                    rhs: Box::new(Expr::Literal(Literal::Number(5))),
                }))),
                rhs: Box::new(Expr::Literal(Literal::Number(6))),
            }),
        };

        let mut parser = AstParser::new(tokens);
        let generated_ast = parser.expression();

        println!("Expected AST:\n{expected_ast:#?}\n\n");
        println!("Generated AST:\n{generated_ast:#?}\n\n");

        assert_eq!(expected_ast, generated_ast);
    }

    #[test]
    fn basic_expression_c() {
        let lexer = Lexer::new("9 > 6 && 5 + 7 == 32 || \"apple\" != \"banana\"");
        let tokens = lexer.collect_vec();

        // TODO:
    }
}