sim-lib-pattern 0.2.0

Shape-based pattern matching and destructuring for SIM runtime values.
Documentation
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
//! Stable tagged-Thompson compilation for validated pattern IR.

use crate::{Anchor, AssertionId, CaptureId, IrNode, PatternIr, SymbolDomain, TextClass};
use core::fmt;
use std::collections::BTreeMap;

/// Stable identifier of an automaton state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StateId(pub u32);

/// The action performed by one automaton state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Instruction<S, E> {
    /// Accept the pattern.
    Accept,
    /// Continue without consuming input.
    Epsilon {
        /// Successor state.
        next: StateId,
    },
    /// Consume one exact symbol.
    Symbol {
        /// Required symbol.
        symbol: S,
        /// Successor after consumption.
        next: StateId,
    },
    /// Consume any one symbol.
    Any {
        /// Successor after consumption.
        next: StateId,
    },
    /// Delegate symbol recognition to an admitted extension.
    Extension {
        /// Admitted extension matcher.
        extension: E,
        /// Successor after consumption.
        next: StateId,
    },
    /// Choose either successor without consuming input.
    Split {
        /// Ordered branch entry states.
        alternatives: Vec<StateId>,
    },
    /// Record a capture boundary without consuming input.
    Tag {
        /// Stable capture identifier.
        capture: CaptureId,
        /// Boundary being recorded.
        boundary: TagBoundary,
        /// Successor state.
        next: StateId,
    },
    /// Test a subject boundary without consuming input.
    Anchor {
        /// Boundary predicate.
        anchor: Anchor,
        /// Successor when the predicate holds.
        next: StateId,
    },
    /// Invoke a separately compiled zero-width assertion.
    Assertion {
        /// Stable assertion identifier.
        assertion: AssertionId,
        /// Successor when the assertion holds.
        next: StateId,
    },
    /// Enter a bounded or unbounded repetition loop.
    Repeat {
        /// Repeated body entry.
        body: StateId,
        /// Loop exit.
        exit: StateId,
        /// Required iteration count.
        min: usize,
        /// Maximum iteration count, or no bound.
        max: Option<usize>,
        /// Whether the body precedes the exit in execution priority.
        greedy: bool,
    },
}

/// A capture-tag boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TagBoundary {
    /// Opening boundary.
    Start,
    /// Closing boundary.
    End,
}

/// One stable state in a compiled automaton.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct State<S, E> {
    /// Stable, dense identifier equal to this state's position.
    pub id: StateId,
    /// State behavior and outgoing edges.
    pub instruction: Instruction<S, E>,
}

/// Browsable facts about a compilation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CompilationEvidence {
    /// Total number of graph states.
    pub state_count: usize,
    /// Number of capture tags in the graph.
    pub capture_count: usize,
    /// Conservative work per subject position for an NFA state-set executor.
    pub estimated_work_per_symbol: usize,
}

/// A compiled, explicitly branching tagged automaton.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Automaton<S, E> {
    start: StateId,
    states: Vec<State<S, E>>,
    evidence: CompilationEvidence,
    assertions: BTreeMap<AssertionId, AssertionProgram<S, E>>,
}

/// A separately compiled lookahead whose width is known before execution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssertionProgram<S, E> {
    automaton: Box<Automaton<S, E>>,
    width: usize,
}

impl<S, E> AssertionProgram<S, E> {
    /// Compiled regular program used by the zero-width assertion.
    pub fn automaton(&self) -> &Automaton<S, E> {
        &self.automaton
    }

    /// Exact number of subject symbols inspected by the assertion.
    pub const fn width(&self) -> usize {
        self.width
    }
}

impl<S, E> Automaton<S, E> {
    /// Entry state.
    pub const fn start(&self) -> StateId {
        self.start
    }
    /// Dense state table.
    pub fn states(&self) -> &[State<S, E>] {
        &self.states
    }
    /// Compilation size and work estimate.
    pub const fn evidence(&self) -> CompilationEvidence {
        self.evidence
    }

    /// Returns a compiled fixed-width assertion when its definition is regular.
    pub fn assertion(&self, id: AssertionId) -> Option<&AssertionProgram<S, E>> {
        self.assertions.get(&id)
    }
}

