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
mod emitter;
pub use self::emitter::*;

pub mod extensions;
use self::extensions::Extension;

use std::convert::TryInto;
use std::fmt;
use std::path::Path;
use std::rc::Rc;

#[derive(PartialEq, Eq, Hash)]
pub struct ExtensionTag(pub &'static str);

impl fmt::Debug for ExtensionTag {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

#[derive(Debug, PartialEq)]
pub enum Block {
    Paragraph(Vec<Element>),
    ExtensionBlocks(ExtensionTag, Vec<Block>),
    ExtensionBlock(ExtensionTag, Vec<Element>),
}

#[derive(Debug, PartialEq)]
pub enum Element {
    Text(String),
    ExtensionElement(ExtensionTag, Box<Element>),
}

#[derive(Debug)]
pub enum ParseError {
    UnexpectedEndOfFile,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ParseError::UnexpectedEndOfFile => write!(f, "Unexpected end of file."),
        }
    }
}

pub type ParseResult<T> = Result<T, ParseError>;

pub struct Parser {
    raw: Vec<char>,
    offset: usize,
    extensions: Vec<Rc<dyn Extension>>,
}

impl Parser {
    pub fn new(raw: String) -> Parser {
        Parser {
            raw: raw.chars().collect(),
            offset: 0,
            extensions: vec![],
        }
    }

