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
use std::fmt;
use std::iter::FusedIterator;
use std::ops::Range;

use line_span::{find_line_range, find_next_line_start};

use crate::syntax::SyntaxRule;

/// Events contain [`raw`] and [`text`].
///
/// Text is the contents of the comment, while raw includes additional
/// characters based on the type of comment, such as the comment
/// delimiters or "start and end symbols" of the comment.
///
/// - `LineComment`'s `raw` includes the whole line.
/// - `BlockComment`'s `raw` includes only the block comment delimiters.
///
/// *The above is only true, for events parsed by [`CommentParser`].*
///
/// [`text`]: enum.Event.html#method.text
/// [`raw`]: enum.Event.html#method.raw
/// [`CommentParser`]: struct.CommentParser.html
///
/// # Example
///
/// ```rust
/// # use comment_parser::Event;
/// let line = Event::LineComment("  // Foo Bar", " Foo Bar");
/// assert_eq!(line.text(), " Foo Bar");
/// assert_eq!(line.raw(),  "  // Foo Bar");
///
/// let block = Event::BlockComment("/* Foo\n  Bar */", " Foo\n  Bar ");
/// assert_eq!(block.text(), " Foo\n  Bar ");
/// assert_eq!(block.raw(),  "/* Foo\n  Bar */");
///
/// # use comment_parser::{get_syntax, CommentParser};
/// #
/// # let code = "  \n  // Foo Bar\r\n foo /* Foo\n  Bar */ foo\n";
/// #
/// # let mut parser = CommentParser::new(code, get_syntax("rust").unwrap());
/// # assert_eq!(parser.next(), Some(line));
/// # assert_eq!(parser.next(), Some(block));
/// # assert_eq!(parser.next(), None);
/// ```
#[derive(PartialEq, Clone)]
pub enum Event<'a> {
    /// `LineComment(raw, text)`
    LineComment(&'a str, &'a str),
    /// `BlockComment(raw, text)`
    BlockComment(&'a str, &'a str),
}

impl<'a> Event<'a> {
    /// Returns the raw part of an `Event`.
    #[inline]
    pub fn raw(&self) -> &str {
        use Event::*;
        match self {
            LineComment(raw, _) | BlockComment(raw, _) => raw,
        }
    }

    /// Returns the text part of an `Event`.
    #[inline]
    pub fn text(&self) -> &str {
        use Event::*;
        match self {
            LineComment(_, text) | BlockComment(_, text) => text,
        }
    }
}

impl<'a> fmt::Debug for Event<'a> {
    /// Renders [`raw`] as `_` as both [`raw`] and
    /// [`text`] are similar.
    ///
    /// [`text`]: enum.Event.html#method.text
    /// [`raw`]: enum.Event.html#method.raw
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        use Event::*;
        let name = match self {
            LineComment(..) => "LineComment",
            BlockComment(..) => "BlockComment",
        };
        fmt.debug_tuple(name)
            .field(&format_args!("_"))
            .field(&self.text())
            .finish()
    }
}

#[derive(Clone, Debug)]
enum RawEvent<'a> {
    LineComment(&'a str, &'a str),
    BlockComment(&'a str, &'a str),
    String(&'a str, &'a str),
}

impl<'a> RawEvent<'a> {
    #[inline]
    fn into_event(self) -> Option<Event<'a>> {
        use RawEvent::*;
        match self {
            LineComment(raw, text) => Some(Event::LineComment(raw, text)),
            BlockComment(raw, text) => Some(Event::BlockComment(raw, text)),
            String(..) => None,
        }
    }
}

/// `CommentParser` parses `text` and produces [`Event`]s.
///
/// [`Event`]: enum.Event.html
#[allow(missing_debug_implementations)]
#[derive(Clone)]
pub struct CommentParser<'a> {
    text: &'a str,
    index: usize,
    rules: &'a [SyntaxRule<'a>],
    max_rule_len: usize,
}

impl<'a> CommentParser<'a> {
    /// Creates a `CommentParser` which parses `text` based on
    /// `rules` and produces [`Event`]s.
    ///
    /// # Panics
    ///
    /// Note that `CommentParser` panics immediately upon calling `new`,
    /// if any [`SyntaxRule`] contains an empty `&[u8]`.
    ///
    /// [`SyntaxRule`]: enum.SyntaxRule.html
    #[inline]
    pub fn new(text: &'a str, rules: &'a [SyntaxRule]) -> Self {
        assert!(SyntaxRule::check_rules(rules), "empty syntax rule");

        Self {
            text,
            index: 0,
            rules,
            max_rule_len: SyntaxRule::max_rule_len(rules),
        }
    }

