1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use crate::expected_scope;
use crate::lexer::token::TokenKind;
use crate::parser::ast::functions::ArrowFunction;
use crate::parser::ast::functions::Closure;
use crate::parser::ast::functions::ClosureUse;
use crate::parser::ast::functions::Function;
use crate::parser::ast::functions::Method;
use crate::parser::ast::modifiers::MethodModifierGroup;
use crate::parser::ast::Expression;
use crate::parser::ast::Statement;
use crate::parser::error::ParseError;
use crate::parser::error::ParseResult;
use crate::parser::expressions;
use crate::parser::internal::blocks;
use crate::parser::internal::data_type;
use crate::parser::internal::identifiers;
use crate::parser::internal::parameters;
use crate::parser::internal::utils;
use crate::parser::state::Scope;
use crate::parser::state::State;
use crate::scoped;

pub fn anonymous_function(state: &mut State) -> ParseResult<Expression> {
    let start = state.stream.current().span;

    let is_static = if state.stream.current().kind == TokenKind::Static {
        state.stream.next();

        true
    } else {
        false
    };

    utils::skip(state, TokenKind::Function)?;

    let by_ref = if state.stream.current().kind == TokenKind::Ampersand {
        state.stream.next();
        true
    } else {
        false
    };

    let attributes = state.get_attributes();
    let parameters = parameters::function_parameter_list(state)?;

    let mut uses = vec![];
    if state.stream.current().kind == TokenKind::Use {
        state.stream.next();

        utils::skip_left_parenthesis(state)?;

        while state.stream.current().kind != TokenKind::RightParen {
            let mut by_ref = false;
            if state.stream.current().kind == TokenKind::Ampersand {
                state.stream.next();

                by_ref = true;
            }

            // TODO(azjezz): this shouldn't call expr, we should have a function
            // just for variables, so we don't have to go through the whole `match` in `expression(...)`
            let var = match expressions::lowest_precedence(state)? {
                s @ Expression::Variable { .. } => ClosureUse { var: s, by_ref },
                _ => {
                    return Err(ParseError::UnexpectedToken(
                        "expected variable".into(),
                        state.stream.current().span,
                    ))
                }
            };

            uses.push(var);

            if state.stream.current().kind == TokenKind::Comma {
                state.stream.next();
            } else {
                break;
            }
        }

        utils::skip_right_parenthesis(state)?;
    }

    let mut return_ty = None;
    if state.stream.current().kind == TokenKind::Colon {
        utils::skip_colon(state)?;

        return_ty = Some(data_type::data_type(state)?);
    }

    let (body, end) = scoped!(state, Scope::AnonymousFunction(is_static), {
        utils::skip_left_brace(state)?;

        let body = blocks::body(state, &TokenKind::RightBrace)?;
        let end = utils::skip_right_brace(state)?;

        (body, end)
    });

    Ok(Expression::Closure(Closure {
        start,
        end,
        attributes,
        parameters,
        uses,
        return_ty,
        body,
        r#static: is_static,
        by_ref,
    }))
}

pub fn arrow_function(state: &mut State) -> ParseResult<Expression> {
    let start = state.stream.current().span;

    let is_static = if state.stream.current().kind == TokenKind::Static {
        state.stream.next();

        true
    } else {
        false
    };

    utils::skip(state, TokenKind::Fn)?;

    let by_ref = if state.stream.current().kind == TokenKind::Ampersand {
        state.stream.next();
        true
    } else {
        false
    };

    let attributes = state.get_attributes();
    let parameters = parameters::function_parameter_list(state)?;

    let mut return_type = None;
    if state.stream.current().kind == TokenKind::Colon {
        utils::skip_colon(state)?;

        return_type = Some(data_type::data_type(state)?);
    }

    utils::skip(state, TokenKind::DoubleArrow)?;

    let body = scoped!(state, Scope::ArrowFunction(is_static), {
        Box::new(expressions::lowest_precedence(state)?)
    });

    let end = state.stream.current().span;

    Ok(Expression::ArrowFunction(ArrowFunction {
        start,
        end,
        attributes,
        parameters,
        return_type,
        body,
        by_ref,
        r#static: is_static,
    }))
}

pub fn function(state: &mut State) -> ParseResult<Statement> {
    let start = state.stream.current().span;

    utils::skip(state, TokenKind::Function)?;

    let by_ref = if state.stream.current().kind == TokenKind::Ampersand {
        state.stream.next();
        true
    } else {
        false
    };

    let name = identifiers::identifier_maybe_soft_reserved(state)?;

    // get attributes before processing parameters, otherwise
    // parameters will steal attributes of this function.
    let attributes = state.get_attributes();

    let parameters = parameters::function_parameter_list(state)?;

    let mut return_type = None;

    if state.stream.current().kind == TokenKind::Colon {
        utils::skip_colon(state)?;

        return_type = Some(data_type::data_type(state)?);
    }

    let (body, end) = scoped!(state, Scope::Function(name.clone()), {
        utils::skip_left_brace(state)?;

        let body = blocks::body(state, &TokenKind::RightBrace)?;
        let end = utils::skip_right_brace(state)?;

        (body, end)
    });

    Ok(Statement::Function(Function {
        start,
        end,
        name,
        attributes,
        parameters,
        return_type,
        body,
        by_ref,
    }))
}

pub fn method(state: &mut State, modifiers: MethodModifierGroup) -> ParseResult<Method> {
    let start = utils::skip(state, TokenKind::Function)?;

    let by_ref = if state.stream.current().kind == TokenKind::Ampersand {
        state.stream.next();
        true
    } else {
        false
    };

    let name = identifiers::identifier_maybe_reserved(state)?;

    let has_body = expected_scope!([
            Scope::Class(_, class_modifiers, _) => {
                if !class_modifiers.has_abstract() && modifiers.has_abstract() {
                    return Err(ParseError::AbstractModifierOnNonAbstractClassMethod(
                        state.stream.current().span,
                    ));
                }

                !modifiers.has_abstract()
            },
            Scope::Trait(_) => !modifiers.has_abstract(),
            Scope::Interface(_) => false,
            Scope::Enum(enum_name, _) => {
                if name.to_string() == "__construct" {
                    return Err(ParseError::ConstructorInEnum(
                        state.named(&enum_name),
                        state.stream.current().span,
                    ));
                }

                true
            },
            Scope::AnonymousClass(_) => true,
        ], state);

    // get attributes before processing parameters, otherwise
    // parameters will steal attributes of this method.
    let attributes = state.get_attributes();

    let (parameters, body, return_type, end) =
        scoped!(state, Scope::Method(name.clone(), modifiers.clone()), {
            let parameters = parameters::method_parameter_list(state)?;

            let mut return_type = None;

            if state.stream.current().kind == TokenKind::Colon {
                utils::skip_colon(state)?;

                return_type = Some(data_type::data_type(state)?);
            }

            if !has_body {
                let end = utils::skip_semicolon(state)?;

                (parameters, None, return_type, end)
            } else {
                utils::skip_left_brace(state)?;

                let body = blocks::body(state, &TokenKind::RightBrace)?;

                let end = utils::skip_right_brace(state)?;

                (parameters, Some(body), return_type, end)
            }
        });

    Ok(Method {
        start,
        end,
        attributes,
        name,
        parameters,
        body,
        return_type,
        by_ref,
        modifiers,
    })
}