From e55d42dad1ec87db84266fc9852bcbe49c071e89 Mon Sep 17 00:00:00 2001 From: Alexandre van Beurden <1949482+alexvbrdn@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:54:35 +0100 Subject: [PATCH 1/4] Walk sets of states instead of determinizing equivalent, subset, cardinality and difference no longer determinize or complement their operands: they walk the sets of states a word can reach (bisimulation up to congruence for equivalent, antichains for subset). Two deterministic automata are compared with Hopcroft & Karp. has_intersection no longer builds the intersection, Term::is_finite looks for a cycle instead of counting, Term::is_total uses subset, and remove_state(s) no longer scan every state's transitions. --- CHANGELOG.md | 8 + benches/operations.rs | 179 ++++++- .../analyze/reference_tests.txt | 12 + src/execution_profile.rs | 31 +- src/fast_automaton/analyze/cardinality.rs | 111 +++- src/fast_automaton/analyze/equivalence.rs | 478 +++++++++++++++++- src/fast_automaton/analyze/mod.rs | 3 + src/fast_automaton/analyze/reference_tests.rs | 438 ++++++++++++++++ src/fast_automaton/analyze/state_sets.rs | 343 +++++++++++++ src/fast_automaton/analyze/subset.rs | 101 +++- src/fast_automaton/builder.rs | 40 +- src/fast_automaton/condition/converter.rs | 50 ++ .../condition/fast_bit_vec/mod.rs | 13 + src/fast_automaton/condition/mod.rs | 19 + src/fast_automaton/generate.rs | 2 +- src/fast_automaton/mod.rs | 5 +- src/fast_automaton/operation/difference.rs | 96 +++- src/fast_automaton/operation/intersection.rs | 106 +--- src/fast_automaton/operation/union.rs | 4 +- src/lib.rs | 63 ++- tests/proptest_strategies.rs | 1 - 21 files changed, 1907 insertions(+), 196 deletions(-) create mode 100644 proptest-regressions/fast_automaton/analyze/reference_tests.txt create mode 100644 src/fast_automaton/analyze/reference_tests.rs create mode 100644 src/fast_automaton/analyze/state_sets.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index fc8924f..91322f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - `Term::to_pattern_with`, the pattern of `Term::to_regex_with`. ### Changed +- `equivalent` and `subset`, on `FastAutomaton` and on `Term`, no longer determinize or complement their operands. They walk the sets of states a word can reach in each automaton and skip the pairs that follow from the ones already met: bisimulation up to congruence (Bonchi & Pous, POPL 2013) for `equivalent`, antichains (De Wulf, Doyen, Henzinger & Raskin, CAV 2006) for `subset`. On the benchmarked patterns both take 2 to 20 times less time, and about 100 times less where most pairs are skipped. Two deterministic automata are compared by `equivalent` state by state (Hopcroft & Karp, 1971), in time close to linear in their number of states: 2 to 8 times less time on the benchmarked pairs that share a spanning set, and about as long as before on pairs that do not. +- `cardinality`, on `FastAutomaton` and on `Term`, no longer determinizes a non-deterministic automaton: strings are counted over the sets of states a word can reach, and `Cardinality::BigInteger` is returned as soon as the count of one set overflows. +- `difference`, on `FastAutomaton` and on `Term`, no longer determinizes and complements the subtrahend first: a state of the result pairs a state of the minuend with the set of states of the subtrahend that the same word reaches, so only the sets the minuend reaches are built. On the benchmarked patterns it takes up to 3 times less time, and 170 times less where the minuend reaches few of the subtrahend's sets. +- `has_intersection` no longer builds the intersection it looks for a string in: it only visits the pairs of states the two automata reach together, in about a third of the time on the benchmarked patterns. +- `Term::is_finite` no longer counts the strings: it looks for a cycle on an accepting path, as `length` does. On a non-deterministic automaton whose strings take thousands of sets of states to count, it takes microseconds instead of milliseconds. +- `FastAutomaton::remove_state` and `FastAutomaton::remove_states` take time proportional to the transitions of the removed states, instead of scanning every state's transitions for each removal. `minimize` takes 17% less time on the large benchmarked pattern. +- `Term::is_total` no longer determinizes a non-deterministic automaton: it checks that every string is included in it, with `subset`. +- When the execution profile disables implicit determinization, `FastAutomaton::equivalent`, `FastAutomaton::subset`, `FastAutomaton::cardinality` and `FastAutomaton::difference` accept non-deterministic automata instead of returning `EngineError::DeterministicAutomatonRequired`. For the first three, which build no automaton, `max_number_of_states` caps the number of pairs or sets visited. - Updated `regex-charclass` to 1.3, which makes `Char::index` and `Char::from_index` public: the mapping of a `char` to its position among all `char` values, the surrogate block skipped. They replace the crate's own copy of that mapping, and since `regex_charclass` is re-exported they are usable through it. ## [1.2.0] - 2026-11-14 diff --git a/benches/operations.rs b/benches/operations.rs index 9a74158..79f3c4e 100644 --- a/benches/operations.rs +++ b/benches/operations.rs @@ -122,15 +122,50 @@ fn bench_set_operations(c: &mut Criterion) { b.iter(|| black_box(&a).union(black_box(&b_op)).unwrap()) }); - let minuend = automaton(".*abc.*"); - let subtrahend = automaton(".*def.*"); - group.bench_function("difference", |b| { - b.iter(|| { - black_box(&minuend) - .difference(black_box(&subtrahend)) + // `via_complement` is the intersection with the complement of the + // determinized subtrahend, which is what `difference` used to do. + let mut bench_difference = |name: &str, minuend: &FastAutomaton, subtrahend: &FastAutomaton| { + let via_complement = || { + let mut complement = subtrahend.determinize().unwrap().into_owned(); + complement.complement().unwrap(); + black_box(minuend).intersection(&complement).unwrap() + }; + assert!( + minuend + .difference(subtrahend) .unwrap() - }) - }); + .equivalent(&via_complement()) + .unwrap() + ); + group.bench_function(name, |b| { + b.iter(|| { + black_box(minuend) + .difference(black_box(subtrahend)) + .unwrap() + }) + }); + group.bench_function(format!("{name}/via_complement"), |b| b.iter(via_complement)); + }; + + bench_difference("difference", &automaton(".*abc.*"), &automaton(".*def.*")); + bench_difference("difference/dfa", &dfa(".*abc.*"), &dfa(".*def.*")); + bench_difference( + "difference/large", + &automaton(LARGE.1), + &automaton(".*abc.*def.*ksd"), + ); + // Every set of states of the subtrahend is reached. + bench_difference( + "difference/blowup_8", + &automaton("(a|b)*"), + &automaton(&blowup_pattern(8)), + ); + // The minuend reaches a few of the 2^13 sets of the subtrahend. + bench_difference( + "difference/blowup_12_short_minuend", + &automaton("(a|b){0,6}"), + &automaton(&blowup_pattern(12)), + ); let complement_input = dfa(".*abc.*"); group.bench_function("complement", |b| { @@ -170,6 +205,73 @@ fn bench_decision(c: &mut Criterion) { b.iter(|| black_box(&smaller).subset(black_box(&bigger)).unwrap()) }); + // The cases below are sized after what `equivalent` and `subset` have to + // walk rather than after the operands: each pair is given to both. + let mut bench_pair = |name: &str, left: &FastAutomaton, right: &FastAutomaton| { + group.bench_function(format!("equivalent/{name}"), |b| { + b.iter(|| black_box(left).equivalent(black_box(right)).unwrap()) + }); + group.bench_function(format!("subset/{name}"), |b| { + b.iter(|| black_box(left).subset(black_box(right)).unwrap()) + }); + }; + + // Nothing to skip: the 2^(N+1) reachable sets of states all accept + // different languages, so the walk is as long as determinization. + for n in [8, 12] { + let left = automaton(&blowup_pattern(n)); + let right = automaton(&format!("(a*b*)*a(a|b){{{n}}}")); + assert!(left.equivalent(&right).unwrap()); + bench_pair(&format!("blowup_{n}"), &left, &right); + } + + // Same family once determinized: thousands of states a side, which + // `equivalent` compares state by state. + let left = dfa(&blowup_pattern(12)); + let right = dfa("(a*b*)*a(a|b){12}"); + assert!(left.equivalent(&right).unwrap()); + bench_pair("blowup_12_dfa", &left, &right); + + // Two deterministic automata of a realistic size: a determinized + // pattern and its minimal automaton. + let left = dfa(LARGE.1); + let mut right = left.clone(); + right.minimize().unwrap(); + assert_ne!(left, right); + assert!(left.equivalent(&right).unwrap()); + bench_pair("dfa", &left, &right); + + // Almost everything to skip: determinizing the right operand takes 512 + // states and the left one far more, the walk fewer than 30 pairs. The + // left operand is united as automata, since as a pattern it would be + // simplified into the right one. + let left = FastAutomaton::union_all(&[ + automaton(".*a.{8}"), + automaton(".*b.{8}"), + automaton(".*c.{8}"), + ]) + .unwrap(); + let right = automaton(".*[abc].{8}"); + assert_ne!(left, right); + assert!(left.equivalent(&right).unwrap()); + bench_pair("pruned", &left, &right); + + // Unicode classes cut differently on each side: the operands do not + // share a spanning set, so every condition is projected first. + let left = automaton(r"\w+@\w+\.\w{2,6}"); + let right = automaton(r"(\d+|[^\d\W]+)+@(\d+|[^\d\W]+)+\.\w{2,6}"); + assert!(left.spanning_set() != right.spanning_set()); + assert!(left.equivalent(&right).unwrap()); + bench_pair("spanning_sets", &left, &right); + + // Different languages: the walk stops at the first counterexample, which + // here is a dozen letters in, so part of the blow-up is still walked. + let left = automaton(&blowup_pattern(12)); + let right = automaton(&blowup_pattern(11)); + assert!(!left.equivalent(&right).unwrap()); + assert!(!left.subset(&right).unwrap()); + bench_pair("counterexample", &left, &right); + let left = automaton(".*abc.*"); let right = automaton(".*cba.*"); group.bench_function("has_intersection", |b| { @@ -180,6 +282,19 @@ fn bench_decision(c: &mut Criterion) { }) }); + // No string in common: every pair of states the operands reach together + // is visited. + let left = automaton(&blowup_pattern(10)); + let right = automaton("(a|b)*b(a|b){10}c"); + assert!(!left.has_intersection(&right).unwrap()); + group.bench_function("has_intersection/disjoint", |b| { + b.iter(|| { + black_box(&left) + .has_intersection(black_box(&right)) + .unwrap() + }) + }); + group.finish(); } @@ -192,6 +307,54 @@ fn bench_analyze(c: &mut Criterion) { b.iter(|| black_box(&finite).cardinality().unwrap()) }); + // Finiteness only depends on the cycles, however many sets of states + // counting the strings takes (a few thousand for `blowup_12`). + for (name, pattern) in [ + ("words", "(foo|foobar|bar)(baz)?"), + ("blowup_12", "(a|b){0,12}a(a|b){12}"), + ] { + let term = Term::from_automaton(automaton(pattern)); + assert!(term.is_finite().unwrap()); + group.bench_function(format!("is_finite/nfa/{name}"), |b| { + b.iter(|| black_box(&term).is_finite().unwrap()) + }); + } + + // Finite languages of non-deterministic automata, where several paths + // spell the same string. `via_determinize` is the count on the + // determinized automaton, which is what `cardinality` used to do. + for (name, pattern) in [ + ("words", "(foo|foobar|bar)(baz)?"), + ("overlaps", "(a|b|ab|ba){6}"), + ( + "ipv4", + r"((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)", + ), + // About a thousand sets to count. + ("blowup_8", "(a|b){0,8}a(a|b){8}"), + // The count overflows after a few dozen of more than 100,000 sets. + ("overflow", "(a|b){0,12}a(a|b){40}"), + ] { + let nfa = automaton(pattern); + assert!(!nfa.is_deterministic(), "{pattern}"); + assert_eq!( + nfa.cardinality().unwrap(), + nfa.determinize().unwrap().cardinality().unwrap() + ); + group.bench_function(format!("cardinality/nfa/{name}"), |b| { + b.iter(|| black_box(&nfa).cardinality().unwrap()) + }); + group.bench_function(format!("cardinality/nfa/{name}/via_determinize"), |b| { + b.iter(|| { + black_box(&nfa) + .determinize() + .unwrap() + .cardinality() + .unwrap() + }) + }); + } + let infinite = automaton(LARGE.1); group.bench_function("length/large", |b| b.iter(|| black_box(&infinite).length())); diff --git a/proptest-regressions/fast_automaton/analyze/reference_tests.txt b/proptest-regressions/fast_automaton/analyze/reference_tests.txt new file mode 100644 index 0000000..8948f7b --- /dev/null +++ b/proptest-regressions/fast_automaton/analyze/reference_tests.txt @@ -0,0 +1,12 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc e9da17c95343886b4f35245e4a5bed98180ba8aa6de32061d552ed5f83f9b1ce # shrinks to a = FastAutomaton { transitions: [{}, {}], transitions_in: {}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: false }, b = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: true } +cc b5b43999ef2bd471149e7ba4597ad7f9db702ed38de217f67af5bd6258d889ab # shrinks to a = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: true }, b = FastAutomaton { transitions: [{}, {}], transitions_in: {}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: false } +cc 707c0ef4c5b7a067f2c18ec5112500ebb728e90129e7e9a6608c7407132fe9ea # shrinks to a = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: false }, b = FastAutomaton { transitions: [{0: Condition(FastBitVec { bits: [2], n: 2 })}], transitions_in: {0: {0}}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([RangeSet([Char('a'), Char('a')])], RangeSet([Char('\0'), Char('`'), Char('b'), Char('\u{10ffff}')])), deterministic: true, minimal: false } +cc 050e4b438d3eabcbf63f9442ab2b0390a353827fd4bf138cd0dcea21e13331bb # shrinks to a = FastAutomaton { transitions: [{1: Condition(FastBitVec { bits: [2], n: 2 })}, {}], transitions_in: {1: {0}}, start_state: 0, accept_states: {1}, removed_states: {}, spanning_set: SpanningSet([RangeSet([Char('a'), Char('a')])], RangeSet([Char('\0'), Char('`'), Char('b'), Char('\u{10ffff}')])), deterministic: true, minimal: false }, b = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: true } +cc 98e1b7f47a70fe23319ce70a59a2398ec004f710ad67ee5048c5b0a26c802e93 # shrinks to a = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: true }, b = FastAutomaton { transitions: [{2: Condition(FastBitVec { bits: [2], n: 2 })}, {}, {1: Condition(FastBitVec { bits: [2], n: 2 })}], transitions_in: {1: {2}, 2: {0}}, start_state: 0, accept_states: {1}, removed_states: {}, spanning_set: SpanningSet([RangeSet([Char('a'), Char('a')])], RangeSet([Char('\0'), Char('`'), Char('b'), Char('\u{10ffff}')])), deterministic: true, minimal: false } +cc 7f7c5f183e1d825e66fda11d87f30636383089f2510c5c0080594c20d87f6240 # shrinks to a = FastAutomaton { transitions: [{}], transitions_in: {}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([], RangeSet([Char('\0'), Char('\u{10ffff}')])), deterministic: true, minimal: false }, b = FastAutomaton { transitions: [{1: Condition(FastBitVec { bits: [2], n: 2 })}, {0: Condition(FastBitVec { bits: [2], n: 2 })}], transitions_in: {0: {1}, 1: {0}}, start_state: 0, accept_states: {0}, removed_states: {}, spanning_set: SpanningSet([RangeSet([Char('a'), Char('a')])], RangeSet([Char('\0'), Char('`'), Char('b'), Char('\u{10ffff}')])), deterministic: true, minimal: false } diff --git a/src/execution_profile.rs b/src/execution_profile.rs index 04153b1..749bc55 100644 --- a/src/execution_profile.rs +++ b/src/execution_profile.rs @@ -100,8 +100,7 @@ const DEFAULT_CLOCK: Option = None; /// ## Disabling implicit determinization /// /// [`FastAutomaton`](crate::fast_automaton::FastAutomaton) operations that -/// require a deterministic automaton (`minimize`, `complement`, -/// `difference`, `equivalent`, `subset`, `cardinality`, ...) +/// require a deterministic automaton (`minimize` and `complement`) /// determinize a non-deterministic input on their own by default. Since /// subset construction can blow up exponentially, this can be disabled; /// those operations then fail fast and determinization only happens through @@ -410,7 +409,9 @@ impl ExecutionProfileBuilder { /// Caps the number of states an automaton may reach; operations that would /// exceed it abort with [`EngineError::AutomatonHasTooManyStates`]. This /// bounds the exponential blow-up of conversions such as determinization. - /// Unset by default (no cap). + /// The operations that walk sets of states without building an automaton + /// (`equivalent`, `subset`, `cardinality`) count what they visit against + /// the same cap. Unset by default (no cap). pub fn max_number_of_states(mut self, max_number_of_states: usize) -> Self { self.max_number_of_states = Some(max_number_of_states); self @@ -747,14 +748,14 @@ mod tests { // non-deterministic input on its own... assert_eq!(nfa.clone().minimize().unwrap_err(), err); assert_eq!(nfa.clone().complement().unwrap_err(), err); - assert_eq!(dfa.difference(&nfa).unwrap_err(), err); - assert_eq!(nfa.equivalent(&dfa).unwrap_err(), err); - assert_eq!(dfa.subset(&nfa).unwrap_err(), err); - assert_eq!(nfa.cardinality().unwrap_err(), err); // ...but operations that work on NFAs directly are unaffected - // (difference only determinizes the subtrahend)... assert!(nfa.difference(&dfa).is_ok()); + assert!(dfa.difference(&nfa).unwrap().is_empty()); + assert_eq!(nfa.cardinality(), dfa.cardinality()); + assert!(nfa.equivalent(&dfa).unwrap()); + assert!(dfa.subset(&nfa).unwrap()); + assert!(nfa.subset(&dfa).unwrap()); // ...deterministic inputs keep working... assert!(dfa.clone().minimize().is_ok()); @@ -781,14 +782,7 @@ mod tests { .run(|| { // Methods that need a DFA internally determinize on Term's // behalf (an explicit choice of the Term layer)... - assert!(term.difference(&other).is_ok()); - assert!(other.difference(&term).is_ok()); assert!(term.complement().is_ok()); - assert!(term.equivalent(&other).is_ok()); - assert!(term.subset(&other).is_ok()); - assert!(other.subset(&term).is_ok()); - assert!(term.is_total().is_ok()); - assert!(term.cardinality().is_ok()); assert!(term.minimize().is_ok()); assert!( term.generate_strings(5, 0, GenerationOptions::new()) @@ -796,6 +790,13 @@ mod tests { ); // ...and the rest of the API never needed one. + assert!(term.difference(&other).is_ok()); + assert!(other.difference(&term).is_ok()); + assert!(term.equivalent(&other).is_ok()); + assert!(term.subset(&other).is_ok()); + assert!(other.subset(&term).is_ok()); + assert!(term.is_total().is_ok()); + assert!(term.cardinality().is_ok()); assert!(term.concat(std::slice::from_ref(&other)).is_ok()); assert!(term.union(std::slice::from_ref(&other)).is_ok()); assert!(term.intersection(std::slice::from_ref(&other)).is_ok()); diff --git a/src/fast_automaton/analyze/cardinality.rs b/src/fast_automaton/analyze/cardinality.rs index 1bf13e4..5e9e076 100644 --- a/src/fast_automaton/analyze/cardinality.rs +++ b/src/fast_automaton/analyze/cardinality.rs @@ -1,15 +1,18 @@ use std::hash::BuildHasherDefault; +use crate::execution_profile::ExecutionProfile; + +use super::state_sets::{Id, Operand}; use super::*; impl FastAutomaton { /// Returns the cardinality of the automaton (i.e., the number of possible matched strings). /// - /// Works on non-deterministic automata too: acyclic NFAs are determinized - /// internally (the only fallible step, subject to the - /// [`crate::execution_profile::ExecutionProfile`] budget, and rejected - /// with [`EngineError::DeterministicAutomatonRequired`] when the profile - /// disables implicit determinization). + /// Non-deterministic automata are not determinized: when the language is + /// finite, its strings are counted over the sets of states a word can + /// reach. That count can visit exponentially many sets; the + /// [`crate::execution_profile::ExecutionProfile`]'s timeout applies, and + /// its `max_number_of_states` caps the number of sets visited. /// /// As in [`length`](Self::length), only cycles **on accepting /// paths** make the count infinite: cycles among dead or unreachable @@ -41,12 +44,10 @@ impl FastAutomaton { Some(states) => states, }; - // The finite count below assumes deterministic (single-path) - // transitions. Determinizing an automaton with a finite language - // yields one whose relevant subgraph is acyclic too, so the - // recursion takes the deterministic path on the second call. + // The count below is a count of paths, which is a count of strings + // only when a string has a single path. if !self.is_deterministic() { - return self.determinize_implicit()?.cardinality(); + return self.cardinality_over_state_sets(); } let len = self.transitions.len(); @@ -88,6 +89,87 @@ impl FastAutomaton { Ok(Cardinality::Integer(temp_cardinality)) } + /// Counts the strings of a non-deterministic automaton whose language is + /// finite. + /// + /// Several paths can spell the same string, so strings are counted from + /// the *set* of states a word reaches, which is the same for all of its + /// paths: one if the set holds an accept state, plus, for each character, + /// the count of the set's successor under that character. Each set is + /// counted once, as determinization would create it once. + /// + /// The count stops at the first set that overflows it: some word reaches + /// that set, so the language holds at least as many strings. + fn cardinality_over_state_sets(&self) -> Result, EngineError> { + let execution_profile = ExecutionProfile::get(); + + let operand = Operand::new(self, 0, None)?; + let Some(start) = operand.start else { + return Ok(Cardinality::Integer(0)); + }; + // The number of characters of each base. + let widths = self + .spanning_bases()? + .iter() + .map(|base| base.cardinality(&self.spanning_set)) + .collect::, EngineError>>()?; + + // The number of strings accepted from each set counted so far. + let mut counts: AHashMap, u32> = AHashMap::new(); + let mut successors = vec![Vec::new(); widths.len()]; + + // The non-empty successors of a set, each with the width of its base. + let mut successors_of = |set: &[Id]| -> Vec<(Vec, u32)> { + operand.successors(set, &mut successors); + successors + .iter() + .zip(&widths) + .filter(|(successor, _)| !successor.is_empty()) + .map(|(successor, width)| (successor.clone(), *width)) + .collect() + }; + // The sets being counted, each waiting for the one above it: a set, + // its successors, and how many of them are counted already. The + // language is finite, so a set never waits for itself. + let mut pending = vec![(vec![start], successors_of(&[start]), 0)]; + + loop { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(counts.len() + pending.len())?; + let Some((set, next, counted)) = pending.last_mut() else { + break; + }; + + // Count the first successor that is not counted yet, and come + // back to this set afterwards. + if let Some(uncounted) = next[*counted..] + .iter() + .position(|(successor, _)| !counts.contains_key(successor)) + { + *counted += uncounted; + let successor = next[*counted].0.clone(); + let next = successors_of(&successor); + pending.push((successor, next, 0)); + continue; + } + + let mut count = u32::from(operand.is_accepting(set)); + for (successor, width) in next.iter() { + let Some(sum) = counts[successor] + .checked_mul(*width) + .and_then(|strings| count.checked_add(strings)) + else { + return Ok(Cardinality::BigInteger); + }; + count = sum; + } + let (set, _, _) = pending.pop().expect("`pending` has a last element"); + counts.insert(set, count); + } + + Ok(Cardinality::Integer(counts[&vec![start]])) + } + /// Kahn's algorithm restricted to the `relevant` subgraph (transitions /// with empty conditions can't be taken and are ignored). Returns `None` /// when that subgraph contains a cycle. @@ -162,11 +244,12 @@ mod tests { assert_eq!(a.cardinality().unwrap(), Cardinality::Integer(1)); } - // `cardinality` determinizes internally, so it returns a finite count for - // an acyclic NFA (the only nondeterministic input that reaches the finite - // count; cyclic ones return Infinite earlier) rather than requiring a DFA. + // `cardinality` returns a finite count for an acyclic NFA (the only + // nondeterministic input that reaches the finite count; cyclic ones + // return Infinite earlier) rather than requiring a DFA, and counts each + // string once however many paths spell it. #[test] - fn get_cardinality_determinizes_acyclic_nfas() { + fn get_cardinality_counts_strings_of_acyclic_nfas() { let mut a = FastAutomaton::new_empty(); let s1 = a.new_state(); let s2 = a.new_state(); diff --git a/src/fast_automaton/analyze/equivalence.rs b/src/fast_automaton/analyze/equivalence.rs index 8324ac6..a1c0e30 100644 --- a/src/fast_automaton/analyze/equivalence.rs +++ b/src/fast_automaton/analyze/equivalence.rs @@ -1,13 +1,24 @@ -use crate::error::EngineError; +use std::ops::Range; +use condition::converter::{ConditionConverter, SharedSpanningSet}; + +use crate::{error::EngineError, execution_profile::ExecutionProfile}; + +use super::state_sets::{Id, Marks, Operand, SetTrie}; use super::*; impl FastAutomaton { /// Returns `true` if both automata accept the same language. /// - /// Non-deterministic operands are determinized internally, unless the - /// execution profile disables implicit determinization, in which case - /// [`EngineError::DeterministicAutomatonRequired`] is returned. + /// Non-deterministic operands are not determinized: the two automata are + /// walked together over the sets of states a word can reach, and a pair + /// of sets is skipped when it follows from the pairs already met + /// (bisimulation up to congruence). The walk is still exponential in the + /// worst case; the execution profile's timeout applies, and its + /// `max_number_of_states` caps the number of pairs walked. + /// + /// Two deterministic automata are compared state by state instead, in + /// time close to linear in their number of states. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn equivalent(&self, other: &FastAutomaton) -> Result { // `is_empty` is exact, so a mismatch proves the languages differ. @@ -20,26 +31,471 @@ impl FastAutomaton { } else if self == other { return Ok(true); } + if self.deterministic && other.deterministic { + self.equivalent_deterministic(other) + } else { + self.equivalent_over_state_sets(other) + } + } + + /// The algorithm of Hopcroft & Karp, *A linear algorithm for testing + /// equivalence of finite automata* (1971), for two deterministic + /// automata. + /// + /// A word reaches one state on each side, so the walk visits pairs of + /// states, and a pair is skipped when its states are already in the same + /// class of [`Classes`]. Each pair walked merges two classes, so there + /// are at most as many as there are states. + /// + /// A missing transition leads to a sink that both automata share, so the + /// states that cannot reach an accept state need no special care: they + /// are merged with the sink like any other state equivalent to it. + pub(super) fn equivalent_deterministic( + &self, + other: &FastAutomaton, + ) -> Result { + let shared = SharedSpanningSet::new(&self.spanning_set, &other.spanning_set); + match shared.converters()? { + (Some(self_converter), Some(other_converter)) => { + let project = |automaton: &FastAutomaton, converter: &ConditionConverter| { + (0..automaton.transitions.len()) + .map(|state| { + automaton + .transitions_from(state) + .map(|(condition, to)| Ok((converter.convert(condition)?, *to))) + .collect() + }) + .collect::>, EngineError>>() + }; + let (left, right) = ( + project(self, &self_converter)?, + project(other, &other_converter)?, + ); + self.walk_deterministic( + other, + shared.spanning_set(), + |state| left[state].iter().map(|(condition, to)| (condition, *to)), + |state| right[state].iter().map(|(condition, to)| (condition, *to)), + ) + } + _ => self.walk_deterministic( + other, + shared.spanning_set(), + |state| { + self.transitions_from(state) + .map(|(condition, to)| (condition, *to)) + }, + |state| { + other + .transitions_from(state) + .map(|(condition, to)| (condition, *to)) + }, + ), + } + } - let mut other_complement = other.determinize_implicit()?.into_owned(); - other_complement.complement()?; + /// The walk of [`equivalent_deterministic`](Self::equivalent_deterministic), + /// over the transitions of both automata expressed in `spanning_set`. + fn walk_deterministic<'a, L, R>( + &self, + other: &FastAutomaton, + spanning_set: &SpanningSet, + left_transitions: impl Fn(State) -> L, + right_transitions: impl Fn(State) -> R, + ) -> Result + where + L: Iterator + Clone, + R: Iterator + Clone, + { + let execution_profile = ExecutionProfile::get(); - if self.has_intersection(&other_complement)? { + // Both automata and the sink share one id space, `self` first. + let other_offset = self.transitions.len(); + let sink = other_offset + other.transitions.len(); + if u32::try_from(sink).is_err() { + return Err(EngineError::AutomatonHasTooManyStates); + } + let accepts = |id: usize| { + if id < other_offset { + self.accept_states.contains(&id) + } else { + id < sink && other.accept_states.contains(&(id - other_offset)) + } + }; + + let start = (self.start_state, other_offset + other.start_state); + if accepts(start.0) != accepts(start.1) { return Ok(false); } + let mut classes = Classes::new(sink + 1); + classes.merge(start.0, start.1); + let mut worklist = VecDeque::new(); + worklist.push_back(start); + let mut pairs = 1; + + // The characters each state of the pair has a transition for. + let mut left_covered = Condition::empty(spanning_set); + let mut right_covered = Condition::empty(spanning_set); + + while let Some((left, right)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(pairs)?; + + // Returns `false` on a counterexample. + let mut relate = |left: usize, right: usize| { + if accepts(left) != accepts(right) { + return false; + } + if classes.merge(left, right) { + worklist.push_back((left, right)); + pairs += 1; + } + true + }; - let mut self_complement = self.determinize_implicit()?.into_owned(); - self_complement.complement()?; + let left_transitions = (left != sink) + .then(|| left_transitions(left)) + .into_iter() + .flatten(); + let right_transitions = (right != sink) + .then(|| right_transitions(right - other_offset)) + .into_iter() + .flatten(); + left_covered.clear(); + for (condition, _) in left_transitions.clone() { + left_covered.union_with(condition); + } + right_covered.clear(); + for (condition, _) in right_transitions.clone() { + right_covered.union_with(condition); + } - Ok(!self_complement.has_intersection(other)?) + for (left_condition, left_to) in left_transitions { + for (right_condition, right_to) in right_transitions.clone() { + if left_condition.has_intersection(right_condition) + && !relate(left_to, other_offset + right_to) + { + return Ok(false); + } + } + if !left_condition.is_subset_of(&right_covered) && !relate(left_to, sink) { + return Ok(false); + } + } + for (right_condition, right_to) in right_transitions { + if !right_condition.is_subset_of(&left_covered) + && !relate(sink, other_offset + right_to) + { + return Ok(false); + } + } + } + Ok(true) + } + + /// Algorithm HKC of Bonchi & Pous, *Checking NFA equivalence with + /// bisimulations up to congruence* (POPL 2013). + /// + /// The walk visits the pairs `(X, Y)` of state sets that one word reaches + /// in `self` and in `other`. A pair is a counterexample when exactly one + /// side accepts, or exactly one side is empty. It is skipped when it + /// follows from the pairs met so far by [`Congruence`], which can hold + /// for a pair neither of whose sets was met before. + pub(super) fn equivalent_over_state_sets( + &self, + other: &FastAutomaton, + ) -> Result { + let execution_profile = ExecutionProfile::get(); + + // Both operands share one id space, `self` first: the sets a rule + // rewrites mix states of the two. + let other_offset = self.transitions.len(); + let (left, right, bases) = Operand::pair(self, 0, other, other_offset)?; + + let (Some(left_start), Some(right_start)) = (left.start, right.start) else { + return Ok(left.start.is_none() && right.start.is_none()); + }; + if left.accepts(left_start) != right.accepts(right_start) { + return Ok(false); + } + + let mut congruence = Congruence::new(other_offset + other.transitions.len()); + let mut worklist = VecDeque::new(); + worklist.push_back(congruence.relate(&[left_start], &[right_start])); + + let mut left_successors = vec![Vec::new(); bases]; + let mut right_successors = vec![Vec::new(); bases]; + let mut pairs = 1; + + while let Some((x, y)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(pairs)?; + + left.successors(&congruence.sets[x], &mut left_successors); + right.successors(&congruence.sets[y], &mut right_successors); + + for (x, y) in left_successors.iter().zip(&right_successors) { + if x.is_empty() && y.is_empty() { + continue; + } + // Only live states are kept, so a non-empty set accepts some + // word, which an empty one does not. + if x.is_empty() != y.is_empty() || left.is_accepting(x) != right.is_accepting(y) { + return Ok(false); + } + if congruence.relates(x, y) { + continue; + } + worklist.push_back(congruence.relate(x, y)); + pairs += 1; + } + } + Ok(true) + } +} + +/// The classes of the states related so far (union-find). +struct Classes { + parent: Vec, + size: Vec, +} + +impl Classes { + fn new(states: usize) -> Self { + Classes { + parent: (0..states as u32).collect(), + size: vec![1; states], + } + } + + fn find(&mut self, mut state: usize) -> usize { + while self.parent[state] as usize != state { + let parent = self.parent[state] as usize; + self.parent[state] = self.parent[parent]; + state = parent; + } + state + } + + /// Puts both states in the same class; returns `false` if they already + /// were. + fn merge(&mut self, a: usize, b: usize) -> bool { + let (a, b) = (self.find(a), self.find(b)); + if a == b { + return false; + } + let (small, large) = if self.size[a] < self.size[b] { + (a, b) + } else { + (b, a) + }; + self.parent[small] = large as u32; + self.size[large] += self.size[small]; + true + } +} + +/// The number of trie nodes one normal form search may visit: `BUDGET_BASE`, +/// plus `BUDGET_PER_STATE` for each state of the two sets compared. +const BUDGET_BASE: usize = 256; +const BUDGET_PER_STATE: usize = 16; + +/// The pairs of sets met by the walk, read as rewriting rules: a pair +/// `(X, Y)` lets any set containing `X` grow by `Y`, and any set containing +/// `Y` grow by `X`. Two sets are related by the congruence closure of the +/// pairs iff rewriting takes them to the same normal form. +struct Congruence { + /// The sets of the pairs, back to back. + sets: Vec, + /// Each side of each pair, valued with where the other side is in `sets`. + rules: SetTrie>, + root: usize, + // Scratch state of `normal_form_contains`, kept to reuse the allocations. + normal_form: Marks, + /// By state, the trie nodes waiting for that state to enter the normal + /// form; `touched` lists the states with a non-empty entry. + parked: Vec>, + touched: Vec, + /// The visited trie nodes with too many children to park one by one. + wide: Vec, + stack: Vec, +} + +impl Congruence { + fn new(states: usize) -> Self { + let mut rules = SetTrie::new(); + let root = rules.new_root(); + Congruence { + sets: Vec::new(), + rules, + root, + normal_form: Marks::new(states), + parked: vec![Vec::new(); states], + touched: Vec::new(), + wide: Vec::new(), + stack: Vec::new(), + } + } + + /// Records the pair `(x, y)` and returns where it is stored in `sets`. + fn relate(&mut self, x: &[Id], y: &[Id]) -> (Range, Range) { + let start = self.sets.len(); + self.sets.extend_from_slice(x); + self.sets.extend_from_slice(y); + let stored = (start..start + x.len(), start + x.len()..self.sets.len()); + self.rules.insert(self.root, x, stored.1.clone()); + self.rules.insert(self.root, y, stored.0.clone()); + stored + } + + /// Returns `true` if `x` and `y` are known to be related: they have the + /// same normal form, which holds iff each is contained in the normal + /// form of the other. + /// + /// `false` is always a safe answer (the pair is then walked like any new + /// one), and is the answer when the search for a normal form runs out of + /// budget. A recorded pair is recognised whatever the budget, which + /// keeps the walk finite. + fn relates(&mut self, x: &[Id], y: &[Id]) -> bool { + let recorded = self + .rules + .get(self.root, x) + .iter() + .any(|other| self.sets[other.clone()] == *y); + recorded || (self.normal_form_contains(x, y) && self.normal_form_contains(y, x)) + } + + /// Returns `true` if the normal form of `set`, the smallest superset + /// closed under every rule, is found to contain `target`. + /// + /// A trie node is reached once every state on its path is in the normal + /// form, at which point the rules ending there fire. A child whose state + /// is missing is parked on that state and resumed if a later rule brings + /// the state in, so no part of the trie is walked twice and the parts the + /// normal form never covers are not walked at all. + /// + /// The number of rules contained in a set can be exponential in its size + /// (when determinization itself blows up and nothing can be skipped), so + /// the search stops after a number of nodes proportional to the sets at + /// hand, and answers from the part of the normal form built so far. + fn normal_form_contains(&mut self, set: &[Id], target: &[Id]) -> bool { + let Congruence { + sets, + rules, + root, + normal_form, + parked, + touched, + wide, + stack, + } = self; + + for &id in set { + normal_form.insert(id); + } + stack.push(*root); + for _ in 0..BUDGET_BASE + BUDGET_PER_STATE * (set.len() + target.len()) { + let Some(index) = stack.pop() else { + break; + }; + let node = rules.node(index); + for rhs in &node.values { + for &id in &sets[rhs.clone()] { + if normal_form.insert(id) { + stack.append(&mut parked[id as usize]); + stack.extend(wide.iter().filter_map(|&wide| rules.node(wide).child(id))); + } + } + } + match node.few_children() { + Some(children) => { + for &(id, child) in children { + if normal_form.contains(id) { + stack.push(child); + } else { + if parked[id as usize].is_empty() { + touched.push(id); + } + parked[id as usize].push(child); + } + } + } + // Too many children to park: look up the states the normal + // form holds now, and the ones it gains later as they come. + None => { + stack.extend( + normal_form + .members() + .iter() + .filter_map(|&id| node.child(id)), + ); + wide.push(index); + } + } + } + + let contained = target.iter().all(|&id| normal_form.contains(id)); + normal_form.clear(); + stack.clear(); + wide.clear(); + for id in touched.drain(..) { + parked[id as usize].clear(); + } + contained } } #[cfg(test)] mod tests { - + use super::super::state_sets::{Id, WIDE}; + use super::Congruence; use crate::regex::RegularExpression; + // {1} ~ {2} and {2, 3} ~ {4}: relating {1, 3} to {4} takes the first + // rule to bring 2 in before the second one can fire, i.e. a trie branch + // that was not coverable when first met has to be resumed. + #[test] + fn normal_form_chains_rules() { + let mut congruence = Congruence::new(8); + congruence.relate(&[1], &[2]); + congruence.relate(&[2, 3], &[4]); + + assert!(congruence.relates(&[1, 3], &[4])); + assert!(congruence.relates(&[1, 3], &[1, 2, 3, 4])); + assert!(congruence.relates(&[2, 3], &[4])); + // Containment in one direction only is not enough. + assert!(!congruence.relates(&[1, 3], &[2])); + assert!(!congruence.relates(&[1], &[4])); + assert!(!congruence.relates(&[3], &[4])); + assert!(!congruence.relates(&[5], &[6])); + } + + // Same chain through a node with more children than are scanned. + #[test] + fn normal_form_chains_rules_through_wide_nodes() { + let states = 4 * WIDE as Id; + let mut congruence = Congruence::new(2 * states as usize + 2); + // i ~ states + i for every i: the root gets 2 * states children. + for id in 0..states { + congruence.relate(&[id], &[states + id]); + } + let last = 2 * states; + congruence.relate(&[states + 3, states + 5], &[last]); + assert!( + congruence + .rules + .node(congruence.root) + .few_children() + .is_none() + ); + + assert!(congruence.relates(&[7], &[states + 7])); + assert!(congruence.relates(&[3, 5], &[last])); + assert!(congruence.relates(&[3, states + 5], &[5, states + 3, last])); + assert!(!congruence.relates(&[3], &[last])); + assert!(!congruence.relates(&[3, 6], &[last])); + } + #[test] fn test_equivalent() -> Result<(), String> { assert_equivalent( diff --git a/src/fast_automaton/analyze/mod.rs b/src/fast_automaton/analyze/mod.rs index 26d302f..9e3a63b 100644 --- a/src/fast_automaton/analyze/mod.rs +++ b/src/fast_automaton/analyze/mod.rs @@ -5,6 +5,9 @@ use super::*; mod cardinality; mod equivalence; mod length; +#[cfg(test)] +mod reference_tests; +pub(super) mod state_sets; mod subset; impl FastAutomaton { diff --git a/src/fast_automaton/analyze/reference_tests.rs b/src/fast_automaton/analyze/reference_tests.rs new file mode 100644 index 0000000..833f8c7 --- /dev/null +++ b/src/fast_automaton/analyze/reference_tests.rs @@ -0,0 +1,438 @@ +//! `equivalent`, `subset`, `cardinality` and `difference`, checked against +//! the textbook definitions (determinize, then complement and intersect, or +//! count paths). + +use proptest::prelude::*; +use regex_charclass::char::Char; + +use crate::CharRange; +use crate::cardinality::Cardinality; +use crate::error::EngineError; +use crate::execution_profile::ExecutionProfileBuilder; +use crate::fast_automaton::FastAutomaton; +use crate::regex::RegularExpression; + +fn automaton(pattern: &str) -> FastAutomaton { + RegularExpression::new(pattern) + .unwrap() + .to_automaton() + .unwrap() +} + +/// The textbook check: `a ∩ ¬b` is empty. +fn subset_by_complement(a: &FastAutomaton, b: &FastAutomaton) -> bool { + let mut complement = b.determinize().unwrap().into_owned(); + complement.complement().unwrap(); + !a.has_intersection(&complement).unwrap() +} + +fn equivalent_by_complement(a: &FastAutomaton, b: &FastAutomaton) -> bool { + subset_by_complement(a, b) && subset_by_complement(b, a) +} + +/// The textbook difference: `a ∩ ¬b`. +fn difference_by_complement(a: &FastAutomaton, b: &FastAutomaton) -> FastAutomaton { + let mut complement = b.determinize().unwrap().into_owned(); + complement.complement().unwrap(); + a.intersection(&complement).unwrap() +} + +fn assert_difference_matches_reference(a: &FastAutomaton, b: &FastAutomaton) { + let difference = a.difference(b).unwrap(); + let reference = difference_by_complement(a, b); + assert!( + equivalent_by_complement(&difference, &reference), + "difference disagrees on\n{a}\n{b}" + ); + // Both build the pairs `a` reaches with the sets of states of `b`, so + // the result is no larger than the reference, and deterministic when + // `a` is. + assert!( + difference.number_of_states() <= reference.number_of_states(), + "difference is larger on\n{a}\n{b}" + ); + assert!(!a.is_deterministic() || difference.is_deterministic()); +} + +/// The check on two deterministic automata, on the determinized operands +/// (which keep their dead states and have missing transitions) and on a +/// minimized one (which has neither, and another spanning set). +fn assert_deterministic_equivalence_matches_reference(a: &FastAutomaton, b: &FastAutomaton) { + let (a_dfa, b_dfa) = (a.determinize().unwrap(), b.determinize().unwrap()); + let mut a_minimal = a_dfa.clone().into_owned(); + a_minimal.minimize().unwrap(); + let expected = equivalent_by_complement(a, b); + for (left, right) in [ + (a_dfa.as_ref(), b_dfa.as_ref()), + (b_dfa.as_ref(), a_dfa.as_ref()), + (&a_minimal, b_dfa.as_ref()), + (b_dfa.as_ref(), &a_minimal), + ] { + assert_eq!( + expected, + left.equivalent_deterministic(right).unwrap(), + "equivalent disagrees on the deterministic\n{left}\n{right}" + ); + } + assert!(a_dfa.equivalent_deterministic(&a_minimal).unwrap()); + assert!(a_minimal.equivalent_deterministic(&a_dfa).unwrap()); +} + +/// Both checks, in both directions, against the complement-based +/// reference. +fn assert_matches_reference(a: &FastAutomaton, b: &FastAutomaton) { + assert_eq!( + equivalent_by_complement(a, b), + a.equivalent_over_state_sets(b).unwrap(), + "equivalent disagrees on\n{a}\n{b}" + ); + assert_eq!( + subset_by_complement(a, b), + a.subset_over_state_sets(b).unwrap(), + "subset disagrees on\n{a}\n{b}" + ); + assert_eq!( + subset_by_complement(b, a), + b.subset_over_state_sets(a).unwrap(), + "subset disagrees on\n{b}\n{a}" + ); +} + +#[test] +fn matches_the_reference_on_patterns() { + let patterns = [ + "", + "a", + "a*", + ".*", + ".+", + "(a|b)*", + "(a*b*)*", + "(a|b)*abc(a|b)*", + "(a*b*)*abc(b*a*)*", + "(a|b)*a(a|b){6}", + "(a*b*)*a(a|b){6}", + "(a|b)*a(a|b){5}", + "(a|b)*a(a|b)*", + "(.*a.{4})|(.*b.{4})", + ".*[ab].{4}", + ".*abc.*def.*", + ".*abc.*(def).*x?", + "abc(de|fg){1,3}", + "abc.*", + "test.{0,9}other", + "test.{0,8}other", + r"\w+@\w+\.\w{2,3}", + r"[\w]+@\w*\w\.\w{2,3}", + r"\d+", + "[0-9]+|x", + ]; + let automata: Vec = patterns.iter().map(|p| automaton(p)).collect(); + let empty = FastAutomaton::new_empty(); + for a in automata.iter().chain([&empty]) { + let determinized = a.determinize().unwrap(); + assert!(a.equivalent_over_state_sets(&determinized).unwrap()); + assert!(determinized.equivalent_over_state_sets(a).unwrap()); + for b in automata.iter().chain([&empty]) { + assert_matches_reference(a, b); + assert_matches_reference(&determinized, b); + assert_difference_matches_reference(a, b); + assert_deterministic_equivalence_matches_reference(a, b); + } + } +} + +// The 2^(n+1) reachable sets of states all accept different languages, so +// nothing can be pruned, most recorded sets are contained in the queried one +// (the normal form search runs out of budget) and, once determinized, every +// recorded set is a singleton hanging off one wide trie node. +#[test] +fn matches_the_reference_when_nothing_can_be_pruned() { + let a = automaton("(a|b)*a(a|b){11}"); + let b = automaton("(a*b*)*a(a|b){11}"); + let c = automaton("(a|b)*a(a|b){11}|b{20}"); + assert!(a.equivalent_over_state_sets(&b).unwrap()); + assert!(!a.equivalent_over_state_sets(&c).unwrap()); + assert!(a.subset_over_state_sets(&c).unwrap()); + assert!(!c.subset_over_state_sets(&a).unwrap()); + + let (a, b) = (a.determinize().unwrap(), b.determinize().unwrap()); + assert!( + a.equivalent_over_state_sets(&c) + .is_ok_and(|equivalent| !equivalent) + ); + assert!(a.equivalent_over_state_sets(&b).unwrap()); + assert!(a.subset_over_state_sets(&b).unwrap()); + assert!( + c.equivalent_over_state_sets(&b) + .is_ok_and(|equivalent| !equivalent) + ); +} + +// Determinizing either operand takes at least 2^9 states, the walk fewer +// than 32 pairs. +#[test] +fn skips_what_the_recorded_pairs_imply() { + // United as automata: as a pattern, the union is simplified into `b`. + let a = FastAutomaton::union_all(&[ + automaton(".*a.{8}"), + automaton(".*b.{8}"), + automaton(".*c.{8}"), + ]) + .unwrap(); + let b = automaton(".*[abc].{8}"); + assert_ne!(a, b); + assert!(a.determinize().unwrap().number_of_states() >= 512); + assert!(b.determinize().unwrap().number_of_states() >= 512); + ExecutionProfileBuilder::new() + .max_number_of_states(32) + .build() + .run(|| { + assert!(a.equivalent(&b).unwrap()); + assert!(a.subset(&b).unwrap()); + assert!(b.subset(&a).unwrap()); + }); +} + +// The minuend only reaches a few of the sets of the subtrahend, which +// cannot be determinized under the same cap. +#[test] +fn difference_only_builds_the_pairs_a_word_reaches() { + let a = automaton("(a|b){0,6}"); + let b = automaton("(a|b)*a(a|b){11}"); + ExecutionProfileBuilder::new() + .max_number_of_states(200) + .build() + .run(|| { + assert_eq!( + b.determinize().unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + assert!(a.difference(&b).unwrap().equivalent(&a).unwrap()); + assert_eq!( + automaton("(a|b)*").difference(&b).unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + }); +} + +#[test] +fn respects_the_state_budget_and_the_timeout() { + let a = automaton("(a|b)*a(a|b){11}"); + let b = automaton("(a*b*)*a(a|b){11}"); + let (a_dfa, b_dfa) = (a.determinize().unwrap(), b.determinize().unwrap()); + ExecutionProfileBuilder::new() + .max_number_of_states(100) + .build() + .run(|| { + let err = EngineError::AutomatonHasTooManyStates; + assert_eq!(a.equivalent(&b).unwrap_err(), err); + assert_eq!(a.subset(&b).unwrap_err(), err); + assert_eq!(a_dfa.equivalent(&b_dfa).unwrap_err(), err); + }); + ExecutionProfileBuilder::new() + .execution_timeout(0) + .clock(|| { + use std::sync::atomic::{AtomicU64, Ordering}; + static READINGS: AtomicU64 = AtomicU64::new(0); + std::time::Duration::from_millis(READINGS.fetch_add(1, Ordering::Relaxed)) + }) + .build() + .run(|| { + let err = EngineError::OperationTimeOutError; + assert_eq!(a.equivalent(&b).unwrap_err(), err); + assert_eq!(a.subset(&b).unwrap_err(), err); + }); +} + +/// A random automaton of up to `max_states` states over ranges cut from +/// the first `letters` letters. Unreachable and dead states, empty languages +/// and non-determinism all occur. +fn arb_automaton(max_states: usize, letters: u8) -> impl Strategy { + arb_automaton_with(max_states, letters, false) +} + +/// [`arb_automaton`], with every transition going to a higher state when +/// `acyclic` is set: the language is then finite. +fn arb_automaton_with( + max_states: usize, + letters: u8, + acyclic: bool, +) -> impl Strategy { + (1..=max_states).prop_flat_map(move |states| { + ( + proptest::collection::vec(any::(), states), + proptest::collection::vec( + (0..states, 0..states, 0..letters, 0..letters), + 0..3 * states, + ), + ) + .prop_map(move |(accept, transitions)| { + let mut automaton = FastAutomaton::new_empty(); + for _ in 1..states { + automaton.new_state(); + } + for (state, accept) in accept.into_iter().enumerate() { + if accept { + automaton.accept(state); + } + } + for (from, to, x, y) in transitions { + let (from, to) = if acyclic { + (from.min(to), from.max(to)) + } else { + (from, to) + }; + if acyclic && from == to { + continue; + } + let (low, high) = (b'a' + x.min(y), b'a' + x.max(y)); + let range = + CharRange::new_from_range(Char::new(low as char)..=Char::new(high as char)); + automaton + .add_transition_from_range(from, to, &range) + .unwrap(); + } + automaton + }) + }) +} + +fn assert_matches_reference_and_itself(a: &FastAutomaton, b: &FastAutomaton) { + assert_matches_reference(a, b); + assert_difference_matches_reference(a, b); + assert_difference_matches_reference(b, a); + assert_deterministic_equivalence_matches_reference(a, b); + let determinized = a.determinize().unwrap(); + assert!(a.equivalent_over_state_sets(&determinized).unwrap()); + assert!(determinized.subset_over_state_sets(a).unwrap()); + // Same language as `a`, over the states of both. + let doubled = a.union(&determinized).unwrap(); + assert!(a.equivalent_over_state_sets(&doubled).unwrap()); + assert!(doubled.subset_over_state_sets(a).unwrap()); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + // Many letters: the operands rarely share a spanning set. + #[test] + fn matches_the_reference_on_random_automata( + a in arb_automaton(6, 6), + b in arb_automaton(6, 6), + ) { + assert_matches_reference_and_itself(&a, &b); + } + + // Two letters and more states: long walks over large sets, where + // pairs are skipped without having been met before. + #[test] + fn matches_the_reference_on_dense_random_automata( + a in arb_automaton(8, 2), + b in arb_automaton(8, 2), + ) { + assert_matches_reference_and_itself(&a, &b); + } + + // Finite languages over few letters: many paths spell the same string. + #[test] + fn cardinality_matches_the_determinized_count(a in arb_automaton_with(9, 3, true)) { + let determinized = a.determinize().unwrap(); + prop_assert!(determinized.is_deterministic()); + prop_assert_eq!(a.cardinality().unwrap(), determinized.cardinality().unwrap()); + } + + // Cycles included: the count is only reached when the language is finite. + #[test] + fn cardinality_matches_the_determinized_count_with_cycles(a in arb_automaton(5, 3)) { + prop_assert_eq!( + a.cardinality().unwrap(), + a.determinize().unwrap().cardinality().unwrap() + ); + } +} + +/// The number of strings over `a`, `b` and `c` of at most `max_length` +/// letters that `automaton` matches. +fn count_matches(automaton: &FastAutomaton, max_length: usize) -> u32 { + let mut strings = vec![String::new()]; + let mut count = 0; + for _ in 0..=max_length { + count += strings.iter().filter(|s| automaton.is_match(s)).count() as u32; + strings = strings + .iter() + .flat_map(|s| ["a", "b", "c"].map(|letter| format!("{s}{letter}"))) + .collect(); + } + count +} + +#[test] +fn cardinality_counts_each_string_once() { + // Several paths spell the same string in each of these: the count is + // checked against matching every string that is short enough. + for (pattern, max_length) in [ + ("(ab|a)(bc|c)?", 4), + ("(a|b|ab|ba){3}", 6), + ("(a|b){0,4}a(a|b){3}", 8), + ("a{2,5}b?a{0,3}", 9), + ] { + let a = automaton(pattern); + assert!(!a.is_deterministic(), "{pattern}"); + let expected = Cardinality::Integer(count_matches(&a, max_length)); + assert_eq!(a.cardinality().unwrap(), expected, "{pattern}"); + assert_eq!( + a.determinize().unwrap().cardinality().unwrap(), + expected, + "{pattern}" + ); + } + assert_eq!( + automaton("(ab|a)(bc|c)?").cardinality().unwrap(), + Cardinality::Integer(5) + ); + + for (pattern, expected) in [ + ( + r"((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)", + Cardinality::BigInteger, + ), + ("(a|b){0,4}a(a|b){40}", Cardinality::BigInteger), + ("(ab|a)(bc|c)*", Cardinality::Infinite), + ] { + let a = automaton(pattern); + assert!(!a.is_deterministic(), "{pattern}"); + assert_eq!(a.cardinality().unwrap(), expected, "{pattern}"); + } +} + +// The count overflows long before every set is visited: determinizing +// exceeds the same cap. +#[test] +fn cardinality_stops_at_the_first_overflow() { + let a = automaton("(a|b){0,20}a(a|b){40}"); + ExecutionProfileBuilder::new() + .max_number_of_states(1000) + .build() + .run(|| { + assert_eq!(a.cardinality().unwrap(), Cardinality::BigInteger); + assert_eq!( + a.determinize().unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + }); +} + +#[test] +fn cardinality_respects_the_state_budget() { + let a = automaton("(a|b){0,12}a(a|b){12}"); + ExecutionProfileBuilder::new() + .max_number_of_states(100) + .build() + .run(|| { + assert_eq!( + a.cardinality().unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + }); +} diff --git a/src/fast_automaton/analyze/state_sets.rs b/src/fast_automaton/analyze/state_sets.rs new file mode 100644 index 0000000..5d6a806 --- /dev/null +++ b/src/fast_automaton/analyze/state_sets.rs @@ -0,0 +1,343 @@ +//! What [`equivalent`](FastAutomaton::equivalent), +//! [`subset`](FastAutomaton::subset), +//! [`cardinality`](FastAutomaton::cardinality) and +//! [`difference`](FastAutomaton::difference) share: each walks the *sets* of +//! states a word can reach, the way subset construction would, without +//! determinizing an operand first. +//! +//! * [`Operand`] is one automaton prepared for that walk. +//! * [`SetTrie`] stores the sets met so far, and answers "which stored sets +//! are contained in this one", the inner loop of the two comparisons. +//! * [`Marks`] is a set with membership in constant time, which such a +//! question is asked about. + +use condition::converter::{ConditionConverter, SharedSpanningSet}; + +use crate::error::EngineError; + +use super::*; + +/// A state of an operand. Sets of states are sorted slices of ids, so their +/// cost follows the size of the set rather than the size of the automaton. +pub(crate) type Id = u32; + +/// One operand of a walk: its transitions restricted to its live states, and +/// projected on the spanning set shared by both operands when there are two. +/// +/// Dropping the states that cannot reach an accept state makes a set denote +/// the empty language iff it is empty, so "one side is stuck while the other +/// is not" is an immediate counterexample instead of a sub-search. +pub(crate) struct Operand { + /// State `s` has the id `offset + s`, which lets two operands share one + /// id space. + offset: usize, + /// Outgoing transitions by state, targets as ids. + transitions: Vec>, + accept: Vec, + /// The start state, unless it is not live (the language is then empty). + pub(crate) start: Option, +} + +impl Operand { + /// Prepares both operands over their merged spanning set, and returns + /// them with its number of bases (the letters of the walk). + pub(crate) fn pair( + left: &FastAutomaton, + left_offset: usize, + right: &FastAutomaton, + right_offset: usize, + ) -> Result<(Operand, Operand, usize), EngineError> { + let shared = SharedSpanningSet::new(&left.spanning_set, &right.spanning_set); + let (left_converter, right_converter) = shared.converters()?; + Ok(( + Operand::new(left, left_offset, left_converter.as_ref())?, + Operand::new(right, right_offset, right_converter.as_ref())?, + shared.spanning_set().spanning_ranges_with_rest_len(), + )) + } + + /// Prepares one operand; `converter` projects its conditions on another + /// spanning set than its own. + pub(crate) fn new( + automaton: &FastAutomaton, + offset: usize, + converter: Option<&ConditionConverter>, + ) -> Result { + let states = automaton.transitions.len(); + if Id::try_from(offset + states).is_err() { + return Err(EngineError::AutomatonHasTooManyStates); + } + let mut operand = Operand { + offset, + transitions: vec![Vec::new(); states], + accept: vec![false; states], + start: None, + }; + let live = automaton.live_states(); + for &state in live.iter().filter(|&&state| automaton.has_state(state)) { + operand.accept[state] = automaton.is_accepted(state); + for (condition, to_state) in automaton.transitions_from(state) { + if condition.is_empty() || !live.contains(to_state) { + continue; + } + let condition = match converter { + Some(converter) => converter.convert(condition)?, + None => condition.clone(), + }; + operand.transitions[state].push((condition, (offset + to_state) as Id)); + } + } + if live.contains(&automaton.start_state) { + operand.start = Some((offset + automaton.start_state) as Id); + } + Ok(operand) + } + + #[inline] + pub(crate) fn transitions_from(&self, id: Id) -> &[(Condition, Id)] { + &self.transitions[id as usize - self.offset] + } + + #[inline] + pub(crate) fn accepts(&self, id: Id) -> bool { + self.accept[id as usize - self.offset] + } + + #[inline] + pub(crate) fn is_accepting(&self, set: &[Id]) -> bool { + set.iter().any(|&id| self.accepts(id)) + } + + /// Writes the successors of `set` under each base into `out`, one sorted + /// set per base. + pub(crate) fn successors(&self, set: &[Id], out: &mut [Vec]) { + out.iter_mut().for_each(Vec::clear); + for &id in set { + for (condition, to) in self.transitions_from(id) { + for base in condition.iter_set_bits() { + out[base].push(*to); + } + } + } + for successors in out.iter_mut().filter(|successors| successors.len() > 1) { + successors.sort_unstable(); + successors.dedup(); + } + } +} + +/// Sorted sets stored as paths, each with values attached. The stored sets +/// contained in a queried set are found by descending only into the children +/// whose state the query holds, instead of scanning every stored set. +/// +/// One trie can hold several independent collections, each below its own +/// root node. +pub(super) struct SetTrie { + nodes: Vec>, +} + +pub(super) struct Node { + /// `(state, child)`, in insertion order. + children: Vec<(Id, usize)>, + /// `children` by state, once there are more than [`WIDE`] of them. + index: Option>, + /// The values of the sets ending at this node. + pub(super) values: Vec, +} + +/// The number of children past which a node is looked up by state instead of +/// scanned. A deterministic operand only yields singletons, which all hang +/// off the same node: scanning it would make every lookup linear in the +/// number of stored sets. +pub(super) const WIDE: usize = 16; + +impl Node { + /// The children, when they are few enough to be scanned; a wide node has + /// to be queried with [`child`](Self::child). + #[inline] + pub(super) fn few_children(&self) -> Option<&[(Id, usize)]> { + self.index.is_none().then_some(&self.children[..]) + } + + #[inline] + pub(super) fn child(&self, id: Id) -> Option { + match &self.index { + Some(index) => index.get(&id).copied(), + None => self + .children + .iter() + .find(|(state, _)| *state == id) + .map(|(_, child)| *child), + } + } +} + +impl SetTrie { + pub(super) fn new() -> Self { + SetTrie { nodes: Vec::new() } + } + + /// Adds a node, to be used as the root of a collection. + pub(super) fn new_root(&mut self) -> usize { + self.nodes.push(Node { + children: Vec::new(), + index: None, + values: Vec::new(), + }); + self.nodes.len() - 1 + } + + #[inline] + pub(super) fn node(&self, node: usize) -> &Node { + &self.nodes[node] + } + + /// Stores `set` below `root` and attaches `value` to it. + pub(super) fn insert(&mut self, root: usize, set: &[Id], value: T) { + let mut node = root; + for &id in set { + node = match self.nodes[node].child(id) { + Some(child) => child, + None => { + let child = self.new_root(); + let parent = &mut self.nodes[node]; + parent.children.push((id, child)); + match &mut parent.index { + Some(index) => { + index.insert(id, child); + } + None if parent.children.len() > WIDE => { + parent.index = Some(parent.children.iter().copied().collect()); + } + None => {} + } + child + } + }; + } + self.nodes[node].values.push(value); + } + + /// The values attached to exactly `set` below `root`. + pub(super) fn get(&self, root: usize, set: &[Id]) -> &[T] { + let mut node = &self.nodes[root]; + for &id in set { + match node.child(id) { + Some(child) => node = &self.nodes[child], + None => return &[], + } + } + &node.values + } + + /// Returns `true` if a set stored below `root` is contained in `set`. + pub(super) fn has_subset_of(&self, root: usize, set: &Marks) -> bool { + let node = &self.nodes[root]; + if !node.values.is_empty() { + return true; + } + match node.few_children() { + Some(children) => children + .iter() + .any(|&(id, child)| set.contains(id) && self.has_subset_of(child, set)), + None => set.members().iter().any(|&id| { + node.child(id) + .is_some_and(|child| self.has_subset_of(child, set)) + }), + } + } +} + +/// A set of states with membership in constant time, and reset in time +/// proportional to its size rather than to the number of states. +pub(super) struct Marks { + marked: Vec, + members: Vec, +} + +impl Marks { + pub(super) fn new(states: usize) -> Self { + Marks { + marked: vec![false; states], + members: Vec::new(), + } + } + + #[inline] + pub(super) fn contains(&self, id: Id) -> bool { + self.marked[id as usize] + } + + /// The states of the set, in insertion order. + #[inline] + pub(super) fn members(&self) -> &[Id] { + &self.members + } + + /// Returns `true` if `id` was not in the set yet. + #[inline] + pub(super) fn insert(&mut self, id: Id) -> bool { + let marked = &mut self.marked[id as usize]; + if *marked { + return false; + } + *marked = true; + self.members.push(id); + true + } + + pub(super) fn clear(&mut self) { + for id in self.members.drain(..) { + self.marked[id as usize] = false; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn has_subset_of_stays_below_its_root() { + let wide = 4 * WIDE as Id; + let mut trie = SetTrie::new(); + let (first, second) = (trie.new_root(), trie.new_root()); + let mut marks = Marks::new(2 * wide as usize); + let mut has_subset_of = |trie: &SetTrie<()>, root: usize, set: &[Id]| { + set.iter().for_each(|&id| assert!(marks.insert(id))); + let found = trie.has_subset_of(root, &marks); + marks.clear(); + found + }; + + trie.insert(first, &[1, 3], ()); + assert!(has_subset_of(&trie, first, &[1, 3])); + assert!(has_subset_of(&trie, first, &[1, 2, 3, 4])); + assert!(!has_subset_of(&trie, first, &[1, 2])); + assert!(!has_subset_of(&trie, first, &[3])); + assert!(!has_subset_of(&trie, second, &[1, 3])); + + // Enough children for the root to be looked up instead of scanned. + for id in 0..wide { + trie.insert(second, &[id, wide + id], ()); + } + assert!(trie.node(second).few_children().is_none()); + assert!(has_subset_of(&trie, second, &[5, wide + 5])); + assert!(has_subset_of(&trie, second, &[2, 5, wide + 5, wide + 6])); + assert!(!has_subset_of(&trie, second, &[5, wide + 6])); + assert!(!has_subset_of(&trie, first, &[5, wide + 5])); + } + + #[test] + fn get_returns_the_values_of_the_exact_set() { + let mut trie = SetTrie::new(); + let root = trie.new_root(); + trie.insert(root, &[1, 2], 'a'); + trie.insert(root, &[1, 2], 'b'); + trie.insert(root, &[1], 'c'); + assert_eq!(trie.get(root, &[1, 2]), ['a', 'b']); + assert_eq!(trie.get(root, &[1]), ['c']); + assert!(trie.get(root, &[2]).is_empty()); + assert!(trie.get(root, &[1, 2, 3]).is_empty()); + } +} diff --git a/src/fast_automaton/analyze/subset.rs b/src/fast_automaton/analyze/subset.rs index da9e4d0..619a147 100644 --- a/src/fast_automaton/analyze/subset.rs +++ b/src/fast_automaton/analyze/subset.rs @@ -1,30 +1,107 @@ -use crate::error::EngineError; +use crate::{error::EngineError, execution_profile::ExecutionProfile}; +use super::state_sets::{Marks, Operand, SetTrie}; use super::*; impl FastAutomaton { /// Returns `true` if all strings accepted by `self` are also accepted by `other`. /// - /// A non-deterministic `other` is determinized internally, unless the - /// execution profile disables implicit determinization, in which case - /// [`EngineError::DeterministicAutomatonRequired`] is returned. + /// Non-deterministic operands are not determinized: each state of `self` + /// is walked together with the set of states of `other` that the same + /// word reaches, and a pair is skipped when the same state was already + /// met with a subset of that set (antichains). The walk is still + /// exponential in `other` in the worst case; the execution profile's + /// timeout applies, and its `max_number_of_states` caps the number of + /// pairs walked. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn subset(&self, other: &FastAutomaton) -> Result { if self.is_empty() || other.is_total() || self == other { return Ok(true); } else if other.is_empty() { return Ok(false); - } else if self.is_total() { - // self ⊆ other iff Σ* ⊆ other iff other = Σ*. We already failed - // the cheap `other.is_total()` check above; that check is sound - // but conservative on NFAs, so retry on the determinized form. - return Ok(other.determinize_implicit()?.is_total()); } + self.subset_over_state_sets(other) + } - let mut other = other.determinize_implicit()?.into_owned(); - other.complement()?; + /// The antichain algorithm of De Wulf, Doyen, Henzinger & Raskin, + /// *Antichains: A New Algorithm for Checking Universality of Finite + /// Automata* (CAV 2006, section 5), in the forward form that Bonchi & Pous + /// describe (section 4). + /// + /// The walk visits the pairs `(x, Y)` of a state of `self` and the set of + /// `other`'s states that one word reaches. A pair is a counterexample + /// when `x` accepts and `Y` does not, or when `Y` is empty (`x` is live). + /// It is skipped when `(x, Y')` was met for some `Y' ⊆ Y`. The pairs + /// kept are not a strict antichain: a pair met earlier with a superset + /// of `Y` is not removed, which costs memory but skips the same pairs. + /// + /// Inclusion is also the equivalence `self ∪ other ≡ other`, but + /// [`equivalent_over_state_sets`](Self::equivalent_over_state_sets) + /// would skip no more pairs: between two automata with no state in + /// common, the two criteria match (Bonchi & Pous, section 4.2.2). + pub(super) fn subset_over_state_sets( + &self, + other: &FastAutomaton, + ) -> Result { + let execution_profile = ExecutionProfile::get(); + + let (left, right, bases) = Operand::pair(self, 0, other, 0)?; + + let Some(start) = left.start else { + return Ok(true); + }; + let Some(right_start) = right.start else { + return Ok(false); + }; + if left.accepts(start) && !right.accepts(right_start) { + return Ok(false); + } - Ok(!self.has_intersection(&other)?) + // The sets each state of `self` was met with, one collection per + // state, created on first use. + let mut visited = SetTrie::new(); + let mut roots: Vec> = vec![None; self.transitions.len()]; + let mut worklist = VecDeque::new(); + let root = visited.new_root(); + roots[start as usize] = Some(root); + visited.insert(root, &[right_start], ()); + // The sets of the queued pairs, back to back. + let mut sets = vec![right_start]; + worklist.push_back((start, 0..1)); + + let mut successors = vec![Vec::new(); bases]; + let mut query = Marks::new(other.transitions.len()); + let mut pairs = 1; + + while let Some((state, set)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(pairs)?; + + right.successors(&sets[set], &mut successors); + + for (condition, to_state) in left.transitions_from(state) { + for base in condition.iter_set_bits() { + let set = &successors[base]; + if set.is_empty() || (left.accepts(*to_state) && !right.is_accepting(set)) { + return Ok(false); + } + let root = *roots[*to_state as usize].get_or_insert_with(|| visited.new_root()); + set.iter().for_each(|&id| { + query.insert(id); + }); + let met = visited.has_subset_of(root, &query); + query.clear(); + if met { + continue; + } + visited.insert(root, set, ()); + worklist.push_back((*to_state, sets.len()..sets.len() + set.len())); + sets.extend_from_slice(set); + pairs += 1; + } + } + } + Ok(true) } } diff --git a/src/fast_automaton/builder.rs b/src/fast_automaton/builder.rs index 7330548..6825e36 100644 --- a/src/fast_automaton/builder.rs +++ b/src/fast_automaton/builder.rs @@ -340,7 +340,7 @@ impl FastAutomaton { } self.minimal = false; self.accept_states.remove(&state); - self.transitions_in.remove(&state); + self.unlink_state(state); if self.transitions.len() - 1 == state { self.transitions.remove(state); @@ -354,12 +354,20 @@ impl FastAutomaton { self.transitions[state].clear(); self.removed_states.insert(state); } + } - for transitions in self.transitions.iter_mut() { - transitions.remove(&state); + /// Removes every transition from or to `state`, in time proportional to + /// their number. + fn unlink_state(&mut self, state: State) { + if let Some(predecessors) = self.transitions_in.remove(&state) { + for predecessor in predecessors { + self.transitions[predecessor].remove(&state); + } } - for transitions in self.transitions_in.values_mut() { - transitions.remove(&state); + for (successor, _) in std::mem::take(&mut self.transitions[state]) { + if let Some(predecessors) = self.transitions_in.get_mut(&successor) { + predecessors.remove(&state); + } } } @@ -381,6 +389,9 @@ impl FastAutomaton { self.minimal = false; + for &state in states { + self.unlink_state(state); + } for &state in states { if self.transitions.len() - 1 == state { self.transitions.remove(state); @@ -396,25 +407,6 @@ impl FastAutomaton { self.removed_states.insert(state); } } - - for transitions in self.transitions.iter_mut() { - for state in states { - if transitions.is_empty() { - break; - } - - transitions.remove(state); - } - } - - for state in states { - self.transitions_in.remove(state); - } - for predecessors in self.transitions_in.values_mut() { - for state in states { - predecessors.remove(state); - } - } } /// Recompute a minimal spanning set for the automaton and apply it. diff --git a/src/fast_automaton/condition/converter.rs b/src/fast_automaton/condition/converter.rs index 624ba4d..6ec9df4 100644 --- a/src/fast_automaton/condition/converter.rs +++ b/src/fast_automaton/condition/converter.rs @@ -96,6 +96,56 @@ impl<'a, 'b> ConditionConverter<'a, 'b> { } } +/// The spanning set two automata have to be projected on before they can be +/// walked together: their own when they already share it, the merge of the +/// two otherwise. +pub(crate) struct SharedSpanningSet<'a> { + left: &'a SpanningSet, + right: &'a SpanningSet, + /// `None` when `left` and `right` are equal (the dominant case in + /// operation chains), which needs no merge and no projection at all. + merged: Option, +} + +impl<'a> SharedSpanningSet<'a> { + pub(crate) fn new(left: &'a SpanningSet, right: &'a SpanningSet) -> Self { + SharedSpanningSet { + left, + right, + merged: (left != right).then(|| left.merge(right)), + } + } + + pub(crate) fn spanning_set(&self) -> &SpanningSet { + self.merged.as_ref().unwrap_or(self.left) + } + + pub(crate) fn into_spanning_set(self) -> SpanningSet { + self.merged.unwrap_or_else(|| self.left.clone()) + } + + /// The converters projecting the conditions of the left and of the right + /// automaton on the shared spanning set, or `None` for both when their + /// conditions are already expressed over it. + pub(crate) fn converters( + &self, + ) -> Result< + ( + Option>, + Option>, + ), + EngineError, + > { + let Some(merged) = &self.merged else { + return Ok((None, None)); + }; + Ok(( + Some(ConditionConverter::new(self.left, merged)?), + Some(ConditionConverter::new(self.right, merged)?), + )) + } +} + #[cfg(test)] mod tests { use crate::CharRange; diff --git a/src/fast_automaton/condition/fast_bit_vec/mod.rs b/src/fast_automaton/condition/fast_bit_vec/mod.rs index 481b157..803a4e2 100644 --- a/src/fast_automaton/condition/fast_bit_vec/mod.rs +++ b/src/fast_automaton/condition/fast_bit_vec/mod.rs @@ -131,6 +131,19 @@ impl FastBitVec { false } + /// Returns `true` if every bit set in `self` is set in `other`. + #[inline] + pub fn is_subset(&self, other: &Self) -> bool { + self.assert_same_len(other); + self.bits.iter().zip(&other.bits).all(|(a, b)| *a & !b == 0) + } + + /// Clears every bit. + #[inline] + pub fn clear(&mut self) { + self.bits.fill(0); + } + #[inline] pub fn empty(&self) -> bool { self.bits.iter().all(|w| w == &0) diff --git a/src/fast_automaton/condition/mod.rs b/src/fast_automaton/condition/mod.rs index 6dcad59..558d104 100644 --- a/src/fast_automaton/condition/mod.rs +++ b/src/fast_automaton/condition/mod.rs @@ -88,6 +88,12 @@ impl Condition { cond } + /// Adds base `i` to the condition (see [`single_base`](Self::single_base)). + #[inline] + pub(crate) fn insert_base(&mut self, i: usize) { + self.0.set(i, true); + } + /// Converts this `Condition` back to the [`CharRange`] it represents, /// evaluated against `spanning_set`. /// @@ -156,6 +162,19 @@ impl Condition { new_cond } + /// Returns `true` if every character of `self` is in `other`. Both must + /// share the same spanning set. + #[inline] + pub(crate) fn is_subset_of(&self, other: &Condition) -> bool { + self.0.is_subset(&other.0) + } + + /// Makes the condition match no character. + #[inline] + pub(crate) fn clear(&mut self) { + self.0.clear(); + } + /// Returns `true` if `self` and `other` share at least one character (their /// intersection is non-empty). Both must share the same spanning set. #[inline] diff --git a/src/fast_automaton/generate.rs b/src/fast_automaton/generate.rs index ea9101c..b34cfc4 100644 --- a/src/fast_automaton/generate.rs +++ b/src/fast_automaton/generate.rs @@ -206,7 +206,7 @@ impl GenerationOptions { /// generates nothing. /// /// A [`CharRange`] is built from bounds, or out of a character class - /// pattern through [`RegularExpression`](crate::regex::RegularExpression): + /// pattern through [`RegularExpression`]: /// /// ``` /// use regexsolver::{CharRange, regex::RegularExpression}; diff --git a/src/fast_automaton/mod.rs b/src/fast_automaton/mod.rs index 0596e63..1a1dec4 100644 --- a/src/fast_automaton/mod.rs +++ b/src/fast_automaton/mod.rs @@ -180,7 +180,10 @@ impl FastAutomaton { /// Returns an iterator over transitions from the given state. /// Returns an empty iterator if the state does not exist. #[inline] - pub fn transitions_from(&self, state: State) -> impl Iterator { + pub fn transitions_from( + &self, + state: State, + ) -> impl Iterator + Clone { self.transitions.get(state).into_iter().flat_map(move |t| { t.iter() .map(|(s, c)| (c, s)) diff --git a/src/fast_automaton/operation/difference.rs b/src/fast_automaton/operation/difference.rs index b5410c6..cbc9074 100644 --- a/src/fast_automaton/operation/difference.rs +++ b/src/fast_automaton/operation/difference.rs @@ -1,6 +1,9 @@ use std::hash::BuildHasherDefault; -use crate::EngineError; +use condition::converter::SharedSpanningSet; + +use crate::fast_automaton::analyze::state_sets::{Id, Operand}; +use crate::{EngineError, execution_profile::ExecutionProfile}; use super::*; @@ -72,14 +75,93 @@ impl FastAutomaton { /// Computes the difference between `self` and `other`. /// - /// If `other` is non-deterministic, it is determinized first, unless - /// the execution profile disables implicit determinization, in which - /// case [`EngineError::DeterministicAutomatonRequired`] is returned. + /// `other` is not determinized or complemented first: a state of the + /// result pairs a state of `self` with the set of states of `other` that + /// the same word reaches, and only the pairs a word reaches are built. + /// The result is still exponential in `other` in the worst case; the + /// execution profile's timeout and `max_number_of_states` apply to it. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn difference(&self, other: &FastAutomaton) -> Result { - let mut complement = other.determinize_implicit()?.into_owned(); - complement.complement()?; - self.intersection(&complement) + if self.is_empty() || other.is_total() || self == other { + return Ok(Self::new_empty()); + } else if other.is_empty() { + return Ok(self.clone()); + } + let execution_profile = ExecutionProfile::get(); + + let shared = SharedSpanningSet::new(&self.spanning_set, &other.spanning_set); + let (self_converter, other_converter) = shared.converters()?; + let left = Operand::new(self, 0, self_converter.as_ref())?; + let right = Operand::new(other, 0, other_converter.as_ref())?; + let spanning_set = shared.spanning_set(); + + let Some(start) = left.start else { + return Ok(Self::new_empty()); + }; + + let mut difference = FastAutomaton::new_empty(); + // The sets of the pairs, back to back. + let mut sets: Vec = right.start.into_iter().collect(); + if left.accepts(start) && !right.is_accepting(&sets) { + difference.accept(difference.start_state); + } + // The state of each pair, keyed by the state of `self` followed by + // the set of states of `other`. + let mut states: AHashMap, State> = AHashMap::new(); + let mut key = vec![start]; + key.extend_from_slice(&sets); + states.insert(key.clone(), difference.start_state); + let mut worklist = VecDeque::new(); + worklist.push_back((difference.start_state, start, 0..sets.len())); + + let mut successors = vec![Vec::new(); spanning_set.spanning_ranges_with_rest_len()]; + // The pairs one transition of `self` leads to: the state of the + // pair, a base that leads to it, and all the bases that do. + let mut targets: Vec<(State, usize, Condition)> = Vec::new(); + + while let Some((state, from, set)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(difference.number_of_states())?; + + right.successors(&sets[set], &mut successors); + + for (condition, to) in left.transitions_from(from) { + targets.clear(); + for base in condition.iter_set_bits() { + let set = &successors[base]; + if let Some((_, _, bases)) = targets + .iter_mut() + .find(|(_, other_base, _)| successors[*other_base] == *set) + { + bases.insert_base(base); + continue; + } + key.clear(); + key.push(*to); + key.extend_from_slice(set); + let target = match states.get(key.as_slice()) { + Some(target) => *target, + None => { + let target = difference.new_state(); + if left.accepts(*to) && !right.is_accepting(set) { + difference.accept(target); + } + states.insert(key.clone(), target); + worklist.push_back((target, *to, sets.len()..sets.len() + set.len())); + sets.extend_from_slice(set); + target + } + }; + targets.push((target, base, Condition::single_base(base, spanning_set))); + } + for (target, _, bases) in &targets { + difference.add_transition(state, *target, bases); + } + } + } + difference.spanning_set = shared.into_spanning_set(); + difference.remove_dead_states(); + Ok(difference) } } diff --git a/src/fast_automaton/operation/intersection.rs b/src/fast_automaton/operation/intersection.rs index 6d4b1a6..2bfd0aa 100644 --- a/src/fast_automaton/operation/intersection.rs +++ b/src/fast_automaton/operation/intersection.rs @@ -1,6 +1,8 @@ use std::borrow::Cow; -use condition::converter::ConditionConverter; +use ahash::AHashSet; + +use condition::converter::{ConditionConverter, SharedSpanningSet}; use crate::{error::EngineError, execution_profile::ExecutionProfile}; @@ -72,31 +74,9 @@ impl FastAutomaton { } let execution_profile = ExecutionProfile::get(); - // Equal spanning sets (the dominant case in operation chains) need no - // merge and no condition projection at all. - let same_spanning_set = self.spanning_set == other.spanning_set; - let new_spanning_set = if same_spanning_set { - self.spanning_set.clone() - } else { - self.spanning_set.merge(&other.spanning_set) - }; - - let condition_converter_self_to_new = if same_spanning_set { - None - } else { - Some(ConditionConverter::new( - &self.spanning_set, - &new_spanning_set, - )?) - }; - let condition_converter_other_to_new = if same_spanning_set { - None - } else { - Some(ConditionConverter::new( - &other.spanning_set, - &new_spanning_set, - )?) - }; + let shared = SharedSpanningSet::new(&self.spanning_set, &other.spanning_set); + let (condition_converter_self_to_new, condition_converter_other_to_new) = + shared.converters()?; let mut projected_self: IntMap> = IntMap::default(); let mut projected_other: IntMap> = IntMap::default(); @@ -154,12 +134,17 @@ impl FastAutomaton { } } } - new_automaton.spanning_set = new_spanning_set; + new_automaton.spanning_set = shared.into_spanning_set(); new_automaton.remove_dead_states(); Ok(Cow::Owned(new_automaton)) } /// Returns `true` if the two automata have a non-empty intersection. + /// + /// The intersection is not built: the pairs of states the two automata + /// reach together are visited until one has both states accepting. The + /// execution profile's timeout applies, and its `max_number_of_states` + /// caps the number of pairs visited. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), other_states = other.number_of_states()))] pub fn has_intersection(&self, other: &FastAutomaton) -> Result { if self.is_empty() || other.is_empty() { @@ -169,83 +154,44 @@ impl FastAutomaton { } let execution_profile = ExecutionProfile::get(); - let same_spanning_set = self.spanning_set == other.spanning_set; - let new_spanning_set = if same_spanning_set { - self.spanning_set.clone() - } else { - self.spanning_set.merge(&other.spanning_set) - }; - - let condition_converter_self_to_new = if same_spanning_set { - None - } else { - Some(ConditionConverter::new( - &self.spanning_set, - &new_spanning_set, - )?) - }; - let condition_converter_other_to_new = if same_spanning_set { - None - } else { - Some(ConditionConverter::new( - &other.spanning_set, - &new_spanning_set, - )?) - }; + let shared = SharedSpanningSet::new(&self.spanning_set, &other.spanning_set); + let (condition_converter_self_to_new, condition_converter_other_to_new) = + shared.converters()?; let mut projected_self: IntMap> = IntMap::default(); let mut projected_other: IntMap> = IntMap::default(); - let mut new_automaton = FastAutomaton::new_empty(); let mut worklist = VecDeque::with_capacity(self.number_of_states() + other.number_of_states()); - let mut new_states: AHashMap<(usize, usize), (usize, usize, usize), _> = - AHashMap::with_capacity(self.number_of_states() + other.number_of_states()); - - let initial_pair = ( - new_automaton.start_state, - self.start_state, - other.start_state, - ); + let mut visited: AHashSet<(usize, usize)> = + AHashSet::with_capacity(self.number_of_states() + other.number_of_states()); - worklist.push_back(initial_pair); - new_states.insert((self.start_state, other.start_state), initial_pair); + worklist.push_back((self.start_state, other.start_state)); + visited.insert((self.start_state, other.start_state)); - while let Some(p) = worklist.pop_front() { + while let Some((state, other_state)) = worklist.pop_front() { execution_profile.assert_not_timed_out()?; - execution_profile.assert_max_number_of_states(new_states.len())?; - if self.accept_states.contains(&p.1) && other.accept_states.contains(&p.2) { + execution_profile.assert_max_number_of_states(visited.len())?; + if self.accept_states.contains(&state) && other.accept_states.contains(&other_state) { return Ok(true); } let transitions_1 = self.projected_transitions( &mut projected_self, - p.1, + state, condition_converter_self_to_new.as_ref(), )?; let transitions_2 = other.projected_transitions( &mut projected_other, - p.2, + other_state, condition_converter_other_to_new.as_ref(), )?; for (condition_1, n1) in transitions_1 { for (condition_2, n2) in transitions_2 { - let intersection = condition_1.intersection(condition_2); - if intersection.is_empty() { - continue; + if condition_1.has_intersection(condition_2) && visited.insert((*n1, *n2)) { + worklist.push_back((*n1, *n2)); } - let k = (*n1, *n2); - let r = match new_states.get(&k) { - Some(new_r) => *new_r, - None => { - let new_r = (new_automaton.new_state(), *n1, *n2); - worklist.push_back(new_r); - new_states.insert(k, new_r); - new_r - } - }; - new_automaton.add_transition(p.0, r.0, &intersection); } } } diff --git a/src/fast_automaton/operation/union.rs b/src/fast_automaton/operation/union.rs index 0380f00..5775240 100644 --- a/src/fast_automaton/operation/union.rs +++ b/src/fast_automaton/operation/union.rs @@ -298,8 +298,8 @@ impl FastAutomaton { self.union_state_count_nondegenerate(other) } - /// [`union_state_count_heuristic`](Self::union_state_count_heuristic) for - /// operands already known to be non-degenerate: no emptiness walks. + /// The test-only `union_state_count_heuristic` for operands already known + /// to be non-degenerate: no emptiness walks. fn union_state_count_nondegenerate(&self, other: &FastAutomaton) -> usize { let v1 = self.number_of_states(); let v2 = other.number_of_states(); diff --git a/src/lib.rs b/src/lib.rs index 5f0de56..3fe5e75 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -502,14 +502,12 @@ impl Term { /// ``` #[tracing::instrument(level = "debug", skip_all, fields(self_deterministic = self.is_deterministic(), other_deterministic = other.is_deterministic()))] pub fn difference(&self, other: &Term) -> Result { - Self::run_with_implicit_determinization(|| { - let minuend_automaton = self.to_automaton()?; - let subtrahend_automaton = other.to_automaton()?; - // `FastAutomaton::difference` determinizes the subtrahend itself. - let return_automaton = minuend_automaton.difference(&subtrahend_automaton)?; + let minuend_automaton = self.to_automaton()?; + let subtrahend_automaton = other.to_automaton()?; - Ok(Term::Automaton(return_automaton)) - }) + Ok(Term::Automaton( + minuend_automaton.difference(&subtrahend_automaton)?, + )) } /// Computes the complement of `self`. @@ -804,11 +802,9 @@ impl Term { return Ok(true); } - Self::run_with_implicit_determinization(|| { - let automaton_1 = self.to_automaton()?; - let automaton_2 = other.to_automaton()?; - automaton_1.equivalent(&automaton_2) - }) + let automaton_1 = self.to_automaton()?; + let automaton_2 = other.to_automaton()?; + automaton_1.equivalent(&automaton_2) } /// Returns `true` if all strings matched by the current term are also matched by the given term. @@ -829,11 +825,9 @@ impl Term { return Ok(true); } - Self::run_with_implicit_determinization(|| { - let automaton_1 = self.to_automaton()?; - let automaton_2 = other.to_automaton()?; - automaton_1.subset(&automaton_2) - }) + let automaton_1 = self.to_automaton()?; + let automaton_2 = other.to_automaton()?; + automaton_1.subset(&automaton_2) } /// Returns `true` if the term matches the given string. @@ -898,7 +892,10 @@ impl Term { } else if automaton.is_deterministic() { Ok(false) } else { - Ok(automaton.determinize()?.is_total()) + // `FastAutomaton::is_total` is conservative on a + // non-deterministic automaton; inclusion of every string is exact + // and does not determinize it. + FastAutomaton::new_total().subset(&automaton) } } @@ -968,7 +965,7 @@ impl Term { /// truncated value. Infinite languages return `Cardinality::Infinite`. #[tracing::instrument(level = "debug", skip_all, fields(self_deterministic = self.is_deterministic()))] pub fn cardinality(&self) -> Result, EngineError> { - Self::run_with_implicit_determinization(|| self.to_automaton()?.cardinality()) + self.to_automaton()?.cardinality() } /// Returns `true` if the term matches a finite number of strings. @@ -986,7 +983,10 @@ impl Term { /// assert!(!Term::from_pattern("a+").unwrap().is_finite().unwrap()); /// ``` pub fn is_finite(&self) -> Result { - Ok(!matches!(self.cardinality()?, Cardinality::Infinite)) + // Finiteness only depends on the cycles of the accepting paths, which + // `length` looks for; counting the strings can be far more work. + let automaton = self.to_automaton()?; + Ok(automaton.is_empty() || automaton.length().1.is_some()) } /// Converts the term to a [`FastAutomaton`]. @@ -1355,6 +1355,29 @@ mod tests { .unwrap() ); assert!(!Term::from_pattern("a+").unwrap().is_finite().unwrap()); + + for pattern in [ + "", + "a", + "a*", + ".*", + "(ab|a)(bc|c)?", + "(a|b){0,4}a(a|b){3}", + "[]", + "(a|b)*a(a|b){3}", + "abc.*", + "x{2,5}", + ] { + let term = Term::from_pattern(pattern).unwrap(); + for term in [term.determinize().unwrap(), term] { + assert_eq!( + term.is_finite().unwrap(), + !matches!(term.cardinality().unwrap(), Cardinality::Infinite), + "{pattern}" + ); + } + } + assert!(Term::new_empty().is_finite().unwrap()); } #[test] diff --git a/tests/proptest_strategies.rs b/tests/proptest_strategies.rs index 162381c..db6f99a 100644 --- a/tests/proptest_strategies.rs +++ b/tests/proptest_strategies.rs @@ -435,7 +435,6 @@ fn assert_set_ops_membership( ); } } - // `difference` determinizes the subtrahend itself. if let Some(diff) = bounded(|| a.difference(b)) { for s in probes { prop_assert_eq!( From e7b3a34c2e00cdca303f574311762b58fbdbfe94 Mon Sep 17 00:00:00 2001 From: Alexandre van Beurden <1949482+alexvbrdn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:26:12 +0100 Subject: [PATCH 2/4] Move the union state count's degenerate cases into the tests Since #11, `union_mut_nondegenerate` checks the state limit with `union_state_count_nondegenerate`, and only `test_heuristic` used `union_state_count_heuristic`, which added the degenerate cases and was kept in the `impl` behind `#[cfg(test)]`. It is now a helper of the tests module, and the remaining count is `union_state_count`. --- src/fast_automaton/operation/union.rs | 42 ++++++++++++--------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/src/fast_automaton/operation/union.rs b/src/fast_automaton/operation/union.rs index 5775240..e261b3e 100644 --- a/src/fast_automaton/operation/union.rs +++ b/src/fast_automaton/operation/union.rs @@ -229,9 +229,7 @@ impl FastAutomaton { /// them on the growing result at every fold step made large alternations /// quadratic. fn union_mut_nondegenerate(&mut self, other: &FastAutomaton) -> Result<(), EngineError> { - self.assert_nondegenerate_operation_fits(other, || { - self.union_state_count_nondegenerate(other) - })?; + self.assert_nondegenerate_operation_fits(other, || self.union_state_count(other))?; // Equal spanning sets (the dominant case in `union_all` folds) skip // the quadratic merge and treat every condition conversion as identity. @@ -282,25 +280,11 @@ impl FastAutomaton { Ok(()) } - /// Computes the expected number of states after calling `union_mut`. - /// Kept as the specification of the union's state growth; the exactness - /// tests validate it against `union_mut`, and the non-degenerate half - /// backs the state-limit check in the union core. - #[cfg(test)] - fn union_state_count_heuristic(&self, other: &FastAutomaton) -> usize { - // Edge cases - if other.is_empty() || self.is_total() { - return self.number_of_states(); - } else if other.is_total() || self.is_empty() { - return other.number_of_states(); - } - - self.union_state_count_nondegenerate(other) - } - - /// The test-only `union_state_count_heuristic` for operands already known - /// to be non-degenerate: no emptiness walks. - fn union_state_count_nondegenerate(&self, other: &FastAutomaton) -> usize { + /// The number of states [`union_mut_nondegenerate`](Self::union_mut_nondegenerate) + /// leaves `self` with, computed without building the union, which backs + /// its state-limit check. Like it, assumes neither operand is `∅` or + /// `Σ*`, so it never walks them to check. + fn union_state_count(&self, other: &FastAutomaton) -> usize { let v1 = self.number_of_states(); let v2 = other.number_of_states(); @@ -657,6 +641,18 @@ mod tests { Ok(()) } + /// The number of states `union_mut` leaves `a1` with: the degenerate + /// cases it handles itself, and `union_state_count` for the rest. + fn expected_union_states(a1: &FastAutomaton, a2: &FastAutomaton) -> usize { + if a2.is_empty() || a1.is_total() { + a1.number_of_states() + } else if a2.is_total() || a1.is_empty() { + a2.number_of_states() + } else { + a1.union_state_count(a2) + } + } + fn assert_heuristic(regex1: &str, regex2: &str) { println!("Testing union heuristic for: '{}' | '{}'", regex1, regex2); @@ -675,7 +671,7 @@ mod tests { actual_union.union_mut(a2).unwrap(); let actual_states = actual_union.number_of_states(); - let heuristic_states = a1.union_state_count_heuristic(a2); + let heuristic_states = expected_union_states(a1, a2); assert_eq!( actual_states, heuristic_states, From fbca8c1d90814309c674e3ce93dc709378f83886 Mon Sep 17 00:00:00 2001 From: Alexandre van Beurden <1949482+alexvbrdn@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:41:02 +0100 Subject: [PATCH 3/4] Update mod.rs --- src/fast_automaton/condition/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fast_automaton/condition/mod.rs b/src/fast_automaton/condition/mod.rs index 558d104..9b4b880 100644 --- a/src/fast_automaton/condition/mod.rs +++ b/src/fast_automaton/condition/mod.rs @@ -84,7 +84,7 @@ impl Condition { #[inline] pub(crate) fn single_base(i: usize, spanning_set: &SpanningSet) -> Self { let mut cond = Self::empty(spanning_set); - cond.0.set(i, true); + cond.insert_base(i); cond } From d17c4c41904fd80041ae17bed0479d50462bda2c Mon Sep 17 00:00:00 2001 From: Alexandre van Beurden <1949482+alexvbrdn@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:14:13 +0100 Subject: [PATCH 4/4] Add symmetric_difference, fix regex emptiness and concatenation `FastAutomaton::symmetric_difference`, `symmetric_difference_all` and `symmetric_difference_all_par`, and `Term::symmetric_difference`, built like `difference` without determinizing an operand. `difference` leaves out the pairs that reach no accept state as it builds its result. `SetTrie::has_subset_of` no longer recurses per state of a stored set, which overflowed the stack of a thread in `subset`. Regular expressions: concatenation folds in place, in time linear in the number of expressions, and parsing checks the timeout as it concatenates; `Term::union` of regular expressions respects the timeout; `is_empty`, `is_empty_string` and `length` are exact on expressions that are not simplified. Rewrites the documentation of the public API. --- CHANGELOG.md | 8 + README.md | 2 +- benches/operations.rs | 86 ++- src/cardinality/mod.rs | 9 +- src/error/mod.rs | 36 +- src/execution_profile.rs | 191 +++--- src/fast_automaton/analyze/cardinality.rs | 19 +- src/fast_automaton/analyze/equivalence.rs | 18 +- src/fast_automaton/analyze/length.rs | 14 +- src/fast_automaton/analyze/mod.rs | 68 +- src/fast_automaton/analyze/reference_tests.rs | 73 +- src/fast_automaton/analyze/state_sets.rs | 56 +- src/fast_automaton/analyze/subset.rs | 59 +- src/fast_automaton/builder.rs | 175 +++-- src/fast_automaton/condition/converter.rs | 24 +- src/fast_automaton/condition/mod.rs | 97 +-- src/fast_automaton/convert/to_regex/mod.rs | 24 +- .../convert/to_regex/neural_synthesis/hub.rs | 7 +- .../convert/to_regex/neural_synthesis/mod.rs | 196 +++--- src/fast_automaton/generate.rs | 199 +++--- src/fast_automaton/mod.rs | 97 ++- src/fast_automaton/operation/concat.rs | 8 +- src/fast_automaton/operation/determinize.rs | 7 +- src/fast_automaton/operation/difference.rs | 648 ++++++++++++++++-- src/fast_automaton/operation/intersection.rs | 22 +- src/fast_automaton/operation/minimize.rs | 15 +- src/fast_automaton/operation/mod.rs | 6 +- src/fast_automaton/operation/repeat.rs | 6 +- src/fast_automaton/operation/union.rs | 14 +- src/fast_automaton/spanning_set/mod.rs | 52 +- src/lib.rs | 392 ++++++----- src/regex/analyze/affixes.rs | 8 +- src/regex/analyze/mod.rs | 83 ++- src/regex/builder.rs | 58 +- src/regex/mod.rs | 144 ++-- src/regex/operation/concat.rs | 190 ++--- src/regex/operation/repeat.rs | 36 +- src/regex/operation/simplify.rs | 7 +- src/regex/operation/union.rs | 29 +- tests/proptest_strategies.rs | 57 +- tests/public_api.rs | 113 +++ 41 files changed, 2184 insertions(+), 1169 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91322f5..f0d8468 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added - `Term::to_pattern_with`, the pattern of `Term::to_regex_with`. +- `FastAutomaton::symmetric_difference`, the strings that exactly one of two automata accepts. Like `difference`, it does not determinize or complement an operand, and the result is deterministic when both operands are. +- `FastAutomaton::symmetric_difference_all` and `FastAutomaton::symmetric_difference_all_par`, the strings that an odd number of the given automata accepts, and `Term::symmetric_difference`, which takes several terms like `Term::union` and `Term::intersection`. The automata are walked together rather than two by two, none of them is determinized, and the result is deterministic when every automaton is. Like `union_all_par` and `intersection_all_par`, `symmetric_difference_all_par` needs the `parallel` feature and is absent on `wasm`. ### Changed - `equivalent` and `subset`, on `FastAutomaton` and on `Term`, no longer determinize or complement their operands. They walk the sets of states a word can reach in each automaton and skip the pairs that follow from the ones already met: bisimulation up to congruence (Bonchi & Pous, POPL 2013) for `equivalent`, antichains (De Wulf, Doyen, Henzinger & Raskin, CAV 2006) for `subset`. On the benchmarked patterns both take 2 to 20 times less time, and about 100 times less where most pairs are skipped. Two deterministic automata are compared by `equivalent` state by state (Hopcroft & Karp, 1971), in time close to linear in their number of states: 2 to 8 times less time on the benchmarked pairs that share a spanning set, and about as long as before on pairs that do not. @@ -20,6 +22,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - When the execution profile disables implicit determinization, `FastAutomaton::equivalent`, `FastAutomaton::subset`, `FastAutomaton::cardinality` and `FastAutomaton::difference` accept non-deterministic automata instead of returning `EngineError::DeterministicAutomatonRequired`. For the first three, which build no automaton, `max_number_of_states` caps the number of pairs or sets visited. - Updated `regex-charclass` to 1.3, which makes `Char::index` and `Char::from_index` public: the mapping of a `char` to its position among all `char` values, the surrogate block skipped. They replace the crate's own copy of that mapping, and since `regex_charclass` is re-exported they are usable through it. +### Fixed +- Parsing a pattern, `RegularExpression::concat_all`, `RegularExpression::simplify` and `Term::concat` take time linear in the number of expressions concatenated, where each expression added copied the ones before it: a pattern of 5,000 concatenated groups is parsed in 10 ms instead of 1.3 s. The parser also checks the execution timeout as it concatenates. +- `Term::union` of terms backed by regular expressions returns `EngineError::OperationTimeOutError` past the execution timeout, as it does for terms backed by automata. +- `RegularExpression::is_empty` and `RegularExpression::is_empty_string` are exact on an expression that is not simplified, built from its variants or parsed with `RegularExpression::parse(pattern, false)`, and so are `Term::is_empty` and `Term::is_empty_string` on a term created from one with `Term::from_regex`. They only recognised the simplified form of the empty language and of the empty string, and returned `false` for `()*` parsed that way. They now take time linear in the size of an expression that is not the empty language or the empty string in simplified form, where they took constant time. +- `RegularExpression::length`, and `Term::length` on a term backed by a regular expression, return a maximum length of 0 for an unbounded repetition of the empty string (`()*`, `()+`, `(){2,}`, which the simplification does not leave in an expression), where they returned no maximum. + ## [1.2.0] - 2026-11-14 ### Added diff --git a/README.md b/README.md index 29e6f75..3a90d1d 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Constructs a regular language can't express, such as backreferences, lookaround, | | Methods | |---|---| | Build | `from_pattern`, `parse`, `concat`, `repeat` | -| Combine | `union`, `intersection`, `difference`, `complement` | +| Combine | `union`, `intersection`, `difference`, `symmetric_difference`, `complement` | | Compare | `equivalent`, `subset`, `is_match` | | Analyze | `is_empty`, `is_total`, `length`, `cardinality` | | Generate | `generate_strings`, `iter_strings` | diff --git a/benches/operations.rs b/benches/operations.rs index 79f3c4e..558d034 100644 --- a/benches/operations.rs +++ b/benches/operations.rs @@ -36,6 +36,14 @@ fn dfa(pattern: &str) -> FastAutomaton { automaton(pattern).determinize().unwrap().into_owned() } +/// The intersection with the complement of the determinized subtrahend, +/// which is what `difference` used to do. +fn difference_via_complement(minuend: &FastAutomaton, subtrahend: &FastAutomaton) -> FastAutomaton { + let mut complement = subtrahend.determinize().unwrap().into_owned(); + complement.complement().unwrap(); + minuend.intersection(&complement).unwrap() +} + /// `(a|b)*a(a|b){n}`: an n+2-state NFA whose minimal DFA has 2^(n+1) states. fn blowup_pattern(n: usize) -> String { format!("(a|b)*a(a|b){{{n}}}") @@ -48,6 +56,11 @@ fn bench_parse(c: &mut Criterion) { b.iter(|| RegularExpression::new(black_box(pattern)).unwrap()) }); } + // A long concatenation, which is folded in time linear in its length. + let concatenation = "[ab]c".repeat(2000); + group.bench_function("concatenation_2000", |b| { + b.iter(|| RegularExpression::new(black_box(&concatenation)).unwrap()) + }); group.finish(); } @@ -122,14 +135,8 @@ fn bench_set_operations(c: &mut Criterion) { b.iter(|| black_box(&a).union(black_box(&b_op)).unwrap()) }); - // `via_complement` is the intersection with the complement of the - // determinized subtrahend, which is what `difference` used to do. let mut bench_difference = |name: &str, minuend: &FastAutomaton, subtrahend: &FastAutomaton| { - let via_complement = || { - let mut complement = subtrahend.determinize().unwrap().into_owned(); - complement.complement().unwrap(); - black_box(minuend).intersection(&complement).unwrap() - }; + let via_complement = || difference_via_complement(black_box(minuend), subtrahend); assert!( minuend .difference(subtrahend) @@ -167,6 +174,71 @@ fn bench_set_operations(c: &mut Criterion) { &automaton(&blowup_pattern(12)), ); + // `via_complement` is the union of the two differences, which + // determinizes both operands. + let mut bench_symmetric_difference = |name: &str, a: &FastAutomaton, b: &FastAutomaton| { + let via_complement = || { + difference_via_complement(black_box(a), b) + .union(&difference_via_complement(black_box(b), a)) + .unwrap() + }; + assert!( + a.symmetric_difference(b) + .unwrap() + .equivalent(&via_complement()) + .unwrap() + ); + group.bench_function(name, |bencher| { + bencher.iter(|| black_box(a).symmetric_difference(black_box(b)).unwrap()) + }); + group.bench_function(format!("{name}/via_complement"), |bencher| { + bencher.iter(via_complement) + }); + }; + + bench_symmetric_difference( + "symmetric_difference", + &automaton(".*abc.*"), + &automaton(".*def.*"), + ); + bench_symmetric_difference("symmetric_difference/dfa", &dfa(".*abc.*"), &dfa(".*def.*")); + bench_symmetric_difference( + "symmetric_difference/large", + &automaton(LARGE.1), + &automaton(".*abc.*def.*ksd"), + ); + // Every set of states of one operand is reached. + bench_symmetric_difference( + "symmetric_difference/blowup_8", + &automaton("(a|b)*"), + &automaton(&blowup_pattern(8)), + ); + // One operand reaches a few of the 2^13 sets of the other. + bench_symmetric_difference( + "symmetric_difference/blowup_12_short_operand", + &automaton("(a|b){0,6}"), + &automaton(&blowup_pattern(12)), + ); + + // More than two automata are walked together: combined two by two, the + // 16 suffixes take thousands of states where 17 are enough. + let suffixes: Vec = ('a'..='p') + .map(|letter| automaton(&format!(".*{letter}"))) + .collect(); + let contains: Vec = ["abc", "def", "ghi", "jkl", "mno", "pqr"] + .iter() + .map(|word| automaton(&format!(".*{word}.*"))) + .collect(); + for (name, automata) in [("suffixes_16", &suffixes), ("contains_6", &contains)] { + group.bench_function(format!("symmetric_difference_all/{name}"), |b| { + b.iter(|| FastAutomaton::symmetric_difference_all(black_box(automata)).unwrap()) + }); + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + group.bench_function(format!("symmetric_difference_all_par/{name}"), |b| { + b.iter(|| FastAutomaton::symmetric_difference_all_par(black_box(automata)).unwrap()) + }); + } + let complement_input = dfa(".*abc.*"); group.bench_function("complement", |b| { b.iter_batched( diff --git a/src/cardinality/mod.rs b/src/cardinality/mod.rs index d2e054c..7be5eb8 100644 --- a/src/cardinality/mod.rs +++ b/src/cardinality/mod.rs @@ -1,10 +1,11 @@ -/// Represents a cardinality: either a specific integer, a number too large to represent exactly, or infinite. +/// The number of strings of a language: a count, a count too large for its +/// integer type, or infinite. #[derive(PartialEq, Eq, Debug, Clone)] pub enum Cardinality { - /// An infinite number. + /// Infinitely many. Infinite, - /// A finite number. + /// A count that fits its integer type. Integer(U), - /// A finite number too big to be represented. + /// A finite count too large for its integer type. BigInteger, } diff --git a/src/error/mod.rs b/src/error/mod.rs index 75b5e08..dd8e132 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -1,34 +1,36 @@ use std::fmt::{self}; -/// An error thrown by the engine. +/// An error returned by an operation of the crate. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum EngineError { - /// Invalid character used in regex. + /// The pattern holds a literal that is not valid UTF-8. InvalidCharacterInRegex, - /// The operation took too much time. + /// The operation ran past the timeout of the + /// [`ExecutionProfile`](crate::execution_profile::ExecutionProfile). OperationTimeOutError, - /// The automaton has too many states. + /// The operation needed more states than the `max_number_of_states` of the + /// [`ExecutionProfile`](crate::execution_profile::ExecutionProfile). AutomatonHasTooManyStates, - /// The regular expression cannot be parsed. + /// The pattern cannot be parsed; the string describes why. RegexSyntaxError(String), - /// The provided range cannot be built from the spanning set. + /// The spanning set cannot express the range. ConditionInvalidRange, - /// The repetition bounds are invalid: the maximum is below the minimum. + /// The maximum of a repetition, the second value, is below its minimum, the + /// first. InvalidRepetitionBounds(u32, u32), - /// The condition does not match the spanning set it is evaluated against. + /// The condition was not built over the spanning set it is read with. IncompatibleSpanningSet, - /// The operation requires a deterministic automaton, and implicit - /// determinization is disabled by the execution profile. + /// The operation needs a deterministic automaton, and the execution profile + /// disables implicit determinization. DeterministicAutomatonRequired, - /// The pattern uses a regex feature the engine cannot represent (an - /// unsupported anchor/boundary position, or inline flags). The string - /// describes the specific feature. + /// The pattern uses a construct the engine cannot represent: an anchor or a + /// word boundary where it is not supported, or an inline flag. The string + /// names it. UnsupportedRegexFeature(String), - /// A directly-constructed [`RegularExpression`](crate::regex::RegularExpression) - /// tree nests deeper than the engine converts safely (the payload is the - /// limit). Parsed patterns never hit this; it only guards against - /// stack-overflowing on pathologically deep hand-built trees. + /// A [`RegularExpression`](crate::regex::RegularExpression) built by hand + /// nests deeper than the limit, which the value holds. A parsed pattern + /// never does. RegexTooDeeplyNested(usize), } diff --git a/src/execution_profile.rs b/src/execution_profile.rs index 749bc55..eca2e66 100644 --- a/src/execution_profile.rs +++ b/src/execution_profile.rs @@ -4,14 +4,12 @@ use std::{sync::OnceLock, time::Instant}; use crate::error::EngineError; -/// A monotonic clock: the time elapsed since a fixed but otherwise arbitrary -/// origin, such as process start or page load. +/// A monotonic clock: the time elapsed since a fixed origin, such as the start +/// of the process. /// -/// The execution timeout is enforced by comparing readings of the profile's -/// clock. Every profile starts with a clock backed by [`std::time::Instant`], -/// except on `wasm32-unknown-unknown`, where the standard library cannot read -/// the time and the host has to supply one through -/// [`ExecutionProfileBuilder::clock`]. +/// The execution timeout compares readings of it. The default clock reads +/// [`std::time::Instant`]; on `wasm32-unknown-unknown`, which has none, supply +/// one with [`ExecutionProfileBuilder::clock`]. pub type Clock = fn() -> Duration; /// [`std::time::Instant`], read as the time elapsed since the first reading. @@ -29,7 +27,12 @@ const DEFAULT_CLOCK: Option = Some(std_clock); #[cfg(all(target_family = "wasm", target_os = "unknown"))] const DEFAULT_CLOCK: Option = None; -/// Holds settings that constrain how operations execute within the engine. +/// The limits that the operations of the crate run under: a timeout, a maximum +/// number of states, and whether an operation may determinize an automaton on +/// its own. +/// +/// A profile applies to the operations run inside [`run`](Self::run), on the +/// current thread. Build one with [`ExecutionProfileBuilder`]. /// /// # Examples /// @@ -68,10 +71,9 @@ const DEFAULT_CLOCK: Option = None; /// /// The timeout compares readings of a monotonic [`Clock`]. The default reads /// [`std::time::Instant`]; on `wasm32-unknown-unknown`, where the standard -/// library has no clock, pass one from the host (a binding to -/// `performance.now()`, which is monotonic; `Date.now()` is not). Any monotonic -/// `fn() -> Duration` works, which also makes a timeout testable without -/// waiting for it: +/// library has no clock, pass one from the host: a binding to +/// `performance.now()`, which is monotonic (`Date.now()` is not). A clock of +/// your own also makes a timeout testable without waiting for it: /// /// ``` /// use std::sync::atomic::{AtomicU64, Ordering}; @@ -99,14 +101,14 @@ const DEFAULT_CLOCK: Option = None; /// /// ## Disabling implicit determinization /// -/// [`FastAutomaton`](crate::fast_automaton::FastAutomaton) operations that -/// require a deterministic automaton (`minimize` and `complement`) -/// determinize a non-deterministic input on their own by default. Since -/// subset construction can blow up exponentially, this can be disabled; -/// those operations then fail fast and determinization only happens through -/// an explicit `determinize()` call. [`Term`](crate::Term) methods are not -/// affected: that layer manages the underlying representation itself, so -/// its determinizations count as explicit. +/// [`FastAutomaton::minimize`](crate::fast_automaton::FastAutomaton::minimize) +/// and +/// [`FastAutomaton::complement`](crate::fast_automaton::FastAutomaton::complement) +/// need a deterministic automaton, and determinize a non-deterministic one on +/// their own by default, which can take exponential time and space. When this +/// is disabled, they return [`EngineError::DeterministicAutomatonRequired`] +/// instead, and an automaton is only determinized by a call to `determinize()`. +/// [`Term`](crate::Term) methods are not affected. /// /// ``` /// use regexsolver::CharRange; @@ -177,25 +179,20 @@ impl PartialEq for ExecutionProfile { } impl ExecutionProfile { - /// Retrieves the current thread-local execution profile. + /// Returns the profile installed on the current thread; the default one, + /// without limits, if there is none. pub fn get() -> ExecutionProfile { ThreadLocalParams::get_execution_profile() } - /// Whether a execution deadline is configured. When it is not, - /// [`assert_not_timed_out`](Self::assert_not_timed_out) can be - /// skipped entirely instead of being computed for a check that - /// cannot fail. + /// Returns `true` if the profile has a timeout. #[inline] pub fn limits_execution_time(&self) -> bool { self.execution_deadline.is_some() } - /// Assert that `execution_timeout` is not exceeded. - /// - /// Return empty if `execution_timeout` is not exceeded. - /// - /// Return [`EngineError::OperationTimeOutError`] otherwise. + /// Returns [`EngineError::OperationTimeOutError`] if the timeout has + /// passed. pub fn assert_not_timed_out(&self) -> Result<(), EngineError> { if let (Some(execution_deadline), Some(clock)) = (self.execution_deadline, self.clock) && clock() > execution_deadline @@ -205,21 +202,15 @@ impl ExecutionProfile { Ok(()) } - /// Whether a maximum number of states is configured. When it is not, the - /// state-count heuristics feeding - /// [`assert_max_number_of_states`](Self::assert_max_number_of_states) can - /// be skipped entirely instead of being computed for a check that cannot - /// fail. + /// Returns `true` if the profile has a maximum number of states. #[inline] pub fn limits_number_of_states(&self) -> bool { self.max_number_of_states.is_some() } - /// Assert that `max_number_of_states` is not exceeded. - /// - /// `max_number_of_states` is the largest number of states an automaton may - /// hold, so `number_of_states == max_number_of_states` is allowed and only - /// strictly exceeding it returns [`EngineError::AutomatonHasTooManyStates`]. + /// Returns [`EngineError::AutomatonHasTooManyStates`] if `number_of_states` + /// is above the maximum number of states. A number equal to the maximum is + /// allowed. pub fn assert_max_number_of_states(&self, number_of_states: usize) -> Result<(), EngineError> { if let Some(max_number_of_states) = self.max_number_of_states && number_of_states > max_number_of_states @@ -229,11 +220,8 @@ impl ExecutionProfile { Ok(()) } - /// Assert that implicit determinization is allowed. - /// - /// Return empty if it is. - /// - /// Return [`EngineError::DeterministicAutomatonRequired`] otherwise. + /// Returns [`EngineError::DeterministicAutomatonRequired`] if the profile + /// disables implicit determinization. pub fn assert_implicit_determinization_allowed(&self) -> Result<(), EngineError> { if self.implicit_determinization { Ok(()) @@ -242,52 +230,51 @@ impl ExecutionProfile { } } - /// Returns a copy of this profile with the execution timeout set to - /// `execution_timeout_in_ms` milliseconds. Use these `with_*` methods to - /// derive a variant of an existing profile (e.g. one from - /// [`get`](Self::get)); to build one from scratch, prefer - /// [`ExecutionProfileBuilder`]. See - /// [`ExecutionProfileBuilder::execution_timeout`]. + /// Returns the profile with its timeout set to `execution_timeout_in_ms` + /// milliseconds: see [`ExecutionProfileBuilder::execution_timeout`]. + /// + /// The `with_*` methods derive a profile from another one, such as the one + /// [`get`](Self::get) returns. pub fn with_execution_timeout(mut self, execution_timeout_in_ms: u64) -> Self { self.execution_timeout = Some(execution_timeout_in_ms); self } - /// Returns a copy of this profile with the maximum number of states set to - /// `max_number_of_states`. See + /// Returns the profile with its maximum number of states set to + /// `max_number_of_states`: see /// [`ExecutionProfileBuilder::max_number_of_states`]. pub fn with_max_number_of_states(mut self, max_number_of_states: usize) -> Self { self.max_number_of_states = Some(max_number_of_states); self } - /// Returns a copy of this profile with implicit determinization enabled or - /// disabled. See [`ExecutionProfileBuilder::implicit_determinization`]. + /// Returns the profile with implicit determinization allowed or not: see + /// [`ExecutionProfileBuilder::implicit_determinization`]. pub fn with_implicit_determinization(mut self, allowed: bool) -> Self { self.implicit_determinization = allowed; self } - /// Returns a copy of this profile reading the time from `clock`. See + /// Returns the profile with `clock` as its clock: see /// [`ExecutionProfileBuilder::clock`]. /// - /// A deadline already computed by [`run`](Self::run) is dropped, since it - /// was measured against the previous clock and the two origins are - /// unrelated. The next `run` computes one against `clock`. + /// A deadline that [`run`](Self::run) has set is dropped, since it was read + /// from the previous clock: the next `run` sets one. pub fn with_clock(mut self, clock: Clock) -> Self { self.clock = Some(clock); self.execution_deadline = None; self } - /// Runs the given closure with this profile installed for the current thread, setting its start time to now. + /// Runs `f` with this profile installed on the current thread, and puts + /// back the previous one afterwards. The timeout counts from the call. /// /// # Panics /// - /// If an execution timeout is set but the profile has no [`Clock`]. That - /// only happens where the standard library cannot read the time and none - /// is installed by default; supply one with [`ExecutionProfileBuilder::clock`] - /// or [`with_clock`](Self::with_clock). + /// Panics if a timeout is set and the profile has no [`Clock`], which only + /// happens on a target where the standard library cannot read the time: + /// supply one with [`ExecutionProfileBuilder::clock`] or + /// [`with_clock`](Self::with_clock). pub fn run(&self, f: F) -> R where F: FnOnce() -> R, @@ -311,7 +298,8 @@ impl ExecutionProfile { f() } - /// Runs the closure like [`run`](Self::run), but does not reset the start time. Use this to propagate an already-started profile to worker threads without restarting the clock. + /// Runs `f` like [`run`](Self::run), without restarting the timeout: it + /// carries a running profile over to another thread. pub fn apply(&self, f: F) -> R where F: FnOnce() -> R, @@ -345,8 +333,8 @@ impl Drop for ProfileRestoreGuard { } } -/// Builder for an [`ExecutionProfile`]. Start from [`new`](Self::new), set the -/// limits you want, and [`build`](Self::build) the immutable profile. +/// Builds an [`ExecutionProfile`]: start from [`new`](Self::new), set the +/// limits, and call [`build`](Self::build). #[derive(Clone, Debug)] pub struct ExecutionProfileBuilder { /// The maximum number of states a non-deterministic finite automaton may @@ -369,9 +357,8 @@ impl Default for ExecutionProfileBuilder { } impl ExecutionProfileBuilder { - /// Creates a builder with no limits set and implicit determinization - /// enabled (i.e. the defaults, equivalent to the ambient profile when none - /// has been installed). + /// Creates a builder with no limit and implicit determinization allowed: + /// the settings of a thread on which no profile is installed. pub fn new() -> Self { Self { max_number_of_states: None, @@ -381,55 +368,61 @@ impl ExecutionProfileBuilder { } } - /// Sets the longest time, in milliseconds, that an operation may run before - /// it aborts with [`EngineError::OperationTimeOutError`]. Enforcement is - /// best-effort (checked between internal steps), so the exact deadline is - /// not guaranteed. Unset by default (no timeout). The time is read from - /// the profile's [`clock`](Self::clock). + /// Sets the time, in milliseconds, after which an operation returns + /// [`EngineError::OperationTimeOutError`]. No timeout by default. + /// + /// The time is checked between the steps of an operation, so an operation + /// can end after it. It is read from the profile's [`clock`](Self::clock). pub fn execution_timeout(mut self, execution_timeout_in_ms: u64) -> Self { self.execution_timeout = Some(execution_timeout_in_ms); self } - /// Sets the [`Clock`] the execution timeout is measured against: any - /// monotonic `fn() -> Duration`, compared by difference only. + /// Sets the [`Clock`] that the timeout reads: any monotonic `fn() -> + /// Duration`. + /// + /// The default reads [`std::time::Instant`], so a clock is only needed on a + /// target where the standard library cannot read the time: pass a binding + /// to `performance.now()` there. A wall clock such as `Date.now()` is not + /// monotonic: it jumps when the system time is set, and an operation then + /// times out early or never. /// - /// Defaults to [`std::time::Instant`], so this is only required where the - /// standard library cannot read the time: bind `performance.now()` from the - /// host and pass it here. A wall clock such as `Date.now()` does not - /// qualify: it steps when the system time is adjusted, which either times - /// an operation out early or never. Elsewhere it is a way to make the - /// timeout deterministic, as in the - /// [type-level example](ExecutionProfile#supplying-the-clock). + /// A clock of your own also makes a timeout testable, as in this + /// [example](ExecutionProfile#supplying-the-clock). pub fn clock(mut self, clock: Clock) -> Self { self.clock = Some(clock); self } - /// Caps the number of states an automaton may reach; operations that would - /// exceed it abort with [`EngineError::AutomatonHasTooManyStates`]. This - /// bounds the exponential blow-up of conversions such as determinization. - /// The operations that walk sets of states without building an automaton - /// (`equivalent`, `subset`, `cardinality`) count what they visit against - /// the same cap. Unset by default (no cap). + /// Sets the largest number of states an automaton may have: an operation + /// that needs more returns [`EngineError::AutomatonHasTooManyStates`]. No + /// maximum by default. + /// + /// An operation that builds an automaton counts the states it builds, + /// including those it leaves out of its result. The operations that build + /// none (`equivalent`, `subset`, `cardinality`, `has_intersection`) count + /// what they visit: states, or sets of states. pub fn max_number_of_states(mut self, max_number_of_states: usize) -> Self { self.max_number_of_states = Some(max_number_of_states); self } - /// Whether [`FastAutomaton`](crate::fast_automaton::FastAutomaton) - /// operations that require a deterministic automaton may determinize a - /// non-deterministic input on their own (the default). When set to - /// `false`, those operations return - /// [`EngineError::DeterministicAutomatonRequired`] instead; explicit - /// `determinize()` calls and [`Term`](crate::Term) methods (which - /// manage the representation themselves) are always allowed. + /// Sets whether + /// [`FastAutomaton::minimize`](crate::fast_automaton::FastAutomaton::minimize) + /// and + /// [`FastAutomaton::complement`](crate::fast_automaton::FastAutomaton::complement) + /// may determinize a non-deterministic automaton on their own. Allowed by + /// default. + /// + /// When it is not, they return + /// [`EngineError::DeterministicAutomatonRequired`]. Calls to + /// `determinize()` and [`Term`](crate::Term) methods are not affected. pub fn implicit_determinization(mut self, allowed: bool) -> Self { self.implicit_determinization = allowed; self } - /// Builds the [`ExecutionProfile`]. Install it around a unit of work with + /// Builds the [`ExecutionProfile`], to install with /// [`ExecutionProfile::run`]. pub fn build(self) -> ExecutionProfile { ExecutionProfile { @@ -752,6 +745,7 @@ mod tests { // ...but operations that work on NFAs directly are unaffected assert!(nfa.difference(&dfa).is_ok()); assert!(dfa.difference(&nfa).unwrap().is_empty()); + assert!(nfa.symmetric_difference(&dfa).unwrap().is_empty()); assert_eq!(nfa.cardinality(), dfa.cardinality()); assert!(nfa.equivalent(&dfa).unwrap()); assert!(dfa.subset(&nfa).unwrap()); @@ -792,6 +786,7 @@ mod tests { // ...and the rest of the API never needed one. assert!(term.difference(&other).is_ok()); assert!(other.difference(&term).is_ok()); + assert!(term.symmetric_difference([&other]).is_ok()); assert!(term.equivalent(&other).is_ok()); assert!(term.subset(&other).is_ok()); assert!(other.subset(&term).is_ok()); diff --git a/src/fast_automaton/analyze/cardinality.rs b/src/fast_automaton/analyze/cardinality.rs index 5e9e076..ef05bd8 100644 --- a/src/fast_automaton/analyze/cardinality.rs +++ b/src/fast_automaton/analyze/cardinality.rs @@ -6,17 +6,18 @@ use super::state_sets::{Id, Operand}; use super::*; impl FastAutomaton { - /// Returns the cardinality of the automaton (i.e., the number of possible matched strings). + /// Returns the number of strings the automaton accepts. /// - /// Non-deterministic automata are not determinized: when the language is - /// finite, its strings are counted over the sets of states a word can - /// reach. That count can visit exponentially many sets; the - /// [`crate::execution_profile::ExecutionProfile`]'s timeout applies, and - /// its `max_number_of_states` caps the number of sets visited. + /// [`Cardinality::Infinite`] when a cycle lies on a path from the start + /// state to an accept state, and [`Cardinality::BigInteger`] when the count + /// exceeds `u32::MAX`. /// - /// As in [`length`](Self::length), only cycles **on accepting - /// paths** make the count infinite: cycles among dead or unreachable - /// states don't add a single matched string. + /// A non-deterministic automaton is not determinized. + /// + /// Linear in the size of a deterministic automaton. Exponential in the + /// worst case otherwise: the timeout of the [`ExecutionProfile`] applies, + /// and its `max_number_of_states` caps the number of sets of states + /// visited. #[tracing::instrument(level = "debug", skip_all, fields(states = self.number_of_states(), deterministic = self.is_deterministic()))] pub fn cardinality(&self) -> Result, EngineError> { if self.is_empty() { diff --git a/src/fast_automaton/analyze/equivalence.rs b/src/fast_automaton/analyze/equivalence.rs index a1c0e30..e7d3bbf 100644 --- a/src/fast_automaton/analyze/equivalence.rs +++ b/src/fast_automaton/analyze/equivalence.rs @@ -8,17 +8,14 @@ use super::state_sets::{Id, Marks, Operand, SetTrie}; use super::*; impl FastAutomaton { - /// Returns `true` if both automata accept the same language. + /// Returns `true` if both automata accept the same strings. /// - /// Non-deterministic operands are not determinized: the two automata are - /// walked together over the sets of states a word can reach, and a pair - /// of sets is skipped when it follows from the pairs already met - /// (bisimulation up to congruence). The walk is still exponential in the - /// worst case; the execution profile's timeout applies, and its - /// `max_number_of_states` caps the number of pairs walked. + /// Neither automaton is determinized. /// - /// Two deterministic automata are compared state by state instead, in - /// time close to linear in their number of states. + /// Close to linear in the number of states for two deterministic automata. + /// Exponential in the worst case otherwise: the timeout of the execution + /// profile applies, and its `max_number_of_states` caps the number of pairs + /// of sets of states visited. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn equivalent(&self, other: &FastAutomaton) -> Result { // `is_empty` is exact, so a mismatch proves the languages differ. @@ -210,7 +207,8 @@ impl FastAutomaton { // Both operands share one id space, `self` first: the sets a rule // rewrites mix states of the two. let other_offset = self.transitions.len(); - let (left, right, bases) = Operand::pair(self, 0, other, other_offset)?; + let (left, right, shared) = Operand::pair(self, 0, other, other_offset)?; + let bases = shared.spanning_set().spanning_ranges_with_rest_len(); let (Some(left_start), Some(right_start)) = (left.start, right.start) else { return Ok(left.start.is_none() && right.start.is_none()); diff --git a/src/fast_automaton/analyze/length.rs b/src/fast_automaton/analyze/length.rs index f858855..13d600b 100644 --- a/src/fast_automaton/analyze/length.rs +++ b/src/fast_automaton/analyze/length.rs @@ -1,17 +1,13 @@ use super::*; impl FastAutomaton { - /// Returns the minimum and maximum length of matched strings. + /// Returns the minimum and maximum length of the strings accepted. /// - /// Cycles are only treated as "language-extending" if they sit on an - /// accepting path. Cycles among dead states (states that can't reach any - /// accept) don't extend the language and therefore don't make the max - /// infinite. + /// Both are `None` when the automaton accepts no string. The maximum is + /// also `None` when the strings have no longest length: a cycle lies on a + /// path from the start state to an accept state. /// - /// Runs in O(V + E): the minimum is a BFS distance; the maximum is a - /// longest path over the subgraph of states lying on accepting paths, - /// which is unbounded exactly when that subgraph has a cycle (any such - /// cycle can be pumped). + /// Linear in the size of the automaton. #[must_use] pub fn length(&self) -> (Option, Option) { // States that can reach an accept state. If the start state can't, diff --git a/src/fast_automaton/analyze/mod.rs b/src/fast_automaton/analyze/mod.rs index 9e3a63b..69fa7bd 100644 --- a/src/fast_automaton/analyze/mod.rs +++ b/src/fast_automaton/analyze/mod.rs @@ -11,11 +11,9 @@ pub(super) mod state_sets; mod subset; impl FastAutomaton { - /// Checks if the automaton matches the empty language. + /// Returns `true` if the automaton accepts no string. /// - /// Sound and complete: works on NFAs and non-minimal automata without - /// requiring determinization or minimization. O(V + E) worst case, with - /// O(1) fast paths for the common cases. + /// Exact whether the automaton is deterministic or not. Linear in its size. pub fn is_empty(&self) -> bool { if self.accept_states.is_empty() { return true; @@ -51,16 +49,14 @@ impl FastAutomaton { true } - /// Checks if the automaton matches all possible strings. + /// Returns `true` if the automaton is found to accept every string. /// - /// Sound and complete for **deterministic** automata: a DFA's language - /// equals Σ\* iff every reachable state is accepting AND its outgoing - /// conditions union to Σ. For NFAs this is sound but conservative: - /// alternative paths may cover a character that no single reachable - /// state covers, so callers that need an exact answer on an NFA should - /// determinize first. + /// Exact for a deterministic automaton. For a non-deterministic one, `true` + /// is reliable, but `false` can be returned for an automaton that accepts + /// every string: [`determinize`](Self::determinize) it first, or test + /// `FastAutomaton::new_total().subset(&automaton)`. /// - /// O(V + E) plus one condition-union per outgoing transition. + /// Linear in the size of the automaton. pub fn is_total(&self) -> bool { let mut visited = IntSet::default(); let mut worklist = VecDeque::new(); @@ -88,12 +84,10 @@ impl FastAutomaton { true } - /// Checks if the automaton only matches the empty string `""`. + /// Returns `true` if the automaton accepts the empty string `""` and no + /// other. /// - /// Sound and complete on any automaton (DFA or NFA): the language equals - /// `{""}` iff start is accepting AND no state reachable from start by at - /// least one non-empty transition is, or can reach, an accept state. - /// O(V + E). + /// Exact whether the automaton is deterministic or not. Linear in its size. pub fn is_empty_string(&self) -> bool { if !self.accept_states.contains(&self.start_state) { return false; @@ -152,17 +146,16 @@ impl FastAutomaton { visited } - /// Returns the "live" (co-reachable) states: those that can **reach an - /// accept state** by following non-empty transitions. Computed by a reverse - /// traversal from the accept states. + /// Returns the states from which an accept state can be reached. They are + /// not the states that can be reached from the start state. /// - /// This is co-reachability; note it is *not* the set of states reachable - /// from the start state. + /// Linear in the size of the automaton. pub fn live_states(&self) -> IntSet { // Reverse BFS over the maintained `transitions_in` adjacency. - // `transitions_in` doesn't filter empty-condition edges - // (constructible via the public `add_transition`), so each edge's - // condition is checked on traversal. The lookup on `transitions` + // `transitions_in` doesn't filter empty-condition edges, so each + // edge's condition is checked on traversal. `add_transition` adds + // none, but `apply_new_spanning_set` can leave one, with a spanning + // set that cannot express a condition. The lookup on `transitions` // also makes tombstoned predecessors fall out naturally. let mut worklist = VecDeque::from_iter(self.accept_states.iter().cloned()); let mut live = self.accept_states.clone(); @@ -187,15 +180,9 @@ impl FastAutomaton { live } - /// Returns one [`Condition`] per base of the spanning set, including the - /// "rest" range when it is non-empty. - /// - /// The bases must partition the whole alphabet Σ: subset construction - /// ([`determinize`](Self::determinize)) and Hopcroft partitioning - /// ([`minimize`](Self::minimize)) iterate them and would otherwise silently - /// drop transitions whose condition lies in the "rest" range. (For a - /// spanning set with an empty rest this is exactly the spanning ranges, so - /// well-formed automata are unaffected.) + /// Returns one [`Condition`] per base of the spanning set: one for each of + /// its ranges, and one for its rest when it is not empty. Together, they + /// cover every character. pub fn spanning_bases(&self) -> Result, EngineError> { // Base `i` is by construction exactly bit `i` of a condition. Ok((0..self.spanning_set.spanning_ranges_with_rest_len()) @@ -236,11 +223,11 @@ mod tests { Ok(()) } - // An empty-condition transition (constructible via the public - // `add_transition`) can't be taken, so a state whose only path to an - // accept state goes through one is dead. `live_states` walks + // An empty-condition transition can't be taken, so a state whose only + // path to an accept state goes through one is dead. `live_states` walks // `transitions_in`, which records such edges, so it must check the - // condition instead of trusting the adjacency. + // condition instead of trusting the adjacency. `add_transition` ignores + // an empty condition: the edge is stored directly. #[test] fn live_states_ignores_empty_condition_edges() { use crate::fast_automaton::condition::Condition; @@ -249,8 +236,11 @@ mod tests { let s1 = a.new_state(); let s2 = a.new_state(); a.add_transition(0, s1, &Condition::total(a.spanning_set())); - a.add_transition(s2, s1, &Condition::empty(a.spanning_set())); + let empty = Condition::empty(a.spanning_set()); + a.transitions[s2].insert(s1, empty); + a.transitions_in.entry(s1).or_default().insert(s2); a.accept(s1); + assert!(a.has_transition(s2, s1)); let live = a.live_states(); assert!(live.contains(&0)); diff --git a/src/fast_automaton/analyze/reference_tests.rs b/src/fast_automaton/analyze/reference_tests.rs index 833f8c7..683d356 100644 --- a/src/fast_automaton/analyze/reference_tests.rs +++ b/src/fast_automaton/analyze/reference_tests.rs @@ -1,6 +1,6 @@ -//! `equivalent`, `subset`, `cardinality` and `difference`, checked against -//! the textbook definitions (determinize, then complement and intersect, or -//! count paths). +//! `equivalent`, `subset`, `cardinality`, `difference` and +//! `symmetric_difference`, checked against the textbook definitions +//! (determinize, then complement and intersect, or count paths). use proptest::prelude::*; use regex_charclass::char::Char; @@ -54,6 +54,21 @@ fn assert_difference_matches_reference(a: &FastAutomaton, b: &FastAutomaton) { assert!(!a.is_deterministic() || difference.is_deterministic()); } +fn assert_symmetric_difference_matches_reference(a: &FastAutomaton, b: &FastAutomaton) { + let symmetric_difference = a.symmetric_difference(b).unwrap(); + let reference = difference_by_complement(a, b) + .union(&difference_by_complement(b, a)) + .unwrap(); + assert!( + equivalent_by_complement(&symmetric_difference, &reference), + "symmetric difference disagrees on\n{a}\n{b}" + ); + // Deterministic when both operands are, where it pairs their states. + assert!( + !a.is_deterministic() || !b.is_deterministic() || symmetric_difference.is_deterministic() + ); +} + /// The check on two deterministic automata, on the determinized operands /// (which keep their dead states and have missing transitions) and on a /// minimized one (which has neither, and another spanning set). @@ -137,6 +152,9 @@ fn matches_the_reference_on_patterns() { assert_matches_reference(a, b); assert_matches_reference(&determinized, b); assert_difference_matches_reference(a, b); + assert_symmetric_difference_matches_reference(a, b); + // Two deterministic operands, whose states are paired. + assert_symmetric_difference_matches_reference(&determinized, &b.determinize().unwrap()); assert_deterministic_equivalence_matches_reference(a, b); } } @@ -216,6 +234,33 @@ fn difference_only_builds_the_pairs_a_word_reaches() { }); } +// Neither difference determinizes its subtrahend: `b` cannot be determinized +// under the cap, and `a` only reaches a few of its sets. +#[test] +fn symmetric_difference_only_builds_the_pairs_a_word_reaches() { + let a = automaton("(a|b){0,6}"); + let b = automaton("(a|b)*a(a|b){11}"); + let symmetric_difference = ExecutionProfileBuilder::new() + .max_number_of_states(200) + .build() + .run(|| { + assert_eq!( + b.determinize().unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + assert_eq!( + automaton("(a|b)*").symmetric_difference(&b).unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + a.symmetric_difference(&b).unwrap() + }); + // The reference determinizes `b`: it is compared outside of the cap. + let reference = difference_by_complement(&a, &b) + .union(&difference_by_complement(&b, &a)) + .unwrap(); + assert!(symmetric_difference.equivalent(&reference).unwrap()); +} + #[test] fn respects_the_state_budget_and_the_timeout() { let a = automaton("(a|b)*a(a|b){11}"); @@ -229,6 +274,9 @@ fn respects_the_state_budget_and_the_timeout() { assert_eq!(a.equivalent(&b).unwrap_err(), err); assert_eq!(a.subset(&b).unwrap_err(), err); assert_eq!(a_dfa.equivalent(&b_dfa).unwrap_err(), err); + assert_eq!(a.difference(&b).unwrap_err(), err); + assert_eq!(a.symmetric_difference(&b).unwrap_err(), err); + assert_symmetric_difference_all_fails(&[&a, &b, a_dfa.as_ref()], &err); }); ExecutionProfileBuilder::new() .execution_timeout(0) @@ -242,9 +290,24 @@ fn respects_the_state_budget_and_the_timeout() { let err = EngineError::OperationTimeOutError; assert_eq!(a.equivalent(&b).unwrap_err(), err); assert_eq!(a.subset(&b).unwrap_err(), err); + assert_eq!(a.difference(&b).unwrap_err(), err); + assert_eq!(a.symmetric_difference(&b).unwrap_err(), err); + assert_symmetric_difference_all_fails(&[&a, &b, a_dfa.as_ref()], &err); }); } +/// Asserts that the symmetric difference of `automata` fails with `error`, +/// walked together and by groups in parallel. +fn assert_symmetric_difference_all_fails(automata: &[&FastAutomaton], error: &EngineError) { + let all = FastAutomaton::symmetric_difference_all(automata.iter().copied()); + assert_eq!(&all.unwrap_err(), error); + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + { + let all = FastAutomaton::symmetric_difference_all_par(automata.to_vec()); + assert_eq!(&all.unwrap_err(), error); + } +} + /// A random automaton of up to `max_states` states over ranges cut from /// the first `letters` letters. Unreachable and dead states, empty languages /// and non-determinism all occur. @@ -302,8 +365,12 @@ fn assert_matches_reference_and_itself(a: &FastAutomaton, b: &FastAutomaton) { assert_matches_reference(a, b); assert_difference_matches_reference(a, b); assert_difference_matches_reference(b, a); + assert_symmetric_difference_matches_reference(a, b); assert_deterministic_equivalence_matches_reference(a, b); let determinized = a.determinize().unwrap(); + // One and two deterministic operands. + assert_symmetric_difference_matches_reference(&determinized, b); + assert_symmetric_difference_matches_reference(&determinized, &b.determinize().unwrap()); assert!(a.equivalent_over_state_sets(&determinized).unwrap()); assert!(determinized.subset_over_state_sets(a).unwrap()); // Same language as `a`, over the states of both. diff --git a/src/fast_automaton/analyze/state_sets.rs b/src/fast_automaton/analyze/state_sets.rs index 5d6a806..0a633bb 100644 --- a/src/fast_automaton/analyze/state_sets.rs +++ b/src/fast_automaton/analyze/state_sets.rs @@ -40,20 +40,18 @@ pub(crate) struct Operand { impl Operand { /// Prepares both operands over their merged spanning set, and returns - /// them with its number of bases (the letters of the walk). - pub(crate) fn pair( - left: &FastAutomaton, + /// them with it: its bases are the letters of the walk. + pub(crate) fn pair<'a>( + left: &'a FastAutomaton, left_offset: usize, - right: &FastAutomaton, + right: &'a FastAutomaton, right_offset: usize, - ) -> Result<(Operand, Operand, usize), EngineError> { + ) -> Result<(Operand, Operand, SharedSpanningSet<'a>), EngineError> { let shared = SharedSpanningSet::new(&left.spanning_set, &right.spanning_set); let (left_converter, right_converter) = shared.converters()?; - Ok(( - Operand::new(left, left_offset, left_converter.as_ref())?, - Operand::new(right, right_offset, right_converter.as_ref())?, - shared.spanning_set().spanning_ranges_with_rest_len(), - )) + let left = Operand::new(left, left_offset, left_converter.as_ref())?; + let right = Operand::new(right, right_offset, right_converter.as_ref())?; + Ok((left, right, shared)) } /// Prepares one operand; `converter` projects its conditions on another @@ -231,20 +229,30 @@ impl SetTrie { } /// Returns `true` if a set stored below `root` is contained in `set`. - pub(super) fn has_subset_of(&self, root: usize, set: &Marks) -> bool { - let node = &self.nodes[root]; - if !node.values.is_empty() { - return true; - } - match node.few_children() { - Some(children) => children - .iter() - .any(|&(id, child)| set.contains(id) && self.has_subset_of(child, set)), - None => set.members().iter().any(|&id| { - node.child(id) - .is_some_and(|child| self.has_subset_of(child, set)) - }), + /// + /// Iterative: a stored set is as deep as it is large, and a word can + /// reach more states than the call stack allows calls. `stack` holds the + /// nodes to visit, and is only passed to be reused from one call to the + /// next. + pub(super) fn has_subset_of(&self, root: usize, set: &Marks, stack: &mut Vec) -> bool { + stack.clear(); + stack.push(root); + while let Some(node) = stack.pop() { + let node = &self.nodes[node]; + if !node.values.is_empty() { + return true; + } + match node.few_children() { + Some(children) => stack.extend( + children + .iter() + .filter(|(id, _)| set.contains(*id)) + .map(|(_, child)| *child), + ), + None => stack.extend(set.members().iter().filter_map(|&id| node.child(id))), + } } + false } } @@ -305,7 +313,7 @@ mod tests { let mut marks = Marks::new(2 * wide as usize); let mut has_subset_of = |trie: &SetTrie<()>, root: usize, set: &[Id]| { set.iter().for_each(|&id| assert!(marks.insert(id))); - let found = trie.has_subset_of(root, &marks); + let found = trie.has_subset_of(root, &marks, &mut Vec::new()); marks.clear(); found }; diff --git a/src/fast_automaton/analyze/subset.rs b/src/fast_automaton/analyze/subset.rs index 619a147..eb282a2 100644 --- a/src/fast_automaton/analyze/subset.rs +++ b/src/fast_automaton/analyze/subset.rs @@ -4,15 +4,15 @@ use super::state_sets::{Marks, Operand, SetTrie}; use super::*; impl FastAutomaton { - /// Returns `true` if all strings accepted by `self` are also accepted by `other`. + /// Returns `true` if every string that `self` accepts is also accepted by + /// `other`. /// - /// Non-deterministic operands are not determinized: each state of `self` - /// is walked together with the set of states of `other` that the same - /// word reaches, and a pair is skipped when the same state was already - /// met with a subset of that set (antichains). The walk is still - /// exponential in `other` in the worst case; the execution profile's - /// timeout applies, and its `max_number_of_states` caps the number of - /// pairs walked. + /// Neither automaton is determinized. + /// + /// Exponential in the size of `other` in the worst case: the timeout of the + /// execution profile applies, and its `max_number_of_states` caps the + /// number of pairs visited, each made of a state of `self` and a set of + /// states of `other`. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn subset(&self, other: &FastAutomaton) -> Result { if self.is_empty() || other.is_total() || self == other { @@ -45,7 +45,8 @@ impl FastAutomaton { ) -> Result { let execution_profile = ExecutionProfile::get(); - let (left, right, bases) = Operand::pair(self, 0, other, 0)?; + let (left, right, shared) = Operand::pair(self, 0, other, 0)?; + let bases = shared.spanning_set().spanning_ranges_with_rest_len(); let Some(start) = left.start else { return Ok(true); @@ -71,6 +72,8 @@ impl FastAutomaton { let mut successors = vec![Vec::new(); bases]; let mut query = Marks::new(other.transitions.len()); + // The nodes `has_subset_of` has to visit, reused by each call. + let mut stack = Vec::new(); let mut pairs = 1; while let Some((state, set)) = worklist.pop_front() { @@ -89,7 +92,7 @@ impl FastAutomaton { set.iter().for_each(|&id| { query.insert(id); }); - let met = visited.has_subset_of(root, &query); + let met = visited.has_subset_of(root, &query, &mut stack); query.clear(); if met { continue; @@ -108,7 +111,43 @@ impl FastAutomaton { #[cfg(test)] mod tests { + use crate::CharRange; + use crate::fast_automaton::FastAutomaton; use crate::regex::RegularExpression; + use regex_charclass::char::Char; + + // One `a` reaches every one of the 20,000 states of `other`, which makes + // a stored set that deep: looking it up must not recurse per state, + // which overflowed the stack of a thread. + #[test] + fn subset_with_a_large_set_of_states() { + let character = |c| CharRange::new_from_range(Char::new(c)..=Char::new(c)); + + let mut a_star = FastAutomaton::new_empty(); + a_star.accept(0); + a_star + .add_transition_from_range(0, 0, &character('a')) + .unwrap(); + + let mut other = FastAutomaton::new_empty(); + other.accept(0); + other + .add_transition_from_range(0, 0, &character('b')) + .unwrap(); + for _ in 0..20_000 { + let state = other.new_state(); + other.accept(state); + other + .add_transition_from_range(0, state, &character('a')) + .unwrap(); + other + .add_transition_from_range(state, state, &character('a')) + .unwrap(); + } + + assert!(a_star.subset(&other).unwrap()); + assert!(!other.subset(&a_star).unwrap()); + } #[test] fn test_subset() -> Result<(), String> { diff --git a/src/fast_automaton/builder.rs b/src/fast_automaton/builder.rs index 6825e36..10d54a3 100644 --- a/src/fast_automaton/builder.rs +++ b/src/fast_automaton/builder.rs @@ -5,7 +5,7 @@ use crate::error::EngineError; use super::*; impl FastAutomaton { - /// Creates an automaton that matches the empty language. + /// Creates an automaton that accepts no string. #[inline] pub fn new_empty() -> Self { Self { @@ -20,7 +20,7 @@ impl FastAutomaton { } } - /// Creates an automaton that only matches the empty string `""`. + /// Creates an automaton that accepts the empty string `""` and no other. #[inline] pub fn new_empty_string() -> Self { let mut automaton = Self::new_empty(); @@ -29,7 +29,7 @@ impl FastAutomaton { automaton } - /// Creates an automaton that matches all possible strings. + /// Creates an automaton that accepts every string. #[inline] pub fn new_total() -> Self { let mut automaton: FastAutomaton = Self::new_empty(); @@ -40,7 +40,8 @@ impl FastAutomaton { automaton } - /// Creates an automaton that matches one of the characters in the given [`CharRange`]. + /// Creates an automaton that accepts the strings made of one character of + /// `range`. pub fn new_from_range(range: &CharRange) -> Self { let mut automaton = Self::new_empty(); if range.is_empty() { @@ -58,7 +59,7 @@ impl FastAutomaton { automaton } - /// Creates a new state and returns its identifier. + /// Adds a state and returns its identifier. #[inline] pub fn new_state(&mut self) -> State { self.minimal = false; @@ -71,7 +72,11 @@ impl FastAutomaton { } } - /// Marks the provided state as an accepting (final) state. + /// Makes `state` an accept state. + /// + /// # Panics + /// + /// Panics if `state` does not exist. #[inline] pub fn accept(&mut self, state: State) { self.assert_state_exists(state); @@ -79,7 +84,11 @@ impl FastAutomaton { self.accept_states.insert(state); } - /// Marks the provided state as a non-accepting state. + /// Makes `state` a state that does not accept. + /// + /// # Panics + /// + /// Panics if `state` does not exist. #[inline] pub fn unaccept(&mut self, state: State) { self.assert_state_exists(state); @@ -87,13 +96,22 @@ impl FastAutomaton { self.accept_states.remove(&state); } - /// Creates a new transition with the given condition; the condition must follow the automaton’s current spanning set. + /// Adds a transition from `from_state` to `to_state` for the characters of + /// `new_cond`, which must be expressed over the automaton's current + /// [`SpanningSet`]. + /// + /// If the two states already have a transition, the characters are added to + /// it. An empty condition adds nothing. /// - /// If you don't want to deal with conditions and spanning sets, use - /// [`add_transition_from_range`](Self::add_transition_from_range), which - /// handles the bookkeeping for you. + /// [`add_transition_from_range`](Self::add_transition_from_range) takes a + /// [`CharRange`] and maintains the spanning set: use it unless you manage + /// the spanning set yourself. + /// + /// # Building the condition + /// + /// [`Condition::from_range`] converts a [`CharRange`] that the spanning set + /// can express: /// - /// This method accepts a [`Condition`] rather than a raw character set. To build a [`Condition`], call: /// ```rust /// # use regexsolver::CharRange; /// # use regexsolver::fast_automaton::{condition::Condition, spanning_set::SpanningSet}; @@ -101,35 +119,46 @@ impl FastAutomaton { /// # let spanning_set = SpanningSet::new_total(); /// Condition::from_range(&range, &spanning_set); /// ``` - /// where `spanning_set` is the automaton's current [`SpanningSet`]. The [`CharRange`] you pass must be fully covered by that spanning set. If it isn't, you have two options: /// - /// 1. Merge an existing spanning set with another: - /// ```rust - /// # use regexsolver::fast_automaton::spanning_set::SpanningSet; - /// # let old_set = SpanningSet::new_total(); - /// # let other_set = SpanningSet::new_total(); - /// let new_set = SpanningSet::merge(&old_set, &other_set); - /// ``` + /// When it cannot, compute a spanning set that can, with + /// [`SpanningSet::merge`] or [`SpanningSet::compute_spanning_set`], and + /// apply it to the automaton first: /// - /// 2. Recompute from a list of ranges: /// ```rust /// # use regexsolver::CharRange; - /// # use regexsolver::fast_automaton::spanning_set::SpanningSet; - /// # let range_set1 = CharRange::total(); - /// # let range_set2 = CharRange::total(); - /// let new_set = SpanningSet::compute_spanning_set(&[range_set1, range_set2]); - /// ``` - /// - /// After constructing `new_set`, apply it to the automaton: - /// ```rust /// # use regexsolver::fast_automaton::{FastAutomaton, spanning_set::SpanningSet}; - /// # let mut fast_automaton = FastAutomaton::new_total(); - /// # let new_set = SpanningSet::new_total(); - /// fast_automaton.apply_new_spanning_set(&new_set); + /// # let mut automaton = FastAutomaton::new_total(); + /// # let range = CharRange::total(); + /// let spanning_set = automaton + /// .spanning_set() + /// .merge(&SpanningSet::compute_spanning_set(&[range])); + /// automaton.apply_new_spanning_set(&spanning_set).unwrap(); /// ``` /// - /// This design allows us to perform unions, intersections, and complements of transition conditions in O(1) time, but it does add some complexity to automaton construction. For more details, you can check [this article](https://alexvbrdn.me/post/optimizing-transition-conditions-automaton-representation). + /// # Panics + /// + /// Panics if a state does not exist. pub fn add_transition(&mut self, from_state: State, to_state: State, new_cond: &Condition) { + self.add_transition_cow(from_state, to_state, Cow::Borrowed(new_cond)); + } + + /// [`add_transition`](Self::add_transition) of a condition the caller + /// has no further use for, which is stored instead of being cloned. + pub(crate) fn add_owned_transition( + &mut self, + from_state: State, + to_state: State, + new_cond: Condition, + ) { + self.add_transition_cow(from_state, to_state, Cow::Owned(new_cond)); + } + + fn add_transition_cow( + &mut self, + from_state: State, + to_state: State, + new_cond: Cow<'_, Condition>, + ) { self.assert_state_exists(from_state); if from_state != to_state { self.assert_state_exists(to_state); @@ -145,7 +174,7 @@ impl FastAutomaton { if state == &to_state { continue; } - if condition.has_intersection(new_cond) { + if condition.has_intersection(&new_cond) { deterministic = false; break; } @@ -159,24 +188,27 @@ impl FastAutomaton { .insert(from_state); match self.transitions[from_state].entry(to_state) { Entry::Occupied(mut o) => { - o.get_mut().union_with(new_cond); + o.get_mut().union_with(&new_cond); } Entry::Vacant(v) => { - v.insert(new_cond.clone()); + v.insert(new_cond.into_owned()); } }; } - /// Adds a transition labeled with the given character range, taking care - /// of the spanning-set bookkeeping. + /// Adds a transition from `from_state` to `to_state` for the characters of + /// `range`. + /// + /// If the two states already have a transition, the characters are added to + /// it. An empty range adds nothing. + /// + /// When the automaton's spanning set cannot express `range`, it is + /// extended, and the conditions of the existing transitions are converted + /// to it: that takes time proportional to their number. /// - /// This is the convenient counterpart to - /// [`add_transition`](Self::add_transition): the range is converted to a - /// [`Condition`] automatically, and when it is not exactly expressible - /// in the automaton's current spanning set, the spanning set is extended - /// and every existing condition is re-projected first. + /// # Panics /// - /// An empty range matches no character, so no transition is added. + /// Panics if a state does not exist and `range` is not empty. /// /// # Examples /// @@ -230,12 +262,17 @@ impl FastAutomaton { Ok(()) } - /// Adds a transition, but refuses if it would turn a DFA into an NFA. + /// Adds a transition as [`add_transition`](Self::add_transition) does, + /// unless it would make a deterministic automaton non-deterministic. + /// + /// # Errors + /// + /// Returns [`DeterminismLost`] in that case, and leaves the automaton + /// unchanged. /// - /// On `Err(DeterminismLost)` the automaton is left untouched; on `Ok`, - /// the transition has been added and `is_deterministic()` still holds - /// (provided it held before the call). This is the opt-in strict - /// counterpart to [`add_transition`](Self::add_transition). + /// # Panics + /// + /// Panics if a state does not exist. pub fn try_add_transition( &mut self, from_state: State, @@ -263,12 +300,17 @@ impl FastAutomaton { Ok(()) } - /// Adds an epsilon transition by eagerly folding `to_state`'s **current** - /// transitions (and acceptance) into `from_state`. + /// Adds an epsilon transition from `from_state` to `to_state`: `from_state` + /// gets a copy of the transitions of `to_state`, and becomes an accept + /// state if `to_state` is one. + /// + /// The copy is made at the time of the call: transitions added to + /// `to_state` afterwards are not copied. When you build an automaton step + /// by step, add its epsilon transitions last. + /// + /// # Panics /// - /// This is a snapshot: transitions added to `to_state` *afterwards* are - /// not propagated retroactively. When building automata incrementally, - /// add epsilon transitions last. + /// Panics if a state does not exist. pub fn add_epsilon_transition(&mut self, from_state: State, to_state: State) { if from_state == to_state { return; @@ -316,7 +358,11 @@ impl FastAutomaton { } } - /// Removes the transition between the two provided states if it exists. + /// Removes the transition from `from_state` to `to_state`, if there is one. + /// + /// # Panics + /// + /// Panics if a state does not exist. pub fn remove_transition(&mut self, from_state: State, to_state: State) { self.assert_state_exists(from_state); if from_state != to_state { @@ -332,7 +378,11 @@ impl FastAutomaton { self.transitions[from_state].remove(&to_state); } - /// Removes the state and its connected transitions; panics if it's a start state. + /// Removes `state` and its transitions. + /// + /// # Panics + /// + /// Panics if `state` does not exist or is the start state. pub fn remove_state(&mut self, state: State) { self.assert_state_exists(state); if self.start_state == state { @@ -371,8 +421,11 @@ impl FastAutomaton { } } - /// Removes the given states and their connected transitions; panics if any - /// state does not exist or is the start state. + /// Removes `states` and their transitions. + /// + /// # Panics + /// + /// Panics if one of them does not exist or is the start state. pub fn remove_states(&mut self, states: &IntSet) { for &state in states { self.assert_state_exists(state); @@ -409,7 +462,8 @@ impl FastAutomaton { } } - /// Recompute a minimal spanning set for the automaton and apply it. + /// Replaces the spanning set with the smallest one that expresses the + /// conditions of the transitions. pub fn recompute_minimal_spanning_set(&mut self) -> Result<(), EngineError> { let mut ranges = Vec::with_capacity(self.number_of_states()); @@ -424,7 +478,8 @@ impl FastAutomaton { self.apply_new_spanning_set(&new_spanning_set) } - /// Applies the provided spanning set and projects all existing conditions onto it. + /// Replaces the spanning set with `new_spanning_set`, which has to express + /// the conditions of all the transitions, and converts them to it. pub fn apply_new_spanning_set( &mut self, new_spanning_set: &SpanningSet, diff --git a/src/fast_automaton/condition/converter.rs b/src/fast_automaton/condition/converter.rs index 6ec9df4..475191a 100644 --- a/src/fast_automaton/condition/converter.rs +++ b/src/fast_automaton/condition/converter.rs @@ -2,7 +2,7 @@ use crate::{CharRange, error::EngineError, fast_automaton::spanning_set::Spannin use super::Condition; -/// Converter to project [`Condition`] on a [`SpanningSet`]. +/// Converts [`Condition`]s from one [`SpanningSet`] to another. pub struct ConditionConverter<'a, 'b> { from_spanning_set: &'a SpanningSet, to_spanning_set: &'b SpanningSet, @@ -10,14 +10,14 @@ pub struct ConditionConverter<'a, 'b> { } impl<'a, 'b> ConditionConverter<'a, 'b> { - /// Build a converter to project [`Condition`] from `from_spanning_set` to `to_spanning_set`. + /// Creates a converter from `from_spanning_set` to `to_spanning_set`. /// - /// Two directions are legitimate: refinement (a merged spanning set - /// before a binary operation) and coarsening (a recomputed minimal - /// spanning set, where bases no transition uses fold into the rest). The - /// pair is therefore not validated here; instead [`convert`](Self::convert) - /// asserts in debug builds that each projection preserves the - /// condition's character range. + /// `to_spanning_set` has to express the conditions converted. A spanning + /// set that splits the ranges of `from_spanning_set` expresses all of them; + /// one that merges some of its ranges only expresses the conditions that + /// hold all or none of the ranges merged. Neither spanning set is checked + /// here, and [`convert`](Self::convert) only checks its result in debug + /// builds. pub fn new( from_spanning_set: &'a SpanningSet, to_spanning_set: &'b SpanningSet, @@ -51,10 +51,12 @@ impl<'a, 'b> ConditionConverter<'a, 'b> { }) } - /// Project the given [`Condition`] from `from_spanning_set` to `to_spanning_set`. + /// Converts `condition` from `from_spanning_set` to `to_spanning_set`. /// - /// Returns [`EngineError::IncompatibleSpanningSet`] if the given - /// [`Condition`] was not built over `from_spanning_set`. + /// # Errors + /// + /// Returns [`EngineError::IncompatibleSpanningSet`] if `condition` was not + /// built over `from_spanning_set`. pub fn convert(&self, condition: &Condition) -> Result { if condition.0.len() != self.from_spanning_set.spanning_ranges_with_rest_len() { return Err(EngineError::IncompatibleSpanningSet); diff --git a/src/fast_automaton/condition/mod.rs b/src/fast_automaton/condition/mod.rs index 9b4b880..b168bdd 100644 --- a/src/fast_automaton/condition/mod.rs +++ b/src/fast_automaton/condition/mod.rs @@ -6,13 +6,19 @@ use regex_charclass::{CharacterClass, char::Char}; use crate::{CharRange, error::EngineError}; use super::spanning_set::SpanningSet; -/// The [`ConditionConverter`](converter::ConditionConverter): remaps a -/// [`Condition`] from one spanning set to another (used when merging automata -/// with different alphabets). +/// The [`ConditionConverter`](converter::ConditionConverter), which converts a +/// [`Condition`] from one spanning set to another. pub mod converter; mod fast_bit_vec; -/// Represents the condition of a transition in a [`crate::FastAutomaton`]. +/// The characters of a transition of a [`FastAutomaton`](crate::FastAutomaton): +/// a set of bases of the automaton's [`SpanningSet`], held as one bit per base. +/// The union, intersection and complement of conditions are bitwise operations +/// (see [this +/// article](https://alexvbrdn.me/post/optimizing-transition-conditions-automaton-representation)). +/// +/// A condition only has a meaning with the spanning set it was built over, and +/// two conditions that are combined must share it. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Condition(FastBitVec); @@ -29,8 +35,7 @@ impl Hash for Condition { } impl Condition { - /// Returns the condition that matches no character, sized for - /// `spanning_set` (every bit cleared). + /// Returns the condition that matches no character, over `spanning_set`. #[inline] pub fn empty(spanning_set: &SpanningSet) -> Self { Self(FastBitVec::from_elem( @@ -39,8 +44,7 @@ impl Condition { )) } - /// Returns the condition that matches every character, sized for - /// `spanning_set` (every bit set). + /// Returns the condition that matches every character, over `spanning_set`. #[inline] pub fn total(spanning_set: &SpanningSet) -> Self { Self(FastBitVec::from_elem( @@ -49,13 +53,19 @@ impl Condition { )) } - /// Converts a [`CharRange`] to a `Condition` sized for `spanning_set`. + /// Converts `range` to a condition over `spanning_set`. /// - /// Returns [`EngineError::ConditionInvalidRange`] if the range is not - /// expressible in the current spanning set (no base is fully contained in - /// `range`). In that case, extend the spanning set first with - /// [`SpanningSet::merge`] or [`SpanningSet::compute_spanning_set`], apply - /// it with [`crate::fast_automaton::FastAutomaton::apply_new_spanning_set`], then retry. + /// Only the bases that lie entirely inside `range` are kept: when + /// `spanning_set` cannot express `range`, the condition matches fewer + /// characters than `range`. Compare [`to_range`](Self::to_range) with + /// `range` to detect it, or let + /// [`FastAutomaton::add_transition_from_range`](crate::fast_automaton::FastAutomaton::add_transition_from_range) + /// extend the spanning set. + /// + /// # Errors + /// + /// Returns [`EngineError::ConditionInvalidRange`] if `range` is not empty + /// and no base lies entirely inside it. pub fn from_range(range: &CharRange, spanning_set: &SpanningSet) -> Result { if range.is_empty() { return Ok(Self::empty(spanning_set)); @@ -94,12 +104,12 @@ impl Condition { self.0.set(i, true); } - /// Converts this `Condition` back to the [`CharRange`] it represents, - /// evaluated against `spanning_set`. + /// Returns the characters the condition matches, read over `spanning_set`. + /// + /// # Errors /// - /// Returns [`EngineError::IncompatibleSpanningSet`] if this condition's - /// bit width does not match `spanning_set` (they were built from different - /// spanning sets). + /// Returns [`EngineError::IncompatibleSpanningSet`] if the condition was + /// built over a spanning set with another number of bases. pub fn to_range(&self, spanning_set: &SpanningSet) -> Result { // A condition only carries meaning relative to the spanning set it // was built from; a width mismatch means they differ, so reject it @@ -119,8 +129,8 @@ impl Condition { Ok(range) } - /// Returns the condition matching characters in `self` or `other` (bitwise - /// OR). Both must share the same spanning set. + /// Returns the condition that matches the characters of `self` and those of + /// `other`. Both must share the same spanning set. #[inline] pub fn union(&self, other: &Condition) -> Self { let mut new_cond = self.clone(); @@ -128,15 +138,15 @@ impl Condition { new_cond } - /// Unions `other` into `self` in place (bitwise OR). Both must share the - /// same spanning set. + /// Adds the characters of `other` to `self`. Both must share the same + /// spanning set. #[inline] pub fn union_with(&mut self, other: &Condition) { self.0.union(&other.0); } - /// Returns the condition matching characters in both `self` and `other` - /// (bitwise AND). Both must share the same spanning set. + /// Returns the condition that matches the characters that `self` and + /// `other` have in common. Both must share the same spanning set. #[inline] pub fn intersection(&self, other: &Condition) -> Self { let mut new_cond = self.clone(); @@ -144,8 +154,7 @@ impl Condition { new_cond } - /// Returns the condition matching exactly the characters `self` does not, - /// relative to its spanning set. + /// Returns the condition that matches the characters that `self` does not. #[inline] pub fn complement(&self) -> Self { let mut new_cond = self.clone(); @@ -153,8 +162,8 @@ impl Condition { new_cond } - /// Returns the condition matching characters in `self` but not in `other` - /// (bitwise AND-NOT). Both must share the same spanning set. + /// Returns the condition that matches the characters of `self` that `other` + /// does not match. Both must share the same spanning set. #[inline] pub fn difference(&self, other: &Condition) -> Self { let mut new_cond = self.clone(); @@ -175,19 +184,21 @@ impl Condition { self.0.clear(); } - /// Returns `true` if `self` and `other` share at least one character (their - /// intersection is non-empty). Both must share the same spanning set. + /// Returns `true` if `self` and `other` have a character in common. Both + /// must share the same spanning set. #[inline] pub fn has_intersection(&self, other: &Condition) -> bool { self.0.has_intersection(&other.0) } - /// Returns `true` if the condition matches `character` (a Unicode scalar - /// value), evaluated against `spanning_set`. Values that are not valid - /// scalar values never match. + /// Returns `true` if the condition, read over `spanning_set`, matches + /// `character`, given as a Unicode scalar value. A value that is not a + /// scalar value is not matched. /// - /// Returns [`EngineError::IncompatibleSpanningSet`] if this condition's - /// bit width does not match `spanning_set`. + /// # Errors + /// + /// Returns [`EngineError::IncompatibleSpanningSet`] if the condition was + /// built over a spanning set with another number of bases. #[inline] pub fn has_character( &self, @@ -233,11 +244,13 @@ impl Condition { self.0.total() } - /// Returns the number of characters the condition matches, evaluated - /// against `spanning_set`. + /// Returns the number of characters the condition matches, read over + /// `spanning_set`. + /// + /// # Errors /// - /// Returns [`EngineError::IncompatibleSpanningSet`] if this condition's - /// bit width does not match `spanning_set`. + /// Returns [`EngineError::IncompatibleSpanningSet`] if the condition was + /// built over a spanning set with another number of bases. #[inline] pub fn cardinality(&self, spanning_set: &SpanningSet) -> Result { if self.0.len() != spanning_set.spanning_ranges_with_rest_len() { @@ -255,8 +268,8 @@ impl Condition { Ok(cardinality) } - /// Returns the condition as a vector of bits, one per range of the spanning - /// set it was built against (the rest range first, when present). + /// Returns the bits of the condition, one per base of its spanning set: the + /// rest first, when it is not empty, then the ranges in order. #[inline] pub fn binary_representation(&self) -> Vec { self.0.bits() diff --git a/src/fast_automaton/convert/to_regex/mod.rs b/src/fast_automaton/convert/to_regex/mod.rs index 70f2233..0d61eb1 100644 --- a/src/fast_automaton/convert/to_regex/mod.rs +++ b/src/fast_automaton/convert/to_regex/mod.rs @@ -8,20 +8,18 @@ mod state_elimination; /// [`FastAutomaton::to_regex_with`] and /// [`Term::to_regex_with`](crate::Term::to_regex_with). /// -/// The crate provides [`StateElimination`], what -/// [`FastAutomaton::to_regex`] uses, and, with the `neural-synthesis` feature, +/// The crate provides [`StateElimination`], which [`FastAutomaton::to_regex`] +/// uses, and, with the `neural-synthesis` feature, /// `neural_synthesis::NeuralSynthesizer`, which asks a learned model for a /// simpler regex. pub trait RegexSynthesizer { - /// A regular expression describing exactly the language of `automaton`. + /// Returns a regular expression that matches the strings `automaton` + /// accepts, and no other. fn synthesize(&self, automaton: &FastAutomaton) -> Result; } -/// Conversion by state elimination, what [`FastAutomaton::to_regex`] uses: -/// the automaton's states are removed one at a time, each removal folding the -/// paths through the state into regexes on the transitions around it, until -/// one transition from the start to acceptance remains. The result is always -/// exact, but often long and hard to read. +/// Conversion by state elimination, which [`FastAutomaton::to_regex`] uses. The +/// result is exact, but often long and hard to read. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct StateElimination; @@ -32,12 +30,12 @@ impl RegexSynthesizer for StateElimination { } impl FastAutomaton { - /// Converts the automaton to a [`RegularExpression`] by state - /// elimination (see [`StateElimination`]). + /// Converts the automaton to a [`RegularExpression`] that matches the same + /// strings, by state elimination (see [`StateElimination`]). /// - /// The result describes exactly the automaton's language, but can be long - /// and hard to read; [`to_regex_with`](Self::to_regex_with) takes other - /// ways to convert it. + /// The result can be long and hard to read: its size can grow exponentially + /// with the number of states. [`to_regex_with`](Self::to_regex_with) takes + /// other ways to convert the automaton. #[tracing::instrument(level = "debug", skip_all, fields(states = self.number_of_states()))] pub fn to_regex(&self) -> Result { state_elimination::convert_to_regex(self) diff --git a/src/fast_automaton/convert/to_regex/neural_synthesis/hub.rs b/src/fast_automaton/convert/to_regex/neural_synthesis/hub.rs index b0c6ba3..991f0d9 100644 --- a/src/fast_automaton/convert/to_regex/neural_synthesis/hub.rs +++ b/src/fast_automaton/convert/to_regex/neural_synthesis/hub.rs @@ -10,11 +10,12 @@ use std::path::PathBuf; use super::{Device, NeuralSynthesisError, NeuralSynthesizer}; impl NeuralSynthesizer { - /// The model [`from_hub`](Self::from_hub) loads by default. + /// The repository of the default model, to pass to + /// [`from_hub`](Self::from_hub). pub const DEFAULT_HUB_MODEL: &str = "alexvbrdn/kleene2-9m-b16-t128"; - /// Downloads a model from the Hugging Face Hub (its latest revision) and - /// loads it. `repo_id` is `owner/name`, e.g. + /// Downloads a model from the Hugging Face Hub, at the head of its `main` + /// branch, and loads it. `repo_id` is `owner/name`, e.g. /// [`DEFAULT_HUB_MODEL`](Self::DEFAULT_HUB_MODEL). pub fn from_hub(repo_id: &str, device: Device) -> Result { Self::from_hub_revision(repo_id, "main", device) diff --git a/src/fast_automaton/convert/to_regex/neural_synthesis/mod.rs b/src/fast_automaton/convert/to_regex/neural_synthesis/mod.rs index babfc9a..e57f1f0 100644 --- a/src/fast_automaton/convert/to_regex/neural_synthesis/mod.rs +++ b/src/fast_automaton/convert/to_regex/neural_synthesis/mod.rs @@ -1,26 +1,24 @@ -//! Short, readable regexes for automata, proposed by learned models. +//! Short, readable regexes for automata, written by learned models. //! //! [`FastAutomaton::to_regex`] converts an automaton by state elimination: -//! always correct, but often long and hard to read. A [`NeuralSynthesizer`] -//! runs a model that reads the automaton's minimal DFA and writes regexes for -//! it, usually much simpler ones. Every candidate is **checked** against the -//! automaton with an equivalence test and discarded unless it describes -//! exactly the same language, so a model can make a result simpler, never -//! wrong. A `NeuralSynthesizer` is a [`RegexSynthesizer`]: pass it to -//! [`FastAutomaton::to_regex_with`] or [`Term::to_regex_with`](crate::Term::to_regex_with). -//! -//! A model can come with its success rate by size and difficulty of the DFA -//! (see [Models](#models)); the conversion does not run it on an automaton, -//! or a piece of one, whose rate is below a threshold -//! ([`NeuralSynthesizer::with_min_success`]): a piece that cannot be split -//! further is then converted by state elimination. +//! exact, but often long and hard to read. A [`NeuralSynthesizer`] runs a model +//! that reads the automaton and writes regexes for it. Every regex is +//! **checked** against the automaton, and dropped unless it matches the same +//! strings: a model can make a result simpler, never wrong. A +//! `NeuralSynthesizer` is a [`RegexSynthesizer`]: pass it to +//! [`FastAutomaton::to_regex_with`] or +//! [`Term::to_regex_with`](crate::Term::to_regex_with). //! //! When the model has no correct regex for an automaton, or the automaton is -//! beyond its limits or below the threshold, the conversion splits the minimal DFA -//! into independent pieces (concatenations, unions, stars, and the paths -//! around a few hub states that break up large cycles), runs the model on -//! every piece small enough, in batches, and combines the simplest regex of -//! each piece. [`NeuralSynthesizer::with_decomposition`] turns this off. +//! too large for it, the automaton is split into pieces that the model converts +//! one by one, and their regexes are combined +//! ([`NeuralSynthesizer::with_decomposition`] turns this off). A piece the +//! model cannot convert is converted by state elimination, so the conversion +//! does not depend on the model succeeding. +//! +//! A model can come with its success rate on automata of a given size and +//! difficulty (see [Models](#models)): it is not run where that rate is below a +//! threshold ([`NeuralSynthesizer::with_min_success`]). //! //! ```no_run //! use regexsolver::{ @@ -50,8 +48,8 @@ //! [`from_dir`](NeuralSynthesizer::from_dir), //! [`from_bytes`](NeuralSynthesizer::from_bytes)), or, with the //! `neural-synthesis-hub` feature, download them from the Hugging Face Hub -//! (`NeuralSynthesizer::from_hub`). The format is read from -//! `config.json`; the formats supported so far: +//! (`NeuralSynthesizer::from_hub`). The format is read from `config.json`. The +//! supported formats: //! //! - `kleene` v1 and v2, the Kleene models (`kleene1-9m-b16-t128`, //! `kleene2-9m-b16-t128`, `kleene2-5m-b16-t128`): a graph transformer over @@ -59,13 +57,13 @@ //! most 16 states and 16 bases (the disjoint character ranges labelling the //! transitions). //! -//! `config.json` may give the model's success rate (`gate`): for each cell of -//! a grid over features of a minimal DFA, the share of the DFAs of a -//! calibration set for which one of the model's candidates is correct. The -//! features are `states`, `bases` (its spanning ranges) and `complexity` (that -//! of its state elimination regex); each axis lists the lower bounds of its -//! bins, and the rates are in row-major order, `null` for a cell without DFAs -//! (the model is then tried). +//! `config.json` may give the model's success rate (`gate`): for each cell of a +//! grid over features of a minimal DFA, the share of the DFAs of a calibration +//! set for which one of the model's regexes is correct. The features are +//! `states`, `bases` (the ranges of its spanning set) and `complexity` (that of +//! its state elimination regex). Each axis lists the lower bounds of its bins, +//! and the rates are in row-major order, `null` for a cell without DFAs, where +//! the model is run. //! //! # Devices //! @@ -363,21 +361,15 @@ impl fmt::Debug for NeuralSynthesizer { } impl NeuralSynthesizer { - /// Default number of candidates per automaton: the hypotheses of the - /// beam search ([`DEFAULT_BEAM`](Self::DEFAULT_BEAM)) alone, as samples - /// added to a beam make the regexes hardly simpler. + /// Default number of regexes the model writes per automaton: see + /// [`with_candidates`](Self::with_candidates). pub const DEFAULT_CANDIDATES: usize = 1; - /// Default width of the beam search replacing the greedy decoding: four - /// hypotheses find simpler regexes than four samples, in about the same - /// time. Each doubling of the width roughly doubles the time. + /// Default width of the beam search: see [`with_beam`](Self::with_beam). pub const DEFAULT_BEAM: usize = 4; - /// Default success rate below which the model is not run on an automaton - /// or a piece of its decomposition (see - /// [`with_min_success`](Self::with_min_success)). Higher thresholds save - /// little time: an automaton the model is not run on is decomposed, and - /// the model runs on its pieces. + /// Default success rate below which the model is not run: see + /// [`with_min_success`](Self::with_min_success). pub const DEFAULT_MIN_SUCCESS: f64 = 0.05; /// Loads a model from its `config.json` and `model.safetensors` files. @@ -448,75 +440,77 @@ impl NeuralSynthesizer { }) } - /// Sets how many candidates are decoded per automaton (at least 1): the - /// greedy decoding, or the hypotheses of the beam search - /// ([`with_beam`](Self::with_beam)), then samples (default - /// [`DEFAULT_CANDIDATES`](Self::DEFAULT_CANDIDATES)). More candidates find - /// a correct regex more often, at the cost of decoding and checking them. + /// Sets the number of regexes the model writes per automaton, at least 1 + /// (default [`DEFAULT_CANDIDATES`](Self::DEFAULT_CANDIDATES)): the result + /// of the beam search ([`with_beam`](Self::with_beam)), then `candidates - + /// 1` samples. + /// + /// More regexes find a correct one more often, and take more time to write + /// and check. pub fn with_candidates(mut self, candidates: usize) -> Self { self.sampling.candidates = candidates.max(1); self } - /// Sets the sampling temperature of the candidates after the first - /// (default 1). A temperature that is not positive samples greedily, so - /// every candidate is the first. + /// Sets the sampling temperature of the regexes after the first (default + /// 1). At 0 or below, they are all the same regex: the one made of the + /// model's most likely choice at each step. pub fn with_temperature(mut self, temperature: f64) -> Self { self.sampling.temperature = temperature; self } - /// Sets the seed of the sampling (default 0). Proposals are - /// deterministic for a given seed and device. + /// Sets the seed of the sampling (default 0). The same seed on the same + /// device gives the same regexes. pub fn with_seed(mut self, seed: u64) -> Self { self.sampling.seed = seed; self } - /// Sets the width of a beam search that replaces the greedy decoding - /// (default [`DEFAULT_BEAM`](Self::DEFAULT_BEAM); 0 or 1 decodes - /// greedily). Its hypotheses, up to `beam` of the most likely regexes, are - /// checked with the [`with_candidates`](Self::with_candidates) `- 1` - /// samples. A beam of width `w` decodes up to `w` sequences per automaton, - /// about the cost of `w` candidates. + /// Sets the width of the beam search (default + /// [`DEFAULT_BEAM`](Self::DEFAULT_BEAM)): the model writes up to `beam` of + /// its most likely regexes, which are all checked. 0 and 1 turn the search + /// off, and the model writes its most likely regex alone. + /// + /// Time grows about in proportion to the width. pub fn with_beam(mut self, beam: usize) -> Self { self.sampling.beam = beam; self } - /// Sets whether converting ([`FastAutomaton::to_regex_with`]) splits an - /// automaton the model has no correct regex for, or is too large for, - /// into independent pieces and runs the model on those (default `true`). - /// Splitting finds simpler regexes for many more automata, at the cost of - /// running the model on many pieces: up to seconds on the CPU for - /// automata of dozens of states. + /// Sets whether [`FastAutomaton::to_regex_with`] splits an automaton that + /// the model has no correct regex for, or that is too large for it, into + /// pieces that the model converts one by one (default `true`). + /// + /// Splitting finds simpler regexes for many more automata, and can take + /// seconds on the CPU for automata of dozens of states. pub fn with_decomposition(mut self, decomposition: bool) -> Self { self.decomposition = decomposition; self } - /// Sets the success rate below which converting - /// ([`FastAutomaton::to_regex_with`]) does not run the model on an - /// automaton, going straight to its decomposition, nor on a piece of the - /// decomposition, which is then split further or converted by state - /// elimination (default [`DEFAULT_MIN_SUCCESS`](Self::DEFAULT_MIN_SUCCESS)). - /// The rate is the model's, from its `config.json`, for DFAs like the - /// automaton's (or the piece's) minimal DFA (see the [module - /// documentation](self)); a model without one is always run, and so is - /// every model with 0. Skipping saves the decoding and checking of - /// candidates that are almost never correct. + /// Sets the success rate below which [`FastAutomaton::to_regex_with`] does + /// not run the model on an automaton, or on a piece of one (default + /// [`DEFAULT_MIN_SUCCESS`](Self::DEFAULT_MIN_SUCCESS)): it is split + /// further, or converted by state elimination. + /// + /// The rate is the one the model's `config.json` gives for automata of that + /// size and difficulty (see the [module documentation](self#models)). A + /// model without rates is always run, and a threshold of 0 runs any model + /// on every automaton. pub fn with_min_success(mut self, min_success: f64) -> Self { self.min_success = min_success; self } - /// The model's success rate for `automaton`, from its `config.json`: - /// how often, on a calibration set, one of its candidates was correct for - /// DFAs like the automaton's minimal DFA. `None` when the model has no - /// rate or none for such DFAs. + /// Returns the model's success rate for `automaton`, from its + /// `config.json`: how often one of its regexes was correct for automata of + /// that size and difficulty. `None` when the model gives no rate for them. + /// + /// # Errors /// /// Fails if `automaton` cannot be minimized, or its minimal DFA converted - /// by state elimination, within the execution profile. + /// by state elimination, within the limits of the execution profile. pub fn success_rate(&self, automaton: &FastAutomaton) -> Result, EngineError> { match &self.gate { Some(gate) => gate.rate(&minimal_dfa(automaton)?, None), @@ -540,16 +534,18 @@ impl NeuralSynthesizer { self.model.max_bases() } - /// Asks the model for a regex describing exactly the language of - /// `automaton`. + /// Asks the model for a regex that matches the strings `automaton` accepts, + /// and no other. + /// + /// Returns the simplest correct regex the model wrote; `None` when the + /// automaton is beyond the model's limits or when no regex is correct. The + /// automaton is not split into pieces: [`FastAutomaton::to_regex_with`] + /// runs the whole conversion. /// - /// Returns the simplest candidate equivalent to the automaton, or `None` - /// when its minimal DFA is beyond the model's limits or no candidate is - /// correct. Candidates whose check fails (for instance on the execution - /// profile's timeout) are skipped. + /// # Errors /// - /// Fails if `automaton` cannot be minimized within the execution - /// profile, or if the profile's deadline passes during inference. + /// Fails if `automaton` cannot be minimized within the limits of the + /// execution profile, or if its timeout passes while the model runs. pub fn propose( &self, automaton: &FastAutomaton, @@ -557,9 +553,9 @@ impl NeuralSynthesizer { Ok(self.propose_batch(&[automaton])?.pop().flatten()) } - /// [`propose`](Self::propose) for several automata at once: the model - /// decodes them together, which is much faster than one by one. The - /// result for each automaton is the same as `propose`'s. + /// [`propose`](Self::propose) for several automata, which the model handles + /// together: it takes less time than one call per automaton, for the same + /// results. pub fn propose_batch( &self, automata: &[&FastAutomaton], @@ -760,19 +756,19 @@ impl NeuralSynthesizer { } impl RegexSynthesizer for NeuralSynthesizer { - /// The model first proposes a regex for the whole automaton, unless its - /// success rate for it is below the threshold - /// ([`with_min_success`](NeuralSynthesizer::with_min_success)). When it has - /// no correct one, or the automaton is beyond its limits or below the - /// threshold, the automaton's - /// minimal DFA is split into independent pieces (unless - /// [`with_decomposition`](NeuralSynthesizer::with_decomposition) disables - /// it), each converted by the model or by state elimination, whichever is - /// simpler, and their regexes combined. Returns the simpler of that result - /// and [`FastAutomaton::to_regex`]'s state elimination; state elimination - /// alone if the model fails (for instance on the execution profile's - /// deadline). The result always describes exactly the automaton's - /// language. + /// Converts `automaton` with the model, as the [module documentation](self) + /// describes, and returns the simpler of the result and the regex of state + /// elimination ([`FastAutomaton::to_regex`]). + /// + /// The regex returned matches the strings the automaton accepts, and no + /// other, whatever the model writes. State elimination alone is returned + /// when the model fails, for instance on the timeout of the execution + /// profile. + /// + /// # Errors + /// + /// Returns the error of state elimination when it fails and the model gave + /// no regex. fn synthesize(&self, automaton: &FastAutomaton) -> Result { let (proposed, dfa_eliminated) = match self.propose_or_decompose(automaton) { Ok(proposed) => proposed, diff --git a/src/fast_automaton/generate.rs b/src/fast_automaton/generate.rs index b34cfc4..53a23ce 100644 --- a/src/fast_automaton/generate.rs +++ b/src/fast_automaton/generate.rs @@ -12,80 +12,51 @@ use std::ops::Range; /// charset leaves nothing of. type RangeIds<'a> = AHashMap<&'a Condition, Option>; -/// How [`FastAutomaton::generate_strings`] schedules the *paths* of a -/// language: one at a time, or interleaved so that every shape the pattern -/// allows is covered early. Orthogonal to [`CharacterOrder`], which chooses -/// the strings within each path. +/// The order [`FastAutomaton::generate_strings`] visits the *paths* of an +/// automaton in. A path is a sequence of transitions from the start state to an +/// accept state: it yields one string per choice of characters, in the order +/// [`CharacterOrder`] sets. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum PathOrder { - /// One path at a time, shortest first, expanded in full before the next - /// path is visited: `.*abc.*` yields `abc`, `abc\u{0}`, `abc\u{1}`, ... - /// The cheapest way to page through a whole language with `offset`. + /// One path at a time, shortest first: all the strings of a path come + /// before the next path. `.*abc.*` yields `abc`, `abc\u{0}`, `abc\u{1}`, + /// ... The fastest order to page through a whole language. #[default] Sweep, - /// A few strings per path before moving to the next one, so `.*abc.*` - /// yields `abc` and a string for each of the other shapes (`abc\u{0}`, - /// `\u{0}abc`, ...) instead of a million variations of one of them. + /// A few strings of each path at a time, so that every path yields a string + /// before any yields a second one: `.*abc.*` yields `abc`, then a string of + /// each other path (`abc\u{0}`, `\u{0}abc`, ...). /// - /// Shape comes first: the strings cover every path the automaton holds - /// before any path is asked for a second one, so a `limit` smaller than - /// the number of shapes is spent entirely on distinct shapes, and only a - /// larger one starts varying the characters within them. - /// - /// Deterministic, and pages with `offset` like [`Sweep`](Self::Sweep). - /// Each pass takes twice as many strings per path as the previous one, so - /// a finite language is still enumerated in full given a large enough - /// `limit`; those repeated passes make it slower than `Sweep`. + /// Slower than [`Sweep`](Self::Sweep), and pages with `offset` like it. Interleave, - /// [`Interleave`](Self::Interleave), with same-length paths visited in an - /// order drawn by the seed ([`GenerationOptions::with_seed`], 0 by - /// default) instead of a fixed one. Shorter paths still come first, since - /// the search has to stay shortest-first to emit anything at all on an - /// infinite language, so the seed only draws among paths of equal length. - /// - /// The draw within a length is a randomized cascade rather than a uniform - /// shuffle: the seed randomizes the pop order of the underlying - /// shortest-first search, and a path only becomes available once its whole - /// prefix chain has popped, so a shape branching off an already-visited - /// path leads more often than one sharing nothing with it. Coverage is - /// untouched, every shape still coming before any shape's second string. + /// [`Interleave`](Self::Interleave), with the paths of the same length + /// visited in an order drawn from the seed + /// ([`GenerationOptions::with_seed`]). Shorter paths still come first. /// - /// Independent of [`CharacterOrder`]: shuffled paths over - /// [`Ascending`](CharacterOrder::Ascending) characters yield each drawn - /// shape's smallest witness; pair with [`CharacterOrder::Shuffled`] for - /// fully random-looking test cases. Deterministic for a given seed, and - /// pages with `offset` like the other orders; offsets are only consistent - /// between calls sharing the seed. + /// The order is the same for the same seed, so `offset` pages through it. + /// It is not a uniform shuffle of the paths. Pair it with + /// [`CharacterOrder::Shuffled`] for strings that look random. Shuffled, } -/// Which strings of a path [`FastAutomaton::generate_strings`] reaches for -/// first: its character combinations in ascending order, or a seeded shuffle -/// of them. Orthogonal to [`PathOrder`], which schedules the paths -/// themselves. +/// The order [`FastAutomaton::generate_strings`] yields the strings of one path +/// in (see [`PathOrder`]). /// -/// Neither changes *what* is generated: on a finite language every -/// combination of the two axes enumerates exactly the same strings, given the -/// `limit`. To generate from specific characters, restrict generation with +/// Over a whole finite language, it changes the order of the strings, not which +/// ones are generated. To generate from chosen characters, see /// [`GenerationOptions::with_charset`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum CharacterOrder { - /// Each position expanded from the low end of its character range first: - /// `[a-z]{8}` yields `aaaaaaaa`, `aaaaaaab`, ... A stable, documented - /// order: the smallest witnesses of a path come first. + /// From the lowest character of each position: `[a-z]{8}` yields + /// `aaaaaaaa`, `aaaaaaab`, ... #[default] Ascending, - /// A seeded permutation of each path's combinations, so `[a-z]{8}` yields - /// something like `sjtwsive` rather than `aaaaaaaa`. To draw the *shapes* - /// by the seed too, pair with [`PathOrder::Shuffled`]. + /// In an order drawn from the seed ([`GenerationOptions::with_seed`]): + /// `[a-z]{8}` yields something like `sjtwsive`. /// - /// Random in look only: the seed ([`GenerationOptions::with_seed`], 0 by - /// default) picks one fixed permutation, so generation is reproducible and - /// pages with `offset` like [`Ascending`](Self::Ascending). The - /// permutation is a bijection, so it repeats no more strings across - /// offsets than `Ascending` does. Offsets are only consistent between - /// calls sharing the seed, and unlike `Ascending`'s the exact sequence is - /// implementation-defined: it may change between releases. + /// The order is the same for the same seed, so `offset` pages through it as + /// it does through [`Ascending`](Self::Ascending). The sequence a seed + /// gives may change between releases of the crate. Shuffled, } @@ -137,15 +108,12 @@ impl PartialOrd for QueueItem { } } -/// What [`FastAutomaton::generate_strings`] is allowed to generate: how paths -/// are scheduled ([`PathOrder`]), how the strings within them are ordered -/// ([`CharacterOrder`], with the seed behind the `Shuffled` modes of both -/// axes), the characters it may use, and the string lengths it is confined -/// to. +/// The options of [`FastAutomaton::generate_strings`]: the order of the paths +/// ([`PathOrder`]) and of the strings of a path ([`CharacterOrder`]), the seed +/// of their `Shuffled` orders, and the characters and lengths allowed. /// -/// Either axis converts into it, so one can be passed on its own wherever -/// options are expected and the other keeps its default; so does a -/// `(PathOrder, CharacterOrder)` pair. +/// A [`PathOrder`], a [`CharacterOrder`] or a pair of them converts into it, +/// the other options keeping their default. /// /// # Examples /// @@ -178,35 +146,28 @@ pub struct GenerationOptions { } impl GenerationOptions { - /// Default options: [`PathOrder::Sweep`] over - /// [`CharacterOrder::Ascending`] combinations, using every character and - /// string length the automaton allows. + /// Creates the default options: [`PathOrder::Sweep`] and + /// [`CharacterOrder::Ascending`], with every character and length allowed. pub fn new() -> Self { Self::default() } - /// Returns a copy of these options scheduling paths in `paths` order. + /// Sets the order of the paths. pub fn with_paths(mut self, paths: PathOrder) -> Self { self.paths = paths; self } - /// Returns a copy of these options ordering each path's strings in - /// `characters` order. + /// Sets the order of the strings of a path. pub fn with_characters(mut self, characters: CharacterOrder) -> Self { self.characters = characters; self } - /// Returns a copy of these options restricted to `charset`. - /// - /// Only strings made entirely of those characters are generated: a path - /// through a transition that `charset` rules out is dropped whole, never - /// shortened. Restricting to characters the automaton never matches - /// generates nothing. + /// Restricts generation to the strings made of characters of `charset`. /// - /// A [`CharRange`] is built from bounds, or out of a character class - /// pattern through [`RegularExpression`]: + /// A [`CharRange`] is built from bounds, or from a character class pattern + /// through [`RegularExpression`]: /// /// ``` /// use regexsolver::{CharRange, regex::RegularExpression}; @@ -224,68 +185,63 @@ impl GenerationOptions { self } - /// Returns a copy of these options drawing [`PathOrder::Shuffled`]'s - /// path draws and [`CharacterOrder::Shuffled`]'s permutation from `seed`; - /// generation using neither ignores it. + /// Sets the seed of [`PathOrder::Shuffled`] and + /// [`CharacterOrder::Shuffled`], 0 by default. /// - /// The default seed is 0, a fixed seed rather than a random one, so two - /// calls with the same options generate the same strings and `offset` - /// pages through them consistently. Change the seed to draw a different - /// sequence of strings from the same pattern. + /// The same options generate the same strings, so `offset` pages through + /// them. Change the seed to get another sequence. pub fn with_seed(mut self, seed: u64) -> Self { self.seed = seed; self } - /// Returns a copy of these options generating only strings at least - /// `min_length` characters long: the shorter strings the automaton - /// matches are left out of the enumeration, `offset` never counting - /// them. 0 by default, which keeps every string. + /// Leaves out the strings shorter than `min_length` characters, which + /// `offset` does not count. 0 by default. pub fn with_min_length(mut self, min_length: usize) -> Self { self.min_length = min_length; self } - /// Returns a copy of these options generating only strings at most - /// `max_length` characters long: the longer strings the automaton - /// matches are left out of the enumeration, `offset` never counting - /// them. Unbounded by default; without a bound, a deep `offset` into a - /// looping language (`.*`) pages into arbitrarily long strings, so set one - /// when the offset is not under your control. + /// Leaves out the strings longer than `max_length` characters, which + /// `offset` does not count. No bound by default. /// - /// A bound below `min_length` leaves nothing to generate. + /// Set one when `offset` is not under your control: without it, a large + /// offset into an infinite language reaches strings of any length. A bound + /// below the minimum length leaves no string. pub fn with_max_length(mut self, max_length: usize) -> Self { self.max_length = Some(max_length); self } - /// The order paths are scheduled in. + /// Returns the order of the paths. pub fn paths(&self) -> PathOrder { self.paths } - /// The order each path's strings come out in. + /// Returns the order of the strings of a path. pub fn characters(&self) -> CharacterOrder { self.characters } - /// The characters generation is restricted to, `None` when it is not. + /// Returns the characters generation is restricted to, `None` when it is + /// not. pub fn charset(&self) -> Option<&CharRange> { self.charset.as_ref() } - /// The seed behind [`PathOrder::Shuffled`] and + /// Returns the seed of [`PathOrder::Shuffled`] and /// [`CharacterOrder::Shuffled`]. pub fn seed(&self) -> u64 { self.seed } - /// The shortest string generation may emit. + /// Returns the length of the shortest strings generated. pub fn min_length(&self) -> usize { self.min_length } - /// The longest string generation may emit, `None` when unbounded. + /// Returns the length of the longest strings generated, `None` when there + /// is no bound. pub fn max_length(&self) -> Option { self.max_length } @@ -320,27 +276,28 @@ impl From<(PathOrder, CharacterOrder)> for GenerationOptions { } impl FastAutomaton { - /// Generates up to `limit` distinct strings matched by the automaton under - /// the given [`GenerationOptions`], skipping the first `offset` strings. + /// Returns up to `limit` distinct strings that the automaton accepts, + /// skipping the first `offset` ones. + /// + /// `options` sets the order of the strings, the seed of the shuffled + /// orders, and the characters and lengths allowed: see + /// [`GenerationOptions`]. A [`PathOrder`], a [`CharacterOrder`] or a pair + /// of them can be passed in its place. + /// + /// # Pagination + /// + /// `offset` pages through the strings. Pages are only consistent across + /// calls on the same automaton with the same options. A non-deterministic + /// automaton can repeat or skip strings from one page to the next: + /// [`determinize`](Self::determinize) it first. /// - /// `options` is a [`PathOrder`] or [`CharacterOrder`] on its own (or a - /// pair of them), or a full [`GenerationOptions`] to also set the seed - /// and restrict the characters and string lengths used. + /// Without [`GenerationOptions::with_max_length`], a large `offset` into an + /// infinite language reaches strings of any length. /// - /// Strings are only guaranteed to be distinct **within a single call**: - /// the offset fast-skips by counting paths, and in a non-deterministic - /// automaton the same string can be reached through several paths, so - /// calls with different offsets may repeat strings (or skip some). - /// [`determinize`](Self::determinize) (and ideally - /// [`minimize`](Self::minimize)) first to make pages disjoint. Offsets are - /// also only consistent between calls made with the same options. + /// # Errors /// - /// [`GenerationOptions::with_min_length`] and - /// [`with_max_length`](GenerationOptions::with_max_length) confine the - /// enumeration to a band of string lengths. Without a max, a deep - /// `offset` into a looping language (`.*`) pages into arbitrarily long - /// strings. Generation runs under the active [`ExecutionProfile`]: its - /// timeout aborts with [`EngineError::OperationTimeOutError`]. + /// Returns [`EngineError::OperationTimeOutError`] when the timeout of the + /// [`ExecutionProfile`] passes. #[tracing::instrument(level = "debug", skip(self, options), fields(states = self.number_of_states(), deterministic=self.is_deterministic(), limit=limit, offset=offset, paths=tracing::field::Empty, characters=tracing::field::Empty, charset=tracing::field::Empty, seed=tracing::field::Empty, min_length=tracing::field::Empty, max_length=tracing::field::Empty))] pub fn generate_strings( &self, diff --git a/src/fast_automaton/mod.rs b/src/fast_automaton/mod.rs index 1a1dec4..76dfb46 100644 --- a/src/fast_automaton/mod.rs +++ b/src/fast_automaton/mod.rs @@ -16,8 +16,8 @@ pub type State = usize; mod analyze; mod builder; -/// Transition labels: the bitvector [`Condition`] type over an automaton's -/// spanning set of disjoint character ranges. +/// The [`Condition`] of a transition: a set of characters, expressed over the +/// spanning set of its automaton. pub mod condition; pub(crate) mod convert; mod generate; @@ -29,7 +29,26 @@ pub mod spanning_set; pub use convert::to_regex::{RegexSynthesizer, StateElimination}; pub use generate::{CharacterOrder, GenerationOptions, PathOrder}; -/// Represents a finite-state automaton. +/// A finite automaton over Unicode characters, deterministic or not. +/// +/// It has one start state, and its states are identified by a [`State`]. A +/// transition holds a [`Condition`]: a set of characters, expressed over the +/// automaton's [`SpanningSet`]. +/// +/// An automaton is built from a pattern with +/// [`RegularExpression::to_automaton`](crate::regex::RegularExpression::to_automaton), +/// or by hand with [`new_state`](Self::new_state) and +/// [`add_transition_from_range`](Self::add_transition_from_range). +/// +/// # Examples +/// +/// ``` +/// use regexsolver::regex::RegularExpression; +/// +/// let automaton = RegularExpression::new("ab*")?.to_automaton()?; +/// assert!(automaton.is_match("abb")); +/// # Ok::<(), regexsolver::error::EngineError>(()) +/// ``` #[derive(Clone, Debug, PartialEq, Eq)] #[must_use = "non-`_mut` operations return a new automaton"] pub struct FastAutomaton { @@ -43,8 +62,9 @@ pub struct FastAutomaton { minimal: bool, } -/// Returned by [`FastAutomaton::try_add_transition`] when adding the requested -/// condition would turn a DFA into an NFA. The automaton is left unchanged. +/// Returned by [`FastAutomaton::try_add_transition`] when the transition would +/// make a deterministic automaton non-deterministic. The automaton is left +/// unchanged. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DeterminismLost; @@ -97,14 +117,14 @@ impl FastAutomaton { } } - /// Returns the number of transitions to the provided state. + /// Returns the number of transitions to `state`, `0` if it does not exist. #[inline] pub fn in_degree(&self, state: State) -> usize { self.transitions_in.get(&state).map_or(0, IntSet::len) } - /// Returns the number of transitions from the provided state. - /// Returns `0` if the state does not exist. + /// Returns the number of transitions from `state`, `0` if it does not + /// exist. #[inline] pub fn out_degree(&self, state: State) -> usize { if !self.has_state(state) { @@ -113,20 +133,20 @@ impl FastAutomaton { self.transitions[state].len() } - /// Returns an iterator over the automaton’s states. + /// Returns an iterator over the states. #[inline] pub fn states(&self) -> impl Iterator + '_ { (0..self.transitions.len()).filter(|s| !self.removed_states.contains(s)) } - /// Returns a vector containing the automaton’s states. + /// Returns the states. #[inline] pub fn states_vec(&self) -> Vec { self.states().collect() } - /// Returns an iterator over states directly reachable from the given state in one transition. - /// Returns an empty iterator if the state does not exist. + /// Returns an iterator over the states that `state` has a transition to; + /// empty if it does not exist. #[inline] pub fn direct_states(&self, state: State) -> impl Iterator + '_ { self.transitions.get(state).into_iter().flat_map(move |t| { @@ -136,13 +156,13 @@ impl FastAutomaton { }) } - /// Returns a vector of states directly reachable from the given state in one transition. + /// Returns the states that `state` has a transition to. #[inline] pub fn direct_states_vec(&self, state: State) -> Vec { self.direct_states(state).collect() } - /// Returns a vector of transitions to the given state. + /// Returns the transitions to `state`, with the state each comes from. pub fn transitions_to_vec(&self, state: State) -> Vec<(State, Condition)> { if !self.has_state(state) { return vec![]; @@ -162,8 +182,8 @@ impl FastAutomaton { in_transitions } - /// Returns a vector of transitions from the given state. - /// Returns an empty vector if the state does not exist. + /// Returns the transitions from `state`, with the state each leads to; + /// empty if it does not exist. #[inline] pub fn transitions_from_vec(&self, state: State) -> Vec<(Condition, State)> { self.transitions @@ -177,8 +197,8 @@ impl FastAutomaton { .unwrap_or_default() } - /// Returns an iterator over transitions from the given state. - /// Returns an empty iterator if the state does not exist. + /// Returns an iterator over the transitions from `state`, with the state + /// each leads to; empty if it does not exist. #[inline] pub fn transitions_from( &self, @@ -191,7 +211,7 @@ impl FastAutomaton { }) } - /// Returns `true` if there is a directed transition from `from_state` to `to_state`. + /// Returns `true` if there is a transition from `from_state` to `to_state`. #[inline] pub fn has_transition(&self, from_state: State, to_state: State) -> bool { if !self.has_state(from_state) || !self.has_state(to_state) { @@ -214,14 +234,14 @@ impl FastAutomaton { .collect() } - /// Returns the number of states in the automaton. + /// Returns the number of states. #[inline] pub fn number_of_states(&self) -> usize { self.transitions.len() - self.removed_states.len() } - /// Returns a reference to the condition of the directed transition between the two states, if any. - /// Returns `None` if either state does not exist. + /// Returns the condition of the transition from `from_state` to `to_state`; + /// `None` if there is none or if a state does not exist. #[inline] pub fn condition(&self, from_state: State, to_state: State) -> Option<&Condition> { self.transitions @@ -235,49 +255,54 @@ impl FastAutomaton { self.start_state } - /// Returns a reference to the set of accept (final) states. + /// Returns the accept states. #[inline] pub fn accept_states(&self) -> &IntSet { &self.accept_states } - /// Returns a reference to the automaton's spanning set. + /// Returns the spanning set: the ranges of characters that the conditions + /// of the transitions are expressed over. #[inline] pub fn spanning_set(&self) -> &SpanningSet { &self.spanning_set } - /// Returns `true` if the given state is one of the accept states. + /// Returns `true` if `state` is an accept state. #[inline] pub fn is_accepted(&self, state: State) -> bool { self.accept_states.contains(&state) } - /// Returns `true` if the automaton is deterministic. + /// Returns `true` if the automaton is known to be deterministic. /// - /// Note: this flag degrades monotonically. Once `add_transition` introduces - /// an overlapping condition, the flag flips to `false` and is not - /// re-checked by `remove_transition` or `remove_state`. The automaton may - /// in fact be deterministic again after such removals; call - /// [`determinize`](Self::determinize) if you need a fresh DFA. + /// `false` does not prove the contrary: adding a transition that overlaps + /// another one makes it `false`, and removing transitions or states does + /// not make it `true` again. [`determinize`](Self::determinize) returns an + /// automaton for which it is `true`. #[inline] pub fn is_deterministic(&self) -> bool { self.deterministic } - /// Returns `true` if the automaton is minimal. + /// Returns `true` if the automaton is known to be the minimal deterministic + /// automaton of its language. [`minimize`](Self::minimize) makes it hold. #[inline] pub fn is_minimal(&self) -> bool { self.minimal } - /// Returns `true` if the automaton contains the given state. + /// Returns `true` if `state` is a state of the automaton. #[inline] pub fn has_state(&self, state: State) -> bool { !(state >= self.transitions.len() || self.removed_states.contains(&state)) } - /// Returns `true` if the automaton matches the given string. + /// Returns `true` if the automaton accepts `string`, as a whole. + /// + /// Linear in the length of `string` for a deterministic automaton. + /// Otherwise, each character can take time proportional to the number of + /// transitions. #[tracing::instrument(level = "debug", skip(self, string), fields(states = self.number_of_states(), string_len=string.len()))] pub fn is_match(&self, string: &str) -> bool { let mut current: IntSet = IntSet::default(); @@ -316,13 +341,13 @@ impl FastAutomaton { current.iter().any(|s| self.accept_states.contains(s)) } - /// Returns the automaton's DOT representation. + /// Returns the automaton in Graphviz DOT format. #[inline] pub fn to_dot(&self) -> String { format!("{self}") } - /// Prints the automaton's DOT representation. + /// Prints the automaton in Graphviz DOT format to the standard output. #[inline] pub fn print_dot(&self) { println!("{self}"); diff --git a/src/fast_automaton/operation/concat.rs b/src/fast_automaton/operation/concat.rs index 804ad84..471a26d 100644 --- a/src/fast_automaton/operation/concat.rs +++ b/src/fast_automaton/operation/concat.rs @@ -7,14 +7,18 @@ use crate::error::EngineError; use super::*; impl FastAutomaton { - /// Computes the concatenation between `self` and `other`. + /// Returns the concatenation of `self` and `other`: the strings made of a + /// string of `self` followed by a string of `other`. + /// + /// The result has about as many states as both automata together. pub fn concat(&self, other: &FastAutomaton) -> Result { let mut new_automaton = self.clone(); new_automaton.concat_mut(other)?; Ok(new_automaton) } - /// Computes the concatenation of all automata in the given iterator. + /// Returns the concatenation of `automata`, in order. An empty iterator + /// gives the automaton that accepts the empty string `""` and no other. #[tracing::instrument(level = "debug", skip_all)] pub fn concat_all<'a, I: IntoIterator>( automata: I, diff --git a/src/fast_automaton/operation/determinize.rs b/src/fast_automaton/operation/determinize.rs index 92d6406..0ffcf9a 100644 --- a/src/fast_automaton/operation/determinize.rs +++ b/src/fast_automaton/operation/determinize.rs @@ -17,7 +17,12 @@ impl FastAutomaton { self.determinize() } - /// Determinizes the automaton and returns the result. + /// Returns an equivalent deterministic automaton. `self` is borrowed when + /// it is known to be deterministic. + /// + /// Exponential in the worst case: an automaton of `n` states can need `2^n` + /// of them once deterministic. The timeout and the `max_number_of_states` + /// of the execution profile apply. #[tracing::instrument(level = "debug", skip_all, fields(states = self.number_of_states(), deterministic = self.is_deterministic()))] pub fn determinize(&self) -> Result, EngineError> { if self.deterministic { diff --git a/src/fast_automaton/operation/difference.rs b/src/fast_automaton/operation/difference.rs index cbc9074..4c44697 100644 --- a/src/fast_automaton/operation/difference.rs +++ b/src/fast_automaton/operation/difference.rs @@ -1,6 +1,7 @@ use std::hash::BuildHasherDefault; +use std::ops::Range; -use condition::converter::SharedSpanningSet; +use condition::converter::ConditionConverter; use crate::fast_automaton::analyze::state_sets::{Id, Operand}; use crate::{EngineError, execution_profile::ExecutionProfile}; @@ -48,12 +49,17 @@ impl FastAutomaton { Ok(()) } - /// Complements the automaton. + /// Replaces the automaton with its complement: the strings it does not + /// accept. /// - /// If `self` is non-deterministic, it is determinized in place first, - /// unless the execution profile disables implicit determinization, in - /// which case [`EngineError::DeterministicAutomatonRequired`] is - /// returned. + /// A non-deterministic automaton is determinized first, which is + /// exponential in the worst case. + /// + /// # Errors + /// + /// Returns [`EngineError::DeterministicAutomatonRequired`] for a + /// non-deterministic automaton when the execution profile disables implicit + /// determinization. #[tracing::instrument(level = "debug", skip_all, fields(states = self.number_of_states(), deterministic = self.is_deterministic()))] pub fn complement(&mut self) -> Result<(), EngineError> { if !self.deterministic { @@ -73,13 +79,17 @@ impl FastAutomaton { Ok(()) } - /// Computes the difference between `self` and `other`. + /// Returns the difference of `self` and `other`: the strings that `self` + /// accepts and `other` does not. + /// + /// Neither automaton is determinized. The result is deterministic when + /// `self` is. /// - /// `other` is not determinized or complemented first: a state of the - /// result pairs a state of `self` with the set of states of `other` that - /// the same word reaches, and only the pairs a word reaches are built. - /// The result is still exponential in `other` in the worst case; the - /// execution profile's timeout and `max_number_of_states` apply to it. + /// With `n` and `m` the numbers of states of `self` and `other`, the result + /// has up to `n × 2^m` states. The timeout of the execution profile + /// applies, and its `max_number_of_states` caps the number of states built, + /// including those left out of the result because no accept state can be + /// reached from them. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] pub fn difference(&self, other: &FastAutomaton) -> Result { if self.is_empty() || other.is_total() || self == other { @@ -87,46 +97,475 @@ impl FastAutomaton { } else if other.is_empty() { return Ok(self.clone()); } + let (left, right, shared) = Operand::pair(self, 0, other, 0)?; + let spanning_set = shared.into_spanning_set(); + let Some(start) = left.start else { + return Ok(Self::new_empty()); + }; + + let mut difference = Draft::default(); + let mut pairs = Pairs::new(&left, &right); + pairs.state(&mut difference, start, right.start.as_slice()); + pairs.walk(&mut difference, &spanning_set)?; + Ok(difference.into_automaton(spanning_set)) + } + + /// Returns the symmetric difference of `self` and `other`: the strings that + /// exactly one of the two accepts. + /// + /// Neither automaton is determinized. The result is deterministic when both + /// are. + /// + /// With `n` and `m` the numbers of states of `self` and `other`, the result + /// has up to `n × m + n × 2^m + m × 2^n` states, and about `n × m` when + /// both are deterministic. The timeout of the execution profile applies, + /// and its `max_number_of_states` caps the number of states built, + /// including those left out of the result because no accept state can be + /// reached from them. + #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), self_deterministic = self.is_deterministic(), other_states = other.number_of_states(), other_deterministic = other.is_deterministic()))] + pub fn symmetric_difference( + &self, + other: &FastAutomaton, + ) -> Result { + match (self.is_empty(), other.is_empty()) { + (true, true) => return Ok(Self::new_empty()), + (true, false) => return Ok(other.clone()), + (false, true) => return Ok(self.clone()), + (false, false) if self == other => return Ok(Self::new_empty()), + (false, false) => {} + } + let (left, right, shared) = Operand::pair(self, 0, other, 0)?; + let spanning_set = shared.into_spanning_set(); + // Neither operand is empty, so both start states are live. An + // operand whose start state is not live would be empty all the same. + let (start, other_start) = match (left.start, right.start) { + (Some(start), Some(other_start)) => (start, other_start), + (None, _) => return Ok(other.clone()), + (_, None) => return Ok(self.clone()), + }; let execution_profile = ExecutionProfile::get(); - let shared = SharedSpanningSet::new(&self.spanning_set, &other.spanning_set); - let (self_converter, other_converter) = shared.converters()?; - let left = Operand::new(self, 0, self_converter.as_ref())?; - let right = Operand::new(other, 0, other_converter.as_ref())?; - let spanning_set = shared.spanning_set(); + let mut difference = Draft::default(); + difference.new_state(left.accepts(start) != right.accepts(other_start)); + // The state of each pair of one state of `self` and one state of + // `other`: the strings that exactly one of the two states accepts. + let mut states: AHashMap<(Id, Id), usize> = AHashMap::new(); + states.insert((start, other_start), Draft::START); + let mut worklist = VecDeque::new(); + worklist.push_back((Draft::START, start, other_start)); + // The pairs met once a word reaches several states of an operand, or + // none: the two differences. + let (mut pairs, mut other_pairs) = (Pairs::new(&left, &right), Pairs::new(&right, &left)); - let Some(start) = left.start else { - return Ok(Self::new_empty()); + let bases = spanning_set.spanning_ranges_with_rest_len(); + let mut successors = vec![Vec::new(); bases]; + let mut other_successors = vec![Vec::new(); bases]; + // A base for each pair of sets the two states lead to, with all the + // bases that lead to it. + let mut targets: Vec<(usize, Condition)> = Vec::new(); + + while let Some((state, from, other_from)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(difference.number_of_states())?; + + left.successors(&[from], &mut successors); + right.successors(&[other_from], &mut other_successors); + + for base in 0..bases { + let (set, other_set) = (&successors[base], &other_successors[base]); + if set.is_empty() && other_set.is_empty() { + continue; + } + match targets.iter_mut().find(|(other_base, _)| { + successors[*other_base] == *set && other_successors[*other_base] == *other_set + }) { + Some((_, bases)) => bases.insert_base(base), + None => targets.push((base, Condition::single_base(base, &spanning_set))), + } + } + for (base, bases) in targets.drain(..) { + let (set, other_set) = (&successors[base], &other_successors[base]); + if let (&[to], &[other_to]) = (set.as_slice(), other_set.as_slice()) { + let target = *states.entry((to, other_to)).or_insert_with(|| { + let target = + difference.new_state(left.accepts(to) != right.accepts(other_to)); + worklist.push_back((target, to, other_to)); + target + }); + difference.add_transition(state, target, bases); + continue; + } + for &to in set { + let target = pairs.state(&mut difference, to, other_set); + difference.add_transition(state, target, bases.clone()); + } + for &to in other_set { + let target = other_pairs.state(&mut difference, to, set); + difference.add_transition(state, target, bases.clone()); + } + } + } + pairs.walk(&mut difference, &spanning_set)?; + other_pairs.walk(&mut difference, &spanning_set)?; + Ok(difference.into_automaton(spanning_set)) + } + + /// Returns the symmetric difference of `automata`: the strings that an odd + /// number of them accepts. + /// + /// The order of the automata does not change the language of the result. An + /// empty iterator gives the automaton that accepts no string, and two + /// automata are combined as + /// [`symmetric_difference`](Self::symmetric_difference) does. + /// + /// No automaton is determinized first. The result is deterministic when + /// every automaton is. + /// + /// Exponential in the worst case: with `n` the total number of states of + /// the automata, the result has up to `2^n` states. The timeout of the + /// execution profile applies, and its `max_number_of_states` caps the + /// number of states built, including those left out of the result because + /// no accept state can be reached from them. + #[tracing::instrument(level = "debug", skip_all)] + pub fn symmetric_difference_all<'a, I: IntoIterator>( + automata: I, + ) -> Result { + let automata: Vec<&FastAutomaton> = automata.into_iter().collect(); + match automata[..] { + [] => Ok(FastAutomaton::new_empty()), + [automaton] => Ok(automaton.clone()), + [automaton, other] => automaton.symmetric_difference(other), + _ => Self::symmetric_difference_over_state_sets(&automata), + } + } + + /// Returns the symmetric difference of `automata`, as + /// [`symmetric_difference_all`](Self::symmetric_difference_all) does, + /// working on groups of automata in parallel. + /// + /// It can take less time than `symmetric_difference_all` on large automata, + /// and takes more on small ones: measure before choosing it. + /// + /// Only available with the `parallel` feature (enabled by default), and not + /// on `wasm`. + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + #[tracing::instrument(level = "debug", skip_all)] + pub fn symmetric_difference_all_par<'a, I: IntoParallelIterator>( + automata: I, + ) -> Result { + let execution_profile = ExecutionProfile::get(); + + // ∅ is the identity. + let empty = FastAutomaton::new_empty(); + + automata + .into_par_iter() + .fold(Vec::new, |mut group, automaton| { + group.push(automaton); + group + }) + .map(|group| { + execution_profile.apply(|| Self::symmetric_difference_over_state_sets(&group)) + }) + .try_reduce( + || empty.clone(), + |acc, next| { + execution_profile + .apply(|| Self::symmetric_difference_over_state_sets(&[&acc, &next])) + }, + ) + } + + /// The symmetric difference of `automata` in one walk, which + /// [`symmetric_difference_all`](Self::symmetric_difference_all) + /// describes. + /// + /// The automata share one space of ids, so the sets of states a word + /// reaches in each of them are one sorted set: the walk is the subset + /// construction of all the automata side by side, where a set accepts + /// when an odd number of automata have an accept state in it. + fn symmetric_difference_over_state_sets( + automata: &[&FastAutomaton], + ) -> Result { + let execution_profile = ExecutionProfile::get(); + + let mut spanning_set = Cow::Owned(SpanningSet::new_empty()); + for (i, automaton) in automata.iter().enumerate() { + if i == 0 { + spanning_set = Cow::Borrowed(&automaton.spanning_set); + } else if automaton.spanning_set != *spanning_set { + spanning_set = Cow::Owned(spanning_set.merge(&automaton.spanning_set)); + } + } + let mut operands = Vec::with_capacity(automata.len()); + // The end of the ids of each operand. + let mut ends: Vec = Vec::with_capacity(automata.len()); + let mut offset = 0; + for automaton in automata { + let converter = (automaton.spanning_set != *spanning_set) + .then(|| ConditionConverter::new(&automaton.spanning_set, &spanning_set)) + .transpose()?; + operands.push(Operand::new(automaton, offset, converter.as_ref())?); + offset += automaton.transitions.len(); + ends.push(offset as Id); + } + let accepts = |set: &[Id]| { + let accepting = operands.iter().zip(parts(set, &ends)); + accepting + .filter(|(operand, part)| operand.is_accepting(part)) + .count() + % 2 + == 1 }; - let mut difference = FastAutomaton::new_empty(); - // The sets of the pairs, back to back. - let mut sets: Vec = right.start.into_iter().collect(); - if left.accepts(start) && !right.is_accepting(&sets) { - difference.accept(difference.start_state); - } - // The state of each pair, keyed by the state of `self` followed by - // the set of states of `other`. - let mut states: AHashMap, State> = AHashMap::new(); - let mut key = vec![start]; - key.extend_from_slice(&sets); - states.insert(key.clone(), difference.start_state); + // The sets met, back to back. + let mut sets: Vec = operands + .iter() + .filter_map(|operand| operand.start) + .collect(); + let mut difference = Draft::default(); + difference.new_state(accepts(&sets)); + let mut states: AHashMap, usize> = AHashMap::new(); + states.insert(sets.clone(), Draft::START); let mut worklist = VecDeque::new(); - worklist.push_back((difference.start_state, start, 0..sets.len())); + worklist.push_back((Draft::START, 0..sets.len())); + // What is left of each operand where a word only reaches states of + // that operand: the operand minus nothing, which is not determinized. + let mut alone: Vec = operands + .iter() + .map(|operand| Pairs::new(operand, operand)) + .collect(); + + let bases = spanning_set.spanning_ranges_with_rest_len(); + let mut successors = vec![Vec::new(); bases]; + let mut operand_successors = vec![Vec::new(); bases]; + // A base for each set the current one leads to, with all the bases + // that lead to it. + let mut targets: Vec<(usize, Condition)> = Vec::new(); + + while let Some((state, set)) = worklist.pop_front() { + execution_profile.assert_not_timed_out()?; + execution_profile.assert_max_number_of_states(difference.number_of_states())?; + + successors.iter_mut().for_each(Vec::clear); + for (operand, part) in operands.iter().zip(parts(&sets[set], &ends)) { + if part.is_empty() { + continue; + } + operand.successors(part, &mut operand_successors); + // The ids of an operand follow those of the previous ones. + for (all, of_operand) in successors.iter_mut().zip(&operand_successors) { + all.extend_from_slice(of_operand); + } + } + + for base in 0..bases { + let set = &successors[base]; + if set.is_empty() { + continue; + } + match targets + .iter_mut() + .find(|(other_base, _)| successors[*other_base] == *set) + { + Some((_, bases)) => bases.insert_base(base), + None => targets.push((base, Condition::single_base(base, &spanning_set))), + } + } + for (base, bases) in targets.drain(..) { + let set = &successors[base]; + let operand = ends.partition_point(|end| *end <= set[0]); + if set[set.len() - 1] < ends[operand] { + for &to in set { + let target = alone[operand].state(&mut difference, to, &[]); + difference.add_transition(state, target, bases.clone()); + } + continue; + } + let target = match states.get(set.as_slice()) { + Some(target) => *target, + None => { + let target = difference.new_state(accepts(set)); + states.insert(set.clone(), target); + worklist.push_back((target, sets.len()..sets.len() + set.len())); + sets.extend_from_slice(set); + target + } + }; + difference.add_transition(state, target, bases); + } + } + for pairs in &mut alone { + pairs.walk(&mut difference, &spanning_set)?; + } + Ok(difference.into_automaton(spanning_set.into_owned())) + } +} + +/// The states of each operand in `set`, a sorted set of states of operands +/// that share one space of ids: `ends` holds the end of the ids of each. +fn parts<'a>(mut set: &'a [Id], ends: &'a [Id]) -> impl Iterator { + ends.iter().map(move |end| { + let (part, others) = set.split_at(set.partition_point(|id| id < end)); + set = others; + part + }) +} + +/// A difference as its walk builds it. The pairs that reach no accept state +/// are common, since they are the strings the subtrahend covers: as entries +/// of a list they are left out of the automaton, which costs less than +/// removing them from it. +#[derive(Default)] +struct Draft { + /// Whether each state accepts. + accept: Vec, + /// `(from, to, bases)`. + transitions: Vec<(usize, usize, Condition)>, +} + +impl Draft { + /// The start state: the first one to be added. + const START: usize = 0; + + #[inline] + fn number_of_states(&self) -> usize { + self.accept.len() + } + + #[inline] + fn new_state(&mut self, accept: bool) -> usize { + self.accept.push(accept); + self.accept.len() - 1 + } + + #[inline] + fn add_transition(&mut self, from: usize, to: usize, bases: Condition) { + self.transitions.push((from, to, bases)); + } + + /// The automaton of the states that reach an accept state, over + /// `spanning_set`. All of them are reached from the start state. + fn into_automaton(self, spanning_set: SpanningSet) -> FastAutomaton { + // The predecessors of each state, back to back: those of `state` + // are at `starts[state]..starts[state + 1]`. + let mut starts = vec![0; self.accept.len() + 1]; + for (_, to, _) in &self.transitions { + starts[*to] += 1; + } + let mut end = 0; + for start in &mut starts { + end += *start; + *start = end; + } + let mut predecessors = vec![0; end]; + for (from, to, _) in &self.transitions { + starts[*to] -= 1; + predecessors[starts[*to]] = *from; + } + + let mut live = self.accept.clone(); + let mut worklist: Vec = (0..live.len()).filter(|&state| live[state]).collect(); + while let Some(state) = worklist.pop() { + for &from in &predecessors[starts[state]..starts[state + 1]] { + if !live[from] { + live[from] = true; + worklist.push(from); + } + } + } + + let mut automaton = FastAutomaton::new_empty(); + if live.first() != Some(&true) { + return automaton; + } + automaton.spanning_set = spanning_set; + let states: Vec = (0..live.len()) + .map(|state| match state { + Self::START => automaton.start_state, + _ if live[state] => automaton.new_state(), + _ => usize::MAX, + }) + .collect(); + for state in (0..live.len()).filter(|&state| self.accept[state]) { + automaton.accept(states[state]); + } + for (from, to, bases) in self.transitions { + if live[from] && live[to] { + automaton.add_owned_transition(states[from], states[to], bases); + } + } + automaton + } +} + +/// The pairs of a state of an operand, `left`, and the set of states of the +/// other, `right`, that the same word reaches: the states of `left` minus +/// `right`, which [`difference`](FastAutomaton::difference) describes. +struct Pairs<'a> { + left: &'a Operand, + right: &'a Operand, + /// The sets of the pairs, back to back. + sets: Vec, + /// The state of each pair, keyed by the state of `left` followed by the + /// set of states of `right`. + states: AHashMap, usize>, + /// The pairs whose transitions are still to be added: their state, their + /// state of `left` and their set in `sets`. + worklist: VecDeque<(usize, Id, Range)>, + key: Vec, +} + +impl<'a> Pairs<'a> { + fn new(left: &'a Operand, right: &'a Operand) -> Self { + Pairs { + left, + right, + sets: Vec::new(), + states: AHashMap::new(), + worklist: VecDeque::new(), + key: Vec::new(), + } + } + + /// The state of the pair of `from` and `set`, which is added to + /// `difference` if the pair was not met yet. + fn state(&mut self, difference: &mut Draft, from: Id, set: &[Id]) -> usize { + self.key.clear(); + self.key.push(from); + self.key.extend_from_slice(set); + if let Some(state) = self.states.get(self.key.as_slice()) { + return *state; + } + let state = difference.new_state(self.left.accepts(from) && !self.right.is_accepting(set)); + self.states.insert(self.key.clone(), state); + self.worklist + .push_back((state, from, self.sets.len()..self.sets.len() + set.len())); + self.sets.extend_from_slice(set); + state + } + + /// Adds to `difference` the transitions of the pairs met, and the pairs + /// they lead to. + fn walk( + &mut self, + difference: &mut Draft, + spanning_set: &SpanningSet, + ) -> Result<(), EngineError> { + let execution_profile = ExecutionProfile::get(); let mut successors = vec![Vec::new(); spanning_set.spanning_ranges_with_rest_len()]; - // The pairs one transition of `self` leads to: the state of the + // The pairs one transition of `left` leads to: the state of the // pair, a base that leads to it, and all the bases that do. - let mut targets: Vec<(State, usize, Condition)> = Vec::new(); + let mut targets: Vec<(usize, usize, Condition)> = Vec::new(); - while let Some((state, from, set)) = worklist.pop_front() { + while let Some((state, from, set)) = self.worklist.pop_front() { execution_profile.assert_not_timed_out()?; execution_profile.assert_max_number_of_states(difference.number_of_states())?; - right.successors(&sets[set], &mut successors); + self.right.successors(&self.sets[set], &mut successors); - for (condition, to) in left.transitions_from(from) { - targets.clear(); + for (condition, to) in self.left.transitions_from(from) { for base in condition.iter_set_bits() { let set = &successors[base]; if let Some((_, _, bases)) = targets @@ -136,37 +575,22 @@ impl FastAutomaton { bases.insert_base(base); continue; } - key.clear(); - key.push(*to); - key.extend_from_slice(set); - let target = match states.get(key.as_slice()) { - Some(target) => *target, - None => { - let target = difference.new_state(); - if left.accepts(*to) && !right.is_accepting(set) { - difference.accept(target); - } - states.insert(key.clone(), target); - worklist.push_back((target, *to, sets.len()..sets.len() + set.len())); - sets.extend_from_slice(set); - target - } - }; + let target = self.state(difference, *to, set); targets.push((target, base, Condition::single_base(base, spanning_set))); } - for (target, _, bases) in &targets { - difference.add_transition(state, *target, bases); + for (target, _, bases) in targets.drain(..) { + difference.add_transition(state, target, bases); } } } - difference.spanning_set = shared.into_spanning_set(); - difference.remove_dead_states(); - Ok(difference) + Ok(()) } } #[cfg(test)] mod tests { + use crate::error::EngineError; + use crate::execution_profile::ExecutionProfileBuilder; use crate::fast_automaton::FastAutomaton; use crate::regex::RegularExpression; @@ -188,6 +612,112 @@ mod tests { assert!(a.is_match("xxxxxxxxxx")); } + fn automaton(pattern: &str) -> FastAutomaton { + RegularExpression::new(pattern) + .unwrap() + .to_automaton() + .unwrap() + } + + #[test] + fn symmetric_difference_all_keeps_what_an_odd_number_accepts() { + let (a, b, c) = ( + automaton("a|ab|abc"), + automaton("ab|abc|b"), + automaton("abc|b|c"), + ); + + assert!( + FastAutomaton::symmetric_difference_all([]) + .unwrap() + .is_empty() + ); + assert!( + FastAutomaton::symmetric_difference_all([&a]) + .unwrap() + .equivalent(&a) + .unwrap() + ); + // An automaton given twice cancels itself. + assert!( + FastAutomaton::symmetric_difference_all([&a, &b, &a]) + .unwrap() + .equivalent(&b) + .unwrap() + ); + + // `a` and `c` are in one automaton, `abc` in the three of them. + let expected = automaton("a|abc|c"); + for automata in [[&a, &b, &c], [&c, &a, &b], [&b, &c, &a]] { + let all = FastAutomaton::symmetric_difference_all(automata).unwrap(); + assert!(all.equivalent(&expected).unwrap()); + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + assert!( + FastAutomaton::symmetric_difference_all_par(automata) + .unwrap() + .equivalent(&expected) + .unwrap() + ); + } + } + + // Combined two by two, each intermediate result is walked again, and + // these 16 automata of 2 states take thousands of states, or hundreds of + // thousands when two intermediate results are combined with each other. + #[test] + fn symmetric_difference_all_walks_all_the_automata_together() { + let automata: Vec = ('a'..='p') + .map(|letter| automaton(&format!(".*{letter}"))) + .collect(); + // No string ends with two letters: an odd number is one. + let expected = FastAutomaton::union_all(&automata).unwrap(); + + ExecutionProfileBuilder::new() + .max_number_of_states(100) + .build() + .run(|| { + // The states reached after each last letter, and the start. + let all = FastAutomaton::symmetric_difference_all(&automata).unwrap(); + assert_eq!(17, all.number_of_states()); + assert!(all.is_deterministic()); + assert!(all.equivalent(&expected).unwrap()); + + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + assert!( + FastAutomaton::symmetric_difference_all_par(&automata) + .unwrap() + .equivalent(&expected) + .unwrap() + ); + }); + } + + // Past the first letter, a word only reaches states of one automaton, + // which is followed as it is: none can be determinized under the cap. + #[test] + fn symmetric_difference_all_does_not_determinize_an_automaton_left_alone() { + let automata: Vec = ['x', 'y', 'z'] + .map(|letter| automaton(&format!("{letter}(a|b)*a(a|b){{11}}"))) + .into(); + let expected = FastAutomaton::union_all(&automata).unwrap(); + + let all = ExecutionProfileBuilder::new() + .max_number_of_states(200) + .build() + .run(|| { + for automaton in &automata { + assert_eq!( + automaton.determinize().unwrap_err(), + EngineError::AutomatonHasTooManyStates + ); + } + FastAutomaton::symmetric_difference_all(&automata).unwrap() + }); + assert!(!all.is_deterministic()); + // Compared outside of the cap, which the comparison would exceed. + assert!(all.equivalent(&expected).unwrap()); + } + // empty.complement() = Σ*. #[test] fn complement_of_empty_is_total() { diff --git a/src/fast_automaton/operation/intersection.rs b/src/fast_automaton/operation/intersection.rs index 2bfd0aa..089d39b 100644 --- a/src/fast_automaton/operation/intersection.rs +++ b/src/fast_automaton/operation/intersection.rs @@ -9,12 +9,17 @@ use crate::{error::EngineError, execution_profile::ExecutionProfile}; use super::*; impl FastAutomaton { - /// Computes the intersection between `self` and `other`. + /// Returns the intersection of `self` and `other`: the strings that both + /// accept. + /// + /// With `n` and `m` the numbers of states of `self` and `other`, the result + /// has up to `n × m` states. It is deterministic when both automata are. pub fn intersection(&self, other: &FastAutomaton) -> Result { FastAutomaton::intersection_all([self, other]) } - /// Computes the intersection of all automata in the given iterator. + /// Returns the intersection of `automata`: the strings that all of them + /// accept. An empty iterator gives the automaton that accepts every string. #[tracing::instrument(level = "debug", skip_all)] pub fn intersection_all<'a, I: IntoIterator>( automata: I, @@ -32,10 +37,11 @@ impl FastAutomaton { Ok(result.into_owned()) } - /// Computes in parallel the intersection of all automata in the given iterator. + /// Returns the intersection of `automata`, as + /// [`intersection_all`](Self::intersection_all) does, working in parallel. /// /// Only available with the `parallel` feature (enabled by default), and not - /// on `wasm`, which has no threads and does not depend on `rayon`. + /// on `wasm`. #[cfg(all(feature = "parallel", not(target_family = "wasm")))] #[tracing::instrument(level = "debug", skip_all)] pub fn intersection_all_par<'a, I: IntoParallelIterator>( @@ -139,11 +145,11 @@ impl FastAutomaton { Ok(Cow::Owned(new_automaton)) } - /// Returns `true` if the two automata have a non-empty intersection. + /// Returns `true` if a string is accepted by both automata. /// - /// The intersection is not built: the pairs of states the two automata - /// reach together are visited until one has both states accepting. The - /// execution profile's timeout applies, and its `max_number_of_states` + /// The intersection is not built. With `n` and `m` the numbers of states of + /// `self` and `other`, up to `n × m` pairs of states are visited: the + /// timeout of the execution profile applies, and its `max_number_of_states` /// caps the number of pairs visited. #[tracing::instrument(level = "debug", skip_all, fields(self_states = self.number_of_states(), other_states = other.number_of_states()))] pub fn has_intersection(&self, other: &FastAutomaton) -> Result { diff --git a/src/fast_automaton/operation/minimize.rs b/src/fast_automaton/operation/minimize.rs index f33f555..1df91a6 100644 --- a/src/fast_automaton/operation/minimize.rs +++ b/src/fast_automaton/operation/minimize.rs @@ -3,12 +3,17 @@ use crate::execution_profile::ExecutionProfile; use super::*; impl FastAutomaton { - /// Minimizes the automaton using Hopcroft's Algorithm. + /// Replaces the automaton with the minimal deterministic automaton of its + /// language, which is unique. /// - /// If `self` is non-deterministic, it is determinized in place first, - /// unless the [`ExecutionProfile`] disables implicit determinization, in - /// which case [`EngineError::DeterministicAutomatonRequired`] is - /// returned. + /// A non-deterministic automaton is determinized first, which is + /// exponential in the worst case. + /// + /// # Errors + /// + /// Returns [`EngineError::DeterministicAutomatonRequired`] for a + /// non-deterministic automaton when the [`ExecutionProfile`] disables + /// implicit determinization. #[tracing::instrument(level = "debug", skip_all, fields(states = self.number_of_states(), deterministic = self.is_deterministic(), minimal = self.is_minimal()))] pub fn minimize(&mut self) -> Result<(), EngineError> { // The `minimal` flag is conservatively cleared on every mutation, so diff --git a/src/fast_automaton/operation/mod.rs b/src/fast_automaton/operation/mod.rs index 3b37afb..0e215e9 100644 --- a/src/fast_automaton/operation/mod.rs +++ b/src/fast_automaton/operation/mod.rs @@ -46,9 +46,9 @@ impl FastAutomaton { Ok(()) } - /// Removes "dead" states (those that cannot reach any accept state), since - /// they never contribute to the language. If the language is empty the whole - /// automaton collapses to the canonical empty automaton. + /// Removes the states from which no accept state can be reached. An + /// automaton that accepts no string becomes the one + /// [`new_empty`](Self::new_empty) creates. pub fn remove_dead_states(&mut self) { if !self.is_empty() { let live_states = self.live_states(); diff --git a/src/fast_automaton/operation/repeat.rs b/src/fast_automaton/operation/repeat.rs index f402346..95f6f12 100644 --- a/src/fast_automaton/operation/repeat.rs +++ b/src/fast_automaton/operation/repeat.rs @@ -1,7 +1,11 @@ use super::*; impl FastAutomaton { - /// Computes the repetition of the automaton between `min` and `max_opt` times; if `max_opt` is `None`, the repetition is unbounded. + /// Returns the repetition of `self`: the strings made of `n` strings of + /// `self` one after the other, for every `n` from `min` to `max_opt`, with + /// no upper bound when `max_opt` is `None`. + /// + /// A `max_opt` below `min` gives the automaton that accepts no string. #[tracing::instrument(level = "debug", skip(self), fields(states = self.number_of_states(), deterministic = self.is_deterministic(), min = min, max_opt = tracing::field::debug(max_opt)))] pub fn repeat(&self, min: u32, max_opt: Option) -> Result { let mut automaton = self.clone(); diff --git a/src/fast_automaton/operation/union.rs b/src/fast_automaton/operation/union.rs index e261b3e..4fc3bb7 100644 --- a/src/fast_automaton/operation/union.rs +++ b/src/fast_automaton/operation/union.rs @@ -7,14 +7,19 @@ use crate::{error::EngineError, execution_profile::ExecutionProfile}; use super::*; impl FastAutomaton { - /// Computes the union between `self` and `other`. + /// Returns the union of `self` and `other`: the strings that at least one + /// of them accepts. + /// + /// Linear in the sizes of both automata. The result is not deterministic in + /// general. pub fn union(&self, other: &FastAutomaton) -> Result { let mut new_automaton = self.clone(); new_automaton.union_mut(other)?; Ok(new_automaton) } - /// Computes the union of all automata in the given iterator. + /// Returns the union of `automata`: the strings that at least one of them + /// accepts. An empty iterator gives the automaton that accepts no string. #[tracing::instrument(level = "debug", skip_all)] pub fn union_all<'a, I: IntoIterator>( automata: I, @@ -44,10 +49,11 @@ impl FastAutomaton { Ok(new_automaton) } - /// Computes in parallel the union of all automata in the given iterator. + /// Returns the union of `automata`, as [`union_all`](Self::union_all) does, + /// working in parallel. /// /// Only available with the `parallel` feature (enabled by default), and not - /// on `wasm`, which has no threads and does not depend on `rayon`. + /// on `wasm`. #[cfg(all(feature = "parallel", not(target_family = "wasm")))] #[tracing::instrument(level = "debug", skip_all)] pub fn union_all_par<'a, I: IntoParallelIterator>( diff --git a/src/fast_automaton/spanning_set/mod.rs b/src/fast_automaton/spanning_set/mod.rs index 5f4a839..c2a93dc 100644 --- a/src/fast_automaton/spanning_set/mod.rs +++ b/src/fast_automaton/spanning_set/mod.rs @@ -19,39 +19,48 @@ fn segments_to_range(segments: &[(u32, u32)]) -> CharRange { RangeSet(bounds) } -/// A set of [`CharRange`] that spans all transitions of a [`crate::FastAutomaton`]. +/// A partition of the characters into disjoint ranges, the *bases*, over which +/// the [`Condition`](crate::fast_automaton::condition::Condition)s of an +/// automaton are expressed: its ranges, and a *rest* that holds every other +/// character. +/// +/// A condition cannot tell apart two characters of the same base, so the +/// spanning set of an automaton has to separate the characters that its +/// transitions do. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SpanningSet(Vec, CharRange); impl SpanningSet { - /// Creates a spanning set from explicit disjoint `ranges` plus the `rest` - /// range covering every character they don't. The caller is responsible for - /// these invariants; prefer [`compute_spanning_set`](Self::compute_spanning_set), - /// which derives a minimal, well-formed set from arbitrary ranges. + /// Creates a spanning set from `ranges` and `rest`, which are not checked: + /// the ranges must be disjoint, and `rest` must hold every character + /// outside of them. [`compute_spanning_set`](Self::compute_spanning_set) + /// builds a valid one from any ranges. pub fn new(ranges: Vec, rest: CharRange) -> Self { SpanningSet(ranges, rest) } - /// Creates the spanning set of an automaton with no transitions: no - /// explicit ranges, with the rest covering all characters. + /// Creates the spanning set with no range, whose rest holds every + /// character: that of an automaton without transitions. pub fn new_empty() -> Self { SpanningSet(vec![], CharRange::total()) } - /// Creates the spanning set with a single range covering all characters and + /// Creates the spanning set with one range that holds every character, and /// an empty rest. pub fn new_total() -> Self { SpanningSet(vec![CharRange::total()], CharRange::empty()) } - /// Returns `true` if this is the empty spanning set (no explicit ranges; - /// see [`new_empty`](Self::new_empty)). + /// Returns `true` if the spanning set has no range (see + /// [`new_empty`](Self::new_empty)). + #[inline] pub fn is_empty(&self) -> bool { self.0.is_empty() && self.1.is_total() } - /// Returns `true` if this is the total spanning set (one all-covering - /// range; see [`new_total`](Self::new_total)). + /// Returns `true` if the spanning set has one range that holds every + /// character (see [`new_total`](Self::new_total)). + #[inline] pub fn is_total(&self) -> bool { self.0.len() == 1 && self.0[0].is_total() && self.1.is_empty() } @@ -70,27 +79,28 @@ impl SpanningSet { .chain(self.0.iter()) } - /// Returns an iterator over the explicit (non-rest) ranges in the spanning set. + /// Returns an iterator over the ranges, the rest excluded. pub fn spanning_ranges(&self) -> Iter<'_, CharRange> { self.0.iter() } - /// Returns the number of explicit (non-rest) ranges in the spanning set. + /// Returns the number of ranges, the rest excluded. pub fn number_of_spanning_ranges(&self) -> usize { self.0.len() } - /// Returns the explicit range at index `i`, or `None` if out of bounds. + /// Returns the range at index `i`, `None` if there is none. pub fn spanning_range(&self, i: usize) -> Option<&CharRange> { self.0.get(i) } - /// Returns the "rest" range covering all characters not in any explicit range. + /// Returns the rest: the characters that no range holds. pub fn rest(&self) -> &CharRange { &self.1 } - /// Compute a new minimal spanning set by merging the provided spanning set. + /// Returns the smallest spanning set that expresses everything `self` and + /// `other` express. pub fn merge(&self, other: &Self) -> Self { let mut ranges = Vec::with_capacity(self.0.len() + other.0.len()); ranges.extend_from_slice(&self.0); @@ -99,12 +109,10 @@ impl SpanningSet { Self::compute_spanning_set(&ranges) } - /// Compute a new minimal spanning set for the provided ranges. + /// Returns the smallest spanning set that expresses each of `ranges`: two + /// characters share a base when the same ranges hold them. /// - /// The bases are the *atoms* of the inputs: the classes of characters - /// covered by exactly the same subset of input ranges. They are computed - /// with one endpoint sweep over the surrogate-free index space, - /// O(E log E) in the total number of input intervals. + /// `O(n log n)`, with `n` the number of intervals in `ranges`. pub fn compute_spanning_set(ranges: &[CharRange]) -> Self { let mut inputs: Vec<&CharRange> = ranges.iter().filter(|r| !r.is_empty()).collect(); inputs.sort_unstable(); diff --git a/src/lib.rs b/src/lib.rs index 3fe5e75..a7d06d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,46 +25,39 @@ //! //! # Semantics //! -//! RegexSolver implements **pure regular languages**, which differs from a -//! typical regex engine in two ways: matching is always **anchored** (a pattern -//! describes whole strings, so `abc` matches only `"abc"`), and `.` matches any -//! character including line feed. +//! A pattern denotes a set of whole strings, which differs from a typical regex +//! engine in two ways: matching is **anchored** (`abc` matches only `"abc"`), +//! and `.` matches any character, line feed included. //! -//! The rest follows from regular-language theory. Patterns are parsed with -//! [`regex-syntax`](https://docs.rs/regex-syntax/latest/regex_syntax/), and a -//! construct that would change matching in a way the engine cannot represent -//! returns an [`EngineError`] rather than being applied incorrectly: +//! Patterns are parsed with +//! [`regex-syntax`](https://docs.rs/regex-syntax/latest/regex_syntax/). A +//! construct the engine cannot represent returns an [`EngineError`] instead of +//! being ignored: //! -//! * **Backreferences** (`\1`, `\2`, ...) go beyond regular languages, as do -//! **look-around** assertions (`(?=...)`, `(?<=...)`). -//! * **Anchors and word boundaries**: since matching is already full-string, a -//! leading `^`/`\A` and a trailing `$`/`\z` are accepted as redundant -//! no-ops. Anchors anywhere else, and word boundaries (`\b`, `\B`), would -//! constrain matching in ways a regular language cannot express, so they +//! * **Backreferences** (`\1`) and **look-around** assertions (`(?=...)`, +//! `(?<=...)`) are not supported. +//! * **Anchors**: a leading `^`/`\A` and a trailing `$`/`\z` are accepted and +//! have no effect. Anchors anywhere else, and word boundaries (`\b`, `\B`), //! return [`EngineError::UnsupportedRegexFeature`]. //! * **Inline flags** (`(?i)`, `(?m)`, `(?s)`, `(?x)`) return -//! [`EngineError::UnsupportedRegexFeature`]: the engine matches character -//! ranges uniformly and cannot honor them, and dropping them silently would -//! diverge from standard regex semantics (`(?i)abc` would stop matching -//! `ABC`). -//! * **All quantifiers are greedy**: as *sets of strings*, `a*` and `a*?` are -//! the same language, so ungreedy markers (`*?`, `+?`, `??`) are accepted and -//! ignored. -//! * **The empty language** (matching no string at all) is written `[]`, an -//! empty character class. It is distinct from the empty string `""`. +//! [`EngineError::UnsupportedRegexFeature`]. +//! * **Ungreedy quantifiers** (`*?`, `+?`, `??`) are read as their greedy form: +//! `a*` and `a*?` match the same strings. +//! * **The empty language**, which matches no string, is written `[]`, as a +//! whole pattern: inside a larger one, `[]` is a syntax error. It is not the +//! empty string `""`. //! //! Character classes are resolved against a compiled-in copy of the Unicode -//! character database, currently Unicode 16.0.0 -//! ([`regex_charclass::UCD_VERSION`]). A class is printed back in canonical -//! form, so `\p{Lu}` comes back as `\p{Uppercase_Letter}` and +//! character database, Unicode 16.0.0 ([`regex_charclass::UCD_VERSION`]). A +//! class is printed back in canonical form: `\p{Lu}` as `\p{Uppercase_Letter}`, //! `\p{Decimal_Number}` as `\d`. //! //! # Bounding execution //! -//! Automaton operations can blow up on adversarial input, so a thread-local -//! [`ExecutionProfile`] can cap runtime and state count and control implicit -//! determinization. Hitting a limit returns a specific [`EngineError`] instead -//! of hanging. +//! Some operations take exponential time or space in the worst case. An +//! [`ExecutionProfile`], installed for the current thread, caps the running +//! time and the number of states: an operation that reaches a limit returns an +//! [`EngineError`]. //! //! # Modules //! @@ -119,16 +112,14 @@ pub use fast_automaton::convert::to_regex::neural_synthesis; /// The parsed-pattern AST: [`RegularExpression`]. pub mod regex; -/// Re-export of [`regex-charclass`](https://docs.rs/regex-charclass), the -/// crate behind [`CharRange`]: everything needed to build transition labels -/// by hand (`Char`, range sets) without adding a separately version-matched -/// dependency. +/// Re-export of [`regex-charclass`](https://docs.rs/regex-charclass), the crate +/// of [`CharRange`] and of its `Char`: use it to build ranges of characters +/// without declaring that crate as a dependency of the same version. pub use regex_charclass; -/// A no-op [`Hasher`](std::hash::Hasher) for integer keys that are already -/// well distributed, such as state ids: the key's value is used as the hash -/// directly. Only the integer key types it is implemented for can be hashed -/// with it; anything else does not compile. +/// A [`Hasher`](std::hash::Hasher) that uses an integer key as its own hash, +/// for keys that are already well distributed, such as state ids. It is only +/// implemented for integer keys. #[derive(Clone, Copy, Debug, Default)] pub struct NoHashHasher(u64, std::marker::PhantomData); @@ -157,12 +148,12 @@ impl_no_hash_hasher!(u32 => write_u32, u64 => write_u64, usize => write_usize); /// A hash map keyed by integer state ids using a no-op hasher. Internal. pub(crate) type IntMap = HashMap>>; -/// A hash set of integer state ids using a no-op hasher (the hasher is fast -/// because state ids are already well-distributed small integers). Returned by -/// [`FastAutomaton::accept_states`] and related inspection methods. +/// A hash set of integer keys, such as state ids, hashed with [`NoHashHasher`]. +/// Returned by [`FastAutomaton::accept_states`] and +/// [`FastAutomaton::live_states`]. pub type IntSet = HashSet>>; -/// A set of character ranges (the transition-label alphabet type), re-exported -/// from [`regex-charclass`](https://docs.rs/regex-charclass). +/// A set of characters, held as ranges: the type of a transition's characters. +/// Re-exported from [`regex-charclass`](https://docs.rs/regex-charclass). pub type CharRange = RangeSet; /// A regular language, held either as a parsed [`RegularExpression`] or as a @@ -205,27 +196,22 @@ pub type CharRange = RangeSet; /// /// # Tracing /// -/// The core operations on [`Term`], [`FastAutomaton`], and [`RegularExpression`] -/// are instrumented with [`tracing`](https://docs.rs/tracing) spans (mostly at -/// `debug` level). Install a [`tracing-subscriber`](https://docs.rs/tracing-subscriber) -/// (or any other `tracing` subscriber) in your application to observe them; if -/// no subscriber is installed, instrumentation has negligible overhead and -/// produces no output. +/// The operations of [`Term`], [`FastAutomaton`] and [`RegularExpression`] emit +/// [`tracing`](https://docs.rs/tracing) spans, at `debug` or `trace` level. +/// They produce no output unless a subscriber is installed. /// /// # Equality /// -/// `PartialEq`/`Eq` (`==`) compare the **underlying representation**, not the -/// language. Two terms that match exactly the same strings can compare -/// unequal (for example, an automaton and an equivalent regular expression, or -/// two differently-written regexes for the same language). To compare -/// *languages*, use [`equivalent`](Self::equivalent); for `self ⊆ other`, use +/// `==` compares the representation, not the language: two terms that match the +/// same strings can be unequal, for example an automaton and a regular +/// expression. To compare languages, use [`equivalent`](Self::equivalent) and /// [`subset`](Self::subset). #[derive(Clone, PartialEq, Eq, Debug)] #[must_use = "terms are immutable; operations return a new term"] pub enum Term { - /// The term is backed by a parsed regular-expression AST. + /// A term held as a regular expression. RegularExpression(RegularExpression), - /// The term is backed by a finite automaton. + /// A term held as an automaton. Automaton(FastAutomaton), } @@ -288,22 +274,28 @@ impl Term { .apply(f) } - /// Creates a term that matches the empty language. + /// Creates a term that matches no string. pub fn new_empty() -> Self { Term::RegularExpression(RegularExpression::new_empty()) } - /// Creates a term that matches all possible strings. + /// Creates a term that matches every string. pub fn new_total() -> Self { Term::RegularExpression(RegularExpression::new_total()) } - /// Creates a term that only matches the empty string `""`. + /// Creates a term that matches the empty string `""` and no other. pub fn new_empty_string() -> Self { Term::RegularExpression(RegularExpression::new_empty_string()) } - /// Parses and simplifies the provided pattern and returns a new [`Term`] holding the resulting [`RegularExpression`]. + /// Parses `pattern` into a term. + /// + /// # Errors + /// + /// Returns an [`EngineError`] if the pattern is not valid or uses a + /// construct the engine does not support (see + /// [Semantics](crate#semantics)). /// /// # Examples /// @@ -316,17 +308,18 @@ impl Term { Ok(Term::RegularExpression(RegularExpression::new(pattern)?)) } - /// Creates a new `Term` holding the provided [`RegularExpression`]. + /// Creates a term from a [`RegularExpression`]. pub fn from_regex(regex: RegularExpression) -> Self { Term::RegularExpression(regex) } - /// Creates a new `Term` holding the provided [`FastAutomaton`]. + /// Creates a term from a [`FastAutomaton`]. pub fn from_automaton(automaton: FastAutomaton) -> Self { Term::Automaton(automaton) } - /// Computes the concatenation of the given terms. + /// Returns the concatenation of `self` and `terms`: the strings made of one + /// string of each, in that order. /// /// # Examples /// @@ -365,7 +358,7 @@ impl Term { } else { match term { Term::RegularExpression(regular_expression) => { - return_regex = return_regex.concat(regular_expression, true); + return_regex.concat_mut(regular_expression.clone()); } Term::Automaton(fast_automaton) => { has_automaton = true; @@ -382,7 +375,8 @@ impl Term { } } - /// Computes the union of the given terms. + /// Returns the union of `self` and `terms`: the strings that at least one + /// of them matches. /// /// # Examples /// @@ -438,13 +432,16 @@ impl Term { let regexes_list = regexes_list.iter().map(AsRef::as_ref).collect::>(); - Ok(Term::RegularExpression(RegularExpression::union_all( - regexes_list, - ))) + // The union of large expressions can take long: it is bounded by + // the execution profile, as the union of automata is. + Ok(Term::RegularExpression( + RegularExpression::union_all_bounded(regexes_list)?, + )) } } - /// Computes the intersection of the given terms. + /// Returns the intersection of `self` and `terms`: the strings that all of + /// them match. /// /// # Examples /// @@ -486,7 +483,11 @@ impl Term { Ok(Term::Automaton(return_automaton)) } - /// Computes the difference between `self` and `other`. + /// Returns the difference of `self` and `other`: the strings that `self` + /// matches and `other` does not. + /// + /// Exponential in the size of `other` in the worst case: see + /// [`FastAutomaton::difference`]. /// /// # Examples /// @@ -510,7 +511,51 @@ impl Term { )) } - /// Computes the complement of `self`. + /// Returns the symmetric difference of `self` and `terms`: the strings that + /// an odd number of them match. With one term, these are the strings that + /// exactly one of the two matches. + /// + /// Exponential in the worst case: see + /// [`FastAutomaton::symmetric_difference_all`]. + /// + /// # Examples + /// + /// ``` + /// use regexsolver::Term; + /// + /// let term1 = Term::from_pattern("(abc|de)").unwrap(); + /// let term2 = Term::from_pattern("(de|fghi)").unwrap(); + /// + /// let symmetric_difference = term1.symmetric_difference([&term2]).unwrap(); + /// + /// assert_eq!("(abc|fghi)", symmetric_difference.to_pattern().unwrap()); + /// ``` + #[tracing::instrument(level = "debug", skip_all)] + pub fn symmetric_difference( + &self, + terms: impl IntoIterator>, + ) -> Result { + let terms: Vec<_> = terms.into_iter().collect(); + let terms: Vec<&Term> = terms.iter().map(Borrow::borrow).collect(); + + let parallel = + cfg!(all(feature = "parallel", not(target_family = "wasm"))) && terms.len() > 3; + + let automaton_list = self.get_automata(&terms, parallel)?; + + let automaton_list = automaton_list.iter().map(AsRef::as_ref).collect::>(); + + // Not `symmetric_difference_all_par`, whatever the number of terms: + // on the benchmarked patterns it only takes less time where the walk + // takes milliseconds, which the number of terms does not tell. + Ok(Term::Automaton(FastAutomaton::symmetric_difference_all( + automaton_list, + )?)) + } + + /// Returns the complement of `self`: the strings it does not match. + /// + /// The term is determinized first, which is exponential in the worst case. /// /// # Examples /// @@ -535,13 +580,11 @@ impl Term { }) } - /// Computes the repetition of the current term over the given range of - /// counts. + /// Returns the repetition of `self`: the strings made of `n` strings of + /// `self` one after the other, for every count `n` in `range`. /// - /// An unbounded end (`n..`) means unlimited repetition; an unset start - /// (`..n` or `..=n`) means zero. Exclusive bounds are normalized to inclusive. - /// A range containing no count at all (`0..0`, `3..3`, `5..2`) yields the - /// empty language. + /// An open end (`n..`) is unbounded and an open start (`..n`) is zero. A + /// range that holds no count (`0..0`, `5..2`) gives the empty language. /// /// # Examples /// @@ -585,48 +628,31 @@ impl Term { } } - /// Generates up to `limit` distinct strings matched by the term under the - /// given [`GenerationOptions`], skipping the first `offset` strings. - /// - /// `options` combines two independent axes, how paths are scheduled and - /// how the strings within them are ordered, plus an optional charset and - /// length bounds. - /// [`PathOrder::Sweep`](fast_automaton::PathOrder::Sweep) walks the - /// language one path at a time, - /// [`Interleave`](fast_automaton::PathOrder::Interleave) spreads the - /// strings over the shapes the pattern allows, and - /// [`PathOrder::Shuffled`](fast_automaton::PathOrder::Shuffled) - /// additionally draws which same-length shapes come first by a seed - /// ([`GenerationOptions::with_seed`]); - /// [`CharacterOrder::Ascending`](fast_automaton::CharacterOrder::Ascending) - /// yields each path's smallest strings first, while - /// [`CharacterOrder::Shuffled`](fast_automaton::CharacterOrder::Shuffled) - /// draws them through a seeded permutation. Shuffling both axes is the - /// combination for deriving test cases from a pattern: it covers every - /// shape with arbitrary-looking strings and stays reproducible and - /// pageable. An axis can be passed on its own wherever options are - /// expected, and so can a `(PathOrder, CharacterOrder)` pair. - /// - /// Strings are only guaranteed to be distinct **within a single call**: - /// the offset fast-skips by counting paths, and in a non-deterministic - /// automaton the same string can be reached through several paths, so - /// calls with different offsets may repeat strings (or skip some). The - /// enumeration order also depends on the automaton's structure, so - /// offsets are only consistent across calls made on the same term with - /// the same options. - /// - /// [`GenerationOptions::with_min_length`] and - /// [`with_max_length`](GenerationOptions::with_max_length) confine the - /// enumeration to a band of string lengths. Without a max, a deep - /// `offset` into a looping language (`.*`) pages into arbitrarily long - /// strings. Generation runs under the active - /// [`ExecutionProfile`]: its - /// timeout aborts with [`EngineError::OperationTimeOutError`]. - /// - /// For pagination without repetition or skipped strings, - /// [`determinize`](Self::determinize) the term once and generate from the - /// result; [`is_deterministic`](Self::is_deterministic) tells you whether - /// it already is. + /// Returns up to `limit` distinct strings that the term matches, skipping + /// the first `offset` ones. + /// + /// `options` sets the order of the strings, the seed of the shuffled + /// orders, and the characters and lengths allowed: see + /// [`GenerationOptions`]. A [`PathOrder`](fast_automaton::PathOrder), a + /// [`CharacterOrder`](fast_automaton::CharacterOrder) or a pair of them can + /// be passed in its place. + /// + /// # Pagination + /// + /// `offset` pages through the strings. Pages are only consistent across + /// calls on the same term with the same options. A term that is not + /// deterministic can repeat or skip strings from one page to the next: + /// [`determinize`](Self::determinize) it once and generate from the result + /// ([`is_deterministic`](Self::is_deterministic) tells whether that is + /// needed). + /// + /// Without [`GenerationOptions::with_max_length`], a large `offset` into an + /// infinite language reaches strings of any length. + /// + /// # Errors + /// + /// Returns [`EngineError::OperationTimeOutError`] when the timeout of the + /// [`ExecutionProfile`] passes. /// /// # Examples /// @@ -679,15 +705,15 @@ impl Term { .generate_strings(limit, offset, options) } - /// Returns a lazy iterator over the strings matched by the term under the - /// given [`GenerationOptions`], fetched in batches behind the scenes so you - /// can stop early without choosing a limit up front. + /// Returns an iterator over the strings that the term matches, in the order + /// `options` gives. + /// + /// Unlike [`generate_strings`](Self::generate_strings), it takes no limit, + /// and it neither repeats nor skips a string: the term is determinized + /// once, when the iterator is created. /// - /// The underlying deterministic automaton is computed once at construction - /// time, not on every batch. Each item is a `Result`: a construction or - /// generation error, such as a timeout from the active - /// [`ExecutionProfile`], surfaces as an `Err`, after which the iterator - /// ends. + /// Each item is a `Result`: an error, such as the timeout of the + /// [`ExecutionProfile`], is returned once, after which the iterator ends. /// /// # Examples /// @@ -737,11 +763,13 @@ impl Term { /// Returns an equivalent term backed by a deterministic automaton. /// - /// Already-deterministic terms are returned as-is. + /// A term that is already deterministic is returned as is. The call is + /// explicit, so the profile's + /// [`implicit_determinization`](crate::execution_profile::ExecutionProfileBuilder::implicit_determinization) + /// setting does not apply to it. /// - /// Determinization is always explicit, so it runs regardless of the - /// profile's [`implicit_determinization`](crate::execution_profile::ExecutionProfileBuilder::implicit_determinization) - /// setting. + /// Exponential in the worst case: an automaton of `n` states can need `2^n` + /// of them once deterministic. /// /// # Examples /// @@ -763,7 +791,9 @@ impl Term { } /// Returns an equivalent term backed by the minimal deterministic - /// automaton. + /// automaton, which is unique for a language. + /// + /// The term is determinized first, which is exponential in the worst case. /// /// # Examples /// @@ -784,7 +814,9 @@ impl Term { }) } - /// Returns `true` if both terms accept the same language. + /// Returns `true` if both terms match the same strings. + /// + /// Exponential in the worst case: see [`FastAutomaton::equivalent`]. /// /// # Examples /// @@ -807,7 +839,11 @@ impl Term { automaton_1.equivalent(&automaton_2) } - /// Returns `true` if all strings matched by the current term are also matched by the given term. + /// Returns `true` if every string that `self` matches is also matched by + /// `other`. + /// + /// Exponential in the size of `other` in the worst case: see + /// [`FastAutomaton::subset`]. /// /// # Examples /// @@ -830,10 +866,9 @@ impl Term { automaton_1.subset(&automaton_2) } - /// Returns `true` if the term matches the given string. + /// Returns `true` if the term matches `input`. /// - /// Matching is **anchored** (full-string), consistent with the rest of the - /// crate: the whole input must be accepted, not just a substring. + /// The whole of `input` has to match, not a part of it. /// /// # Examples /// @@ -850,18 +885,18 @@ impl Term { Ok(self.to_automaton()?.is_match(input)) } - /// Returns `true` if the term matches the given string: see - /// [`is_match`](Self::is_match). + /// Alias of [`is_match`](Self::is_match). #[deprecated(since = "1.2.0", note = "renamed to `is_match`")] pub fn matches(&self, input: &str) -> Result { self.is_match(input) } - /// Returns `true` if the term matches the empty language (no strings at all). + /// Returns `true` if the term matches no string. + /// + /// The empty language is not the empty string `""`, which + /// [`is_empty_string`](Self::is_empty_string) tests. /// - /// Note: the empty language is distinct from the language containing only - /// the empty string `""`. Use [`is_empty_string`](Self::is_empty_string) to - /// test for the latter. + /// Linear in the size of the term. /// /// # Examples /// @@ -879,7 +914,11 @@ impl Term { }) } - /// Returns `true` if the term matches all possible strings. + /// Returns `true` if the term matches every string. + /// + /// Unlike [`FastAutomaton::is_total`], the answer is exact for a + /// non-deterministic automaton, for which it takes exponential time in the + /// worst case. pub fn is_total(&self) -> Result { if let Term::RegularExpression(regex) = self && regex.is_total() @@ -899,7 +938,9 @@ impl Term { } } - /// Returns `true` if the term matches only the empty string `""`. + /// Returns `true` if the term matches the empty string `""` and no other. + /// + /// Linear in the size of the term. /// /// # Examples /// @@ -917,12 +958,10 @@ impl Term { }) } - /// Returns `true` if the term is *already backed by* a deterministic - /// automaton. - /// - /// A deterministic automaton has one path per accepted string. + /// Returns `true` if the term is backed by a deterministic automaton: + /// `false` for a term backed by a regular expression. /// - /// To determinize a term call [`determinize`](Self::determinize). + /// [`determinize`](Self::determinize) returns a term for which it holds. #[must_use] pub fn is_deterministic(&self) -> bool { match self { @@ -931,12 +970,11 @@ impl Term { } } - /// Returns `true` if the term is *already backed by* the minimal - /// deterministic automaton. + /// Returns `true` if the term is backed by the minimal deterministic + /// automaton of its language: `false` for a term backed by a regular + /// expression. /// - /// The minimal deterministic automaton of a given language is unique. - /// - /// To minimize a term call [`minimize`](Self::minimize). + /// [`minimize`](Self::minimize) returns a term for which it holds. #[must_use] pub fn is_minimal(&self) -> bool { match self { @@ -945,11 +983,10 @@ impl Term { } } - /// Returns the minimum and maximum length of matched strings. + /// Returns the minimum and maximum length of the strings matched. /// - /// `None` for the minimum means the language is empty (no strings are - /// matched). `None` for the maximum means the language is infinite - /// (unbounded match length). + /// Both are `None` when the term matches no string. The maximum is also + /// `None` when the strings have no longest length. #[must_use] pub fn length(&self) -> (Option, Option) { match self { @@ -958,11 +995,13 @@ impl Term { } } - /// Returns the cardinality of the term (the number of distinct matched strings). + /// Returns the number of strings the term matches. + /// + /// [`Cardinality::BigInteger`] when the count exceeds `u32::MAX`, + /// [`Cardinality::Infinite`] when the language is infinite. /// - /// The exact count is represented as `u32`. If the exact count exceeds - /// `u32::MAX`, the result is `Cardinality::BigInteger` rather than a - /// truncated value. Infinite languages return `Cardinality::Infinite`. + /// Linear in the size of a deterministic term. Exponential in the worst + /// case otherwise: see [`FastAutomaton::cardinality`]. #[tracing::instrument(level = "debug", skip_all, fields(self_deterministic = self.is_deterministic()))] pub fn cardinality(&self) -> Result, EngineError> { self.to_automaton()?.cardinality() @@ -970,9 +1009,8 @@ impl Term { /// Returns `true` if the term matches a finite number of strings. /// - /// A finite language is one with no unbounded repetition (`*`, `+`, ...). - /// Convenience over [`cardinality`](Self::cardinality) when only the - /// finite/infinite distinction matters. + /// Linear in the size of the term's automaton, where + /// [`cardinality`](Self::cardinality) can be exponential. /// /// # Examples /// @@ -991,9 +1029,8 @@ impl Term { /// Converts the term to a [`FastAutomaton`]. /// - /// Returns a [`Cow`]: borrows the automaton when the term is already - /// automaton-backed, and allocates a new one when converting from a - /// [`RegularExpression`]. + /// Borrows the automaton of an automaton-backed term, and builds one + /// otherwise. #[tracing::instrument(level = "debug", skip_all, fields(self_deterministic = self.is_deterministic()))] pub fn to_automaton(&self) -> Result, EngineError> { Ok(match self { @@ -1012,10 +1049,9 @@ impl Term { /// Converts the term to a [`RegularExpression`]. /// - /// Returns a [`Cow`]: borrows the expression when the term is already - /// regex-backed, and allocates a new one when converting from a - /// [`FastAutomaton`] via state elimination (see - /// [`FastAutomaton::to_regex`]). + /// Borrows the expression of a regex-backed term. An automaton is converted + /// by state elimination, whose result can be long: see + /// [`FastAutomaton::to_regex`]. #[tracing::instrument(level = "debug", skip_all, fields(self_deterministic = self.is_deterministic()))] pub fn to_regex(&self) -> Result, EngineError> { Ok(match self { @@ -1037,7 +1073,8 @@ impl Term { }) } - /// Converts the term to a regular expression pattern. + /// Returns the pattern of the term, converted as + /// [`to_regex`](Self::to_regex) does. pub fn to_pattern(&self) -> Result { Ok(self.to_regex()?.to_string()) } @@ -1098,12 +1135,11 @@ impl Term { } } -/// Lazy iterator over the strings matched by a [`Term`], created by +/// Iterator over the strings matched by a [`Term`], created by /// [`Term::iter_strings`]. /// -/// The underlying automaton is computed once at construction. Yields -/// `Result`: errors (from construction or generation) -/// are surfaced as `Err` items, after which the iterator ends. +/// Yields `Result`: an error is returned once, after which +/// the iterator ends. #[derive(Debug)] pub struct StringGenerator<'a> { automaton: Option>, diff --git a/src/regex/analyze/affixes.rs b/src/regex/analyze/affixes.rs index cb07b00..4d09803 100644 --- a/src/regex/analyze/affixes.rs +++ b/src/regex/analyze/affixes.rs @@ -29,7 +29,7 @@ impl RegularExpression { Option, // common affix (RegularExpression, RegularExpression), ) { - if self.is_empty() || other.is_empty() { + if self.is_simplified_empty() || other.is_simplified_empty() { return (None, (self.clone(), other.clone())); } else if self == other { return ( @@ -220,12 +220,14 @@ impl RegularExpression { new_common_affix = new_common_affix.concat(&common_affix_temp, is_prefix); } - if !self_concat_element_temp.is_empty_string() || other_temp.is_empty_string() { + if !self_concat_element_temp.is_simplified_empty_string() + || other_temp.is_simplified_empty_string() + { new_self_concat = new_self_concat.concat(&self_concat_element_temp, is_prefix); break; } } - if !new_common_affix.is_empty_string() { + if !new_common_affix.is_simplified_empty_string() { let iter: Box> = if is_prefix { Box::new(c..this_elements.len()) } else { diff --git a/src/regex/analyze/mod.rs b/src/regex/analyze/mod.rs index 44935e5..01dd0a9 100644 --- a/src/regex/analyze/mod.rs +++ b/src/regex/analyze/mod.rs @@ -4,7 +4,12 @@ mod affixes; mod number_of_states; impl RegularExpression { - /// Returns the minimum and maximum length of possible matched strings. + /// Returns the minimum and maximum length of the strings matched. + /// + /// Both are `None` when the expression matches no string. The maximum is + /// also `None` when the strings have no longest length. + /// + /// Linear in the size of the expression. #[must_use] pub fn length(&self) -> (Option, Option) { match self { @@ -31,10 +36,11 @@ impl RegularExpression { let (min_length, max_length_opt) = regex.length(); if let Some(min_length) = min_length { let new_min_length = min.saturating_mul(min_length); - let new_max_length = if let Some(max_length) = max_length_opt { - max_opt.as_ref().map(|max| max.saturating_mul(max_length)) - } else { - None + let new_max_length = match (max_length_opt, max_opt) { + // The empty string, however many times. + (Some(0), _) => Some(0), + (Some(max_length), Some(max)) => Some(max.saturating_mul(max_length)), + _ => None, }; (Some(new_min_length), new_max_length) } else if min == &0 { @@ -123,6 +129,73 @@ mod tests { assert_eq!(RegularExpression::new_empty().length(), degenerate.length()); } + /// A random expression built from the variants, in forms the parser and + /// the combinators do not produce: empty classes, concatenations and + /// alternations at any depth, and repetitions with any bounds. + fn arbitrary(depth: u32, seed: &mut u64) -> RegularExpression { + let mut random = |below: u64| { + *seed = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (*seed >> 33) % below + }; + let choice = if depth == 0 { random(4) } else { random(10) }; + match choice { + 0 => RegularExpression::Character(CharRange::empty()), + 1 => RegularExpression::Concat(VecDeque::new()), + 2 => RegularExpression::Alternation(vec![]), + 3 | 4 => RegularExpression::new("[ab]").unwrap(), + 5 | 6 => { + let min = random(3) as u32; + let max = [None, Some(0), Some(1), Some(2), Some(3)][random(5) as usize]; + RegularExpression::Repetition(Box::new(arbitrary(depth - 1, seed)), min, max) + } + 7 | 8 => { + let parts = random(4); + RegularExpression::Concat((0..parts).map(|_| arbitrary(depth - 1, seed)).collect()) + } + _ => { + let parts = random(4); + RegularExpression::Alternation( + (0..parts).map(|_| arbitrary(depth - 1, seed)).collect(), + ) + } + } + } + + // `is_empty`, `is_empty_string` and `length` are exact on expressions + // that are not simplified, as the automaton tells. + #[test] + fn emptiness_and_length_are_exact_on_any_expression() { + let mut seed = 7; + let (mut empty, mut empty_string, mut invalid) = (0, 0, 0); + for _ in 0..5000 { + let regex = arbitrary(4, &mut seed); + let Ok(automaton) = regex.to_automaton() else { + // A repetition whose maximum is below its minimum. + invalid += 1; + assert_eq!(regex.is_empty(), regex.length().0.is_none(), "{regex}"); + continue; + }; + assert_eq!(regex.is_empty(), automaton.is_empty(), "{regex}"); + assert_eq!( + regex.is_empty_string(), + automaton.is_empty_string(), + "{regex}" + ); + assert_eq!(regex.length(), automaton.length(), "{regex}"); + empty += usize::from(regex.is_empty()); + empty_string += usize::from(regex.is_empty_string()); + } + // Every case is met many times. + assert!(empty > 500 && empty_string > 500 && invalid > 100); + + // An unbounded repetition of the empty string is the empty string. + let unbounded = RegularExpression::parse("()*", false).unwrap(); + assert!(!unbounded.is_simplified_empty_string() && unbounded.is_empty_string()); + assert_eq!((Some(0), Some(0)), unbounded.length()); + } + #[test] fn test_length() -> Result<(), String> { assert_length(".{1,1000}"); diff --git a/src/regex/builder.rs b/src/regex/builder.rs index 12b2dda..d277621 100644 --- a/src/regex/builder.rs +++ b/src/regex/builder.rs @@ -4,12 +4,24 @@ use regex_syntax::ParserBuilder; use super::*; impl RegularExpression { - /// Parses and simplifies the provided pattern and returns the resulting [`RegularExpression`]. + /// Parses `pattern` and simplifies the result. + /// + /// # Errors + /// + /// Returns an [`EngineError`] if the pattern is not valid or uses a + /// construct the engine does not support (see + /// [Semantics](crate#semantics)). pub fn new(pattern: &str) -> Result { Self::parse(pattern, true) } - /// Parses the provided pattern and returns the resulting [`RegularExpression`]. If `simplify` is `true`, the expression is simplified during parsing. + /// Parses `pattern`, and simplifies the result if `simplify` is `true`. + /// + /// # Errors + /// + /// Returns an [`EngineError`] if the pattern is not valid or uses a + /// construct the engine does not support (see + /// [Semantics](crate#semantics)). #[tracing::instrument(level = "debug", skip(pattern), fields(pattern_len = pattern.len()))] pub fn parse(pattern: &str, simplify: bool) -> Result { if pattern.is_empty() { @@ -73,7 +85,7 @@ impl RegularExpression { } } - /// Creates a regular expression that matches all possible strings. + /// Creates the regular expression `.*`, which matches every string. pub fn new_total() -> Self { RegularExpression::Repetition( Box::new(RegularExpression::Character(CharRange::total())), @@ -82,12 +94,13 @@ impl RegularExpression { ) } - /// Creates a regular expression that matches the empty language. + /// Creates the regular expression `[]`, which matches no string. pub fn new_empty() -> Self { RegularExpression::Character(CharRange::empty()) } - /// Creates a regular expression that matches only the empty string `""`. + /// Creates the regular expression that matches the empty string `""` and no + /// other. pub fn new_empty_string() -> Self { RegularExpression::Concat(VecDeque::new()) } @@ -153,9 +166,11 @@ impl RegularExpression { Self::convert_to_regex(&capture.sub, simplify, at_start, at_end) } HirKind::Concat(concat) => { + let execution_profile = ExecutionProfile::get(); let len = concat.len(); let mut concat_regex = RegularExpression::Concat(VecDeque::with_capacity(len)); for (i, c) in concat.iter().enumerate() { + execution_profile.assert_not_timed_out()?; // Only the first element can be at the overall start, and // only the last at the overall end. let child_at_start = at_start && i == 0; @@ -163,7 +178,7 @@ impl RegularExpression { let concat_value = Self::convert_to_regex(c, simplify, child_at_start, child_at_end)?; if simplify { - concat_regex = concat_regex.concat(&concat_value, true); + concat_regex.concat_mut(concat_value); } else if let RegularExpression::Concat(mut values) = concat_regex { values.push_back(concat_value); concat_regex = RegularExpression::Concat(values); @@ -258,6 +273,37 @@ impl RegularExpression { mod tests { use crate::regex::RegularExpression; + // A long concatenation is folded in place, in time linear in its length: + // copying the expression accumulated so far for each element took + // minutes on this pattern. The fold also checks the execution deadline. + #[test] + fn parse_folds_a_long_concatenation_in_place() { + use crate::error::EngineError; + use crate::execution_profile::ExecutionProfileBuilder; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::time::Duration; + + let pattern = "[ab]c".repeat(20_000); + match RegularExpression::new(&pattern).unwrap() { + RegularExpression::Concat(elements) => assert_eq!(40_000, elements.len()), + other => panic!("not a concatenation: {other}"), + } + + // A clock that advances at each reading: the deadline passes after a + // number of elements, whatever the machine. + static READINGS: AtomicU64 = AtomicU64::new(0); + ExecutionProfileBuilder::new() + .execution_timeout(100) + .clock(|| Duration::from_millis(READINGS.fetch_add(1, Ordering::Relaxed))) + .build() + .run(|| { + assert_eq!( + EngineError::OperationTimeOutError, + RegularExpression::new(&pattern).unwrap_err() + ); + }); + } + // Folding an alternation with many shared-affix branches is quadratic in // the branch count; the parse must honor the execution deadline instead // of burning CPU outside the profile. diff --git a/src/regex/mod.rs b/src/regex/mod.rs index 02e8898..fe9d8bb 100644 --- a/src/regex/mod.rs +++ b/src/regex/mod.rs @@ -12,16 +12,12 @@ mod analyze; mod builder; mod operation; -/// Represents a regular expression. +/// A regular expression, held as a tree. /// -/// The variants are public and freely constructible and matchable. Values -/// can also be built with the parser ([`new`](Self::new) / -/// [`parse`](Self::parse)) or the simplifying combinators -/// ([`concat`](Self::concat), [`union`](Self::union), -/// [`repeat`](Self::repeat)). A directly-constructed repetition whose -/// maximum is below its minimum denotes no valid language and is rejected -/// with [`EngineError::InvalidRepetitionBounds`] when converted by -/// [`to_automaton`](Self::to_automaton). +/// It is built by parsing a pattern ([`new`](Self::new), +/// [`parse`](Self::parse)), by combining expressions ([`concat`](Self::concat), +/// [`union`](Self::union), [`repeat`](Self::repeat)), which simplify their +/// result, or from its variants. /// /// ``` /// use regexsolver::regex::RegularExpression; @@ -35,16 +31,16 @@ mod operation; #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] #[must_use = "regular expressions are immutable; operations return a new expression"] pub enum RegularExpression { - /// A single character drawn from the given range; an empty range denotes - /// the empty language `[]`. + /// One character of the range. An empty range is the empty language `[]`. Character(CharRange), - /// `r{min,max}`; `None` means unbounded. Expected invariant: `max >= min` - /// when bounded (checked by [`to_automaton`](Self::to_automaton)). + /// `r{min,max}`, with no upper bound when the maximum is `None`. A maximum + /// below the minimum is rejected by [`to_automaton`](Self::to_automaton) + /// with [`EngineError::InvalidRepetitionBounds`]. Repetition(Box, u32, Option), - /// The concatenation of the parts in order; no parts denotes the empty - /// string `""`. + /// The concatenation of the parts, in order. With no parts, it is the + /// empty string `""`. Concat(VecDeque), - /// The union of the parts; no parts denotes the empty language `[]`. + /// The union of the parts. With no parts, it is the empty language `[]`. Alternation(Vec), } @@ -154,8 +150,30 @@ impl RegularExpression { } } - /// Returns `true` if the regular expression matches the empty language. + /// Returns `true` if the expression matches no string. + /// + /// A repetition whose maximum is below its minimum matches no string. + /// + /// Linear in the size of the expression. + #[inline] pub fn is_empty(&self) -> bool { + self.is_simplified_empty() || self.length().0.is_none() + } + + /// Returns `true` if the expression matches the empty string `""` and no + /// other. + /// + /// Linear in the size of the expression. + #[inline] + pub fn is_empty_string(&self) -> bool { + self.is_simplified_empty_string() || self.length() == (Some(0), Some(0)) + } + + /// Whether the expression is the empty language in its simplified form: + /// an empty character class or an empty alternation. In constant time, + /// for the combinators, whose operands are simplified; + /// [`is_empty`](Self::is_empty) is exact on any expression. + pub(crate) fn is_simplified_empty(&self) -> bool { match self { RegularExpression::Alternation(alternation) => alternation.is_empty(), RegularExpression::Character(range) => range.is_empty(), @@ -163,15 +181,21 @@ impl RegularExpression { } } - /// Returns `true` if the regular expression matches only the empty string `""`. - pub fn is_empty_string(&self) -> bool { + /// Whether the expression is the empty string in its simplified form: an + /// empty concatenation. In constant time, for the combinators, whose + /// operands are simplified; [`is_empty_string`](Self::is_empty_string) is + /// exact on any expression. + pub(crate) fn is_simplified_empty_string(&self) -> bool { match self { RegularExpression::Concat(concat) => concat.is_empty(), _ => false, } } - /// Returns `true` if the regular expression matches all possible strings. + /// Returns `true` if the expression is `.*`, which matches every string. + /// + /// An expression of another form can match every string too, for which this + /// returns `false`: [`Term::is_total`](crate::Term::is_total) is exact. pub fn is_total(&self) -> bool { match self { RegularExpression::Repetition(regular_expression, min, max_opt) => { @@ -188,11 +212,9 @@ impl RegularExpression { } } - /// The deepest a directly-constructed expression tree may nest before - /// [`to_automaton`](Self::to_automaton) refuses to convert it. Parsed - /// patterns never approach this (`regex-syntax` caps parse nesting far - /// lower); it only bounds the recursion so a pathologically deep hand-built - /// tree returns an error instead of overflowing the stack. + /// The depth of nesting past which [`to_automaton`](Self::to_automaton) + /// returns [`EngineError::RegexTooDeeplyNested`]. Only an expression built + /// by hand can reach it: the parser stops well below. pub const MAX_NESTING_DEPTH: usize = 1000; /// Returns an error if the tree nests deeper than [`MAX_NESTING_DEPTH`](Self::MAX_NESTING_DEPTH). @@ -219,7 +241,16 @@ impl RegularExpression { Ok(()) } - /// Converts the regular expression to an equivalent [`FastAutomaton`]. + /// Converts the regular expression to a [`FastAutomaton`] that accepts the + /// strings it matches. + /// + /// # Errors + /// + /// Returns [`EngineError::InvalidRepetitionBounds`] for a repetition whose + /// maximum is below its minimum, [`EngineError::RegexTooDeeplyNested`] for + /// an expression nested deeper than + /// [`MAX_NESTING_DEPTH`](Self::MAX_NESTING_DEPTH), and the errors of the + /// limits of the execution profile. #[tracing::instrument(level = "trace", skip_all)] pub fn to_automaton(&self) -> Result { // Both whole-tree checks run once here: a subtree can never nest @@ -272,19 +303,12 @@ impl RegularExpression { } } - /// Returns the cognitive complexity of the pattern: a readability score, - /// independent of the characters used. + /// Returns a score of how hard the pattern is to read: the higher, the + /// harder. /// - /// - class: 1. - /// - concatenation: the sum of its parts. - /// - alternation: its branches read one level deeper, plus `1 + depth` per - /// extra branch. - /// - quantifier: its operand, plus the quantifier's weight × `(1 + depth)`; - /// `?`, `*`, `+` are cheapest, then `{n}`, `{n,}`, `{m,n}`. A quantified - /// group reads one level deeper, and a quantifier with another quantifier - /// inside it pays an extra `1 + depth`. - /// - /// The empty string costs 0; the empty language `[]` is a class (1). + /// It grows with the number of character classes, alternations and + /// quantifiers, and with their nesting; it does not depend on the + /// characters used. The empty string scores 0 and a character class 1. pub fn evaluate_complexity(&self) -> f64 { const CLASS: f64 = 1.0; const NESTED_QUANTIFIER: f64 = 1.0; @@ -400,47 +424,12 @@ mod tests { Ok(()) } - /// Drops a deep chain-shaped tree level by level. `Box`'s drop glue - /// recurses (see [`RegularExpression::MAX_NESTING_DEPTH`]), so the deep - /// trees below must not be dropped whole. - fn drop_chain_iteratively(mut regex: RegularExpression) { - loop { - regex = match regex { - RegularExpression::Repetition(inner, _, _) => *inner, - RegularExpression::Concat(mut parts) if parts.len() == 1 => { - parts.pop_front().expect("len() == 1") - } - RegularExpression::Alternation(mut parts) if parts.len() == 1 => { - parts.pop().expect("len() == 1") - } - _ => return, - }; - } - } - - // Display streams via an explicit work stack: a hand-built tree far - // deeper than any recursive formatter could survive must still print. + // A chain of singleton wrappers prints transparently, and the + // quantifier's parenthesization must look through all of them. #[test] - fn display_does_not_recurse_on_deep_trees() { - const DEPTH: usize = 100_000; - - // `((...(a*)*...)*)*`: every level goes through the parenthesization - // decision and the quantifier path. - let mut regex = RegularExpression::new("a").unwrap(); - for _ in 0..DEPTH { - regex = RegularExpression::Repetition(Box::new(regex), 0, None); - } - let printed = regex.to_string(); - assert_eq!(3 * DEPTH - 1, printed.len()); - assert!(printed.starts_with("(((")); - assert!(printed.ends_with(")*)*)*")); - drop_chain_iteratively(regex); - - // A deep chain of singleton wrappers prints transparently, and the - // quantifier's parenthesization must look through all of them - // without recursing. + fn display_looks_through_singleton_wrappers() { let mut regex = RegularExpression::new("ab").unwrap(); - for i in 0..DEPTH { + for i in 0..6 { regex = if i % 2 == 0 { RegularExpression::Concat(VecDeque::from([regex])) } else { @@ -449,6 +438,5 @@ mod tests { } let regex = RegularExpression::Repetition(Box::new(regex), 0, None); assert_eq!("(ab)*", regex.to_string()); - drop_chain_iteratively(regex); } } diff --git a/src/regex/operation/concat.rs b/src/regex/operation/concat.rs index b127bea..95b5f5b 100644 --- a/src/regex/operation/concat.rs +++ b/src/regex/operation/concat.rs @@ -1,7 +1,7 @@ use super::*; impl RegularExpression { - /// Returns a regular expression that is the concatenation of all expressions in `regexes`. + /// Returns the concatenation of `regexes`, in order, simplified. #[tracing::instrument(level = "trace", skip_all)] pub fn concat_all<'a, I: IntoIterator>( regexes: I, @@ -9,162 +9,78 @@ impl RegularExpression { let mut result = RegularExpression::new_empty_string(); for other in regexes { - result = result.concat(other, true); + result.concat_mut(other.clone()); } result } - /// Returns a new regular expression representing the concatenation of `self` and `other`; `append_back` determines their order. + /// Returns the concatenation of `self` and `other`, simplified: `self` + /// comes first if `append_back` is `true`, `other` if it is `false`. #[tracing::instrument(level = "trace", skip(self, other), fields(append_back = append_back))] pub fn concat(&self, other: &RegularExpression, append_back: bool) -> RegularExpression { - if self.is_empty() || other.is_empty() { - return RegularExpression::new_empty(); - } else if self.is_empty_string() { - return other.clone(); - } else if other.is_empty_string() { - return self.clone(); - } - let (front, back) = if append_back { (self, other) } else { (other, self) }; - match (front, back) { - (RegularExpression::Concat(..), RegularExpression::Concat(..)) => { - Self::opconcat_concat_and_concat(front, back) - } - (RegularExpression::Concat(..), _) => Self::opconcat_concat_and_other(front, back), - (_, RegularExpression::Concat(..)) => Self::opconcat_other_and_concat(front, back), - (_, _) => Self::opconcat_other_and_other(front, back), - } - } - - fn opconcat_other_and_other( - this: &RegularExpression, - that: &RegularExpression, - ) -> RegularExpression { - if let Some(merged) = Self::opconcat_can_be_merged(this, that) { - merged - } else { - let mut vec = VecDeque::with_capacity(2); - vec.push_back(this.clone()); - vec.push_back(that.clone()); - RegularExpression::Concat(vec) - } + let mut result = front.clone(); + result.concat_mut(back.clone()); + result } - fn opconcat_other_and_concat( - this: &RegularExpression, - that: &RegularExpression, - ) -> RegularExpression { - if let RegularExpression::Concat(that_elements) = that { - if that_elements.is_empty() { - return this.clone(); - } - - if let Some(merged) = Self::opconcat_can_be_merged(this, that) { - return merged; - } - - // Clone the surviving elements only: the boundary element is - // either replaced by the merge or kept alongside `this`. - let mut vec: VecDeque; - if let Some(merged) = Self::opconcat_can_be_merged(this, &that_elements[0]) { - vec = that_elements.iter().skip(1).cloned().collect(); - vec.push_front(merged); - } else { - vec = that_elements.clone(); - vec.push_front(this.clone()); - } - - if vec.len() == 1 { - vec[0].clone() - } else { - RegularExpression::Concat(vec) - } - } else { - panic!("Not concat") + /// Appends `that` to `self`, simplified: [`concat`](Self::concat) in + /// place. A fold of `concat` copies the expression accumulated so far at + /// each step, which takes quadratic time; a fold of `concat_mut` does + /// not. + pub(crate) fn concat_mut(&mut self, that: RegularExpression) { + if self.is_simplified_empty() || that.is_simplified_empty() { + *self = RegularExpression::new_empty(); + return; + } else if that.is_simplified_empty_string() { + return; + } else if self.is_simplified_empty_string() { + *self = that; + return; } - } - - fn opconcat_concat_and_other( - this: &RegularExpression, - that: &RegularExpression, - ) -> RegularExpression { - if let RegularExpression::Concat(this_elements) = this { - if this_elements.is_empty() { - return that.clone(); - } - - if let Some(merged) = Self::opconcat_can_be_merged(this, that) { - return merged; - } - // Clone the surviving elements only (see opconcat_other_and_concat). - let this_index = this_elements.len() - 1; - let mut vec: VecDeque; - if let Some(merged) = Self::opconcat_can_be_merged(&this_elements[this_index], that) { - vec = this_elements.iter().take(this_index).cloned().collect(); - vec.push_back(merged); - } else { - vec = this_elements.clone(); - vec.push_back(that.clone()); - } - - if vec.len() == 1 { - vec[0].clone() - } else { - RegularExpression::Concat(vec) - } - } else { - panic!("Not concat") + // The two as a whole, as `(ab)*` and `ab`. + if let Some(merged) = Self::opconcat_can_be_merged(self, &that) { + *self = merged; + return; } - } - - fn opconcat_concat_and_concat( - this: &RegularExpression, - that: &RegularExpression, - ) -> RegularExpression { - if let ( - RegularExpression::Concat(this_elements), - RegularExpression::Concat(that_elements), - ) = (this, that) - { - if this_elements.is_empty() { - return RegularExpression::Concat(that_elements.clone()); - } else if that_elements.is_empty() { - return RegularExpression::Concat(this_elements.clone()); - } - - if let Some(merged) = Self::opconcat_can_be_merged(this, that) { - return merged; - } - - // Clone the surviving elements only (see opconcat_other_and_concat). - let (this_index, that_index) = (this_elements.len() - 1, 0); - let mut vec: VecDeque; - if let Some(merged) = - Self::opconcat_can_be_merged(&this_elements[this_index], &that_elements[that_index]) - { - vec = this_elements.iter().take(this_index).cloned().collect(); - vec.push_back(merged); - vec.extend(that_elements.iter().skip(1).cloned()); - } else { - vec = this_elements.clone(); - vec.extend(that_elements.iter().cloned()); - } - if vec.len() == 1 { - vec[0].clone() - } else { - RegularExpression::Concat(vec) + let this = std::mem::replace(self, RegularExpression::new_empty_string()); + let mut elements = match (this, that) { + (RegularExpression::Concat(mut elements), RegularExpression::Concat(mut others)) => { + // Only the elements that meet can be merged. + if let Some(first) = others.pop_front() { + Self::push_concat_element(&mut elements, first); + } + elements.extend(others); + elements + } + (RegularExpression::Concat(mut elements), that) => { + Self::push_concat_element(&mut elements, that); + elements + } + (this, RegularExpression::Concat(mut elements)) => { + match elements + .front() + .and_then(|first| Self::opconcat_can_be_merged(&this, first)) + { + Some(merged) => elements[0] = merged, + None => elements.push_front(this), + } + elements } - } else { - panic!("Not concat") - } + (this, that) => VecDeque::from([this, that]), + }; + *self = match elements.len() { + 1 => elements.pop_front().expect("len() == 1"), + _ => RegularExpression::Concat(elements), + }; } /// Appends `that` to the fold accumulator `elements`, merging with the diff --git a/src/regex/operation/repeat.rs b/src/regex/operation/repeat.rs index 6376b61..752f8d0 100644 --- a/src/regex/operation/repeat.rs +++ b/src/regex/operation/repeat.rs @@ -1,11 +1,11 @@ use super::*; impl RegularExpression { - /// Computes the repetition of the expression between `min` and `max_opt` times; if `max_opt` is `None`, the repetition is unbounded. + /// Returns the repetition of `self`, simplified: the strings made of `n` + /// strings of `self` one after the other, for every `n` from `min` to + /// `max_opt`, with no upper bound when `max_opt` is `None`. /// - /// When `max_opt` is below `min` there is no valid repetition count and - /// the result is the empty language, consistently with - /// [`FastAutomaton::repeat`](crate::fast_automaton::FastAutomaton::repeat). + /// A `max_opt` below `min` gives the empty language. #[tracing::instrument(level = "trace", skip(self), fields(min = min, max_opt = tracing::field::debug(max_opt)))] pub fn repeat(&self, min: u32, max_opt: Option) -> RegularExpression { if let Some(max) = max_opt { @@ -18,13 +18,13 @@ impl RegularExpression { if self.is_total() { return RegularExpression::new_total(); - } else if self.is_empty() { + } else if self.is_simplified_empty() { return if min == 0 { Self::new_empty_string() } else { RegularExpression::new_empty() }; - } else if self.is_empty_string() { + } else if self.is_simplified_empty_string() { return Self::new_empty_string(); } else if min == 1 && max_opt == Some(1) { return self.clone(); @@ -113,22 +113,22 @@ mod tests { #[test] fn repeat_count_guards_precede_receiver_shortcuts() { let total = RegularExpression::new_total(); - assert!(total.repeat(0, Some(0)).is_empty_string()); - assert!(total.repeat(5, Some(2)).is_empty()); + assert!(total.repeat(0, Some(0)).is_simplified_empty_string()); + assert!(total.repeat(5, Some(2)).is_simplified_empty()); assert!(total.repeat(0, Some(3)).is_total()); assert!(total.repeat(2, None).is_total()); let empty = RegularExpression::new_empty(); - assert!(empty.repeat(0, Some(0)).is_empty_string()); - assert!(empty.repeat(0, Some(5)).is_empty_string()); - assert!(empty.repeat(0, None).is_empty_string()); - assert!(empty.repeat(2, Some(5)).is_empty()); - assert!(empty.repeat(2, None).is_empty()); + assert!(empty.repeat(0, Some(0)).is_simplified_empty_string()); + assert!(empty.repeat(0, Some(5)).is_simplified_empty_string()); + assert!(empty.repeat(0, None).is_simplified_empty_string()); + assert!(empty.repeat(2, Some(5)).is_simplified_empty()); + assert!(empty.repeat(2, None).is_simplified_empty()); let empty_string = RegularExpression::new_empty_string(); - assert!(empty_string.repeat(0, Some(0)).is_empty_string()); - assert!(empty_string.repeat(5, Some(2)).is_empty()); - assert!(empty_string.repeat(3, Some(7)).is_empty_string()); + assert!(empty_string.repeat(0, Some(0)).is_simplified_empty_string()); + assert!(empty_string.repeat(5, Some(2)).is_simplified_empty()); + assert!(empty_string.repeat(3, Some(7)).is_simplified_empty_string()); // Each case must agree with the automaton construction. for receiver in [&total, &empty, &empty_string] { @@ -157,7 +157,7 @@ mod tests { // on these edges. let degenerate = RegularExpression::Repetition(Box::new(RegularExpression::new_total()), 0, Some(0)); - assert!(degenerate.simplify().is_empty_string()); + assert!(degenerate.simplify().is_simplified_empty_string()); } // The nested-repetition collapse must treat 0·∞ as 0: an unbounded @@ -192,7 +192,7 @@ mod tests { #[test] fn repeat_with_max_below_min_is_empty() { let a = RegularExpression::new("a").unwrap(); - assert!(a.repeat(5, Some(2)).is_empty()); + assert!(a.repeat(5, Some(2)).is_simplified_empty()); let automaton = a.to_automaton().unwrap().repeat(5, Some(2)).unwrap(); assert!(automaton.is_empty()); diff --git a/src/regex/operation/simplify.rs b/src/regex/operation/simplify.rs index 1c0830c..25a5d1c 100644 --- a/src/regex/operation/simplify.rs +++ b/src/regex/operation/simplify.rs @@ -1,7 +1,7 @@ use super::*; impl RegularExpression { - /// Returns a simplified version by eliminating redundant constructs and applying canonical reductions. + /// Returns an expression that matches the same strings, in a simpler form. #[tracing::instrument(level = "trace", skip_all)] pub fn simplify(&self) -> Self { match self { @@ -15,13 +15,10 @@ impl RegularExpression { regex.simplify().repeat(*min, *max_opt) } RegularExpression::Concat(elements) => { - let elements: VecDeque<_> = - elements.iter().map(|element| element.simplify()).collect(); - let mut regex = RegularExpression::new_empty_string(); elements .iter() - .for_each(|element| regex = regex.concat(element, true)); + .for_each(|element| regex.concat_mut(element.simplify())); regex } RegularExpression::Alternation(elements) => { diff --git a/src/regex/operation/union.rs b/src/regex/operation/union.rs index 689a9d3..5a0f93d 100644 --- a/src/regex/operation/union.rs +++ b/src/regex/operation/union.rs @@ -3,18 +3,17 @@ use std::collections::BTreeSet; use super::*; impl RegularExpression { - /// Returns a regular expression matching the union of `self` and `other`. + /// Returns the union of `self` and `other`, simplified: it matches the + /// strings that at least one of them matches. #[tracing::instrument(level = "trace", skip_all)] pub fn union(&self, other: &RegularExpression) -> RegularExpression { Self::union_all([self, other]) } - /// Returns a regular expression that is the union of all expressions in `regexes`. + /// Returns the union of `regexes`, simplified. /// - /// Folding through [`union`](Self::union) directly would clone the whole - /// accumulated alternation once per operand (quadratic in the number of - /// operands); the accumulator below applies the same element-merging - /// rules in place instead. + /// Takes less time than a chain of [`union`](Self::union) calls, each of + /// which copies the result of the previous one. #[tracing::instrument(level = "trace", skip_all)] pub fn union_all<'a, I: IntoIterator>( regexes: I, @@ -59,13 +58,13 @@ impl RegularExpression { fn union_<'a>(&self, other: &'a RegularExpression) -> Cow<'a, RegularExpression> { if self.is_total() || other.is_total() { return Cow::Owned(RegularExpression::new_total()); - } else if self.is_empty() { + } else if self.is_simplified_empty() { return Cow::Borrowed(other); - } else if other.is_empty() || self == other { + } else if other.is_simplified_empty() || self == other { return Cow::Owned(self.clone()); - } else if other.is_empty_string() { + } else if other.is_simplified_empty_string() { return Cow::Owned(self.repeat(0, Some(1))); - } else if self.is_empty_string() { + } else if self.is_simplified_empty_string() { return Cow::Owned(other.repeat(0, Some(1))); } Cow::Owned(match (self, other) { @@ -160,8 +159,8 @@ impl RegularExpression { regex = regex.concat(prefix, true); } - let regex_from_alternate = if !self_regex.is_empty_string() { - if !other_regex.is_empty_string() { + let regex_from_alternate = if !self_regex.is_simplified_empty_string() { + if !other_regex.is_simplified_empty_string() { if prefix.is_none() && suffix.is_none() { let mut alternate_elements = vec![self_regex, other_regex]; alternate_elements.sort_unstable(); @@ -172,7 +171,7 @@ impl RegularExpression { } else { Cow::Owned(self_regex.repeat(0, Some(1))) } - } else if !other_regex.is_empty_string() { + } else if !other_regex.is_simplified_empty_string() { Cow::Owned(other_regex.repeat(0, Some(1))) } else { Cow::Owned(RegularExpression::new_empty_string()) @@ -555,10 +554,10 @@ impl UnionAccumulator { if other.is_total() { return Some(RegularExpression::new_total()); } - if other.is_empty() { + if other.is_simplified_empty() { return None; } - if other.is_empty_string() { + if other.is_simplified_empty_string() { // L ∪ {""} = L?, exactly like the empty-string arm of `union_`. return Some(Self::materialize(set).repeat(0, Some(1))); } diff --git a/tests/proptest_strategies.rs b/tests/proptest_strategies.rs index db6f99a..aec044b 100644 --- a/tests/proptest_strategies.rs +++ b/tests/proptest_strategies.rs @@ -408,8 +408,30 @@ fn probes() -> Vec { probes_over(ALPHABET, 4) } -/// Asserts that intersection / union / difference of `a` and `b` agree with -/// the boolean combination of the operands on every probe string. +/// Asserts that a probe string is in the symmetric difference of `automata` +/// iff an odd number of them accepts it, sequentially and in parallel. +fn assert_symmetric_difference_all_membership( + automata: &[FastAutomaton], + probes: &[String], +) -> Result<(), TestCaseError> { + let odd = |s: &str| automata.iter().filter(|a| a.is_match(s)).count() % 2 == 1; + if let Some(all) = bounded(|| FastAutomaton::symmetric_difference_all(automata)) { + for s in probes { + prop_assert_eq!(all.is_match(s), odd(s), "membership for {:?}", s); + } + } + #[cfg(all(feature = "parallel", not(target_family = "wasm")))] + if let Some(all) = bounded(|| FastAutomaton::symmetric_difference_all_par(automata)) { + for s in probes { + prop_assert_eq!(all.is_match(s), odd(s), "parallel membership for {:?}", s); + } + } + Ok(()) +} + +/// Asserts that intersection / union / difference / symmetric difference of +/// `a` and `b` agree with the boolean combination of the operands on every +/// probe string. fn assert_set_ops_membership( a: &FastAutomaton, b: &FastAutomaton, @@ -445,6 +467,16 @@ fn assert_set_ops_membership( ); } } + if let Some(diff) = bounded(|| a.symmetric_difference(b)) { + for s in probes { + prop_assert_eq!( + diff.is_match(s), + a.is_match(s) != b.is_match(s), + "symmetric difference membership for {:?}", + s + ); + } + } Ok(()) } @@ -554,6 +586,27 @@ proptest! { assert_set_ops_membership(&a, &b, &probes())?; } + /// A string is in the symmetric difference of several automata iff an + /// odd number of them accepts it, whether they are walked together or + /// by groups in parallel. + #[test] + fn symmetric_difference_all_membership(automata in prop::collection::vec(arb_nfa(), 0..5)) { + assert_symmetric_difference_all_membership(&automata, &probes())?; + } + + /// The same across automata built over *different* alphabets ({a,b}, + /// {b,c} and {c,d}), whose spanning sets are merged into one for the + /// walk. + #[test] + fn symmetric_difference_all_membership_different_alphabets( + a in arb_nfa_over(&['a', 'b']), + b in arb_nfa_over(&['b', 'c']), + c in arb_nfa_over(&['c', 'd']), + ) { + let probes = probes_over(&['a', 'b', 'c', 'd'], 4); + assert_symmetric_difference_all_membership(&[a, b, c], &probes)?; + } + /// Set operations across operands built over *overlapping but different* /// alphabets ({a,b} vs {b,c}): the operands carry different spanning /// sets, so `SpanningSet::merge` and the `ConditionConverter` diff --git a/tests/public_api.rs b/tests/public_api.rs index 03de9ca..b6134e1 100644 --- a/tests/public_api.rs +++ b/tests/public_api.rs @@ -335,6 +335,34 @@ fn set_identities_hold() { .unwrap() ); + // symmetric_difference(a, b) == difference(union(a, b), intersection(a, b)) + let symmetric_difference = a.symmetric_difference([&b]).unwrap(); + assert!( + symmetric_difference + .equivalent( + &a.union([&b]) + .unwrap() + .difference(&a.intersection([&b]).unwrap()) + .unwrap() + ) + .unwrap() + ); + assert!(a.symmetric_difference([&a]).unwrap().is_empty().unwrap()); + // Commutative and associative: a term given twice cancels itself, + // wherever it is. + assert!( + b.symmetric_difference([&a]) + .unwrap() + .equivalent(&symmetric_difference) + .unwrap() + ); + assert!( + a.symmetric_difference([&b, &complement, &a, &complement]) + .unwrap() + .equivalent(&b) + .unwrap() + ); + // Both operands are subsets of their union, and their intersection is a // subset of both. let union = a.union([&b]).unwrap(); @@ -367,6 +395,91 @@ fn patterns_round_trip_through_their_language() { } } +/// `is_empty` and `is_empty_string` are exact on an expression that is not +/// simplified, on `RegularExpression` and on `Term`. +#[test] +fn emptiness_is_exact_on_an_expression_that_is_not_simplified() { + use regexsolver::regex_charclass::char::Char; + let a = + || RegularExpression::Character(CharRange::new_from_range(Char::new('a')..=Char::new('a'))); + + // Built from the variants: `[]a` matches no string, `a{0}` only `""`. + let nothing = + RegularExpression::Concat([RegularExpression::Character(CharRange::empty()), a()].into()); + let empty_string = RegularExpression::Repetition(Box::new(a()), 0, Some(0)); + assert!(nothing.is_empty() && !nothing.is_empty_string()); + assert!(empty_string.is_empty_string() && !empty_string.is_empty()); + assert!(Term::from_regex(nothing.clone()).is_empty().unwrap()); + assert!(!Term::from_regex(nothing).is_empty_string().unwrap()); + assert!( + Term::from_regex(empty_string.clone()) + .is_empty_string() + .unwrap() + ); + assert!(!Term::from_regex(empty_string).is_empty().unwrap()); + + // Parsed without simplification, against the automaton. + for pattern in [ + "()*", + "()?()*", + "(|(b){0})", + "((a){0})*", + "a?", + "(a|)", + "[]", + "", + ] { + let regex = RegularExpression::parse(pattern, false).unwrap(); + let automaton = regex.to_automaton().unwrap(); + assert_eq!(regex.is_empty(), automaton.is_empty(), "{pattern}"); + assert_eq!( + regex.is_empty_string(), + automaton.is_empty_string(), + "{pattern}" + ); + let term = Term::from_regex(regex); + assert_eq!(term.is_empty().unwrap(), automaton.is_empty(), "{pattern}"); + assert_eq!( + term.is_empty_string().unwrap(), + automaton.is_empty_string(), + "{pattern}" + ); + assert_eq!(term.length(), automaton.length(), "{pattern}"); + } + + // A repetition whose maximum is below its minimum matches no string, as + // for `length` and `repeat`, although it cannot be converted. + let invalid = RegularExpression::Repetition(Box::new(a()), 5, Some(2)); + assert!(invalid.is_empty() && invalid.to_automaton().is_err()); + assert!(Term::from_regex(invalid).is_empty().unwrap()); +} + +/// The union of terms backed by regular expressions is bounded by the +/// execution profile, as the union of automata is. +#[test] +fn union_of_regular_expressions_honors_the_timeout() { + use regexsolver::execution_profile::ExecutionProfileBuilder; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::time::Duration; + + let terms: Vec = (0..300).map(|i| term(&format!("x{i:05}y"))).collect(); + assert!(terms[0].union(&terms[1..]).is_ok()); + + // A clock that advances at each reading: the deadline passes after a + // number of terms, whatever the machine. + static READINGS: AtomicU64 = AtomicU64::new(0); + ExecutionProfileBuilder::new() + .execution_timeout(100) + .clock(|| Duration::from_millis(READINGS.fetch_add(1, Ordering::Relaxed))) + .build() + .run(|| { + assert_eq!( + EngineError::OperationTimeOutError, + terms[0].union(&terms[1..]).unwrap_err() + ); + }); +} + /// The empty language and the language of the empty string are different. #[test] fn the_empty_language_is_not_the_empty_string() {