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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Iterator for grammar tokens.
use logos::{Lexer as Lex, Logos, Span};

/// Identity type for the lexer modes.
#[derive(Clone, Default)]
pub struct Extras;

/// Tokens for the document and nested blocks.
#[derive(Logos, Clone, Debug, Eq, PartialEq)]
#[logos(extras = Extras)]
#[logos(subpattern identifier = r#"[^\s"!#%&'()*+,./;<=>@\[/\]^`{|}~]"#)]
pub enum Block {
    /// Start a raw block.
    #[regex(r"\{\{\{\{~?[\t ]*")]
    StartRawBlock,

    /// Start a raw comment.
    #[regex(r"\{\{!--")]
    StartRawComment,

    /// Start a raw (escaped) statement.
    #[regex(r"\\\{\{\{?")]
    StartRawStatement,

    /// Start a comment.
    #[regex(r"\{\{!")]
    StartComment,

    /// Start a statement.
    #[regex(r"\{\{\{?~?[\t ]*")]
    StartStatement,

    /// Start a block.
    #[regex(r"\{\{\~?[\t ]*#[\t ]*")]
    StartBlockScope,

    /// Start a link.
    #[token("[[")]
    StartLink,

    /// End a block.
    #[regex(r"\{\{\~?[\t ]*/")]
    EndBlockScope,

    /// End a raw block.
    #[regex(r"\{\{\{\{~?[\t ]*/")]
    EndRawBlock,

    /// Text token.
    #[regex(r".")]
    Text,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for raw comments.
///
/// Raw comments can contain statements and blocks which will
/// not be rendered. They begin with `{{!--` and are terminated
/// with `--}}`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum RawComment {
    /// Text token.
    #[regex(r".")]
    Text,

    /// End of raw comment.
    #[regex(r"--\}\}")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for raw statements.
///
/// Raw statements are single-line statements escaped with a
/// backslash, for example: `\{{title}}`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum RawStatement {
    /// Text token.
    #[regex(r".")]
    Text,

