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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use logos::Span;
use serde_json::{Number, Value};

use crate::{
    error::{ErrorInfo, SourcePos, SyntaxError},
    lexer::{Lexer, Parameters, DoubleQuoteString, SingleQuoteString, Token},
    parser::{
        ast::{Call, CallTarget, Element, ParameterValue},
        path, ParseState,
    },
    SyntaxResult,
};

/// Indicate if this call statement is being parsed
/// in the context of a statement or block which is used
/// to determine if the `else` keyword is allowed.
#[derive(Eq, PartialEq)]
pub(crate) enum CallParseContext {
    /// Parsing as an open block.
    Block,
    /// Parsing as a raw block.
    Raw,
    /// Parsing as a statement out side a block
    Statement,
    /// Parsing as a statement inside a block scope
    /// in which case the `else` keyword should be parsed.
    ScopeStatement,
}

/// Repesents the types of calls that can be parsed.
///
/// Either a top-level call or a sub-expression.
///
/// Sub expressions do not parse partial information and must
/// use a path for the call target.
#[derive(Eq, PartialEq)]
enum CallContext {
    Call,
    SubExpr,
}

enum StringType {
    Double,
    Single,
}

/// Parse a quoted string literal value.
fn string_literal<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    current: (Parameters, Span),
    string_type: StringType,
) -> SyntaxResult<Value> {
    let (_lex, span) = current;
    let str_start = span.end;
    let mut str_end = span.end;

    while let Some(token) = lexer.next() {

        match string_type {
            StringType::Double => {
                match token {
                    Token::DoubleQuoteString(lex, span) => match &lex {
                        DoubleQuoteString::End => {
                            let str_value = &source[str_start..str_end];
                            return Ok(Value::String(str_value.to_string()));
                        }
                        _ => {
                            *state.byte_mut() = span.end;
                            str_end = span.end;
                        }
                    },
                    _ => panic!("Expecting string literal token"),
                }
            }
            StringType::Single => {
                match token {
                    Token::SingleQuoteString(lex, span) => match &lex {
                        SingleQuoteString::End => {
                            let str_value = &source[str_start..str_end];
                            return Ok(Value::String(str_value.to_string()));
                        }
                        _ => {
                            *state.byte_mut() = span.end;
                            str_end = span.end;
                        }
                    },
                    _ => panic!("Expecting string literal token"),
                }
            }
        }

    }
    panic!("Failed to parse string literal");
}

/// Parse a JSON literal value.
fn json_literal<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    current: (Parameters, Span),
) -> SyntaxResult<Value> {
    let (lex, span) = current;
    let value = match lex {
        Parameters::Null => Value::Null,
        Parameters::True => Value::Bool(true),
        Parameters::False => Value::Bool(false),
        Parameters::Number => {
            let num: Number = source[span].parse().unwrap();
            Value::Number(num)
        }
        Parameters::DoubleQuoteString => {
            string_literal(source, lexer, state, (lex, span), StringType::Double)?
        }
        Parameters::SingleQuoteString => {
            string_literal(source, lexer, state, (lex, span), StringType::Single)?
        }
        _ => {
            // FIXME: how to handle this?
            panic!("Expecting JSON literal token.");
        }
    };

    Ok(value)
}

fn value<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    current: (Parameters, Span),
) -> SyntaxResult<(ParameterValue<'source>, Option<Token>)> {
    let (lex, span) = current;

    match &lex {
        // Path components
        Parameters::ExplicitThisKeyword
        | Parameters::ExplicitThisDotSlash
        | Parameters::Identifier
        | Parameters::LocalIdentifier
        | Parameters::ParentRef
        | Parameters::ArrayAccess => {
            let (mut path, token) =
                path::parse(source, lexer, state, (lex, span))?;
            if let Some(path) = path.take() {
                return Ok((ParameterValue::Path(path), token));
            }
        }
        // Open a nested call
        Parameters::StartSubExpression => {
            let (call, token) = sub_expr(source, lexer, state, span)?;
            if !call.is_closed() {
                panic!("Sub expression was not terminated");
            }

            return Ok((ParameterValue::SubExpr(call), token));
        }
        // Literal components
        Parameters::DoubleQuoteString
        | Parameters::SingleQuoteString
        | Parameters::Number
        | Parameters::True
        | Parameters::False
        | Parameters::Null => {
            let value = json_literal(source, lexer, state, (lex, span))?;
            return Ok((ParameterValue::Json(value), lexer.next()));
        }
        _ => panic!("Unexpected token while parsing value! {:?}", lex),
    }

    panic!("Expecting value!");
}

