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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! The regex "compiler", which parses the regex itself.
//! Produces a matcher ready to match input.

#[cfg(feature = "no_std")]
use std::prelude::*;

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use {ctype, PosixRegex};

/// Repetition bounds, for example + is (1, None), and ? is (0, Some(1))
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Range(pub u32, pub Option<u32>);
impl fmt::Debug for Range {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Range(start, None) => write!(f, "{}..", start),
            Range(start, Some(end)) => write!(f, "{}..{}", start, end),
        }
    }
}

/// An item inside square brackets, like `[abc]` or `[[:digit:]]`
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Collation {
    Char(u8),
    Class(fn(u8) -> bool)
}
impl Collation {
    /// Compare this collation to a character
    pub fn matches(&self, other: u8, insensitive: bool) -> bool {
        match *self {
            Collation::Char(me) if insensitive => me & !32 == other & !32,
            Collation::Char(me) => me == other,
            Collation::Class(f) => f(other)
        }
    }
}

/// A single "compiled" token, such as a `.` or a character literal
#[derive(Clone, PartialEq, Eq)]
pub enum Token {
    InternalStart,

    Any,
    Char(u8),
    End,
    Group(Vec<Vec<(Token, Range)>>),
    OneOf {
        invert: bool,
        list: Vec<Collation>
    },
    Start,
    WordEnd,
    WordStart
}
impl fmt::Debug for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Token::InternalStart => write!(f, "<START>"),

            Token::Any => write!(f, "."),
            Token::Char(c) => write!(f, "{:?}", c as char),
            Token::End => write!(f, "$"),
            Token::Group(ref inner) => write!(f, "Group({:?})", inner),
            Token::OneOf { invert, ref list } => write!(f, "[invert: {}; {:?}]", invert, list),
            Token::Start => write!(f, "^"),
            Token::WordEnd => write!(f, ">"),
            Token::WordStart => write!(f, "<")
        }
    }
}
/// An error that occurred while compiling the regex
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    EOF,
    EmptyRepetition,
    Expected(u8, Option<u8>),
    IllegalRange,
    IntegerOverflow,
    LeadingRepetition,
    UnclosedRepetition,
    UnexpectedToken(u8),
    UnknownClass(Vec<u8>),
    UnknownCollation
}