    fn next_event(&mut self) -> Option<RawEvent<'a>> {
        let bytes = self.text.as_bytes();

        let rule = bytes[self.index..]
            .windows(self.max_rule_len)
            .enumerate()
            .filter_map(|(i, w)| {
                let rule = self
                    .rules
                    .iter()
                    .position(|rule| w.starts_with(rule.start()))?;
                Some((self.index + i, &self.rules[rule]))
            })
            .next();

        if let Some((start, rule)) = rule {
            Some(match rule.parse_rule() {
                ParseRule::LineComment => self.parse_line_comment(start, rule),
                ParseRule::BlockComment => self.parse_block_comment(start, rule),
                ParseRule::String => self.parse_string(start, rule),
            })
        } else {
            self.index = bytes.len();
            None
        }
    }

    fn parse_line_comment(&mut self, start: usize, rule: &SyntaxRule) -> RawEvent<'a> {
        let after_start = start + rule.start().len();
        let Range { start, end } = find_line_range(self.text, start);

        self.index = find_next_line_start(self.text, end).unwrap_or_else(|| self.text.len());

        let line = &self.text[start..end];
        let comment = &self.text[after_start..end];

        RawEvent::LineComment(line, comment)
    }

    fn parse_block_comment(&mut self, start: usize, rule: &SyntaxRule) -> RawEvent<'a> {
        let after_start = start + rule.start().len();

        let rule_end = rule.end();

        let (before_end, end) = self.text.as_bytes()[after_start..]
            .windows(rule_end.len())
            .position(|w| w == rule_end)
            .map(|i| {
                let i = after_start + i;
                (i, i + rule_end.len())
            })
            .unwrap_or_else(|| {
                let i = self.text.len();
                (i, i)
            });

        self.index = end;

        let lines = &self.text[start..end];
        let comment = &self.text[after_start..before_end];

        RawEvent::BlockComment(lines, comment)
    }

    fn parse_string(&mut self, start: usize, rule: &SyntaxRule) -> RawEvent<'a> {
        let after_start = start + rule.start().len();
        let rule_end = rule.start();

        let mut skip = false;

        let (before_end, end) = self.text.as_bytes()[after_start..]
            .windows(rule_end.len())
            .position(|w| {
                if skip {
                    skip = false;
                    false
                // TODO: This should be part of SyntaxRule
                } else if w[0] == b'\\' {
                    skip = true;
                    false
                } else {
                    w == rule_end
                }
            })
            .map(|i| {
                let i = after_start + i;
                (i, i + rule_end.len())
            })
            .unwrap_or_else(|| {
                let i = self.text.len();
                (i, i)
            });

        self.index = end;

        let lines = &self.text[start..end];
        let string = &self.text[after_start..before_end];

        RawEvent::String(lines, string)
    }
}

impl<'a> Iterator for CommentParser<'a> {
    type Item = Event<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == self.text.len() {
            return None;
        }

        while let Some(event) = self.next_event() {
            let event = event.into_event();
            if event.is_some() {
                return event;
            }
        }

        None
    }
}

impl<'a> FusedIterator for CommentParser<'a> {}

enum ParseRule {
    LineComment,
    BlockComment,
    String,
}

impl<'a> SyntaxRule<'a> {
    #[inline]
    fn parse_rule(&self) -> ParseRule {
        use SyntaxRule::*;
        match self {
            LineComment(..) => ParseRule::LineComment,
            BlockComment(..) => ParseRule::BlockComment,
            String(..) => ParseRule::String,
        }
    }

    #[inline]
    fn start(&self) -> &[u8] {
        use SyntaxRule::*;
        match self {
            LineComment(start) | BlockComment(start, _) | String(start) => start,
        }
    }

    #[inline]
    fn end(&self) -> &[u8] {
        use SyntaxRule::*;
        match self {
            BlockComment(_, end) => end,
            _ => unreachable!(),
        }
    }

    #[inline]
    fn max_rule_len(rules: &[Self]) -> usize {
        rules
            .iter()
            .map(Self::start)
            .map(<[u8]>::len)
            .max()
            .unwrap_or(0)
    }

    /// Returns `true` if the rules are valid.
    #[inline]
    fn check_rules(rules: &[Self]) -> bool {
        !rules.iter().any(|rule| {
            use SyntaxRule::*;
            match rule {
                LineComment(start) | String(start) => start.is_empty(),
                BlockComment(start, end) => start.is_empty() || end.is_empty(),
            }
        })
    }
}