Skip to main content

rl_lang/parser/expressions/
term.rs

1use crate::{
2    ast::{ExprId, nodes::ExpressionKind},
3    lexer::tokentypes::TokenType,
4    parser::parser_logic::Parser,
5    utils::errors::Error,
6};
7
8impl Parser {
9    /// Parses additive expressions: `+` and `-`.
10    ///
11    /// Left-associative: `a + b - c` is `(a + b) - c`.
12    pub fn parse_term(&mut self) -> Result<ExprId, Error> {
13        let mut left = self.parse_factor()?;
14        while self.match_type(&[TokenType::Plus, TokenType::Minus]) {
15            while self.match_type(&[TokenType::Newline]) {}
16            let operator = self.previous();
17            while self.match_type(&[TokenType::Newline]) {}
18            let right = self.parse_factor()?;
19            let left_id = self.ast_arena.exprs.get(left);
20            let right_id = self.ast_arena.exprs.get(right);
21
22            let span = left_id.span.join(right_id.span);
23            left = self.ast_arena.alloc_expr(
24                ExpressionKind::Binary {
25                    left,
26                    operator,
27                    right,
28                },
29                span,
30            );
31        }
32        Ok(left)
33    }
34}