kotlin_parser/parse/declaration/
constructor.rs

1use crate::{
2    ast::*,
3    parse::{
4        expression::call::{block_parser, call_arg_parser},
5        ty::function::function_params_parser,
6    },
7};
8use chumsky::prelude::*;
9
10use super::modifier_parser;
11
12pub fn constructor_parser(
13    stmt_parser: impl Parser<char, Statement, Error = Simple<char>>,
14    expr_parser: impl Parser<char, Expression, Error = Simple<char>> + Clone,
15) -> impl Parser<char, ConstructorDeclaration, Error = Simple<char>> {
16    modifier_parser()
17        .repeated()
18        .or_not()
19        .then_ignore(just("constructor").padded())
20        .then(
21            function_params_parser(expr_parser.clone())
22                .delimited_by(just('(').padded(), just(')').padded()),
23        )
24        .then(constructor_delegate_parser(expr_parser).or_not())
25        .then(block_parser(stmt_parser).or_not())
26        .map(
27            |(((modifiers, params), delegate), body)| ConstructorDeclaration {
28                modifiers: modifiers.unwrap_or_default(),
29                params,
30                delegate,
31                body,
32            },
33        )
34}
35
36pub fn constructor_delegate_parser(
37    expr_parser: impl Parser<char, Expression, Error = Simple<char>>,
38) -> impl Parser<char, ConstructorDelegate, Error = Simple<char>> {
39    just(':')
40        .padded()
41        .ignore_then(choice((
42            just("this").to(ConstructorDelegateKind::This),
43            just("super").to(ConstructorDelegateKind::Super),
44        )))
45        .then(
46            call_arg_parser(expr_parser)
47                .separated_by(just(',').padded())
48                .or_not()
49                .delimited_by(just('(').padded(), just(')').padded()),
50        )
51        .map(|(kind, args)| ConstructorDelegate {
52            kind,
53            args: args.unwrap_or_default(),
54        })
55}