kotlin_parser/parse/expression/
if_expr.rs1use crate::ast::*;
2use chumsky::prelude::*;
3
4use super::call::block_parser;
5
6pub fn if_expr_parser(
7 stmt_parser: impl Parser<char, Statement, Error = Simple<char>> + Clone,
8 expr_parser: impl Parser<char, Expression, Error = Simple<char>> + Clone,
9) -> impl Parser<char, Expression, Error = Simple<char>> {
10 let if_branch = just("if")
11 .padded()
12 .ignore_then(
13 expr_parser
14 .clone()
15 .delimited_by(just('(').padded(), just(')').padded()),
16 )
17 .then(block_parser(stmt_parser.clone()))
18 .map(|(condition, body)| (condition, body));
19
20 let otherwise = just("else")
21 .padded()
22 .ignore_then(expr_parser)
23 .map(Box::new)
24 .or_not();
25
26 if_branch.then(otherwise).map(|(if_branch, otherwise)| {
27 Expression::If(IfExpression {
28 expr: if_branch.0.into(),
29 then: if_branch.1,
30 otherwise,
31 })
32 })
33}