triblespace-paths 0.47.0

Exact regular-path indexes for TribleSpace.
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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use std::cmp::Ordering;
use std::collections::BTreeSet;

use crate::{Automaton, StateId, Step, Transition};

/// A canonical regular expression over graph-property [`Step`]s.
///
/// Construction normalizes exclusion lists, flattens associative sequences,
/// and flattens, sorts, and deduplicates alternatives. This is structural
/// canonicalization, not full language minimization: distributively equivalent
/// expressions may still compile to different (but language-equivalent)
/// automata. The durable alternative order is atom, sequence, alternative,
/// star, plus, optional; atom kinds are forward, reverse, forward-except,
/// reverse-except, with payloads ordered lexicographically.
///
/// ```
/// use triblespace_paths::{PathExpr, Step};
///
/// let parent = [1; 16];
/// let sibling = [2; 16];
/// let expression = PathExpr::from(Step::Forward(parent))
///     .plus()
///     .or(PathExpr::from(Step::Forward(sibling)).inverse());
/// let automaton = expression.compile();
///
/// assert_eq!(automaton.initial_states().collect::<Vec<_>>(), vec![0]);
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PathExpr {
    node: Node,
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Node {
    Atom(Step),
    Sequence(Vec<PathExpr>),
    Alternative(Vec<PathExpr>),
    Star(Box<PathExpr>),
    Plus(Box<PathExpr>),
    Optional(Box<PathExpr>),
}

// This order is part of PathExpr's canonical form. Keep the explicit tags
// stable: changing source enum order must not perturb alternative order or the
// automaton fingerprint produced by `compile`.
const TAG_ATOM: u8 = 0;
const TAG_SEQUENCE: u8 = 1;
const TAG_ALTERNATIVE: u8 = 2;
const TAG_STAR: u8 = 3;
const TAG_PLUS: u8 = 4;
const TAG_OPTIONAL: u8 = 5;

fn node_tag(node: &Node) -> u8 {
    match node {
        Node::Atom(_) => TAG_ATOM,
        Node::Sequence(_) => TAG_SEQUENCE,
        Node::Alternative(_) => TAG_ALTERNATIVE,
        Node::Star(_) => TAG_STAR,
        Node::Plus(_) => TAG_PLUS,
        Node::Optional(_) => TAG_OPTIONAL,
    }
}

fn step_tag(step: &Step) -> u8 {
    match step {
        Step::Forward(_) => 0,
        Step::Reverse(_) => 1,
        Step::ForwardExcept(_) => 2,
        Step::ReverseExcept(_) => 3,
    }
}

fn cmp_steps(left: &Step, right: &Step) -> Ordering {
    step_tag(left)
        .cmp(&step_tag(right))
        .then_with(|| match (left, right) {
            (Step::Forward(left), Step::Forward(right))
            | (Step::Reverse(left), Step::Reverse(right)) => left.cmp(right),
            (Step::ForwardExcept(left), Step::ForwardExcept(right))
            | (Step::ReverseExcept(left), Step::ReverseExcept(right)) => left.cmp(right),
            _ => Ordering::Equal,
        })
}

impl Ord for PathExpr {
    fn cmp(&self, other: &Self) -> Ordering {
        node_tag(&self.node)
            .cmp(&node_tag(&other.node))
            .then_with(|| match (&self.node, &other.node) {
                (Node::Atom(left), Node::Atom(right)) => cmp_steps(left, right),
                (Node::Sequence(left), Node::Sequence(right))
                | (Node::Alternative(left), Node::Alternative(right)) => left.cmp(right),
                (Node::Star(left), Node::Star(right))
                | (Node::Plus(left), Node::Plus(right))
                | (Node::Optional(left), Node::Optional(right)) => left.cmp(right),
                _ => Ordering::Equal,
            })
    }
}

impl PartialOrd for PathExpr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl From<Step> for PathExpr {
    fn from(step: Step) -> Self {
        Self {
            node: Node::Atom(canonical_step(step)),
        }
    }
}

impl PathExpr {
    /// Concatenates this expression with `next`.
    ///
    /// Nested sequences are flattened without reordering their operands.
    #[must_use]
    pub fn then(self, next: impl Into<Self>) -> Self {
        Self::sequence([self, next.into()])
    }

    /// Forms the set union of this expression and `alternative`.
    ///
    /// Nested alternatives are flattened, sorted by an explicit stable node
    /// order, and deduplicated.
    #[must_use]
    pub fn or(self, alternative: impl Into<Self>) -> Self {
        Self::alternative([self, alternative.into()])
    }

    /// Matches zero or more repetitions of this expression.
    #[must_use]
    pub fn star(self) -> Self {
        Self {
            node: Node::Star(Box::new(self)),
        }
    }

    /// Matches one or more repetitions of this expression.
    #[must_use]
    pub fn plus(self) -> Self {
        Self {
            node: Node::Plus(Box::new(self)),
        }
    }

    /// Matches this expression zero or one time.
    #[must_use]
    pub fn optional(self) -> Self {
        Self {
            node: Node::Optional(Box::new(self)),
        }
    }

    /// Reverses path direction.
    ///
    /// Inversion flips every atomic step, reverses sequence order, distributes
    /// through alternatives, and preserves repetition operators.
    #[must_use]
    pub fn inverse(self) -> Self {
        match self.node {
            Node::Atom(step) => canonical_step(inverse_step(step)).into(),
            Node::Sequence(parts) => Self::sequence(parts.into_iter().rev().map(Self::inverse)),
            Node::Alternative(arms) => Self::alternative(arms.into_iter().map(Self::inverse)),
            Node::Star(body) => body.inverse().star(),
            Node::Plus(body) => body.inverse().plus(),
            Node::Optional(body) => body.inverse().optional(),
        }
    }

    /// Whether this expression accepts the empty path.
    pub fn is_nullable(&self) -> bool {
        match &self.node {
            Node::Atom(_) => false,
            Node::Sequence(parts) => parts.iter().all(Self::is_nullable),
            Node::Alternative(arms) => arms.iter().any(Self::is_nullable),
            Node::Star(_) | Node::Optional(_) => true,
            Node::Plus(body) => body.is_nullable(),
        }
    }

    /// Compiles to a fixed epsilon-free position automaton.
    ///
    /// Atomic occurrences are numbered deterministically in canonical-tree
    /// order. State zero is the sole initial state; every other state denotes
    /// the most recently consumed atomic occurrence. The construction is
    /// output-sensitive in the expression and generated `follow` relation;
    /// ordered-set maintenance may add logarithmic factors. It introduces no
    /// epsilon transitions or determinization step.
    ///
    /// # Panics
    ///
    /// Panics if the expression contains `u32::MAX` atomic occurrences. Such
    /// an expression cannot be represented by [`StateId`].
    pub fn compile(&self) -> Automaton {
        let mut compiler = PositionCompiler::default();
        let fragment = compiler.analyze(self);
        let position_count = compiler.steps.len();
        let state_count = position_count
            .checked_add(1)
            .and_then(|count| StateId::try_from(count).ok())
            .expect("path expression exceeds the u32 automaton state space");

        let mut transitions = Vec::new();
        for position in &fragment.first {
            transitions.push(Transition::new(
                0,
                *position,
                compiler.step(*position).clone(),
            ));
        }
        for (from, targets) in compiler.follow.iter().enumerate() {
            let from = StateId::try_from(from + 1).expect("position checked above");
            for to in targets {
                transitions.push(Transition::new(from, *to, compiler.step(*to).clone()));
            }
        }

        let mut accepting = fragment.last;
        if fragment.nullable {
            accepting.insert(0);
        }
        Automaton::new(state_count, [0], accepting, transitions)
            .expect("the position construction emits a valid fixed automaton")
    }

    fn sequence(parts: impl IntoIterator<Item = Self>) -> Self {
        let mut flattened = Vec::new();
        for part in parts {
            match part.node {
                Node::Sequence(nested) => flattened.extend(nested),
                node => flattened.push(Self { node }),
            }
        }
        debug_assert!(!flattened.is_empty());
        if flattened.len() == 1 {
            flattened.pop().expect("checked length")
        } else {
            Self {
                node: Node::Sequence(flattened),
            }
        }
    }

    fn alternative(arms: impl IntoIterator<Item = Self>) -> Self {
        let mut flattened = Vec::new();
        for arm in arms {
            match arm.node {
                Node::Alternative(nested) => flattened.extend(nested),
                node => flattened.push(Self { node }),
            }
        }
        flattened.sort_unstable();
        flattened.dedup();
        debug_assert!(!flattened.is_empty());
        if flattened.len() == 1 {
            flattened.pop().expect("checked length")
        } else {
            Self {
                node: Node::Alternative(flattened),
            }
        }
    }
}

fn canonical_step(step: Step) -> Step {
    match step {
        Step::ForwardExcept(mut excluded) => {
            excluded.sort_unstable();
            excluded.dedup();
            Step::ForwardExcept(excluded)
        }
        Step::ReverseExcept(mut excluded) => {
            excluded.sort_unstable();
            excluded.dedup();
            Step::ReverseExcept(excluded)
        }
        step @ (Step::Forward(_) | Step::Reverse(_)) => step,
    }
}

fn inverse_step(step: Step) -> Step {
    match step {
        Step::Forward(attribute) => Step::Reverse(attribute),
        Step::Reverse(attribute) => Step::Forward(attribute),
        Step::ForwardExcept(excluded) => Step::ReverseExcept(excluded),
        Step::ReverseExcept(excluded) => Step::ForwardExcept(excluded),
    }
}

#[derive(Default)]
struct PositionCompiler {
    steps: Vec<Step>,
    follow: Vec<BTreeSet<StateId>>,
}

struct Fragment {
    nullable: bool,
    first: BTreeSet<StateId>,
    last: BTreeSet<StateId>,
}

impl PositionCompiler {
    fn analyze(&mut self, expression: &PathExpr) -> Fragment {
        match &expression.node {
            Node::Atom(step) => {
                let position = StateId::try_from(self.steps.len() + 1)
                    .expect("path expression exceeds the u32 automaton state space");
                self.steps.push(step.clone());
                self.follow.push(BTreeSet::new());
                Fragment {
                    nullable: false,
                    first: BTreeSet::from([position]),
                    last: BTreeSet::from([position]),
                }
            }
            Node::Sequence(parts) => {
                let mut parts = parts.iter();
                let mut result =
                    self.analyze(parts.next().expect("canonical sequence is nonempty"));
                for part in parts {
                    let right = self.analyze(part);
                    self.link(&result.last, &right.first);

                    let mut first = result.first;
                    if result.nullable {
                        first.extend(right.first.iter().copied());
                    }
                    let mut last = right.last;
                    if right.nullable {
                        last.extend(result.last.iter().copied());
                    }
                    result = Fragment {
                        nullable: result.nullable && right.nullable,
                        first,
                        last,
                    };
                }
                result
            }
            Node::Alternative(arms) => {
                let mut nullable = false;
                let mut first = BTreeSet::new();
                let mut last = BTreeSet::new();
                for arm in arms {
                    let fragment = self.analyze(arm);
                    nullable |= fragment.nullable;
                    first.extend(fragment.first);
                    last.extend(fragment.last);
                }
                Fragment {
                    nullable,
                    first,
                    last,
                }
            }
            Node::Star(body) => {
                let fragment = self.analyze(body);
                self.link(&fragment.last, &fragment.first);
                Fragment {
                    nullable: true,
                    ..fragment
                }
            }
            Node::Plus(body) => {
                let fragment = self.analyze(body);
                self.link(&fragment.last, &fragment.first);
                fragment
            }
            Node::Optional(body) => {
                let fragment = self.analyze(body);
                Fragment {
                    nullable: true,
                    ..fragment
                }
            }
        }
    }

    fn link(&mut self, from: &BTreeSet<StateId>, to: &BTreeSet<StateId>) {
        for &source in from {
            self.follow[source as usize - 1].extend(to.iter().copied());
        }
    }

    fn step(&self, position: StateId) -> &Step {
        &self.steps[position as usize - 1]
    }
}

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

    type Token = (bool, [u8; 16]);

    fn label(byte: u8) -> [u8; 16] {
        [byte; 16]
    }

    fn atom(byte: u8) -> PathExpr {
        Step::Forward(label(byte)).into()
    }

    fn step_matches(step: &Step, token: Token) -> bool {
        step.is_reverse() == token.0 && step.matches(&token.1)
    }

    fn direct_ends(expression: &PathExpr, word: &[Token], start: usize) -> BTreeSet<usize> {
        match &expression.node {
            Node::Atom(step) => {
                if word
                    .get(start)
                    .is_some_and(|&token| step_matches(step, token))
                {
                    BTreeSet::from([start + 1])
                } else {
                    BTreeSet::new()
                }
            }
            Node::Sequence(parts) => {
                let mut positions = BTreeSet::from([start]);
                for part in parts {
                    positions = positions
                        .into_iter()
                        .flat_map(|position| direct_ends(part, word, position))
                        .collect();
                }
                positions
            }
            Node::Alternative(arms) => arms
                .iter()
                .flat_map(|arm| direct_ends(arm, word, start))
                .collect(),
            Node::Star(body) => repeat_ends(body, word, start, true),
            Node::Plus(body) => repeat_ends(body, word, start, false),
            Node::Optional(body) => {
                let mut ends = direct_ends(body, word, start);
                ends.insert(start);
                ends
            }
        }
    }

    fn repeat_ends(
        body: &PathExpr,
        word: &[Token],
        start: usize,
        include_empty: bool,
    ) -> BTreeSet<usize> {
        let mut result = if include_empty {
            BTreeSet::from([start])
        } else {
            BTreeSet::new()
        };
        let mut frontier = direct_ends(body, word, start);
        while let Some(position) = frontier.pop_first() {
            if result.insert(position) {
                frontier.extend(direct_ends(body, word, position));
            }
        }
        result
    }

    fn automaton_accepts(automaton: &Automaton, word: &[Token]) -> bool {
        let mut active = automaton.initial_states().collect::<BTreeSet<_>>();
        for &token in word {
            active = automaton
                .transitions()
                .iter()
                .filter(|transition| {
                    active.contains(&transition.from) && step_matches(&transition.step, token)
                })
                .map(|transition| transition.to)
                .collect();
        }
        active
            .into_iter()
            .any(|state| automaton.is_accepting(state))
    }

    fn words(alphabet: &[Token], max_len: usize) -> Vec<Vec<Token>> {
        let mut words = vec![Vec::new()];
        let mut frontier = vec![Vec::new()];
        for _ in 0..max_len {
            frontier = frontier
                .iter()
                .flat_map(|prefix| {
                    alphabet.iter().map(move |&token| {
                        let mut word = prefix.clone();
                        word.push(token);
                        word
                    })
                })
                .collect();
            words.extend(frontier.iter().cloned());
        }
        words
    }

    #[test]
    fn exhaustive_small_expressions_match_the_direct_word_oracle() {
        let base = vec![
            atom(1),
            atom(2),
            PathExpr::from(Step::Reverse(label(1))),
            PathExpr::from(Step::ForwardExcept(vec![label(2)])),
            PathExpr::from(Step::ReverseExcept(vec![label(1)])),
            PathExpr::from(Step::forward_any()),
            PathExpr::from(Step::reverse_any()),
        ];
        let mut expressions = base.iter().cloned().collect::<BTreeSet<_>>();
        for body in &base {
            expressions.extend([
                body.clone().star(),
                body.clone().plus(),
                body.clone().optional(),
                body.clone().inverse(),
            ]);
        }
        for left in &base {
            for right in &base {
                expressions.insert(left.clone().then(right.clone()));
                expressions.insert(left.clone().or(right.clone()));
            }
        }
        let first_layer = expressions.iter().cloned().collect::<Vec<_>>();
        for expression in &first_layer {
            expressions.extend([
                expression.clone().star(),
                expression.clone().plus(),
                expression.clone().optional(),
                expression.clone().inverse(),
            ]);
            for right in &base {
                expressions.insert(expression.clone().then(right.clone()));
                expressions.insert(right.clone().then(expression.clone()));
                expressions.insert(expression.clone().or(right.clone()));
            }
        }

        let alphabet = [
            (false, label(1)),
            (false, label(2)),
            (true, label(1)),
            (true, label(2)),
        ];
        let words = words(&alphabet, 3);
        for (expression_index, expression) in expressions.iter().enumerate() {
            let automaton = expression.compile();
            assert_eq!(expression.is_nullable(), automaton.is_accepting(0));
            for word in &words {
                assert_eq!(
                    automaton_accepts(&automaton, word),
                    direct_ends(expression, word, 0).contains(&word.len()),
                    "expression {expression_index}: {expression:?}, word {word:?}"
                );
            }
        }
    }

    #[test]
    fn repeated_sequence_completes_a_second_cycle() {
        let expression = atom(1).then(atom(2)).star();
        let word = [
            (false, label(1)),
            (false, label(2)),
            (false, label(1)),
            (false, label(2)),
        ];

        assert!(direct_ends(&expression, &word, 0).contains(&word.len()));
        assert!(automaton_accepts(&expression.compile(), &word));
    }

    #[test]
    fn canonical_builders_stabilize_structure_and_automata() {
        let a = atom(1);
        let b = atom(2);
        let c = atom(3);

        assert_eq!(
            a.clone().then(b.clone()).then(c.clone()),
            a.clone().then(b.clone().then(c.clone()))
        );
        assert_eq!(
            a.clone().or(b.clone()).or(a.clone()).or(c.clone()),
            c.clone().or(b.clone().or(a.clone()))
        );
        assert_eq!(
            PathExpr::from(Step::ForwardExcept(vec![label(2), label(1), label(1)])),
            PathExpr::from(Step::ForwardExcept(vec![label(1), label(2)]))
        );

        let left = a.clone().or(b.clone()).or(a.clone()).compile();
        let right = b.or(a).compile();
        assert_eq!(left, right);
        assert_eq!(
            crate::automaton_fingerprint(&left),
            crate::automaton_fingerprint(&right)
        );
    }

    #[test]
    fn inverse_is_an_involution_and_reverses_sequences() {
        let expression = atom(1)
            .then(atom(2).optional())
            .or(PathExpr::from(Step::ForwardExcept(vec![label(3)])).plus());
        assert_eq!(expression.clone().inverse().inverse(), expression);

        let forward = atom(1).then(atom(2));
        let expected =
            PathExpr::from(Step::Reverse(label(2))).then(PathExpr::from(Step::Reverse(label(1))));
        assert_eq!(forward.inverse(), expected);
    }
}