kotlin_parser/parse/declaration/
function.rs

1use crate::{
2    ast::*,
3    parse::ty::{
4        function::function_params_parser, type_bounds_parser,
5        type_params_parser, type_parser,
6    },
7};
8use chumsky::prelude::*;
9
10use super::modifier_parser;
11
12pub fn function_parser(
13    stmt_parser: impl Parser<char, Statement, Error = Simple<char>> + Clone,
14    expr_parser: impl Parser<char, Expression, Error = Simple<char>> + Clone,
15) -> impl Parser<char, FunctionDeclaration, Error = Simple<char>> {
16    let modifiers = modifier_parser().repeated().or_not();
17    let name = text::ident().padded();
18    let type_params = type_params_parser(expr_parser.clone()).or_not();
19    let receiver = type_parser().then_ignore(just('.').padded()).or_not();
20    let params = function_params_parser(expr_parser.clone())
21        .delimited_by(just('(').padded(), just(')').padded())
22        .or_not();
23    let return_ty = just(':')
24        .padded()
25        .ignore_then(type_parser())
26        .padded()
27        .or_not();
28    let body = choice((
29        just('=')
30            .padded()
31            .ignore_then(stmt_parser.clone())
32            .map(|statement| Block {
33                statements: vec![statement],
34            }),
35        just('{')
36            .padded()
37            .ignore_then(stmt_parser.repeated())
38            .then_ignore(just('}').padded())
39            .map(|statements: Vec<Statement>| Block { statements }),
40    ))
41    .or_not();
42    let bounds = type_bounds_parser().or_not();
43
44    modifiers
45        .then_ignore(just("fun"))
46        .then(name)
47        .then(type_params)
48        .then(receiver)
49        .then(params)
50        .then(return_ty)
51        .then(body)
52        .then(bounds)
53        .map(
54            |(
55                (
56                    (
57                        ((((modifiers, name), type_params), receiver), params),
58                        return_ty,
59                    ),
60                    body,
61                ),
62                bounds,
63            )| {
64                FunctionDeclaration {
65                    modifiers: modifiers.unwrap_or_default(),
66                    name: name.into(),
67                    type_params: type_params.unwrap_or_default(),
68                    receiver,
69                    params: params.unwrap_or_default(),
70                    return_ty,
71                    body,
72                    bounds: bounds.unwrap_or_default(),
73                }
74            },
75        )
76}