/// A regex builder struct
pub struct PosixRegexBuilder<'a> {
    input: &'a [u8],
    classes: HashMap<&'a [u8], fn(u8) -> bool>
}
impl<'a> PosixRegexBuilder<'a> {
    /// Create a new instance that is ready to parse the regex `input`
    pub fn new(input: &'a [u8]) -> Self {
        Self {
            input,
            classes: HashMap::new()
        }
    }
    /// Add a custom collation class, for use within square brackets (such as `[[:digit:]]`)
    pub fn with_class(mut self, name: &'a [u8], callback: fn(u8) -> bool) -> Self {
        self.classes.insert(name, callback);
        self
    }
    /// Add all the default collation classes, like `[[:digit:]]` and `[[:alnum:]]`
    pub fn with_default_classes(mut self) -> Self {
        #[cfg(not(feature = "no_std"))]
        self.classes.reserve(12);

        self.classes.insert(b"alnum", ctype::is_alnum);
        self.classes.insert(b"alpha", ctype::is_alpha);
        self.classes.insert(b"blank", ctype::is_blank);
        self.classes.insert(b"cntrl", ctype::is_cntrl);
        self.classes.insert(b"digit", ctype::is_digit);
        self.classes.insert(b"graph", ctype::is_graph);
        self.classes.insert(b"lower", ctype::is_lower);
        self.classes.insert(b"print", ctype::is_print);
        self.classes.insert(b"punct", ctype::is_punct);
        self.classes.insert(b"space", ctype::is_space);
        self.classes.insert(b"upper", ctype::is_upper);
        self.classes.insert(b"xdigit", ctype::is_xdigit);

        self
    }
    /// "Compile" this regex to a struct ready to match input
    pub fn compile(&mut self) -> Result<PosixRegex<'static>, Error> {
        let search = self.compile_tokens()?;
        Ok(PosixRegex::new(Cow::Owned(search)))
    }

    fn consume(&mut self, amount: usize) {
        self.input = &self.input[amount..];
    }
    fn take_int(&mut self) -> Result<Option<u32>, Error> {
        let mut out: Option<u32> = None;
        while let Some(&c @ b'0'..=b'9') = self.input.first() {
            self.consume(1);
            out = Some(out.unwrap_or(0)
                .checked_mul(10)
                .and_then(|out| out.checked_add((c - b'0') as u32))
                .ok_or(Error::IntegerOverflow)?);
        }
        Ok(out)
    }
    fn next(&mut self) -> Result<u8, Error> {
        self.input.first()
            .map(|&c| { self.consume(1); c })
            .ok_or(Error::EOF)
    }
    fn expect(&mut self, c: u8) -> Result<(), Error> {
        if self.input.first() != Some(&c) {
            return Err(Error::Expected(c, self.input.first().cloned()));
        }
        self.consume(1);
        Ok(())
    }
    pub fn compile_tokens(&mut self) -> Result<Vec<Vec<(Token, Range)>>, Error> {
        let mut alternatives = Vec::new();
        let mut chain: Vec<(Token, Range)> = Vec::new();

        while let Some(&c) = self.input.first() {
            self.consume(1);
            let token = match c {
                b'^' => Token::Start,
                b'$' => Token::End,
                b'.' => Token::Any,
                b'*' => if let Some(last) = chain.last_mut() {
                    last.1 = Range(0, None);
                    continue;
                } else {
                    return Err(Error::LeadingRepetition);
                },
                b'[' => {
                    let mut list = Vec::new();
                    let invert = self.input.first() == Some(&b'^');

                    if invert {
                        self.consume(1);
                    }

                    loop {
                        let mut c = self.next()?;

                        let mut push = true;

                        if c == b'[' {
                            // TODO: Handle collation characters properly,
                            // because currently idk what they are and only
                            // have the behavior of `grep` to go on.
                            match self.next()? {
                                b'.' => {
                                    c = self.next()?;
                                    self.expect(b'.')?;
                                    self.expect(b']')?;
                                },
                                b'=' => {
                                    c = self.next()?;
                                    self.expect(b'=')?;
                                    self.expect(b']')?;
                                },
                                b':' => {
                                    let end = self.input.iter().position(|&c| c == b':').ok_or(Error::EOF)?;
                                    let key = &self.input[..end];
                                    let class = *self.classes.get(key).ok_or_else(|| Error::UnknownClass(key.to_vec()))?;
                                    self.consume(end + 1);
                                    self.expect(b']')?;

                                    list.push(Collation::Class(class));
                                    push = false;
                                },
                                _ => return Err(Error::UnknownCollation)
                            }
                        }

                        if push {
                            list.push(Collation::Char(c));

                            if self.input.first() == Some(&b'-') && self.input.get(1) != Some(&b']') {
                                self.consume(1);
                                let dest = self.next()?;
                                for c in (c+1)..=dest {
                                    list.push(Collation::Char(c));
                                }
                            }
                        }

                        if self.input.first() == Some(&b']') {
                            self.consume(1);
                            break;
                        }
                    }

                    Token::OneOf {
                        invert,
                        list
                    }
                },
                b'\\' => match self.next()? {
                    b'(' => Token::Group(self.compile_tokens()?),
                    b')' => {
                        alternatives.push(chain);
                        return Ok(alternatives);
                    }
                    b'|' => {
                        alternatives.push(chain);
                        chain = Vec::new();
                        continue;
                    },
                    b'<' => Token::WordStart,
                    b'>' => Token::WordEnd,
                    c@b'?' | c@b'+' => if let Some(last) = chain.last_mut() {
                        last.1 = match c {
                            b'?' => Range(0, Some(1)),
                            b'+' => Range(1, None),
                            _ => unreachable!(c)
                        };
                        continue;
                    } else {
                        return Err(Error::LeadingRepetition);
                    },
                    b'{' => if let Some(last) = chain.last_mut() {
                        let first = self.take_int()?.ok_or(Error::EmptyRepetition)?;
                        let mut second = Some(first);
                        if let Some(b',') = self.input.first() {
                            self.consume(1);
                            second = self.take_int()?;
                        }
                        if self.input.first() == Some(&b'}') {
                            self.consume(1);
                        } else if self.input.starts_with(br"\}") {
                            self.consume(2);
                        } else {
                            return Err(Error::UnclosedRepetition);
                        }
                        if second.map(|second| first > second).unwrap_or(false) {
                            return Err(Error::IllegalRange);
                        }
                        last.1 = Range(first, second);
                        continue;
                    } else {
                        return Err(Error::LeadingRepetition);
                    },
                    b'a' => Token::OneOf { invert: false, list: vec![Collation::Class(ctype::is_alnum)] },
                    b'd' => Token::OneOf { invert: false, list: vec![Collation::Class(ctype::is_digit)] },
                    b's' => Token::OneOf { invert: false, list: vec![Collation::Class(ctype::is_space)] },
                    b'S' => Token::OneOf { invert: true,  list: vec![Collation::Class(ctype::is_space)] },
                    b'n' => Token::Char(b'\n'),
                    b'r' => Token::Char(b'\r'),
                    b't' => Token::Char(b'\t'),
                    c => Token::Char(c)
                },
                c => Token::Char(c)
            };
            chain.push((token, Range(1, Some(1))));
        }

        alternatives.push(chain);
        Ok(alternatives)
    }
}

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

    fn compile(input: &[u8]) -> Vec<(Token, Range)> {
        PosixRegexBuilder::new(input)
            .with_default_classes()
            .compile_tokens()
            .expect("error compiling regex")
            .into_iter()
            .next()
            .unwrap()
    }
    fn t(t: Token) -> (Token, Range) {
        (t, Range(1, Some(1)))
    }
    fn c(c: u8) -> (Token, Range) {
        t(Token::Char(c))
    }

    #[test]
    fn basic() {
        assert_eq!(compile(b"abc"), &[c(b'a'), c(b'b'), c(b'c')]);
    }
    #[test]
    fn groups() {
        assert_eq!(compile(br"\(abc\|bcd\|cde\)"), &[t(Token::Group(vec![
            vec![c(b'a'), c(b'b'), c(b'c')],
            vec![c(b'b'), c(b'c'), c(b'd')],
            vec![c(b'c'), c(b'd'), c(b'e')]
        ]))]);
        assert_eq!(compile(br"\(abc\|\(bcd\|cde\)\)"), &[
            t(Token::Group(vec![
                vec![c(b'a'), c(b'b'), c(b'c')],
                vec![t(Token::Group(vec![
                    vec![c(b'b'), c(b'c'), c(b'd')],
                    vec![c(b'c'), c(b'd'), c(b'e')]
                ]))]
            ]))
        ]);
    }
    #[test]
    fn words() {
        assert_eq!(
            compile(br"\<word\>"),
            &[t(Token::WordStart), c(b'w'), c(b'o'), c(b'r'), c(b'd'), t(Token::WordEnd)]
        );
    }
    #[test]
    fn repetitions() {
        assert_eq!(
            compile(br"yeee*"),
            &[c(b'y'), c(b'e'), c(b'e'), (Token::Char(b'e'), Range(0, None))]
        );
        assert_eq!(
            compile(br"yee\?"),
            &[c(b'y'), c(b'e'), (Token::Char(b'e'), Range(0, Some(1)))]
        );
        assert_eq!(
            compile(br"yee\+"),
            &[c(b'y'), c(b'e'), (Token::Char(b'e'), Range(1, None))]
        );
        assert_eq!(
            compile(br"ye\{2}"),
            &[c(b'y'), (Token::Char(b'e'), Range(2, Some(2)))]
        );
        assert_eq!(
            compile(br"ye\{2,}"),
            &[c(b'y'), (Token::Char(b'e'), Range(2, None))]
        );
        assert_eq!(
            compile(br"ye\{2,3}"),
            &[c(b'y'), (Token::Char(b'e'), Range(2, Some(3)))]
        );
    }
    #[test]
    fn bracket() {
        assert_eq!(
            compile(b"[abc]"),
            &[t(Token::OneOf {
                invert: false,
                list: vec![
                    Collation::Char(b'a'),
                    Collation::Char(b'b'),
                    Collation::Char(b'c')
                ]
            })]
        );
        assert_eq!(
            compile(b"[^abc]"),
            &[t(Token::OneOf {
                invert: true,
                list: vec![
                    Collation::Char(b'a'),
                    Collation::Char(b'b'),
                    Collation::Char(b'c')
                ]
            })]
        );
        assert_eq!(
            compile(b"[]] [^]]"),
            &[
                t(Token::OneOf { invert: false, list: vec![ Collation::Char(b']') ] }),
                c(b' '),
                t(Token::OneOf { invert: true,  list: vec![ Collation::Char(b']') ] }),
            ]
        );
        assert_eq!(
            compile(b"[0-3] [a-c] [-1] [1-]"),
            &[
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Char(b'0'),
                    Collation::Char(b'1'),
                    Collation::Char(b'2'),
                    Collation::Char(b'3')
                ] }),
                c(b' '),
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Char(b'a'),
                    Collation::Char(b'b'),
                    Collation::Char(b'c')
                ] }),
                c(b' '),
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Char(b'-'),
                    Collation::Char(b'1')
                ] }),
                c(b' '),
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Char(b'1'),
                    Collation::Char(b'-')
                ] })
            ]
        );
        assert_eq!(
            compile(b"[[.-.]-/]"),
            &[
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Char(b'-'),
                    Collation::Char(b'.'),
                    Collation::Char(b'/')
                ] })
            ]
        );
        assert_eq!(
            compile(b"[[:digit:][:upper:]]"),
            &[
                t(Token::OneOf { invert: false, list: vec![
                    Collation::Class(ctype::is_digit),
                    Collation::Class(ctype::is_upper)
                ] })
            ]
        );
    }
    #[test]
    fn newline() {
        assert_eq!(
            compile(br"\r\n"),
            &[c(b'\r'), c(b'\n')]
        );
    }
}