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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use crate::expect_token;
use crate::expected_token_err;
use crate::lexer::error::SyntaxError;
use crate::lexer::token::DocStringIndentationKind;
use crate::lexer::token::TokenKind;
use crate::parser::ast::identifiers::Identifier;
use crate::parser::ast::literals::Literal;
use crate::parser::ast::literals::LiteralInteger;
use crate::parser::ast::literals::LiteralString;
use crate::parser::ast::operators::ArithmeticOperation;
use crate::parser::ast::variables::Variable;
use crate::parser::ast::Expression;
use crate::parser::ast::StringPart;
use crate::parser::error::ParseResult;
use crate::parser::expressions::create;
use crate::parser::internal::identifiers;
use crate::parser::internal::utils;
use crate::parser::internal::variables;
use crate::parser::state::State;

#[inline(always)]
pub fn interpolated(state: &mut State) -> ParseResult<Expression> {
    let mut parts = Vec::new();

    while state.stream.current().kind != TokenKind::DoubleQuote {
        if let Some(part) = part(state)? {
            parts.push(part);
        }
    }

    state.stream.next();

    Ok(Expression::InterpolatedString { parts })
}

#[inline(always)]
pub fn shell_exec(state: &mut State) -> ParseResult<Expression> {
    state.stream.next();

    let mut parts = Vec::new();

    while state.stream.current().kind != TokenKind::Backtick {
        if let Some(part) = part(state)? {
            parts.push(part);
        }
    }

    state.stream.next();

    Ok(Expression::ShellExec { parts })
}

#[inline(always)]
pub fn heredoc(state: &mut State) -> ParseResult<Expression> {
    let span = state.stream.current().span;
    state.stream.next();

    let mut parts = Vec::new();

    while !matches!(state.stream.current().kind, TokenKind::EndDocString(_, _)) {
        if let Some(part) = part(state)? {
            parts.push(part);
        }
    }

    let (indentation_type, indentation_amount) = match &state.stream.current().kind {
        TokenKind::EndDocString(indentation_type, indentation_amount) => {
            (indentation_type.clone(), *indentation_amount)
        }
        _ => unreachable!(),
    };

    state.stream.next();

    let mut new_line = true;
    if indentation_type != DocStringIndentationKind::None {
        let indentation_char: u8 = indentation_type.into();

        for part in parts.iter_mut() {
            // We only need to strip and validate indentation
            // for individual lines, so we can skip checks if
            // we know we're not on a new line.
            if !new_line {
                continue;
            }

            match part {
                StringPart::Literal(bytes) => {
                    // 1. If this line doesn't start with any whitespace,
                    //    we can return an error early because we know
                    //    the label was indented.
                    if !bytes.starts_with(&[b' ']) && !bytes.starts_with(&[b'\t']) {
                        return Err(SyntaxError::InvalidDocBodyIndentationLevel(
                            indentation_amount,
                            span,
                        )
                        .into());
                    }

                    // 2. If this line doesn't start with the correct
                    //    type of whitespace, we can also return an error.
                    if !bytes.starts_with(&[indentation_char]) {
                        return Err(SyntaxError::InvalidDocIndentation(span).into());
                    }

                    // 3. We now know that the whitespace at the start of
                    //    this line is correct, so we need to check that the
                    //    amount of whitespace is correct too. In this case,
                    //    the amount of whitespace just needs to be at least
                    //    the same, so we can create a vector containing the
                    //    minimum and check using `starts_with()`.
                    let expected_whitespace_buffer = vec![indentation_char; indentation_amount];
                    if !bytes.starts_with(&expected_whitespace_buffer) {
                        return Err(SyntaxError::InvalidDocBodyIndentationLevel(
                            indentation_amount,
                            span,
                        )
                        .into());
                    }

                    // 4. All of the above checks have passed, so we know
                    //    there are no more possible errors. Let's now
                    //    strip the leading whitespace accordingly.
                    *bytes = bytes
                        .strip_prefix(&expected_whitespace_buffer[..])
                        .unwrap()
                        .into();
                    new_line = bytes.ends_with(&[b'\n']);
                }
                _ => continue,
            }
        }
    }

    Ok(Expression::Heredoc { parts })
}

