Skip to main content

rl_lang/parser/statements/
while_statement.rs

1//! `while` loop parser.
2//!
3//! Handles the single `while` form:
4//!
5//! ```text
6//! while (condition) { body }
7//! ```
8
9use crate::{
10    ast::statements::{Statement, StatementKind},
11    lexer::tokentypes::TokenType,
12    parser::parser_logic::Parser,
13    utils::{errors::Error, span::Span},
14};
15
16impl Parser {
17    /// Parses a `while` loop.
18    ///
19    /// Called after `while` has been consumed. Reads the loop condition as an
20    /// expression, then the loop body via [`parse_block`], and produces
21    /// [`StatementKind::While`].
22    ///
23    /// [`parse_block`]: Parser::parse_block
24    pub fn parse_while(&mut self, start: Span) -> Result<Statement, Error> {
25        while self.match_type(&[TokenType::Newline]) {}
26        let condition = self.parse_expression()?;
27        while self.match_type(&[TokenType::Newline]) {}
28        let body = self.parse_block()?;
29        let span = start.join(self.previous_span());
30        Ok(Statement::new(
31            StatementKind::While { condition, body },
32            span,
33        ))
34    }
35}