/// Compile validated IR into a stable tagged Thompson graph.
pub fn compile<D, E>(ir: &PatternIr<D, E>) -> Automaton<D::Symbol, E>
where
    D: SymbolDomain,
    D::Symbol: Clone,
    E: Clone + fmt::Debug + Ord,
{
    let mut builder = Builder { states: Vec::new() };
    let accept = builder.push(Instruction::Accept);
    let start = builder.node(ir.root(), accept);
    let capture_count = builder
        .states
        .iter()
        .filter(|state| {
            matches!(
                state.instruction,
                Instruction::Tag {
                    boundary: TagBoundary::Start,
                    ..
                }
            )
        })
        .count();
    let state_count = builder.states.len();
    let assertions: BTreeMap<AssertionId, AssertionProgram<D::Symbol, E>> = ir
        .assertions()
        .iter()
        .filter_map(|(id, node)| {
            fixed_width(node).map(|width| {
                (
                    *id,
                    AssertionProgram {
                        automaton: Box::new(compile_node(node)),
                        width,
                    },
                )
            })
        })
        .collect();
    let assertion_state_count = assertions
        .values()
        .map(|program| program.automaton.evidence.state_count)
        .sum::<usize>();
    Automaton {
        start,
        states: builder.states,
        evidence: CompilationEvidence {
            state_count: state_count + assertion_state_count,
            capture_count,
            estimated_work_per_symbol: state_count + assertion_state_count,
        },
        assertions,
    }
}

fn compile_node<S: Clone, E: Clone>(node: &IrNode<S, E>) -> Automaton<S, E> {
    let mut builder = Builder { states: Vec::new() };
    let accept = builder.push(Instruction::Accept);
    let start = builder.node(node, accept);
    let state_count = builder.states.len();
    Automaton {
        start,
        states: builder.states,
        evidence: CompilationEvidence {
            state_count,
            capture_count: 0,
            estimated_work_per_symbol: state_count,
        },
        assertions: BTreeMap::new(),
    }
}

fn fixed_width<S, E>(node: &IrNode<S, E>) -> Option<usize> {
    match node {
        IrNode::Symbol(_) | IrNode::Any | IrNode::Extension(_) => Some(1),
        IrNode::Anchor(_) => Some(0),
        // Nested assertion composition needs its referenced definition to prove
        // width. Keep it in the typed extension lane until compilation carries
        // that dependency closure explicitly.
        IrNode::Assertion(_) => None,
        IrNode::Concat(nodes) => nodes
            .iter()
            .try_fold(0usize, |sum, node| sum.checked_add(fixed_width(node)?)),
        IrNode::Alternation(nodes) => {
            let mut widths = nodes.iter().map(fixed_width);
            let first = widths.next()??;
            widths.all(|width| width == Some(first)).then_some(first)
        }
        IrNode::Repeat { node, bounds, .. } if bounds.max() == Some(bounds.min()) => {
            fixed_width(node)?.checked_mul(bounds.min())
        }
        IrNode::Group(node) | IrNode::Capture { node, .. } => fixed_width(node),
        IrNode::Repeat { .. } => None,
    }
}

struct Builder<S, E> {
    states: Vec<State<S, E>>,
}

impl<S: Clone, E: Clone> Builder<S, E> {
    fn push(&mut self, instruction: Instruction<S, E>) -> StateId {
        let id =
            StateId(u32::try_from(self.states.len()).expect("pattern state count exceeds u32"));
        self.states.push(State { id, instruction });
        id
    }

    fn node(&mut self, node: &IrNode<S, E>, next: StateId) -> StateId {
        match node {
            IrNode::Symbol(symbol) => self.push(Instruction::Symbol {
                symbol: symbol.clone(),
                next,
            }),
            IrNode::Any => self.push(Instruction::Any { next }),
            IrNode::Concat(nodes) => nodes
                .iter()
                .rev()
                .fold(next, |tail, node| self.node(node, tail)),
            IrNode::Alternation(nodes) => {
                let alternatives = nodes.iter().map(|node| self.node(node, next)).collect();
                self.push(Instruction::Split { alternatives })
            }
            IrNode::Repeat {
                node,
                bounds,
                greedy,
            } => {
                let repeat = self.push(Instruction::Epsilon { next });
                let body = self.node(node, repeat);
                self.states[repeat.0 as usize].instruction = Instruction::Repeat {
                    body,
                    exit: next,
                    min: bounds.min(),
                    max: bounds.max(),
                    greedy: *greedy,
                };
                repeat
            }
            IrNode::Group(node) => self.node(node, next),
            IrNode::Capture { id, node } => {
                let end = self.push(Instruction::Tag {
                    capture: *id,
                    boundary: TagBoundary::End,
                    next,
                });
                let body = self.node(node, end);
                self.push(Instruction::Tag {
                    capture: *id,
                    boundary: TagBoundary::Start,
                    next: body,
                })
            }
            IrNode::Anchor(anchor) => self.push(Instruction::Anchor {
                anchor: *anchor,
                next,
            }),
            IrNode::Assertion(assertion) => self.push(Instruction::Assertion {
                assertion: *assertion,
                next,
            }),
            IrNode::Extension(extension) => self.push(Instruction::Extension {
                extension: extension.clone(),
                next,
            }),
        }
    }
}