    /// End of raw statement.
    #[regex(r"~?\}?\}\}")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for comments.
///
/// Comments may **not** contain statements and blocks.
/// They begin with `{{!` and are terminated with `}}`.
///
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum Comment {
    /// Text token.
    #[regex(r".")]
    Text,

    /// End of comment.
    #[regex(r"\}\}")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for parameters.
///
/// Parameters are converted to a call statement by the parser and must
/// represent all the tokens in a statement (`{{...}}`) and the start
/// of a block (`{{# block}}...{{/block}}`).
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
#[logos(subpattern identifier = r#"[^\s"!#%&'()*+,./;<=>@\[/\]^`{|}~]"#)]
pub enum Parameters {
    /// Token for a partial instruction.
    #[token(r">")]
    Partial,

    /// Token for the `else` conditional keyword.
    #[token(r"else")]
    ElseKeyword,

    /// Token for the explicit `this` keyword.
    #[token(r"this")]
    ExplicitThisKeyword,

    /// Token for explicit `this` notation using a dot and a slash.
    #[token("./")]
    ExplicitThisDotSlash,

    /// Token for a reference to a parent scope.
    #[token("../")]
    ParentRef,

    /// Token for a valid identifier.
    #[regex(r"(?&identifier)+", priority = 2)]
    Identifier,

    /// Token for a local identifier (preceeded by an `@` symbol).
    #[regex(r"@(?&identifier)+")]
    LocalIdentifier,

    /// Token for the delimiter between path components.
    #[regex(r"[./]")]
    PathDelimiter,

    /// Token that starts a double-quoted string literal.
    #[token("\"")]
    DoubleQuoteString,

    /// Token that starts a single-quoted string literal.
    #[token("'")]
    SingleQuoteString,

    /// Token that starts a raw literal using square brackets.
    #[token("[")]
    StartArray,

    /// Token that starts a sub-expression.
    #[token("(", priority = 3)]
    StartSubExpression,

    /// Token that ends a sub-expression.
    #[token(")")]
    EndSubExpression,

    /// Token for key/value pairs (hash parameters).
    #[regex(r"(?&identifier)+=")]
    HashKey,

    /// Token for numeric values.
    // NOTE: Must have higher priority than identifier
    // NOTE: otherwise numbers become identifiers
    #[regex(r"-?([0-9]+\.)?[0-9]+((e|E)[+-]?[0-9]+)?", priority = 3)]
    Number,

    /// Token for the `true` keyword.
    #[token("true")]
    True,

    /// Token for the `false` keyword.
    #[token("false")]
    False,

    /// Token for the `null` keyword.
    #[token("null")]
    Null,

    /// Token for whitespace delimiters.
    #[regex(r"[ \t]+")]
    WhiteSpace,

    /// Token for the end of a statement or block open tag.
    #[regex(r"~?\}?\}?\}\}")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for double-quoted string literals.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum DoubleQuoteString {
    /// Text token.
    #[regex(r#"[^\\"\n]+"#)]
    Text,

    /// Escaped newline token.
    #[token("\\n")]
    EscapedNewline,

    /// Escaped quote.
    #[token(r#"\""#)]
    Escaped,

    /// End of the string literal.
    #[token("\"")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for single-quoted string literals.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum SingleQuoteString {
    /// Text token.
    #[regex(r#"[^\\'\n]+"#)]
    Text,

    /// Escaped newline token.
    #[token("\\n")]
    EscapedNewline,

    /// Escaped quote.
    #[token(r#"\'"#)]
    Escaped,

    /// End of the string literal.
    #[token("'")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for square bracket raw literals.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum Array {
    /// Text token.
    #[regex(r#"[^\]\n]+"#)]
    Text,

    //#[token("\\n")]
    //EscapedNewline,
    /// Escaped bracket.
    #[token(r#"\]"#)]
    Escaped,

    /// End of the raw literal.
    #[token("]")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Tokens for links.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Logos)]
#[logos(extras = Extras)]
pub enum Link {
    /// Text token.
    #[regex(r#"[^\\|\]]+"#)]
    Text,

    /// Pipe delimiter token.
    #[token("|")]
    Pipe,

    /// Escaped newline token.
    #[token("\\n")]
    EscapedNewline,

    /// Escaped pipe token.
    #[token(r#"\|"#)]
    EscapedPipe,

    /// Escaped bracket token.
    #[token(r#"\]"#)]
    Escaped,

    /// End of square bracket literal.
    #[token(r"]]")]
    End,

    /// Newline token.
    #[token("\n")]
    Newline,

    /// Error token.
    #[error]
    Error,
}

/// Enumeration of the token types.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Token {
    /// Block token.
    Block(Block, Span),
    /// Raw comment token.
    RawComment(RawComment, Span),
    /// Raw statement token.
    RawStatement(RawStatement, Span),
    /// Comment token.
    Comment(Comment, Span),
    /// Token for call parameters.
    Parameters(Parameters, Span),
    /// Token for a double-quoted string literal.
    DoubleQuoteString(DoubleQuoteString, Span),
    /// Token for a single-quoted string literal.
    SingleQuoteString(SingleQuoteString, Span),
    /// Token for a raw square bracket literal.
    Array(Array, Span),
    /// Token for links.
    Link(Link, Span),
}

impl Token {
    /// Get the span for a token.
    pub fn span(&self) -> &Span {
        match self {
            Token::Block(_, ref span) => span,
            Token::RawComment(_, ref span) => span,
            Token::RawStatement(_, ref span) => span,
            Token::Comment(_, ref span) => span,
            Token::Parameters(_, ref span) => span,
            Token::DoubleQuoteString(_, ref span) => span,
            Token::SingleQuoteString(_, ref span) => span,
            Token::Array(_, ref span) => span,
            Token::Link(_, ref span) => span,
        }
    }

    /// Determine if a token should be treated as text.
    pub fn is_text(&self) -> bool {
        match self {
            Token::Block(ref t, _) => t == &Block::Text || t == &Block::Newline,
            Token::RawComment(ref t, _) => {
                t == &RawComment::Text || t == &RawComment::Newline
            }
            Token::RawStatement(ref t, _) => {
                t == &RawStatement::Text || t == &RawStatement::Newline
            }
            Token::Comment(ref t, _) => {
                t == &Comment::Text || t == &Comment::Newline
            }
            Token::Parameters(_, _) => false,
            Token::DoubleQuoteString(_, _) => false,
            Token::SingleQuoteString(_, _) => false,
            Token::Array(_, _) => false,
            Token::Link(_, _) => false,
        }
    }

    /// Determine if a token is the newline token.
    pub fn is_newline(&self) -> bool {
        match *self {
            Token::RawComment(ref lex, _) => lex == &RawComment::Newline,
            Token::RawStatement(ref lex, _) => lex == &RawStatement::Newline,
            Token::Comment(ref lex, _) => lex == &Comment::Newline,
            //Token::RawBlock(ref lex, _) => lex == &Block::Newline,
            Token::Block(ref lex, _) => lex == &Block::Newline,
            Token::Parameters(ref lex, _) => lex == &Parameters::Newline,
            Token::DoubleQuoteString(ref lex, _) => {
                lex == &DoubleQuoteString::Newline
            }
            Token::SingleQuoteString(ref lex, _) => {
                lex == &SingleQuoteString::Newline
            }
            Token::Array(ref lex, _) => lex == &Array::Newline,
            Token::Link(ref lex, _) => lex == &Link::Newline,
        }
    }
}

enum Modes<'source> {
    Block(Lex<'source, Block>),
    RawComment(Lex<'source, RawComment>),
    RawStatement(Lex<'source, RawStatement>),
    Comment(Lex<'source, Comment>),
    Parameters(Lex<'source, Parameters>),
    DoubleQuoteString(Lex<'source, DoubleQuoteString>),
    SingleQuoteString(Lex<'source, SingleQuoteString>),
    Array(Lex<'source, Array>),
    Link(Lex<'source, Link>),
}

impl<'source> Modes<'source> {
    fn new(s: &'source str) -> Self {
        Self::Block(Block::lexer(s))
    }
}

/// Iterator for a stream of grammar tokens.
pub struct Lexer<'source> {
    mode: Modes<'source>,
}

impl<'source> Lexer<'source> {
    /// Utility for switching the lexer to parameters mode.
    ///
    /// Must be called immediately after creating the lexer otherwise
    /// it is not guaranteed to change the lexer mode.
    pub(crate) fn set_parameters_mode(&mut self) {
        match &mut self.mode {
            Modes::Block(lexer) => {
                self.mode = Modes::Parameters(lexer.to_owned().morph())
            }
            _ => {}
        }
    }

    /// Consume nodes until we can return to the top-level mode.
    ///
    /// This is used during *lint* mode to move back to the top-level
    /// parsing mode.
    pub(crate) fn until_mode(&mut self) -> Option<Token> {
        while let Some(token) = self.next() {
            match token {
                Token::Block(_, _) => return Some(token),
                _ => {}
            }
        }
        None
    }
}

/// Clone lexers as we switch between modes.
impl<'source> Iterator for Lexer<'source> {
    type Item = Token;
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.mode {
            Modes::Block(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if Block::StartRawBlock == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    } else if Block::EndRawBlock == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    } else if Block::StartRawComment == token {
                        self.mode = Modes::RawComment(lexer.to_owned().morph());
                    } else if Block::StartRawStatement == token {
                        self.mode =
                            Modes::RawStatement(lexer.to_owned().morph());
                    } else if Block::StartComment == token {
                        self.mode = Modes::Comment(lexer.to_owned().morph());
                    } else if Block::StartStatement == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    } else if Block::StartBlockScope == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    } else if Block::EndBlockScope == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    } else if Block::StartLink == token {
                        self.mode = Modes::Link(lexer.to_owned().morph());
                    }
                    Some(Token::Block(token, span))
                } else {
                    None
                }
            }
            Modes::RawComment(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if RawComment::End == token {
                        self.mode = Modes::Block(lexer.to_owned().morph());
                    }
                    Some(Token::RawComment(token, span))
                } else {
                    None
                }
            }
            Modes::RawStatement(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if RawStatement::End == token {
                        self.mode = Modes::Block(lexer.to_owned().morph());
                    }
                    Some(Token::RawStatement(token, span))
                } else {
                    None
                }
            }
            Modes::Comment(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if Comment::End == token {
                        self.mode = Modes::Block(lexer.to_owned().morph());
                    }
                    Some(Token::Comment(token, span))
                } else {
                    None
                }
            }
            Modes::Parameters(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if Parameters::DoubleQuoteString == token {
                        self.mode =
                            Modes::DoubleQuoteString(lexer.to_owned().morph());
                    } else if Parameters::SingleQuoteString == token {
                        self.mode =
                            Modes::SingleQuoteString(lexer.to_owned().morph());
                    } else if Parameters::StartArray == token {
                        self.mode = Modes::Array(lexer.to_owned().morph());
                    } else if Parameters::End == token {
                        self.mode = Modes::Block(lexer.to_owned().morph());
                    }
                    Some(Token::Parameters(token, span))
                } else {
                    None
                }
            }
            Modes::DoubleQuoteString(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if DoubleQuoteString::End == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    }
                    Some(Token::DoubleQuoteString(token, span))
                } else {
                    None
                }
            }
            Modes::SingleQuoteString(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if SingleQuoteString::End == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    }
                    Some(Token::SingleQuoteString(token, span))
                } else {
                    None
                }
            }
            Modes::Array(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if Array::End == token {
                        self.mode = Modes::Parameters(lexer.to_owned().morph());
                    }
                    Some(Token::Array(token, span))
                } else {
                    None
                }
            }
            Modes::Link(lexer) => {
                let result = lexer.next();
                let span = lexer.span();

                if let Some(token) = result {
                    if Link::End == token {
                        self.mode = Modes::Block(lexer.to_owned().morph());
                    }
                    Some(Token::Link(token, span))
                } else {
                    None
                }
            }
        }
    }
}