    pub fn add_extension<E: Extension + 'static>(&mut self, extension: E) {
        self.extensions.push(Rc::new(extension));
    }

    pub fn emit_with(mut self, emitter: &dyn Emitter) -> ParseResult<String> {
        let mut out = String::new();
        self.move_past_whitespace();
        while !self.is_at_end() {
            emitter.emit_block(self.parse_block()?, &mut out);
            self.move_past_whitespace();
        }
        Ok(out)
    }

    pub fn parse(mut self) -> ParseResult<Vec<Block>> {
        let mut out = vec![];
        self.move_past_whitespace();
        while !self.is_at_end() {
            out.push(self.parse_block()?);
            self.move_past_whitespace();
        }
        Ok(out)
    }

    #[inline]
    pub fn is_at_end(&self) -> bool {
        self.raw.len() == self.offset
    }

    #[inline]
    fn peek_at(&self, offset: usize) -> char {
        self.raw.get(offset).cloned().unwrap_or('\0')
    }

    #[inline]
    pub fn peek(&self) -> char {
        self.peek_at(self.offset)
    }

    pub fn peek_many(&self, len: usize) -> &[char] {
        let raw_len = self.raw.len();
        if raw_len > self.offset + len {
            &self.raw[self.offset..self.offset+len]
        } else if raw_len > self.offset {
            &self.raw[self.offset..]
        } else {
            &[]
        }
    }

    #[inline]
    pub fn take(&mut self) -> char {
        let c = self.peek();
        self.offset += 1;
        c
    }

    #[inline]
    pub fn take_many(&mut self, len: usize) -> Vec<char> {
        let c = self.peek_many(len).to_vec();
        self.offset += len;
        c
    }

    pub fn move_past_whitespace(&mut self) {
        loop {
            match self.peek() {
                '#' => self.move_past_comment(),
                w if w.is_whitespace() => self.offset += 1,
                _ => break,
            }
        }
    }

    pub fn move_past_comment(&mut self) {
        loop {
            match self.peek() {
                '\n' => {
                    self.offset += 1;
                    return;
                }
                '\0' => return,
                _ => self.offset += 1,
            }
        }
    }

    pub fn parse_block(&mut self) -> ParseResult<Block> {
        for ext in self.extensions.clone() {
            let offset_before_ext = self.offset;
            if let Some(block) = ext.parse_block(self)? {
                return Ok(block);
            }
            self.offset = offset_before_ext;
        }
        self.parse_paragraph_block()
    }

    fn parse_paragraph_block(&mut self) -> ParseResult<Block> {
        if self.is_at_end() {
            return Err(ParseError::UnexpectedEndOfFile);
        }

        Ok(Block::Paragraph(self.parse_elements()?))
    }

    pub fn parse_elements(&mut self) -> ParseResult<Vec<Element>> {
        let mut elements = vec![];

        let mut paragraph = String::new();
        let mut whitespace = false;
        'elements: while !self.sees_end_of_block() {
            for ext in self.extensions.clone() {
                let offset_before_ext = self.offset;
                if let Some(el) = ext.parse_element(self)? {
                    if whitespace {
                        paragraph.push(' ');
                        whitespace = false;
                    }
                    if !paragraph.is_empty() {
                        elements.push(Element::Text(std::mem::replace(
                            &mut paragraph,
                            String::new(),
                        )));
                    }
                    elements.push(el);
                    continue 'elements;
                }
                self.offset = offset_before_ext;
            }

            match self.take() {
                '#' => self.move_past_comment(),
                w if w.is_whitespace() => {
                    whitespace |= true;
                }
                c => {
                    if whitespace {
                        paragraph.push(' ');
                        whitespace = false;
                    }
                    paragraph.push(c)
                }
            }
        }
        if !paragraph.is_empty() {
            elements.push(Element::Text(paragraph));
        }
        Ok(elements)
    }

    pub fn sees_end_of_block(&self) -> bool {
        for ext in self.extensions.iter() {
            if ext.sees_end_of_block(self) {
                return true;
            }
        }

        match (self.peek(), self.peek_at(self.offset + 1)) {
            ('\n', '\n') | ('\n', '\0') | ('\0', '\0') => true,
            _ => false,
        }
    }
}

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

    #[test]
    fn empty_source() {
        let parser = Parser::new("".into());

        assert_eq!(parser.parse().unwrap(), vec![]);
    }

    #[test]
    fn just_a_bit_of_text() {
        let parser = Parser::new("Hello! This is a sentence!".into());

        assert_eq!(
            parser.parse().unwrap(),
            vec![Block::Paragraph(vec![Element::Text(
                "Hello! This is a sentence!".into()
            )])]
        );
    }

    #[test]
    fn comments_and_extraneous_whitespace_is_removed() {
        let parser = Parser::new(
            r#"
              # This is a comment
              
              This is a paragraph! # Which happens to include a comment
              And it spans multiple
              lines!
            "#
            .into(),
        );

        assert_eq!(
            parser.parse().unwrap(),
            vec![Block::Paragraph(vec![Element::Text(
                "This is a paragraph! And it spans multiple lines!".into()
            )])]
        );
    }

    #[test]
    fn html_emitter_escapes() {
        let parser = Parser::new(
            r#"
              This isn't Markdown!
            "#
            .into(),
        );

        assert_eq!(
            parser.emit_with(&HtmlEmitter::new()).unwrap(),
            "<p>\n  This isn&apos;t Markdown!\n</p>\n"
        );
    }

    #[test]
    fn bold_extension() {
        let mut parser = Parser::new(
            r#"
              This *isn't* Markdown!
            "#
            .into(),
        );

        parser.add_extension(extensions::Bold);

        assert_eq!(
            parser.emit_with(&HtmlEmitter::new()).unwrap(),
            "<p>\n  This <strong>isn&apos;t</strong> Markdown!\n</p>\n"
        );
    }

    #[test]
    fn italics_extension() {
        let mut parser = Parser::new(
            r#"
              This /isn't/ Markdown!
            "#
            .into(),
        );

        parser.add_extension(extensions::Italics);

        assert_eq!(
            parser.emit_with(&HtmlEmitter::new()).unwrap(),
            "<p>\n  This <em>isn&apos;t</em> Markdown!\n</p>\n"
        );
    }

    #[test]
    fn lists_extension() {
        let mut parser = Parser::new(
            r#"
              This is a paragraph.
              ** This is a list item.

              ** This is a different list.
              ** With two items!
            "#
            .into(),
        );

        parser.add_extension(extensions::Lists::new("**"));

        assert_eq!(
            parser.parse().unwrap(),
            vec![
                Block::Paragraph(vec![Element::Text("This is a paragraph.".into())]),
                Block::ExtensionBlocks(
                    extensions::LIST,
                    vec![Block::ExtensionBlock(
                        extensions::LIST_ITEM,
                        vec![Element::Text("This is a list item.".into())]
                    )]
                ),
                Block::ExtensionBlocks(
                    extensions::LIST,
                    vec![
                        Block::ExtensionBlock(
                            extensions::LIST_ITEM,
                            vec![Element::Text("This is a different list.".into())]
                        ),
                        Block::ExtensionBlock(
                            extensions::LIST_ITEM,
                            vec![Element::Text("With two items!".into())]
                        ),
                    ]
                ),
            ],
        );
    }
}