Skip to main content

rl_lang/parser/expressions/
unary.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 unary prefix expressions: `!` (logical not) and `-` (negation).
10    ///
11    /// Right-associative by recursion: `--x` parses as `-(-(x))`.
12    /// Falls through to [`parse_primary`] when no prefix operator is present.
13    ///
14    /// [`parse_primary`]: Parser::parse_primary
15    pub fn parse_unary(&mut self) -> Result<ExprId, Error> {
16        let start = self.peek_span();
17        if self.match_type(&[TokenType::Bang, TokenType::Minus]) {
18            let operator = self.previous();
19            let operand = self.parse_unary()?;
20            let operand_id = self.ast_arena.exprs.get(operand);
21            let span = start.join(operand_id.span);
22            return Ok(self
23                .ast_arena
24                .alloc_expr(ExpressionKind::Unary { operator, operand }, span));
25        }
26        self.parse_primary()
27    }
28}