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
//! Lua text-pattern compiler for the shared VM.

use sim_kernel::{Error, Result};

use crate::{
    Anchor, CaptureId, EnginePolicy, IrNode, PatternDialect, PatternIr, RepeatBounds, ScalarDomain,
    TextClass, TextOp,
};
use std::collections::BTreeMap;

/// Lua-only operations admitted by the shared text automaton.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum LuaExtension {
    /// Match one character from a Lua character class.
    Class(TextClass),
    /// Match a delimiter pair, including nested pairs.
    Balanced {
        /// Opening delimiter.
        open: char,
        /// Closing delimiter.
        close: char,
    },
    /// Assert a transition from outside to inside a Lua character class.
    Frontier(TextClass),
}

/// Compiler for Lua-style text patterns.
#[derive(Clone, Copy, Debug, Default)]
pub struct LuaPatternDialect;

impl PatternDialect for LuaPatternDialect {
    fn compile(&self, pattern: &str) -> Result<Vec<TextOp>> {
        let ir = self.compile_ir(pattern)?;
        Ok(project_compatibility_program(ir.root()))
    }
}

impl LuaPatternDialect {
    /// Lowers Lua syntax directly into validated shared pattern IR.
    pub fn compile_ir(self, pattern: &str) -> Result<PatternIr<ScalarDomain, LuaExtension>> {
        LuaCompiler::new(pattern).compile()
    }
}

/// Compiles a Lua-style text pattern into shared VM operations.
///
/// # Errors
///
/// Returns an error when the pattern is malformed.
pub fn compile_lua_pattern(pattern: &str) -> Result<Vec<TextOp>> {
    LuaPatternDialect.compile(pattern)
}

struct LuaCompiler {
    chars: Vec<char>,
    index: usize,
}

impl LuaCompiler {
    fn new(pattern: &str) -> Self {
        Self {
            chars: pattern.chars().collect(),
            index: 0,
        }
    }

    fn compile(mut self) -> Result<PatternIr<ScalarDomain, LuaExtension>> {
        let mut frames = vec![Vec::new()];
        let mut next_capture = 0u32;
        while let Some(ch) = self.next() {
            match ch {
                '^' if frames.len() == 1 && frames[0].is_empty() => {
                    frames[0].push(IrNode::Anchor(Anchor::SubjectStart));
                }
                '^' => self.push_atom(&mut frames, IrNode::Symbol('^'))?,
                '$' if self.is_end() => frames
                    .last_mut()
                    .expect("root frame exists")
                    .push(IrNode::Anchor(Anchor::SubjectEnd)),
                '$' => self.push_atom(&mut frames, IrNode::Symbol('$'))?,
                '.' => self.push_atom(&mut frames, IrNode::Any)?,
                '(' => frames.push(Vec::new()),
                ')' => {
                    if frames.len() == 1 {
                        return Err(malformed("capture close without open"));
                    }
                    let body = IrNode::Concat(frames.pop().expect("capture frame exists"));
                    frames
                        .last_mut()
                        .expect("parent frame exists")
                        .push(IrNode::Capture {
                            id: CaptureId(next_capture),
                            node: Box::new(body),
                        });
                    next_capture += 1;
                }
                '[' => {
                    let set = self.parse_set()?;
                    self.push_atom(&mut frames, IrNode::Extension(LuaExtension::Class(set)))?;
                }
                '%' => {
                    let escaped = self.parse_percent()?;
                    match escaped {
                        Escaped::Atom(node) => self.push_atom(&mut frames, node)?,
                        Escaped::ZeroWidth(node) => {
                            frames.last_mut().expect("root frame exists").push(node)
                        }
                    }
                }
                '*' | '+' | '-' | '?' => return Err(malformed("quantifier without atom")),
                literal => self.push_atom(&mut frames, IrNode::Symbol(literal))?,
            }
        }
        if frames.len() != 1 {
            return Err(malformed("unterminated capture"));
        }
        let root = IrNode::Concat(frames.pop().expect("root frame exists"));
        let extensions = collect_extensions(&root);
        PatternIr::new(root, BTreeMap::new(), &EnginePolicy::new(extensions))
            .map_err(|error| malformed(&error.to_string()))
    }

    fn push_atom(
        &mut self,
        frames: &mut [Vec<IrNode<char, LuaExtension>>],
        mut node: IrNode<char, LuaExtension>,
    ) -> Result<()> {
        if let Some((min, max, greedy)) = self.peek().and_then(lua_quantifier) {
            self.index += 1;
            node = IrNode::Repeat {
                node: Box::new(node),
                bounds: RepeatBounds::new(min, max)
                    .expect("Lua quantifiers have valid static bounds"),
                greedy,
            };
        }
        frames.last_mut().expect("root frame exists").push(node);
        Ok(())
    }

