kotlin_parser/parse/expression/
when_expr.rs

1use crate::ast::*;
2use chumsky::prelude::*;
3use text::newline;
4
5use super::call::expr_block_parser;
6
7pub fn when_expr_parser(
8    stmt_parser: impl Parser<char, Statement, Error = Simple<char>> + Clone,
9    expr_parser: impl Parser<char, Expression, Error = Simple<char>> + Clone,
10) -> impl Parser<char, Expression, Error = Simple<char>> {
11    just("when")
12        .padded()
13        .ignore_then(
14            expr_parser
15                .clone()
16                .delimited_by(just('(').padded(), just(')').padded())
17                .map(Box::new)
18                .or_not(),
19        )
20        .then(
21            when_entry_parser(stmt_parser.clone(), expr_parser.clone())
22                .separated_by(
23                    newline().or(just(';').ignored()).padded().repeated(),
24                ),
25        )
26        .map(|(expr, entries)| {
27            Expression::When(WhenExpression { expr, entries })
28        })
29}
30
31pub fn when_entry_parser(
32    stmt_parser: impl Parser<char, Statement, Error = Simple<char>> + Clone,
33    expr_parser: impl Parser<char, Expression, Error = Simple<char>> + Clone,
34) -> impl Parser<char, WhenEntry, Error = Simple<char>> {
35    expr_parser
36        .separated_by(just(',').padded())
37        .at_least(1)
38        .or(just("else").map(|_| vec![]))
39        .then(
40            just("->")
41                .padded()
42                .ignore_then(expr_block_parser(stmt_parser)),
43        )
44        .map(|(exprs, body)| WhenEntry { exprs, body })
45}