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
use block::{Block, Line, LineSegment};
use pest::iterators::Pair;
use pest::Parser;

#[derive(Debug, PartialEq)]
enum Segment {
    Content(String),
    Placeholder(String),
}

impl<'a> From<Pair<'a, Rule>> for Segment {
    fn from(pair: Pair<'a, Rule>) -> Segment {
        match pair.as_rule() {
            Rule::not_placeholder => Segment::Content(String::from(pair.as_str())),
            Rule::placeholder => {
                Segment::Placeholder(String::from(pair.into_inner().next().unwrap().as_str()))
            }
            unknown => panic!("Unexpected rule '{:?}' found", unknown),
        }
    }
}

#[derive(Parser)]
#[grammar = "grammar.pest"]
struct GrammarParser;

#[derive(Debug)]
struct TemplateLine {
    indentation: String,
    content: Vec<Segment>,
}

impl TemplateLine {
    fn empty() -> Self {
        TemplateLine {
            indentation: String::from(""),
            content: vec![],
        }
    }
}

impl<'a> From<Pair<'a, Rule>> for TemplateLine {
    fn from(pair: Pair<'a, Rule>) -> TemplateLine {
        let mut indentation = String::from("");
        let mut content = vec![];
        for item in pair.into_inner() {
            match item.as_rule() {
                Rule::significant_whitespace => indentation = String::from(item.as_str()),
                Rule::template_content => {
                    let result = GrammarParser::parse(Rule::template_phase2, item.as_str())
                        .unwrap()
                        .next()
                        .unwrap();
                    for segment in result.into_inner() {
                        content.push(Segment::from(segment));
                    }
                }
                unknown => panic!("Unexpected rule '{:?}' found", unknown),
            }
        }
        TemplateLine {
            indentation,
            content,
        }
    }
}

#[derive(Debug)]
struct Template {
    name: String,
    indent_ignored: usize,
    lines: Vec<TemplateLine>,
}

impl<'a> From<Pair<'a, Rule>> for Template {
    fn from(pair: Pair<'a, Rule>) -> Template {
        let mut name = String::from("noname");
        let mut indent_ignored = 0;
        let mut lines = vec![];
        for item in pair.into_inner() {
            match item.as_rule() {
                Rule::template_decl => {
                    name = String::from(item.into_inner().next().unwrap().as_str())
                }
                Rule::template_line => lines.push(TemplateLine::from(item)),
                Rule::template_terminator => indent_ignored = item.as_str().len() - 1,
                Rule::template_empty_line => lines.push(TemplateLine::empty()),
                unknown => panic!("Unexpected rule '{:?}' found", unknown),
            }
        }
        Template {
            name,
            indent_ignored,
            lines,
        }
    }
}

impl<'a> From<&'a Template> for Block {
    fn from(t: &'a Template) -> Block {
        let mut lines: Vec<Line> = Vec::with_capacity(t.lines.len());
        let indent_ignored = t.indent_ignored;

        for template_line in &t.lines {
            let mut segments: Vec<LineSegment> =
                Vec::with_capacity(template_line.content.len() + 1);

            // Add correct amount of whitespace at the beginning of the block
            let indentation_len = template_line.indentation.len();
            if indentation_len > indent_ignored {
                let indentation: &str = &template_line.indentation[indent_ignored..];
                segments.push(LineSegment::Content(String::from(indentation)));
            }

            for template_segment in &template_line.content {
                segments.push(match template_segment {
                    Segment::Placeholder(x) => LineSegment::Placeholder(x.clone()),
                    Segment::Content(x) => LineSegment::Content(x.clone()),
                })
            }
            lines.push(Line(segments));
        }
        Block(lines)
    }
}

#[derive(Debug)]
pub struct File {
    templates: Vec<Template>,
}

impl<'a> From<Pair<'a, Rule>> for File {
    fn from(pair: Pair<'a, Rule>) -> File {
        let mut v: Vec<Template> = vec![];
        for item in pair.into_inner() {
            match item.as_rule() {
                Rule::template => v.push(Template::from(item)),
                unknown => panic!("Unexpected rule '{:?}' found", unknown),
            }
        }
        File { templates: v }
    }
}

impl File {
    pub fn parse(content: &str) -> File {
        let result = GrammarParser::parse(Rule::file, content);

        match result {
            Err(e) => {
                println!("Parse error: {}", e);
                panic!();
            }
            Ok(mut r) => r.next().unwrap().into(),
        }
    }

    /// Find a template in the template definition file.
    pub fn template_opt(&self, template_name: &str) -> Option<Block> {
        for t in &self.templates {
            if t.name == template_name {
                return Some(t.into());
            }
        }
        None
    }

    /// Find a template in the template definition file. Panics if not found.
    pub fn template(&self, template_name: &str) -> Block {
        self.template_opt(template_name).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_TEMPLATE: &str = "template1 =
    line 1 with ${placeholder} in the middle
----

template2 =
  a line without a placeholder
  another line
--
";

    #[test]
    fn parses_a_template() {
        let result = GrammarParser::parse(Rule::file, TEST_TEMPLATE);
        let file: File = result.unwrap().next().unwrap().into();
        assert_eq!(file.templates[0].name, "template1");
        assert_eq!(file.templates[0].indent_ignored, 4);
        assert_eq!(
            file.templates[0].lines[0].content[1],
            Segment::Placeholder(String::from("placeholder"))
        );
        assert_eq!(file.templates[1].name, "template2");
        assert_eq!(file.templates[1].indent_ignored, 2);
        assert_eq!(
            file.templates[1].lines[1].content[0],
            Segment::Content(String::from("another line"))
        );

        let template = file
            .template_opt("template2")
            .expect("template2 should exist");
        println!("-----\n{}\n-----", template);
    }
}