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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Intermediate representation for a regex

use crate::api;
use crate::types::{BracketContents, CaptureGroupID};
use std::fmt;

#[derive(Debug, Copy, Clone)]
pub enum AnchorType {
    StartOfLine, // ^
    EndOfLine,   // $
}

/// A Quantifier.
#[derive(Debug, Copy, Clone)]
pub struct Quantifier {
    /// Minimum number of iterations of the loop, inclusive.
    pub min: usize,

    /// Maximum number of iterations of the loop, inclusive.
    pub max: usize,

    /// Whether the loop is greedy.
    pub greedy: bool,
}

/// The node types of our IR.
#[derive(Debug)]
pub enum Node {
    /// Matches the empty string.
    Empty,

    /// Reaching this node terminates the match successfully.
    Goal,

    /// Match a literal character.
    Char { c: char, icase: bool },

    /// Match a literal sequence of bytes.
    ByteSequence(Vec<u8>),

    /// Match any of a sequence of *bytes*.
    /// This may not exceed length MAX_BYTE_SET_LENGTH.
    ByteSet(Vec<u8>),

    /// Match any of a sequence of *chars*, case-insensitive.
    /// This may not exceed length MAX_CHAR_SET_LENGTH.
    CharSet(Vec<char>),

    /// Match the catenation of multiple nodes.
    Cat(Vec<Node>),

    /// Match an alternation like a|b.
    Alt(Box<Node>, Box<Node>),

    /// Match anything including newlines.
    MatchAny,

    /// Match anything except a newline.
    MatchAnyExceptLineTerminator,

    /// Match an anchor like ^ or $
    Anchor(AnchorType),

    /// Word boundary (\b or \B).
    WordBoundary { invert: bool },

    /// A capturing group.
    CaptureGroup(Box<Node>, CaptureGroupID),

    /// A backreference.
    BackRef(u32),

    /// A bracket.
    Bracket(BracketContents),

    /// A lookaround assertions like (?:) or (?!).
    LookaroundAssertion {
        negate: bool,
        backwards: bool,
        start_group: CaptureGroupID,
        end_group: CaptureGroupID,
        contents: Box<Node>,
    },

    /// A loop like /.*/ or /x{3, 5}?/
    Loop {
        loopee: Box<Node>,
        quant: Quantifier,
        enclosed_groups: std::ops::Range<u16>,
    },

    /// A loop whose body matches exactly one character.
    /// Enclosed capture groups are forbidden here.
    Loop1CharBody {
        loopee: Box<Node>,
        quant: Quantifier,
    },
}

pub type NodeList = Vec<Node>;

impl Node {
    /// Reverse the children of \p self if in a lookbehind.
    /// Used as a parameter to walk_mut.
    pub fn reverse_cats(&mut self, w: &mut Walk) {
        match self {
            Node::Cat(nodes) if w.in_lookbehind => nodes.reverse(),
            Node::ByteSequence(..) => panic!("Should not be reversing literal bytes"),
            _ => {}
        }
    }

    /// \return whether this is an Empty node.
    pub fn is_empty(&self) -> bool {
        matches!(self, Node::Empty)
    }

    /// \return whether this is a Cat node.
    pub fn is_cat(&self) -> bool {
        matches!(self, Node::Cat(..))
    }

    /// \return whether this node is known to match exactly one char.
    /// This is best-effort: a false return is always safe.
    pub fn matches_exactly_one_char(&self) -> bool {
        match self {
            Node::Char { .. } => true,
            Node::CharSet { .. } => true,
            Node::Bracket { .. } => true,
            Node::MatchAny => true,
            Node::MatchAnyExceptLineTerminator => true,
            _ => false,
        }
    }