fn key_value<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    call: &mut Call<'source>,
    current: (Parameters, Span),
) -> SyntaxResult<Option<Token>> {
    let (_lex, span) = current;
    let key = &source[span.start..span.end - 1];
    let mut next: Option<Token> = None;

    // Consume the first value
    if let Some(token) = lexer.next() {
        match token {
            Token::Parameters(lex, span) => {
                let (value, token) = value(source, lexer, state, (lex, span))?;
                call.add_hash(key, value);
                next = token;
            }
            _ => panic!("Expecting parameter token for key/value pair!"),
        }
    }

    // Read in other key/value pairs
    while let Some(token) = next {
        match token {
            Token::Parameters(lex, span) => match &lex {
                Parameters::WhiteSpace | Parameters::Newline => {
                    if lex == Parameters::Newline {
                        *state.line_mut() += 1;
                    }
                }
                Parameters::HashKey => {
                    return key_value(source, lexer, state, call, (lex, span));
                }
                Parameters::End => {
                    call.exit(span);
                    return Ok(None);
                }
                _ => {
                    panic!("Unexpected parameter token parsing hash parameters")
                }
            },
            _ => panic!("Unexpected token whilst parsing hash parameters"),
        }
        next = lexer.next();
    }
    Ok(None)
}

fn arguments<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    call: &mut Call<'source>,
    next: Option<Token>,
    context: CallContext,
) -> SyntaxResult<Option<Token>> {
    //println!("Arguments {:?}", next);

    if let Some(token) = next {
        match token {
            Token::Parameters(lex, span) => {
                match &lex {
                    Parameters::WhiteSpace | Parameters::Newline => {
                        if lex == Parameters::Newline {
                            *state.line_mut() += 1;
                        }
                        let next = lexer.next();
                        return arguments(
                            source, lexer, state, call, next, context,
                        );
                    }
                    Parameters::Partial => {
                        panic!("Partial indicator (>) must be the first part of a call statement");
                    }
                    Parameters::ElseKeyword => {}
                    // Path components
                    Parameters::ExplicitThisKeyword
                    | Parameters::ExplicitThisDotSlash
                    | Parameters::Identifier
                    | Parameters::LocalIdentifier
                    | Parameters::ParentRef
                    | Parameters::ArrayAccess => {
                        // Handle path arguments values
                        let (value, token) =
                            value(source, lexer, state, (lex, span))?;
                        call.add_argument(value);
                        return arguments(
                            source, lexer, state, call, token, context,
                        );
                    }
                    // Hash parameters
                    Parameters::HashKey => {
                        return key_value(
                            source,
                            lexer,
                            state,
                            call,
                            (lex, span),
                        );
                    }
                    // Open a nested call
                    Parameters::StartSubExpression => {
                        let (value, token) =
                            value(source, lexer, state, (lex, span))?;
                        call.add_argument(value);
                        return arguments(
                            source, lexer, state, call, token, context,
                        );
                    }
                    // Literal components
                    Parameters::DoubleQuoteString
                    | Parameters::SingleQuoteString
                    | Parameters::Number
                    | Parameters::True
                    | Parameters::False
                    | Parameters::Null => {
                        // Handle json literal argument values
                        let (value, token) =
                            value(source, lexer, state, (lex, span))?;
                        call.add_argument(value);
                        return arguments(
                            source, lexer, state, call, token, context,
                        );
                    }
                    Parameters::PathDelimiter => {
                        panic!("Unexpected path delimiter");
                    }
                    Parameters::EndSubExpression => {
                        if context == CallContext::SubExpr {
                            call.exit(span);
                            return Ok(lexer.next());
                        } else {
                            panic!("Unexpected end of sub expression");
                        }
                    }
                    Parameters::Error => {
                        panic!("Unexpected token");
                    }
                    Parameters::End => {
                        call.exit(span);
                        return Ok(None);
                    }
                }
            }
            _ => {
                panic!("Expecting parameter token");
            }
        }
    }

    Ok(None)
}

