Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,26 @@ 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.
- `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.

### 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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
251 changes: 243 additions & 8 deletions benches/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}}}")
Expand All @@ -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();
}

Expand Down Expand Up @@ -122,15 +135,109 @@ 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))
let mut bench_difference = |name: &str, minuend: &FastAutomaton, subtrahend: &FastAutomaton| {
let via_complement = || difference_via_complement(black_box(minuend), subtrahend);
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)),
);

// `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<FastAutomaton> = ('a'..='p')
.map(|letter| automaton(&format!(".*{letter}")))
.collect();
let contains: Vec<FastAutomaton> = ["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| {
Expand Down Expand Up @@ -170,6 +277,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| {
Expand All @@ -180,6 +354,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();
}

Expand All @@ -192,6 +379,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()));

Expand Down
Loading
Loading