kotlin_parser/parse/expression/
while_expr.rs1use crate::ast::*;
2use chumsky::prelude::*;
3
4use super::call::block_parser;
5
6pub fn while_expr_parser<'a>(
7 stmt_parser: impl Parser<char, Statement, Error = Simple<char>> + Clone + 'a,
8 expr_parser: impl Parser<char, Expression, Error = Simple<char>> + 'a,
9) -> impl Parser<char, Expression, Error = Simple<char>> + 'a {
10 let condition = just("while")
11 .padded()
12 .ignore_then(
13 expr_parser.delimited_by(just('(').padded(), just(')').padded()),
14 )
15 .boxed();
16
17 let while_loop = condition.clone().then(block_parser(stmt_parser.clone()));
18 let do_while = just("do")
19 .padded()
20 .ignore_then(block_parser(stmt_parser))
21 .then(condition);
22
23 choice((
24 while_loop.map(|(expr, body)| {
25 Expression::While(WhileExpression {
26 expr: expr.into(),
27 body,
28 is_do_while: false,
29 })
30 }),
31 do_while.map(|(body, expr)| {
32 Expression::While(WhileExpression {
33 expr: expr.into(),
34 body,
35 is_do_while: true,
36 })
37 }),
38 ))
39}