    fn parse_percent(&mut self) -> Result<Escaped> {
        let Some(ch) = self.next() else {
            return Err(malformed("dangling percent escape"));
        };
        Ok(match ch {
            'a' => class_atom(TextClass::Alpha),
            'A' => class_atom(TextClass::Not(Box::new(TextClass::Alpha))),
            'd' => class_atom(TextClass::Digit),
            'D' => class_atom(TextClass::Not(Box::new(TextClass::Digit))),
            'l' => class_atom(TextClass::Lower),
            'L' => class_atom(TextClass::Not(Box::new(TextClass::Lower))),
            'u' => class_atom(TextClass::Upper),
            'U' => class_atom(TextClass::Not(Box::new(TextClass::Upper))),
            'w' => class_atom(TextClass::Alnum),
            'W' => class_atom(TextClass::Not(Box::new(TextClass::Alnum))),
            's' => class_atom(TextClass::Space),
            'S' => class_atom(TextClass::Not(Box::new(TextClass::Space))),
            'p' => class_atom(TextClass::Punct),
            'P' => class_atom(TextClass::Not(Box::new(TextClass::Punct))),
            'x' => class_atom(TextClass::Hex),
            'X' => class_atom(TextClass::Not(Box::new(TextClass::Hex))),
            'z' => class_atom(TextClass::Zero),
            'b' => {
                let open = self
                    .next()
                    .ok_or_else(|| malformed("balanced pattern missing open delimiter"))?;
                let close = self
                    .next()
                    .ok_or_else(|| malformed("balanced pattern missing close delimiter"))?;
                Escaped::Atom(IrNode::Extension(LuaExtension::Balanced { open, close }))
            }
            'f' => {
                if self.next() != Some('[') {
                    return Err(malformed("frontier pattern requires a character set"));
                }
                Escaped::ZeroWidth(IrNode::Extension(LuaExtension::Frontier(self.parse_set()?)))
            }
            literal => Escaped::Atom(IrNode::Symbol(literal)),
        })
    }

    fn parse_set(&mut self) -> Result<TextClass> {
        let mut negated = false;
        if self.peek() == Some('^') {
            self.index += 1;
            negated = true;
        }
        parse_set_body(
            &self.chars,
            &mut self.index,
            negated,
            "unterminated character set",
        )
    }

    fn next(&mut self) -> Option<char> {
        let ch = self.chars.get(self.index).copied()?;
        self.index += 1;
        Some(ch)
    }

    fn peek(&self) -> Option<char> {
        self.chars.get(self.index).copied()
    }

    fn is_end(&self) -> bool {
        self.index >= self.chars.len()
    }
}

enum Escaped {
    Atom(IrNode<char, LuaExtension>),
    ZeroWidth(IrNode<char, LuaExtension>),
}

fn class_atom(class: TextClass) -> Escaped {
    Escaped::Atom(IrNode::Extension(LuaExtension::Class(class)))
}

pub(crate) fn parse_set_body(
    chars: &[char],
    index: &mut usize,
    negated: bool,
    unterminated: &str,
) -> Result<TextClass> {
    let mut literals = Vec::new();
    let mut ranges = Vec::new();
    let mut classes = Vec::new();
    let mut first = true;
    while let Some(ch) = chars.get(*index).copied() {
        *index += 1;
        if ch == ']' && !first {
            return Ok(TextClass::Set {
                chars: literals,
                ranges,
                classes,
                negated,
            });
        }
        first = false;
        let item = if ch == '%' {
            let escaped = chars
                .get(*index)
                .copied()
                .ok_or_else(|| malformed("dangling set escape"))?;
            *index += 1;
            set_escape(escaped)
        } else {
            SetItem::Literal(ch)
        };
        if let SetItem::Literal(start) = item {
            if chars.get(*index).copied() == Some('-')
                && chars.get(*index + 1).is_some_and(|end| *end != ']')
            {
                *index += 1;
                let end = chars
                    .get(*index)
                    .copied()
                    .ok_or_else(|| malformed(unterminated))?;
                *index += 1;
                ranges.push((start, end));
            } else {
                literals.push(start);
            }
        } else if let SetItem::Class(class) = item {
            classes.push(class);
        }
    }
    Err(malformed(unterminated))
}

enum SetItem {
    Literal(char),
    Class(TextClass),
}

fn set_escape(ch: char) -> SetItem {
    match ch {
        'a' => SetItem::Class(TextClass::Alpha),
        'd' => SetItem::Class(TextClass::Digit),
        'l' => SetItem::Class(TextClass::Lower),
        'u' => SetItem::Class(TextClass::Upper),
        'w' => SetItem::Class(TextClass::Alnum),
        's' => SetItem::Class(TextClass::Space),
        'p' => SetItem::Class(TextClass::Punct),
        'x' => SetItem::Class(TextClass::Hex),
        'z' => SetItem::Class(TextClass::Zero),
        literal => SetItem::Literal(literal),
    }
}