    /// Duplicate a node, perhaps assigning new loop IDs. Note we must never
    /// copy a capture group.
    pub fn duplicate(&self) -> Node {
        match self {
            Node::Empty => Node::Empty,
            Node::Goal => Node::Goal,
            &Node::Char { c, icase } => Node::Char { c, icase },
            Node::ByteSequence(bytes) => Node::ByteSequence(bytes.clone()),
            Node::ByteSet(bytes) => Node::ByteSet(bytes.clone()),
            Node::CharSet(chars) => Node::CharSet(chars.clone()),
            Node::Cat(nodes) => Node::Cat(nodes.iter().map(|n| n.duplicate()).collect()),
            Node::Alt(left, right) => {
                Node::Alt(Box::new(left.duplicate()), Box::new(right.duplicate()))
            }
            Node::MatchAny => Node::MatchAny,
            Node::MatchAnyExceptLineTerminator => Node::MatchAnyExceptLineTerminator,
            &Node::Anchor(anchor_type) => Node::Anchor(anchor_type),

            Node::Loop {
                loopee,
                quant,
                enclosed_groups,
            } => {
                assert!(
                    enclosed_groups.start >= enclosed_groups.end,
                    "Cannot duplicate a loop with enclosed groups"
                );
                Node::Loop {
                    loopee: Box::new(loopee.as_ref().duplicate()),
                    quant: *quant,
                    enclosed_groups: enclosed_groups.clone(),
                }
            }

            Node::Loop1CharBody { loopee, quant } => Node::Loop1CharBody {
                loopee: Box::new(loopee.as_ref().duplicate()),
                quant: *quant,
            },

            Node::CaptureGroup(..) => {
                panic!("Refusing to duplicate a capture group");
            }
            &Node::WordBoundary { invert } => Node::WordBoundary { invert },
            &Node::BackRef(idx) => Node::BackRef(idx),
            Node::Bracket(bc) => Node::Bracket(bc.clone()),
            // Do not reverse into lookarounds, they already have the right sense.
            Node::LookaroundAssertion {
                negate,
                backwards,
                start_group,
                end_group,
                contents,
            } => {
                assert!(
                    start_group >= end_group,
                    "Cannot duplicate an assertion with enclosed groups"
                );
                Node::LookaroundAssertion {
                    negate: *negate,
                    backwards: *backwards,
                    start_group: *start_group,
                    end_group: *end_group,
                    contents: Box::new((*contents).duplicate()),
                }
            }
        }
    }
}

/// A helper type for walking.
#[derive(Debug, Clone, Default)]
pub struct Walk {
    // It set to true, skip the children of this node.
    pub skip_children: bool,

    // The current depth of the walk.
    pub depth: usize,

    // If true, we are in a lookbehind (and so the cursor will move backwards).
    pub in_lookbehind: bool,
}

#[derive(Debug)]
struct Walker<'a, F>
where
    F: FnMut(&Node, &mut Walk),
{
    func: &'a mut F,
    postorder: bool,
    walk: Walk,
}

impl<'a, F> Walker<'a, F>
where
    F: FnMut(&Node, &mut Walk),
{
    fn process_children(&mut self, n: &Node) {
        match n {
            Node::Empty => {}
            Node::Goal => {}
            Node::Char { .. } => {}
            Node::ByteSequence(..) => {}
            Node::ByteSet(..) => {}
            Node::CharSet(..) => {}
            Node::Cat(nodes) => {
                for node in nodes {
                    self.process(node);
                }
            }
            Node::Alt(left, right) => {
                self.process(left.as_ref());
                self.process(right.as_ref());
            }
            Node::MatchAny => {}
            Node::MatchAnyExceptLineTerminator => {}
            Node::Anchor { .. } => {}
            Node::Loop { loopee, .. } => self.process(loopee),
            Node::Loop1CharBody { loopee, .. } => self.process(loopee),
            Node::CaptureGroup(contents, ..) => self.process(contents.as_ref()),
            Node::WordBoundary { .. } => {}
            Node::BackRef { .. } => {}
            Node::Bracket { .. } => {}
            Node::LookaroundAssertion {
                backwards,
                contents,
                ..
            } => {
                let saved = self.walk.in_lookbehind;
                self.walk.in_lookbehind = *backwards;
                self.process(contents.as_ref());
                self.walk.in_lookbehind = saved;
            }
        }
    }

    fn process(&mut self, n: &Node) {
        self.walk.skip_children = false;
        if !self.postorder {
            (self.func)(n, &mut self.walk);
        }
        if !self.walk.skip_children {
            self.walk.depth += 1;
            self.process_children(n);
            self.walk.depth -= 1;
        }
        if self.postorder {
            (self.func)(n, &mut self.walk)
        }
    }
}

#[derive(Debug)]
struct MutWalker<'a, F>
where
    F: FnMut(&mut Node, &mut Walk),
{
    func: &'a mut F,
    postorder: bool,
    walk: Walk,
}

impl<'a, F> MutWalker<'a, F>
where
    F: FnMut(&mut Node, &mut Walk),
{
    fn process_children(&mut self, n: &mut Node) {
        match n {
            Node::Empty => {}
            Node::Goal => {}
            Node::Char { .. } => {}
            Node::ByteSequence(..) => {}
            Node::ByteSet(..) => {}
            Node::CharSet(..) => {}
            Node::Cat(nodes) => {
                for node in nodes {
                    self.process(node);
                }
            }
            Node::Alt(left, right) => {
                self.process(left.as_mut());
                self.process(right.as_mut());
            }
            Node::MatchAny => {}
            Node::MatchAnyExceptLineTerminator => {}
            Node::Anchor { .. } => {}
            Node::Loop { loopee, .. } => {
                self.process(loopee);
            }
            Node::Loop1CharBody { loopee, .. } => {
                self.process(loopee);
            }
            Node::CaptureGroup(contents, ..) => self.process(contents.as_mut()),
            Node::WordBoundary { .. } => {}
            Node::BackRef { .. } => {}
            Node::Bracket { .. } => {}
            Node::LookaroundAssertion {
                backwards,
                contents,
                ..
            } => {
                let saved = self.walk.in_lookbehind;
                self.walk.in_lookbehind = *backwards;
                self.process(contents.as_mut());
                self.walk.in_lookbehind = saved;
            }
        }
    }

    fn process(&mut self, n: &mut Node) {
        self.walk.skip_children = false;
        if !self.postorder {
            (self.func)(n, &mut self.walk);
        }
        if !self.walk.skip_children {
            self.walk.depth += 1;
            self.process_children(n);
            self.walk.depth -= 1;
        }
        if self.postorder {
            (self.func)(n, &mut self.walk);
        }
    }
}