fn normalize(tokens: Vec<Token>) -> Vec<Token> {
    let mut normalized: Vec<Token> = Vec::new();
    let mut span: Option<Span> = None;

    for t in tokens.into_iter() {
        if t.is_text() {
            if let Some(ref mut span) = span {
                span.end = t.span().end;
            } else {
                span = Some(t.span().clone());
            }
        } else {
            if let Some(span) = span.take() {
                normalized.push(Token::Block(Block::Text, span));
                normalized.push(t);
            } else {
                normalized.push(t);
            }
        }
    }

    if let Some(span) = span.take() {
        normalized.push(Token::Block(Block::Text, span));
    }

    normalized
}

/// Get a token iterator for the given source template.
///
/// The returned iterator will emit tokens of type `Token`.
pub fn lex(s: &str) -> Lexer {
    Lexer {
        mode: Modes::new(s),
    }
}

/// Collect the input source into a vector of tokens.
///
/// If the normalized flag is given consecutive text tokens
/// are coalesced into a single token.
///
/// The normalized flag is useful for test cases; the parser
/// will perform it's own normalization to reduce the number of
/// passes on the token stream.
pub fn collect(s: &str, normalized: bool) -> Vec<Token> {
    let tokens = lex(s).collect();
    if normalized {
        normalize(tokens)
    } else {
        tokens
    }
}