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
use std::borrow::Cow;
use std::cmp::min;

use eyre::Result;
use smallvec::SmallVec;

use crate::{Block, SelPart, Selector, Template};


/*
Approx grammar

doc = lit+
    | if
    | for
lit = HtmlLit | PutUnescaped  | PutEscaped
for = For, doc, Endfor
if = IF , doc, ifinner?, Endif
ifinner = (Else doc)
    | Elif, doc, ifinner?
*/

peg::parser! {
    pub grammar template_parser() for str {
        //
        // Entry
        //

        pub rule template() -> Template<'input>
            = parts:blocks() ![_] { Template {parts}}

        rule blocks() -> Vec<Block<'input>>
            = block()*

        rule block() -> Block<'input>
            = for_block()
            / if_block()
            / put_unescaped_block()
            / put_escaped_block()
            / text_block()
            / comment_block()

        //
        // complex chains
        //

        rule for_block() -> Block<'input>
            = f:for_tag() body:blocks() endfor_tag() { Block::For {
                name: Cow::Borrowed(f.0),
                iter_over: f.1,
                each: body
            }}

        rule if_block() -> Block<'input>
            = sel:if_tag() if_true:blocks() if_false:if_inner()? endif_tag()
            { Block::If {
                sel,
                if_true,
                if_false: if_false.unwrap_or_default()
            }}

        rule if_inner() -> Vec<Block<'input>>
            = if_else_case() / if_elif_case()

        rule if_else_case() -> Vec<Block<'input>>
            = else_tag() bs:blocks() { bs }

        rule if_elif_case() -> Vec<Block<'input>>
            = sel:elif_tag() if_true:blocks() if_false:if_inner()? {
                vec![Block::If {
                    sel,
                    if_true,
                    if_false: if_false.unwrap_or_default()
                }]
            }

        //
        // Simple Blocks
        //
        rule text_block() -> Block<'input>
            = s:text() { Block::HtmlLit(Cow::Borrowed(s)) }

        rule put_escaped_block() -> Block<'input>
            = s:put_escaped() { Block::PutEscaped(s) }

        rule put_unescaped_block() -> Block<'input>
            = s:put_unescaped() { Block::PutUnescaped(s) }


        rule comment_block() -> Block<'input>
            // TODO: Allow # in comment
            = "{#" $([x if x != '#'])* "#}" { Block::Comment }

        //
        // Tags
        //
        rule text() -> &'input str
            // TODO: Allow { in text
            = s:$([x if x != '{']+) { s }

        rule put_escaped() -> Selector<'input>
            = "{{" " "* s:selector() " "* "}}" { s }

        rule put_unescaped() -> Selector<'input>
            = "{{{" " "* s:selector() " "* "}}}" { s }

        rule if_tag() -> Selector<'input>
            = "{%" " "* "if" " "+ s:selector() " "* "%}" { s }

        rule elif_tag() -> Selector<'input>
            = "{%" " "* "elif" " "+ s:selector() " "* "%}" { s }

        rule for_tag() -> (&'input str, Selector<'input>)
            = "{%" " "* "for" " "+ i:ident() " "+ "in" " "+ s:selector() " "* "%}"
            { (i, s) }

        rule else_tag() -> ()
            = "{%" " "* "else" " "* "%}"
        rule endif_tag() -> ()
            = "{%" " "* "endif" " "* "%}"
        rule endfor_tag() -> ()
            = "{%" " "* "endfor" " "* "%}"

        //
        // Selecors
        //

        rule selector() -> Selector<'input>
            = first:ident() rest:sel_part()* {
                // Hack
                let mut rest = rest;
                rest.insert(0, SelPart::Map(Cow::Borrowed(first)));
                Selector {
                    items: SmallVec::from_vec(rest)
                }
            }

        rule sel_part() -> SelPart<'input>
            = sel_part_map() / sel_part_array()

        rule sel_part_map() -> SelPart<'input>
            = "." id:ident() { SelPart::Map(Cow::Borrowed(id))}

        rule sel_part_array() -> SelPart<'input>
            = "[" n:number() "]" { SelPart::Array(n) }

        rule number() -> usize
        // Unwrap is fine, as this is garenteed to be a valid number
            = n:$(['0'..='9']+) { n.parse().unwrap() }

        rule ident() -> &'input str
            = n:$(['a'..='z' | 'A'..='Z' | '0'..='9' | '_' ]+) { n }
    }
}

impl<'t> Template<'t> {
    pub fn new(input: &'t str) -> Result<Self> {
        match crate::parse::template_parser::template(input) {
            Ok(tpl) => Ok(tpl),
            Err(e) => {
                let start = e.location.offset;
                let end = min(input.len(), start + 20);
                let relevent = &input[start..end];
                Err(eyre::Error::new(e).wrap_err(format!("Error starts at `{}`", relevent)))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta::{assert_yaml_snapshot, glob};
    use std::fs;

    #[test]
    fn all() {
        glob! {
            "templates/*.html", |path| {
                let input = fs::read_to_string(path).unwrap();
                let tpl =Template::new(&input).unwrap();
                assert_yaml_snapshot!(tpl);
            }
        }
    }
}