#[inline(always)]
pub fn nowdoc(state: &mut State) -> ParseResult<Expression> {
    let span = state.stream.current().span;

    state.stream.next();

    let mut string_part = state.stream.current().value.clone();
    expect_token!([TokenKind::StringPart => ()], state, "constant string");

    let (indentation_type, indentation_amount) = match &state.stream.current().kind {
        TokenKind::EndDocString(indentation_type, indentation_amount) => {
            (indentation_type.clone(), *indentation_amount)
        }
        _ => unreachable!(),
    };

    state.stream.next();

    if indentation_type != DocStringIndentationKind::None {
        let indentation_char: u8 = indentation_type.into();

        let mut lines = string_part
            .split(|b| *b == b'\n')
            .map(|s| s.to_vec())
            .collect::<Vec<Vec<u8>>>();

        for line in lines.iter_mut() {
            if line.is_empty() {
                continue;
            }

            // 1. If this line doesn't start with any whitespace,
            //    we can return an error early because we know
            //    the label was indented.
            if !line.starts_with(&[b' ']) && !line.starts_with(&[b'\t']) {
                return Err(
                    SyntaxError::InvalidDocBodyIndentationLevel(indentation_amount, span).into(),
                );
            }

            // 2. If this line doesn't start with the correct
            //    type of whitespace, we can also return an error.
            if !line.starts_with(&[indentation_char]) {
                return Err(SyntaxError::InvalidDocIndentation(span).into());
            }

            // 3. We now know that the whitespace at the start of
            //    this line is correct, so we need to check that the
            //    amount of whitespace is correct too. In this case,
            //    the amount of whitespace just needs to be at least
            //    the same, so we can create a vector containing the
            //    minimum and check using `starts_with()`.
            let expected_whitespace_buffer = vec![indentation_char; indentation_amount];
            if !line.starts_with(&expected_whitespace_buffer) {
                return Err(
                    SyntaxError::InvalidDocBodyIndentationLevel(indentation_amount, span).into(),
                );
            }

            // 4. All of the above checks have passed, so we know
            //    there are no more possible errors. Let's now
            //    strip the leading whitespace accordingly.
            *line = line
                .strip_prefix(&expected_whitespace_buffer[..])
                .unwrap()
                .into();
        }

        let mut bytes = Vec::new();
        for (i, line) in lines.iter().enumerate() {
            bytes.extend(line);
            if i < lines.len() - 1 {
                bytes.push(b'\n');
            }
        }
        string_part = bytes.into();
    }

    Ok(Expression::Nowdoc { value: string_part })
}

fn part(state: &mut State) -> ParseResult<Option<StringPart>> {
    Ok(match &state.stream.current().kind {
        TokenKind::StringPart => {
            let s = state.stream.current().value.clone();
            let part = if s.len() > 0 {
                Some(StringPart::Literal(s))
            } else {
                None
            };

            state.stream.next();
            part
        }
        TokenKind::DollarLeftBrace => {
            let variable = variables::dynamic_variable(state)?;

            Some(StringPart::Expression(Box::new(Expression::Variable(
                variable,
            ))))
        }
        TokenKind::LeftBrace => {
            // "{$expr}"
            state.stream.next();
            let e = create(state)?;
            utils::skip_right_brace(state)?;
            Some(StringPart::Expression(Box::new(e)))
        }
        TokenKind::Variable => {
            // "$expr", "$expr[0]", "$expr[name]", "$expr->a"
            let variable = Expression::Variable(variables::dynamic_variable(state)?);
            let current = state.stream.current();
            let e = match &current.kind {
                TokenKind::LeftBracket => {
                    let left_bracket = utils::skip_left_bracket(state)?;

                    let current = state.stream.current();
                    // Full expression syntax is not allowed here,
                    // so we can't call expression.
                    let index = match &current.kind {
                        TokenKind::LiteralInteger => {
                            state.stream.next();

                            Expression::Literal(Literal::Integer(LiteralInteger {
                                span: current.span,
                                value: current.value.clone(),
                            }))
                        }
                        TokenKind::Minus => {
                            let span = current.span;
                            state.stream.next();
                            let literal = state.stream.current();
                            if let TokenKind::LiteralInteger = &literal.kind {
                                state.stream.next();

                                Expression::ArithmeticOperation(ArithmeticOperation::Negative {
                                    minus: span,
                                    right: Box::new(Expression::Literal(Literal::Integer(
                                        LiteralInteger {
                                            span: literal.span,
                                            value: literal.value.clone(),
                                        },
                                    ))),
                                })
                            } else {
                                return expected_token_err!("an integer", state);
                            }
                        }
                        TokenKind::Identifier => {
                            state.stream.next();

                            Expression::Literal(Literal::String(LiteralString {
                                span: current.span,
                                value: current.value.clone(),
                            }))
                        }
                        TokenKind::Variable => Expression::Variable(Variable::SimpleVariable(
                            variables::simple_variable(state)?,
                        )),
                        _ => {
                            return expected_token_err!(
                                ["`-`", "an integer", "an identifier", "a variable"],
                                state
                            );
                        }
                    };

                    let right_bracket = utils::skip_right_bracket(state)?;

                    Expression::ArrayIndex {
                        array: Box::new(variable),
                        left_bracket,
                        index: Some(Box::new(index)),
                        right_bracket,
                    }
                }
                TokenKind::Arrow => {
                    let span = current.span;
                    state.stream.next();
                    Expression::PropertyFetch {
                        target: Box::new(variable),
                        arrow: span,
                        property: Box::new(Expression::Identifier(Identifier::SimpleIdentifier(
                            identifiers::identifier_maybe_reserved(state)?,
                        ))),
                    }
                }
                TokenKind::QuestionArrow => {
                    let span = current.span;
                    state.stream.next();
                    Expression::NullsafePropertyFetch {
                        target: Box::new(variable),
                        question_arrow: span,
                        property: Box::new(Expression::Identifier(Identifier::SimpleIdentifier(
                            identifiers::identifier_maybe_reserved(state)?,
                        ))),
                    }
                }
                _ => variable,
            };
            Some(StringPart::Expression(Box::new(e)))
        }
        _ => {
            return expected_token_err!(["`${`", "`{$", "`\"`", "a variable"], state);
        }
    })
}