use crate::core::pattern::QuantifierBounds;
use crate::core::{Pattern, RepetitionPreference, RepetitionQuantifier, Symbol};
pub(super) fn normalize_symbol_runs(pattern: Pattern) -> Pattern {
normalize_runs(pattern, false)
}
pub(super) fn normalize_symbol_and_anchor_runs(pattern: Pattern) -> Pattern {
normalize_runs(pattern, true)
}
fn normalize_runs(pattern: Pattern, dedup_anchors: bool) -> Pattern {
match pattern {
Pattern::Group(inner) => normalize_runs(*inner, dedup_anchors),
Pattern::Concat(parts) => {
let mut normalized = Vec::with_capacity(parts.len());
for part in parts {
match normalize_runs(part, dedup_anchors) {
Pattern::Concat(parts) => {
for part in parts {
push_concat_part(&mut normalized, part, dedup_anchors);
}
}
part => push_concat_part(&mut normalized, part, dedup_anchors),
}
}
if normalized.len() == 1 {
normalized.pop().expect("one normalized concat part")
} else {
Pattern::Concat(normalized)
}
}
Pattern::Alternation(parts) => Pattern::Alternation(
parts
.into_iter()
.map(|part| normalize_runs(part, dedup_anchors))
.collect(),
),
Pattern::Repetition(inner, quantifier) => {
let inner = normalize_runs(*inner, dedup_anchors);
let quantifier = quantifier.normalized();
let outer = quantifier.bounds();
if !valid_bounds(outer) {
return Pattern::Repetition(Box::new(inner), quantifier);
}
if outer.fixed_count() == Some(0)
|| matches!(&inner, Pattern::Concat(parts) if parts.is_empty())
{
return Pattern::Concat(vec![]);
}
if outer.fixed_count() == Some(1) {
return inner;
}
if matches!(&inner, Pattern::Repetition(_, _))
&& let Some((leaf, bounds)) = symbol_run(&inner)
&& let Some(bounds) = nested_bounds(bounds, outer)
{
return run_pattern(leaf.clone(), bounds);
}
Pattern::Repetition(Box::new(inner), quantifier)
}
other => other,
}
}
fn push_concat_part(parts: &mut Vec<Pattern>, part: Pattern, dedup_anchors: bool) {
if dedup_anchors
&& matches!(&part, Pattern::Symbol(Symbol::Start | Symbol::End))
&& parts.last() == Some(&part)
{
return;
}
let merged = parts.last().and_then(|previous| {
let (left, left_bounds) = symbol_run(previous)?;
let (right, right_bounds) = symbol_run(&part)?;
if left != right {
return None;
}
let preference = common_preference(left_bounds, right_bounds)?;
let bounds = QuantifierBounds {
min: left_bounds.min.checked_add(right_bounds.min)?,
max: add_max(left_bounds.max, right_bounds.max)?,
preference,
};
Some(run_pattern(left.clone(), bounds))
});
if let Some(merged) = merged {
*parts.last_mut().expect("merged a preceding concat part") = merged;
} else {
parts.push(part);
}
}
fn symbol_run(pattern: &Pattern) -> Option<(&Pattern, QuantifierBounds)> {
match pattern {
Pattern::Symbol(Symbol::Named(_)) | Pattern::Exclude(Symbol::Named(_)) => {
Some((pattern, RepetitionQuantifier::Exactly(1).bounds()))
}
Pattern::Repetition(inner, quantifier)
if matches!(
inner.as_ref(),
Pattern::Symbol(Symbol::Named(_)) | Pattern::Exclude(Symbol::Named(_))
) && valid_bounds(quantifier.bounds()) =>
{
Some((inner, quantifier.bounds()))
}
_ => None,
}
}
fn valid_bounds(bounds: QuantifierBounds) -> bool {
bounds.max.is_none_or(|max| bounds.min <= max)
}
fn common_preference(
left: QuantifierBounds,
right: QuantifierBounds,
) -> Option<RepetitionPreference> {
match (left.fixed_count(), right.fixed_count()) {
(Some(_), Some(_)) => Some(RepetitionPreference::Greedy),
(Some(_), None) if !right.is_possessive() => Some(right.preference),
(None, Some(_)) if !left.is_possessive() => Some(left.preference),
(None, None) if left.preference == right.preference && !left.is_possessive() => {
Some(left.preference)
}
_ => None,
}
}
fn nested_bounds(
inner: QuantifierBounds,
outer: QuantifierBounds,
) -> Option<QuantifierBounds> {
let preference = common_preference(inner, outer)?;
if outer.fixed_count().is_none() && inner.min > 1 {
return None;
}
Some(QuantifierBounds {
min: inner.min.checked_mul(outer.min)?,
max: match (inner.max, outer.max) {
(Some(inner), Some(outer)) => Some(inner.checked_mul(outer)?),
_ => None,
},
preference,
})
}
fn add_max(left: Option<u32>, right: Option<u32>) -> Option<Option<u32>> {
Some(match (left, right) {
(Some(left), Some(right)) => Some(left.checked_add(right)?),
_ => None,
})
}
fn run_pattern(leaf: Pattern, bounds: QuantifierBounds) -> Pattern {
if bounds.fixed_count() == Some(0) {
return Pattern::Concat(vec![]);
}
if bounds.fixed_count() == Some(1) {
return leaf;
}
let quantifier = match bounds.max {
Some(max) => RepetitionQuantifier::Range(bounds.min, max),
None => RepetitionQuantifier::AtLeast(bounds.min),
};
let quantifier = if bounds.is_reluctant() {
quantifier
.reluctant_variant()
.expect("constructed a greedy quantifier")
} else {
quantifier
};
Pattern::Repetition(Box::new(leaf), quantifier.normalized())
}