use crate::core::{Pattern, RepetitionQuantifier, Symbol};
pub(super) fn factor(pattern: Pattern, disjoint: &[(String, String)]) -> Pattern {
let visit = |part| factor(part, disjoint);
match pattern {
Pattern::Group(inner) => Pattern::Group(Box::new(visit(*inner))),
Pattern::Concat(parts) => Pattern::Concat(parts.into_iter().map(visit).collect()),
Pattern::Repetition(inner, quantifier) => {
Pattern::Repetition(Box::new(visit(*inner)), quantifier)
}
Pattern::Alternation(branches) => {
factor_adjacent(branches.into_iter().map(visit).collect(), disjoint)
}
other => other,
}
}
fn parts(pattern: &Pattern) -> &[Pattern] {
match pattern {
Pattern::Concat(parts) => parts,
other => std::slice::from_ref(other),
}
}
fn into_parts(pattern: Pattern) -> Vec<Pattern> {
match pattern {
Pattern::Concat(parts) => parts,
other => vec![other],
}
}
fn concat(mut parts: Vec<Pattern>) -> Pattern {
if parts.len() == 1 {
parts.pop().expect("one fixed-prefix part")
} else {
Pattern::Concat(parts)
}
}
fn shared_word_start<'a>(left: &'a Pattern, right: &Pattern) -> Option<&'a str> {
match (left, right) {
(Pattern::Symbol(Symbol::Named(left)), Pattern::Symbol(Symbol::Named(right))) => {
(left == right).then_some(left)
}
(Pattern::Group(left), _) => shared_word_start(left, right),
(_, Pattern::Group(right)) => shared_word_start(left, right),
(Pattern::Concat(left), Pattern::Concat(right)) if left.len() == right.len() => {
let (first, rest) = left.split_first()?;
let head = shared_word_start(first, &right[0])?;
rest.iter()
.zip(&right[1..])
.all(|(a, b)| same_fixed_part(a, b))
.then_some(head)
}
(Pattern::Repetition(left, lq), Pattern::Repetition(right, rq))
if !lq.is_possessive()
&& !rq.is_possessive()
&& lq
.fixed_count()
.is_some_and(|n| n > 0 && rq.fixed_count() == Some(n)) =>
{
shared_word_start(left, right)
}
_ => None,
}
}
fn same_fixed_part(left: &Pattern, right: &Pattern) -> bool {
shared_word_start(left, right).is_some()
}
fn repeated_word(pattern: &Pattern) -> Option<(&Pattern, RepetitionQuantifier)> {
match pattern {
Pattern::Repetition(body, quantifier)
if !quantifier.is_possessive()
&& quantifier
.max_repetitions()
.is_none_or(|max| max >= quantifier.min_repetitions())
&& same_fixed_part(body, body) =>
{
Some((body, quantifier.clone()))
}
other if same_fixed_part(other, other) => {
Some((other, RepetitionQuantifier::Exactly(1)))
}
_ => None,
}
}
fn remaining_word(
body: &Pattern,
quantifier: &RepetitionQuantifier,
consumed: u32,
) -> Option<Pattern> {
let min = quantifier.min_repetitions() - consumed;
let max = quantifier.max_repetitions().map(|max| max - consumed);
if max == Some(0) {
return None;
}
if min == 1 && max == Some(1) {
return Some(body.clone());
}
let remaining = match max {
Some(max) => RepetitionQuantifier::Range(min, max),
None => RepetitionQuantifier::AtLeast(min),
};
let remaining = if quantifier.is_reluctant() {
remaining
.reluctant_variant()
.expect("greedy remaining bounds")
} else {
remaining
};
Some(Pattern::Repetition(
Box::new(body.clone()),
remaining.normalized(),
))
}
fn share_mandatory_word(
left: &Pattern,
right: &Pattern,
) -> Option<(Pattern, Option<Pattern>, Option<Pattern>)> {
let (left, lq) = repeated_word(left)?;
let (right, rq) = repeated_word(right)?;
let count = lq.min_repetitions().min(rq.min_repetitions());
if count == 0 || !same_fixed_part(left, right) {
return None;
}
let shared = if count == 1 {
left.clone()
} else {
Pattern::Repetition(Box::new(left.clone()), RepetitionQuantifier::Exactly(count))
};
Some((
shared,
remaining_word(left, &lq, count),
remaining_word(right, &rq, count),
))
}
fn shared_delimited_word(
left: &[Pattern],
right: &[Pattern],
disjoint: &[(String, String)],
) -> bool {
let (
[Pattern::Repetition(a, aq), a_end, ..],
[Pattern::Repetition(b, bq), b_end, ..],
) = (left, right)
else {
return false;
};
if disjoint.is_empty()
|| aq != bq
|| aq.is_possessive()
|| aq
.max_repetitions()
.is_some_and(|max| max < aq.min_repetitions())
{
return false;
}
let (Some(start), Some(end)) =
(shared_word_start(a, b), shared_word_start(a_end, b_end))
else {
return false;
};
disjoint.iter().any(|(l, r)| {
(l.eq_ignore_ascii_case(start) && r.eq_ignore_ascii_case(end))
|| (r.eq_ignore_ascii_case(start) && l.eq_ignore_ascii_case(end))
})
}
fn factor_adjacent(branches: Vec<Pattern>, disjoint: &[(String, String)]) -> Pattern {
let mut result: Vec<Pattern> = Vec::with_capacity(branches.len());
for branch in branches {
let common = result.last().map_or(0, |previous| {
let (left, right) = (parts(previous), parts(&branch));
let mut common = 0;
while common < left.len().min(right.len()) {
if same_fixed_part(&left[common], &right[common]) {
common += 1;
} else if shared_delimited_word(
&left[common..],
&right[common..],
disjoint,
) {
common += 2;
} else {
break;
}
}
common
});
let partial = result.last().and_then(|previous| {
parts(previous)
.get(common)
.zip(parts(&branch).get(common))
.and_then(|(left, right)| share_mandatory_word(left, right))
});
if common == 0 && partial.is_none() {
result.push(branch);
continue;
}
let previous = result.pop().expect("a shared preceding branch");
let mut prefix = into_parts(previous);
let mut tail = prefix.split_off(common);
let mut suffix = into_parts(branch)
.into_iter()
.skip(common)
.collect::<Vec<_>>();
if let Some((shared, left, right)) = partial {
prefix.push(shared);
if let Some(left) = left {
tail[0] = left;
} else {
tail.remove(0);
}
if let Some(right) = right {
suffix[0] = right;
} else {
suffix.remove(0);
}
}
let tail = concat(tail);
let suffix = concat(suffix);
let mut choices = match tail {
Pattern::Alternation(choices) => choices,
other => vec![other],
};
choices.push(suffix);
prefix.push(Pattern::Alternation(choices));
result.push(concat(prefix));
}
if result.len() == 1 {
result.pop().expect("one factored branch")
} else {
Pattern::Alternation(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::test_support::all_matches;
fn factor(pattern: Pattern) -> Pattern {
super::factor(pattern, &[])
}
fn symbol(name: &str) -> Pattern {
Pattern::Symbol(Symbol::Named(name.into()))
}
fn word(names: &[&str]) -> Pattern {
concat(names.iter().map(|name| symbol(name)).collect())
}
fn alt(branches: Vec<Pattern>) -> Pattern {
Pattern::Alternation(branches)
}
fn repeat(pattern: Pattern, quantifier: RepetitionQuantifier) -> Pattern {
Pattern::Repetition(Box::new(pattern), quantifier)
}
fn assert_same_matches(before: &Pattern, after: &Pattern, signatures: &[&str]) {
for length in 0..=3 {
for mut assignment in 0..signatures.len().pow(length) {
let rows = (0..length)
.map(|_| {
let row = signatures[assignment % signatures.len()];
assignment /= signatures.len();
row
})
.collect::<Vec<_>>();
assert_eq!(
all_matches(before, &rows),
all_matches(after, &rows),
"{before} -> {after}, rows={rows:?}"
);
}
}
}
#[test]
fn delimited_repeats_preserve_classifiers_and_ordered_empty_suffixes() {
use RepetitionQuantifier::{
OneOrMoreReluctant, Range, RangeReluctant, ZeroOrMore,
};
let disjoint = [("b".into(), "x".into())];
let signatures = ["", "X", "B", "C", "XC", "BC"];
for body in [symbol("X"), word(&["X", "C"])] {
for quantifier in [
ZeroOrMore,
OneOrMoreReluctant,
Range(0, 2),
RangeReluctant(1, 3),
] {
let repeated = repeat(body.clone(), quantifier);
for (left, right) in [(symbol("C"), word(&[])), (word(&[]), symbol("C"))]
{
let arm = |tail| concat(vec![repeated.clone(), symbol("B"), tail]);
let before = alt(vec![arm(left.clone()), arm(right.clone())]);
let expected = concat(vec![
repeated.clone(),
symbol("B"),
alt(vec![left, right]),
]);
let after = super::factor(before.clone(), &disjoint);
assert_eq!(after, expected);
assert_same_matches(&before, &after, &signatures);
let rows = ["XC", "C", "X", "BC", "C", "C"];
assert_eq!(all_matches(&before, &rows), all_matches(&after, &rows));
}
}
}
}
#[test]
fn overlapping_delimiter_keeps_the_branch_choice_before_the_split_choice() {
let star = repeat(symbol("X"), RepetitionQuantifier::ZeroOrMore);
let original = alt(vec![
concat(vec![star.clone(), symbol("B"), symbol("C")]),
concat(vec![star.clone(), symbol("B")]),
]);
let invalid = concat(vec![star, symbol("B"), alt(vec![symbol("C"), word(&[])])]);
let unrelated = [("X".into(), "C".into())];
assert_eq!(super::factor(original.clone(), &unrelated), original);
let rows = ["XB", "BC"];
let labels = |p| {
all_matches(p, &rows)
.into_iter()
.map(|r| r.classifier.unwrap())
.collect::<Vec<_>>()
};
assert_eq!(labels(&original), ["B", "C"]);
assert_eq!(labels(&invalid), ["X", "B"]);
}
#[test]
fn exact_repetitions_share_without_expansion_or_internal_choices() {
use RepetitionQuantifier::{Exactly, ExactlyReluctant, OneOrMore};
for body in [symbol("A"), word(&["A", "B"])] {
let prefix = repeat(body.clone(), Exactly(3));
let reluctant = repeat(body, ExactlyReluctant(3));
for (before, tails) in [
(
alt(vec![
concat(vec![prefix.clone(), symbol("C")]),
reluctant.clone(),
]),
vec![symbol("C"), word(&[])],
),
(
alt(vec![prefix.clone(), concat(vec![reluctant, symbol("C")])]),
vec![word(&[]), symbol("C")],
),
] {
assert_eq!(factor(before), concat(vec![prefix.clone(), alt(tails)]));
}
}
for body in [
repeat(symbol("A"), OneOrMore),
alt(vec![symbol("A"), symbol("B")]),
Pattern::Exclude(Symbol::Named("A".into())),
concat(vec![symbol("A"), Pattern::Symbol(Symbol::Start)]),
word(&[]),
] {
let prefix = repeat(body, Exactly(2));
let pattern = alt(vec![concat(vec![prefix.clone(), symbol("C")]), prefix]);
assert_eq!(factor(pattern.clone()), pattern);
}
assert!(!same_fixed_part(
&repeat(symbol("A"), Exactly(2)),
&repeat(symbol("A"), Exactly(3)),
));
}
#[test]
fn mandatory_copies_leave_each_branches_length_choices_in_place() {
use RepetitionQuantifier::{
Exactly, OneOrMore, Range, RangeReluctant, ZeroOrMore,
};
let a = symbol("A");
for (left, right, shared, left_tail, right_tail) in [
(
repeat(a.clone(), Exactly(5)),
repeat(a.clone(), Exactly(2)),
repeat(a.clone(), Exactly(2)),
concat(vec![repeat(a.clone(), Exactly(3)), symbol("B")]),
symbol("C"),
),
(
repeat(a.clone(), OneOrMore),
repeat(a.clone(), OneOrMore),
a.clone(),
concat(vec![repeat(a.clone(), ZeroOrMore), symbol("B")]),
concat(vec![repeat(a.clone(), ZeroOrMore), symbol("C")]),
),
(
repeat(a.clone(), Range(2, 4)),
repeat(a.clone(), RangeReluctant(1, 3)),
a.clone(),
concat(vec![repeat(a.clone(), Range(1, 3)), symbol("B")]),
concat(vec![repeat(a.clone(), RangeReluctant(0, 2)), symbol("C")]),
),
] {
let before = alt(vec![
concat(vec![left, symbol("B")]),
concat(vec![right, symbol("C")]),
]);
assert_eq!(
factor(before),
concat(vec![shared, alt(vec![left_tail, right_tail])])
);
}
let prefix = repeat(a, Exactly(2));
let original = alt(vec![
concat(vec![prefix.clone(), symbol("B")]),
concat(vec![repeat(symbol("A"), Exactly(5)), symbol("B")]),
]);
assert_eq!(
factor(original),
concat(vec![
prefix,
alt(vec![
symbol("B"),
concat(vec![repeat(symbol("A"), Exactly(3)), symbol("B")])
])
])
);
}
#[test]
fn adjacent_fixed_prefixes_preserve_branch_order_and_empty_suffixes() {
let a = symbol("A");
for (before, after) in [
(
alt(vec![word(&["A", "B"]), a.clone()]),
concat(vec![a.clone(), alt(vec![symbol("B"), word(&[])])]),
),
(
alt(vec![a.clone(), word(&["A", "B"])]),
concat(vec![a.clone(), alt(vec![word(&[]), symbol("B")])]),
),
(
alt(vec![word(&["A", "B", "C"]), word(&["A", "B", "D"])]),
concat(vec![
a.clone(),
symbol("B"),
alt(vec![symbol("C"), symbol("D")]),
]),
),
(
alt(vec![
word(&["A", "B"]),
word(&["A", "C"]),
word(&["A", "D"]),
]),
concat(vec![a, alt(vec![symbol("B"), symbol("C"), symbol("D")])]),
),
] {
assert_eq!(factor(before), after);
}
let star =
Pattern::Repetition(Box::new(symbol("A")), RepetitionQuantifier::ZeroOrMore);
let excluded = Pattern::Exclude(Symbol::Named("A".into()));
for pattern in [
alt(vec![word(&["A", "B"]), symbol("X"), word(&["A", "C"])]),
alt(vec![
concat(vec![star.clone(), symbol("B")]),
concat(vec![star, symbol("C")]),
]),
alt(vec![
concat(vec![excluded.clone(), symbol("B")]),
concat(vec![excluded, symbol("C")]),
]),
] {
assert_eq!(factor(pattern.clone()), pattern);
}
}
#[test]
fn fixed_prefix_factoring_preserves_reference_classifiers_and_preference() {
use RepetitionQuantifier::{
Exactly, ExactlyReluctant, OneOrMore, Range, RangeReluctant,
};
let fixed = repeat(symbol("A"), Exactly(2));
let patterns = [
alt(vec![word(&["A", "B"]), symbol("A")]),
alt(vec![symbol("A"), word(&["A", "B"])]),
alt(vec![
word(&["A", "B"]),
word(&["A", "C"]),
word(&["A", "B", "C"]),
]),
alt(vec![word(&["A", "B"]), symbol("C"), word(&["A", "C"])]),
concat(vec![alt(vec![word(&["A", "B"]), symbol("A")]), symbol("C")]),
Pattern::Repetition(
Box::new(alt(vec![word(&["A", "B"]), symbol("A")])),
OneOrMore,
),
Pattern::Repetition(
Box::new(alt(vec![symbol("A"), word(&["A", "B"])])),
RepetitionQuantifier::OneOrMoreReluctant,
),
alt(vec![
concat(vec![fixed.clone(), symbol("B")]),
concat(vec![repeat(symbol("A"), ExactlyReluctant(2)), symbol("C")]),
]),
alt(vec![
concat(vec![fixed.clone(), symbol("B")]),
fixed.clone(),
]),
alt(vec![fixed.clone(), concat(vec![fixed, symbol("B")])]),
alt(vec![
concat(vec![repeat(symbol("A"), Exactly(3)), symbol("B")]),
concat(vec![repeat(symbol("A"), Exactly(2)), symbol("C")]),
]),
alt(vec![
concat(vec![repeat(symbol("A"), Exactly(2)), symbol("B")]),
concat(vec![repeat(symbol("A"), Exactly(3)), symbol("C")]),
]),
alt(vec![
concat(vec![repeat(symbol("A"), OneOrMore), symbol("B")]),
concat(vec![repeat(symbol("A"), OneOrMore), symbol("C")]),
]),
alt(vec![
concat(vec![repeat(symbol("A"), Range(2, 4)), symbol("B")]),
concat(vec![repeat(symbol("A"), RangeReluctant(1, 3)), symbol("C")]),
]),
concat(vec![
repeat(
alt(vec![
concat(vec![repeat(symbol("A"), OneOrMore), symbol("B")]),
concat(vec![repeat(symbol("A"), Exactly(2)), symbol("C")]),
]),
RepetitionQuantifier::OneOrMoreReluctant,
),
symbol("C"),
]),
];
for pattern in patterns {
let factored = factor(pattern.clone());
for rows in [
vec!["A", "A", "A", "A", "A", "B", "A", "A", "C"],
vec!["AB", "AB", "ABC", "A", "AC", "C"],
vec!["A", "A", "B", "A", "A", "C", "C"],
] {
assert_eq!(
all_matches(&factored, &rows),
all_matches(&pattern, &rows),
"{pattern} -> {factored}, rows={rows:?}"
);
}
assert_same_matches(
&pattern,
&factored,
&["", "A", "B", "C", "AB", "AC", "BC", "ABC"],
);
}
let fixed = repeat(word(&["A", "B"]), Exactly(2));
for pattern in [
alt(vec![
concat(vec![fixed.clone(), symbol("C")]),
fixed.clone(),
]),
alt(vec![fixed.clone(), concat(vec![fixed, symbol("C")])]),
alt(vec![
concat(vec![repeat(word(&["A", "B"]), Exactly(3)), symbol("C")]),
concat(vec![repeat(word(&["A", "B"]), Exactly(2)), symbol("C")]),
]),
] {
let factored = factor(pattern.clone());
for rows in [
vec!["A", "B", "A", "B", "A", "B", "C"],
vec!["A", "B", "A", "B", "C", "A", "B", "A", "B"],
vec!["AB", "AB", "AB", "AB", "BC"],
vec!["A", "B", "", "A", "B", "A", "B", "C"],
] {
assert_eq!(all_matches(&factored, &rows), all_matches(&pattern, &rows));
}
}
}
}