fn lua_quantifier(ch: char) -> Option<(usize, Option<usize>, bool)> {
    match ch {
        '*' => Some((0, None, true)),
        '+' => Some((1, None, true)),
        '-' => Some((0, None, false)),
        '?' => Some((0, Some(1), true)),
        _ => None,
    }
}

fn collect_extensions(node: &IrNode<char, LuaExtension>) -> Vec<LuaExtension> {
    let mut extensions = Vec::new();
    visit(node, &mut |extension| extensions.push(extension.clone()));
    extensions
}

fn project_compatibility_program(node: &IrNode<char, LuaExtension>) -> Vec<TextOp> {
    let mut ops = Vec::new();
    project(node, &mut ops);
    ops
}

fn project(node: &IrNode<char, LuaExtension>, ops: &mut Vec<TextOp>) {
    match node {
        IrNode::Symbol(ch) => ops.push(TextOp::Literal(*ch)),
        IrNode::Any => ops.push(TextOp::Any),
        IrNode::Concat(nodes) | IrNode::Alternation(nodes) => {
            for node in nodes {
                project(node, ops);
            }
        }
        IrNode::Repeat {
            node,
            bounds,
            greedy,
        } => {
            project(node, ops);
            ops.push(TextOp::Repeat {
                min: bounds.min(),
                max: bounds.max(),
                greedy: *greedy,
            });
        }
        IrNode::Group(node) => project(node, ops),
        IrNode::Capture { node, .. } => {
            ops.push(TextOp::CaptureStart);
            project(node, ops);
            ops.push(TextOp::CaptureEnd);
        }
        IrNode::Anchor(Anchor::SubjectStart) => ops.push(TextOp::AnchorStart),
        IrNode::Anchor(Anchor::SubjectEnd) => ops.push(TextOp::AnchorEnd),
        IrNode::Extension(LuaExtension::Class(class)) => ops.push(TextOp::Class(class.clone())),
        IrNode::Extension(LuaExtension::Balanced { open, close }) => {
            ops.push(TextOp::Balanced {
                open: *open,
                close: *close,
            });
        }
        IrNode::Extension(LuaExtension::Frontier(class)) => {
            ops.push(TextOp::Frontier(class.clone()));
        }
        IrNode::Assertion(_) => unreachable!("Lua lowering does not create assertions"),
    }
}

fn visit(node: &IrNode<char, LuaExtension>, f: &mut impl FnMut(&LuaExtension)) {
    match node {
        IrNode::Concat(nodes) | IrNode::Alternation(nodes) => {
            for node in nodes {
                visit(node, f);
            }
        }
        IrNode::Repeat { node, .. } | IrNode::Group(node) | IrNode::Capture { node, .. } => {
            visit(node, f);
        }
        IrNode::Extension(extension) => f(extension),
        IrNode::Symbol(_) | IrNode::Any | IrNode::Anchor(_) | IrNode::Assertion(_) => {}
    }
}

fn malformed(message: &str) -> Error {
    Error::Eval(format!("malformed Lua pattern: {message}"))
}

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

    #[test]
    fn balanced_match_is_one_named_adapter_node() {
        let ir = LuaPatternDialect.compile_ir("%b()").unwrap();
        let mut extensions = Vec::new();
        visit(ir.root(), &mut |extension| {
            extensions.push(extension.clone())
        });
        assert_eq!(
            extensions,
            vec![LuaExtension::Balanced {
                open: '(',
                close: ')'
            }]
        );
    }

    #[test]
    fn capture_ids_and_compatibility_boundaries_are_frozen() {
        let ir = LuaPatternDialect.compile_ir("(%a+)%s+(%d+)").unwrap();
        let mut ids = Vec::new();
        fn collect(node: &IrNode<char, LuaExtension>, ids: &mut Vec<CaptureId>) {
            match node {
                IrNode::Concat(nodes) | IrNode::Alternation(nodes) => {
                    for node in nodes {
                        collect(node, ids);
                    }
                }
                IrNode::Repeat { node, .. } | IrNode::Group(node) => collect(node, ids),
                IrNode::Capture { id, node } => {
                    ids.push(*id);
                    collect(node, ids);
                }
                IrNode::Symbol(_)
                | IrNode::Any
                | IrNode::Anchor(_)
                | IrNode::Assertion(_)
                | IrNode::Extension(_) => {}
            }
        }
        collect(ir.root(), &mut ids);
        assert_eq!(ids, vec![CaptureId(0), CaptureId(1)]);
        assert_eq!(
            project_compatibility_program(ir.root())
                .iter()
                .filter(|op| matches!(op, TextOp::CaptureStart | TextOp::CaptureEnd))
                .count(),
            4
        );
    }
}