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
use pom::char_class::*;
use pom::parser::*;
use pom::Parser;

use crate::document::{DocumentTemplate, Partial};

/// A `StringLiteral` parser combinator is responsible for parsing the following
/// fragment:
///
/// ```ebnf
/// <StringLiteral> ::= <StringLiteralCharacter>+
///
/// <StringLiteralCharacter> ::= <EscapedCharacter>
///                          |   <UnescapedCharacter>
///
/// <EscapedCharacter> ::= '\\{'
///                    |   '\\}'
///                    |   '\\'
///                    |   '\\t'
///                    |   '\\b'
///                    |   '\\f'
///
/// <UnescapedCharacter> ::= [^\\{}]
/// ```
pub fn string_literal() -> Parser<u8, Partial> {
    let special_char = sym(b'\\').map(|_| b'\\')
        | sym(b'{').map(|_| b'{')
        | sym(b'}').map(|_| b'}');
    let escape_sequence = sym(b'\\') * special_char;
    let string = (none_of(b"\\}{") | escape_sequence).repeat(1..);
    string
        .convert(String::from_utf8)
        .map(|s| Partial::StringLiteral(s))
}

/// The `tag` parser combinator is responsible for parsing a `Tag(identifier)`
/// which is delimited between `{{ tag_id }}`.
///
/// ```enbf
/// <Tag> ::= "{{" <TagId> "}}"
/// <TagId> ::= [a-zA-Z][_a-zA-Z0-9]*
/// ```
pub fn tag() -> Parser<u8, Partial> {
    let tag_left_delimiter = seq(b"{{").discard();
    let tag_right_delimiter = seq(b"}}").discard();

    let tag = tag_left_delimiter * skip_whitespace() * tag_id()
        - skip_whitespace()
        - tag_right_delimiter;

    tag.map(|s| Partial::Tag(s))
}

fn tag_id() -> Parser<u8, String> {
    let id = tag_id_head() + tag_id_tail();
    id.map(|(head, tail)| {
        let mut s = String::new();
        s.push_str(&head);
        s.push_str(&tail);
        s
    })
}

fn tag_id_head() -> Parser<u8, String> {
    let head = is_a(alpha) | sym(b'_');
    head.map(|v| vec![v]).convert(String::from_utf8)
}

fn tag_id_tail() -> Parser<u8, String> {
    let tail = (is_a(alphanum) | sym(b'_')).repeat(0..);
    tail.convert(String::from_utf8)
}

fn skip_whitespace() -> Parser<u8, ()> {
    one_of(b" \t\r\n").repeat(0..).discard()
}

/// A `Partial` is either a `StringLiteral` or a `Tag`.
pub fn partial() -> Parser<u8, Partial> {
    string_literal() | tag()
}

/// A `DocumentTemplate` consists of a list of `Partial`s.
pub fn document_template() -> Parser<u8, DocumentTemplate> {
    let partials = partial().repeat(0..) - end();
    partials.map(|ps| DocumentTemplate::with_partials(&ps))
}

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

    #[test]
    fn test_ascii_string_literal() -> Result<(), String> {
        let raw = b"HELLO_WORLD";
        let expected_string_literal =
            Partial::StringLiteral("HELLO_WORLD".to_string());

        assert_eq!(
            expected_string_literal,
            string_literal().parse(raw).unwrap()
        );

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_unescaped_left_brace() {
        let raw = b"{";
        string_literal().parse(raw).unwrap();
    }

    #[test]
    fn test_escaped_left_brace() -> Result<(), String> {
        let raw = b"\\{";
        let expected_string_literal = Partial::StringLiteral("{".to_string());

        assert_eq!(
            expected_string_literal,
            string_literal().parse(raw).unwrap()
        );

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_unescaped_right_brace() {
        let raw = b"}";
        string_literal().parse(raw).unwrap();
    }

    #[test]
    fn test_escaped_right_brace() -> Result<(), String> {
        let raw = b"\\}";
        let expected_string_literal = Partial::StringLiteral("}".to_string());

        assert_eq!(
            expected_string_literal,
            string_literal().parse(raw).unwrap()
        );

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_unescaped_backslash() {
        let raw = b"\\";
        string_literal().parse(raw).unwrap();
    }

    #[test]
    fn test_escaped_backslash() -> Result<(), String> {
        let raw = b"\\\\";
        let expected_string_literal = Partial::StringLiteral("\\".to_string());

        assert_eq!(
            expected_string_literal,
            string_literal().parse(raw).unwrap()
        );

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_empty_tag() {
        let raw = b"{{}}";
        tag().parse(raw).unwrap();
    }

    #[test]
    fn test_tag() -> Result<(), String> {
        let raw = b"{{abc}}";
        let expected_tag = Partial::Tag("abc".to_string());
        assert_eq!(expected_tag, tag().parse(raw).unwrap());

        Ok(())
    }

    #[test]
    fn test_tag_id_with_middle_underscore() -> Result<(), String> {
        let raw = b"{{ a_c }}";
        let expected_tag = Partial::Tag("a_c".to_string());
        assert_eq!(expected_tag, tag().parse(raw).unwrap());

        Ok(())
    }

    #[test]
    fn test_tag_id_with_starting_underscore() -> Result<(), String> {
        let raw = b"{{ _x }}";
        let expected_tag = Partial::Tag("_x".to_string());
        assert_eq!(expected_tag, tag().parse(raw).unwrap());

        Ok(())
    }

    #[test]
    fn test_tag_id_with_trailing_underscore() -> Result<(), String> {
        let raw = b"{{ a_ }}";
        let expected_tag = Partial::Tag("a_".to_string());
        assert_eq!(expected_tag, tag().parse(raw).unwrap());

        Ok(())
    }

    #[test]
    fn test_tag_whitespace() -> Result<(), String> {
        let raw = b"{{ \t xxxx   }}";
        let expected_tag = Partial::Tag("xxxx".to_string());
        assert_eq!(expected_tag, tag().parse(raw).unwrap());

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_malformed_tag() {
        let raw = b"{{ \t separated identifiers illegal }}";
        tag().parse(raw).unwrap();
    }

    #[test]
    fn test_document_template() -> Result<(), String> {
        let raw = b"abc {{def}} ghi";
        let expected_document_template =
            DocumentTemplate::with_partials(&vec![
                Partial::StringLiteral("abc ".to_string()),
                Partial::Tag("def".to_string()),
                Partial::StringLiteral(" ghi".to_string()),
            ]);

        assert_eq!(
            expected_document_template,
            document_template().parse(raw).unwrap()
        );

        Ok(())
    }
}