impl Instruction<char, TextClass> {
    /// Tests whether this instruction consumes `symbol`, reusing `TextClass` membership.
    pub fn matches(&self, symbol: char) -> bool {
        match self {
            Self::Symbol {
                symbol: expected, ..
            } => *expected == symbol,
            Self::Any { .. } => true,
            Self::Extension { extension, .. } => extension.matches(symbol),
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ByteDomain, EnginePolicy, RepeatBounds, ScalarDomain};
    use std::collections::BTreeMap;

    fn byte_ir(root: IrNode<u8, &'static str>) -> PatternIr<ByteDomain, &'static str> {
        PatternIr::new(root, BTreeMap::new(), &EnginePolicy::new([])).unwrap()
    }

    #[test]
    fn state_growth_is_linear_across_regular_constructs() {
        let patterns = [
            IrNode::Symbol(b'a'),
            IrNode::Concat(vec![
                IrNode::Symbol(b'a'),
                IrNode::Any,
                IrNode::Anchor(Anchor::SubjectEnd),
            ]),
            IrNode::Alternation(vec![IrNode::Symbol(b'a'), IrNode::Symbol(b'b')]),
            IrNode::Alternation(vec![
                IrNode::Alternation(vec![IrNode::Symbol(b'a'), IrNode::Symbol(b'b')]),
                IrNode::Alternation(vec![IrNode::Symbol(b'c'), IrNode::Symbol(b'd')]),
            ]),
            IrNode::Repeat {
                node: Box::new(IrNode::Group(Box::new(IrNode::Symbol(b'x')))),
                bounds: RepeatBounds::new(3, None).unwrap(),
                greedy: true,
            },
        ];
        for root in patterns {
            let automaton = compile(&byte_ir(root.clone()));
            assert!(automaton.evidence().state_count <= 2 * node_count(&root) + 1);
            assert_eq!(
                automaton.evidence().estimated_work_per_symbol,
                automaton.states().len()
            );
        }
    }

    #[test]
    fn capture_and_state_ids_survive_recompilation() {
        let ir = byte_ir(IrNode::Capture {
            id: CaptureId(41),
            node: Box::new(IrNode::Alternation(vec![
                IrNode::Symbol(b'a'),
                IrNode::Symbol(b'b'),
            ])),
        });
        let first = compile(&ir);
        assert_eq!(first, compile(&ir));
        assert!(first.states().iter().any(|state| matches!(
            state.instruction,
            Instruction::Tag {
                capture: CaptureId(41),
                boundary: TagBoundary::Start,
                ..
            }
        )));
        assert!(
            first
                .states()
                .iter()
                .enumerate()
                .all(|(index, state)| state.id.0 as usize == index)
        );
    }

    #[test]
    fn text_classes_reuse_shared_membership() {
        let ir = PatternIr::<ScalarDomain, TextClass>::new(
            IrNode::Extension(TextClass::Digit),
            BTreeMap::new(),
            &EnginePolicy::new([TextClass::Digit]),
        )
        .unwrap();
        let automaton = compile(&ir);
        let instruction = &automaton.states()[automaton.start().0 as usize].instruction;
        assert!(instruction.matches('7'));
        assert!(!instruction.matches('x'));
    }

    fn node_count<S, E>(node: &IrNode<S, E>) -> usize {
        1 + match node {
            IrNode::Concat(nodes) | IrNode::Alternation(nodes) => {
                nodes.iter().map(node_count).sum()
            }
            IrNode::Repeat { node, .. } | IrNode::Group(node) | IrNode::Capture { node, .. } => {
                node_count(node)
            }
            _ => 0,
        }
    }
}