use crate::parser::{
MathicParser, ParserResult,
ast::control_flow::{ForStmt, IfStmt, WhileStmt},
token::Token,
};
impl<'a> MathicParser<'a> {
pub fn parse_if_stmt(&self) -> ParserResult<IfStmt> {
self.next()?;
let condition = self.parse_expr_no_init()?;
let then_block = self.parse_block()?;
let else_block = if self.check_next(Token::Else)? {
self.consume_token(Token::Else)?;
Some(self.parse_block()?)
} else {
None
};
Ok(IfStmt {
condition,
then_block,
else_block,
})
}
pub fn parse_while_stmt(&self) -> ParserResult<WhileStmt> {
self.next()?;
let condition = self.parse_expr_no_init()?;
let body = self.parse_block()?;
Ok(WhileStmt { condition, body })
}
pub fn parse_for_stmt(&self) -> ParserResult<ForStmt> {
self.next()?;
let variable = self.consume_token(Token::Ident)?.lexeme.to_string();
self.consume_token(Token::In)?;
let start = self.parse_expr_no_init()?;
self.consume_token(Token::Dot)?;
self.consume_token(Token::Dot)?;
let end = self.parse_expr_no_init()?;
let body = self.parse_block()?;
Ok(ForStmt {
variable,
start,
end,
body,
})
}
}