/// Call a function on every Node.
/// If \p postorder is true, then process children before the node;
/// otherwise process children after the node.
pub fn walk<F>(postorder: bool, n: &Node, func: &mut F)
where
    F: FnMut(&Node, &mut Walk),
{
    let mut walker = Walker {
        func,
        postorder,
        walk: Walk::default(),
    };
    walker.process(n);
}

/// Call a function on every Node, which may mutate the node.
/// If \p postorder is true, then process children before the node;
/// otherwise process children after the node.
/// If postorder is false, the function should return true to process children,
/// false to avoid descending into children. If postorder is true, the return
/// value is ignored.
pub fn walk_mut<F>(postorder: bool, n: &mut Node, func: &mut F)
where
    F: FnMut(&mut Node, &mut Walk),
{
    let mut walker = MutWalker {
        func,
        postorder,
        walk: Walk::default(),
    };
    walker.process(n);
}

/// A regex in IR form.
pub struct Regex {
    pub node: Node,
    pub flags: api::Flags,
}

impl Regex {}

fn display_node(node: &Node, depth: usize, f: &mut fmt::Formatter) -> fmt::Result {
    for _ in 0..depth {
        write!(f, "..")?;
    }
    match node {
        Node::Empty => {
            writeln!(f, "Empty")?;
        }
        Node::Goal => {
            writeln!(f, "Goal")?;
        }
        Node::Char { c, icase: _ } => {
            writeln!(f, "'{}'", &c.to_string())?;
        }
        Node::ByteSequence(bytes) => {
            write!(f, "ByteSeq{} 0x", bytes.len())?;
            for &b in bytes {
                write!(f, "{:x}", b)?;
            }
            writeln!(f)?;
        }
        Node::ByteSet(bytes) => {
            let len = bytes.len();
            write!(f, "ByteSet{}", len)?;
            if len > 0 {
                write!(f, "0x")?;
                for &b in bytes {
                    write!(f, "{:x}", b)?;
                }
            }
            writeln!(f)?;
        }
        Node::CharSet(chars) => {
            write!(f, "CharSet 0x")?;
            for &c in chars {
                write!(f, "{:x}", c as u32)?;
            }
            writeln!(f)?;
        }
        Node::Cat(..) => {
            writeln!(f, "Cat")?;
        }
        Node::Alt(..) => {
            writeln!(f, "Alt")?;
        }
        Node::MatchAny => {
            writeln!(f, "MatchAny")?;
        }
        Node::MatchAnyExceptLineTerminator => {
            writeln!(f, "MatchAnyExceptLineTerminator")?;
        }
        Node::Anchor(anchor_type) => {
            writeln!(f, "Anchor {:?}", anchor_type)?;
        }
        Node::Loop {
            quant,
            enclosed_groups,
            ..
        } => {
            writeln!(f, "Loop (groups {:?}) {:?}", enclosed_groups, quant)?;
        }
        Node::Loop1CharBody { quant, .. } => {
            writeln!(f, "Loop1Char {:?}", quant)?;
        }
        Node::CaptureGroup(_node, idx, ..) => {
            writeln!(f, "CaptureGroup {:?}", idx)?;
        }
        &Node::WordBoundary { invert } => {
            let kind = if invert { "\\B" } else { "\\b" };
            writeln!(f, "WordBoundary {:?} ", kind)?;
        }
        &Node::BackRef(group) => {
            writeln!(f, "BackRef {:?} ", group)?;
        }
        Node::Bracket(contents) => {
            writeln!(f, "Bracket {:?}", contents)?;
        }

        &Node::LookaroundAssertion {
            negate,
            backwards,
            start_group,
            end_group,
            ..
        } => {
            let sense = if negate { "negative" } else { "positive" };
            let direction = if backwards { "backwards" } else { "forwards" };
            writeln!(
                f,
                "LookaroundAssertion {} {} {:?} {:?}",
                sense, direction, start_group, end_group
            )?;
        }
    }
    Ok(())
}

impl fmt::Display for Regex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        //display_node(&self.node, 0, f)
        let mut result = Ok(());
        walk(false, &self.node, &mut |node: &Node, walk: &mut Walk| {
            if result.is_ok() {
                result = display_node(node, walk.depth, f)
            }
        });
        result
    }
}