/// Parse the call target.
fn target<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    call: &mut Call<'source>,
    mut next: Option<Token>,
    context: CallContext,
) -> SyntaxResult<Option<Token>> {
    while let Some(token) = next {
        match token {
            Token::Parameters(lex, span) => {
                match &lex {
                    Parameters::WhiteSpace | Parameters::Newline => {
                        if lex == Parameters::Newline {
                            *state.line_mut() += 1;
                        }
                    }
                    Parameters::ElseKeyword => {
                        panic!("Got else keyword parsing call target");
                    }
                    // Path components
                    Parameters::ExplicitThisKeyword
                    | Parameters::ExplicitThisDotSlash
                    | Parameters::Identifier
                    | Parameters::LocalIdentifier
                    | Parameters::ParentRef
                    | Parameters::ArrayAccess
                    | Parameters::PathDelimiter => {
                        let (mut path, token) =
                            path::parse(source, lexer, state, (lex, span))?;

                        if let Some(path) = path.take() {
                            call.set_target(CallTarget::Path(path));
                        }

                        return Ok(token);
                    }
                    Parameters::StartSubExpression => {
                        if context == CallContext::SubExpr {
                            panic!("Sub expressions must use a path or identifier for the target");
                        }

                        let (sub_call, token) =
                            sub_expr(source, lexer, state, span)?;
                        call.set_target(CallTarget::SubExpr(Box::new(
                            sub_call,
                        )));
                        return Ok(token);
                    }
                    Parameters::End => {
                        if !call.has_target() && !call.is_conditional() {
                            //panic!("Got end of statement with no call target...");
                            return Err(SyntaxError::EmptyStatement(
                                ErrorInfo::new(
                                    source,
                                    state.file_name(),
                                    SourcePos::from((
                                        state.line(),
                                        state.byte(),
                                    )),
                                )
                                .into(),
                            ));
                        }
                        call.exit(span);
                        return Ok(None);
                    }
                    _ => {
                        panic!(
                            "Unexpected token parsing call target {:?}",
                            lex
                        );
                    }
                }
            }
            _ => {
                panic!("Expecting parameter token, got {:?}", token);
            }
        }

        next = lexer.next();
    }
    Ok(None)
}

/// Parse the partial and conditional flags.
fn flags<'source>(
    _source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    call: &mut Call<'source>,
    mut next: Option<Token>,
) -> SyntaxResult<Option<Token>> {
    while let Some(token) = next {
        match token {
            Token::Parameters(lex, span) => match &lex {
                Parameters::WhiteSpace | Parameters::Newline => {
                    if lex == Parameters::Newline {
                        *state.line_mut() += 1;
                    }
                }
                Parameters::Partial => {
                    call.set_partial(true);
                    return Ok(lexer.next());
                }
                Parameters::ElseKeyword => {
                    call.set_conditional(true);
                    return Ok(lexer.next());
                }
                _ => return Ok(Some(Token::Parameters(lex, span))),
            },
            _ => return Ok(Some(token)),
        }
        next = lexer.next();
    }
    Ok(None)
}

pub(crate) fn sub_expr<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    open: Span,
) -> SyntaxResult<(Call<'source>, Option<Token>)> {
    *state.byte_mut() = open.end;

    let mut call = Call::new(source, open);
    let next = lexer.next();
    let next =
        target(source, lexer, state, &mut call, next, CallContext::SubExpr)?;
    let next =
        arguments(source, lexer, state, &mut call, next, CallContext::SubExpr)?;
    if !call.is_closed() {
        panic!("Sub expression statement was not terminated");
    }
    Ok((call, next))
}

pub(crate) fn parse<'source>(
    source: &'source str,
    lexer: &mut Lexer<'source>,
    state: &mut ParseState,
    open: Span,
    // TODO: use this to determine whether `else` keyword is legal
    _parse_context: CallParseContext,
) -> SyntaxResult<Call<'source>> {
    *state.byte_mut() = open.end;

    let mut call = Call::new(source, open);
    let next = lexer.next();
    let next = flags(source, lexer, state, &mut call, next)?;

    if call.is_partial() && call.is_conditional() {
        panic!("Partials and conditionals may not be combined.");
    }

    let next =
        target(source, lexer, state, &mut call, next, CallContext::Call)?;
    let _next =
        arguments(source, lexer, state, &mut call, next, CallContext::Call)?;

    // FIXME: we should return the next token here so it is consumed ???
    if !call.is_closed() {
        //println!("{:?}", call);
        panic!("Call statement was not terminated");
    }
    Ok(call)
}