use super::{Pattern, RepetitionQuantifier, Symbol};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PatternStructuralInfo {
min_match_rows: usize,
max_match_rows: Option<usize>,
has_anchors: bool,
has_exclusions: bool,
anchored_at_end: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FixedPrefixSuffixInfo {
pub prefix: Vec<(String, usize)>,
pub middle: String,
pub suffix: Vec<(String, usize)>,
pub prefix_rows: usize,
pub suffix_rows: usize,
pub middle_min_rows: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatternAnalysisSummary {
structural_info: PatternStructuralInfo,
compact_single_symbol_name: Option<String>,
fixed_prefix_suffix: Option<FixedPrefixSuffixInfo>,
}
enum PatternElement<'a> {
Fixed(&'a str, usize),
Variable(&'a str, usize),
}
impl PatternStructuralInfo {
const fn new(
min_match_rows: usize,
max_match_rows: Option<usize>,
has_anchors: bool,
has_exclusions: bool,
anchored_at_end: bool,
) -> Self {
Self {
min_match_rows,
max_match_rows,
has_anchors,
has_exclusions,
anchored_at_end,
}
}
fn analyze(pattern: &Pattern) -> Self {
match pattern {
Pattern::Symbol(symbol) => Self::symbol_info(symbol, false),
Pattern::Exclude(symbol) => Self::symbol_info(symbol, true),
Pattern::Permute(symbols) => Self::for_permute(symbols),
Pattern::Concat(patterns) => {
let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
Self::from_concat_children(&child_info)
}
Pattern::Group(inner) => Self::analyze(inner),
Pattern::Alternation(patterns) => {
let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
Self::from_alternation_children(&child_info)
}
Pattern::Repetition(inner, quantifier) => {
Self::from_repetition_child(Self::analyze(inner), quantifier)
}
}
}
const fn symbol_info(symbol: &Symbol, is_excluded: bool) -> Self {
match symbol {
Symbol::Named(_) => Self::new(1, Some(1), false, is_excluded, false),
Symbol::Start => Self::new(0, Some(0), true, is_excluded, false),
Symbol::End => Self::new(0, Some(0), true, is_excluded, !is_excluded),
}
}
pub fn for_permute(symbols: &[Symbol]) -> Self {
let mut named_count = 0usize;
let mut has_anchors = false;
for symbol in symbols {
match symbol {
Symbol::Named(_) => named_count += 1,
Symbol::Start | Symbol::End => has_anchors = true,
}
}
Self::new(named_count, Some(named_count), has_anchors, false, false)
}
pub fn from_concat_children(child_info: &[Self]) -> Self {
let mut min_match_rows = 0usize;
let mut max_match_rows = Some(0usize);
let mut has_anchors = false;
let mut has_exclusions = false;
let mut anchored_at_end = false;
for info in child_info {
min_match_rows = min_match_rows.saturating_add(info.min_match_rows);
max_match_rows = match (max_match_rows, info.max_match_rows) {
(Some(lhs), Some(rhs)) => lhs.checked_add(rhs),
_ => None,
};
has_anchors |= info.has_anchors;
has_exclusions |= info.has_exclusions;
anchored_at_end = if info.can_match_empty() {
anchored_at_end || info.anchored_at_end
} else {
info.anchored_at_end
};
}
Self::new(
min_match_rows,
max_match_rows,
has_anchors,
has_exclusions,
anchored_at_end,
)
}
pub fn from_alternation_children(child_info: &[Self]) -> Self {
let mut min_match_rows: Option<usize> = None;
let mut max_match_rows = Some(0usize);
let mut has_anchors = false;
let mut has_exclusions = false;
let mut anchored_at_end = !child_info.is_empty();
for info in child_info {
min_match_rows =
Some(min_match_rows.map_or(info.min_match_rows, |current| {
current.min(info.min_match_rows)
}));
max_match_rows = match (max_match_rows, info.max_match_rows) {
(Some(lhs), Some(rhs)) => Some(lhs.max(rhs)),
_ => None,
};
has_anchors |= info.has_anchors;
has_exclusions |= info.has_exclusions;
anchored_at_end &= info.anchored_at_end;
}
Self::new(
min_match_rows.unwrap_or(0),
max_match_rows,
has_anchors,
has_exclusions,
anchored_at_end,
)
}
pub fn from_repetition_child(
inner_info: Self,
quantifier: &RepetitionQuantifier,
) -> Self {
let min_match_rows = inner_info
.min_match_rows
.saturating_mul(quantifier.min_repetitions() as usize);
let max_match_rows =
match (inner_info.max_match_rows, quantifier.max_repetitions()) {
(Some(0), _) | (_, Some(0)) => Some(0),
(Some(inner_max), Some(count)) => inner_max.checked_mul(count as usize),
_ => None,
};
Self::new(
min_match_rows,
max_match_rows,
inner_info.has_anchors,
inner_info.has_exclusions,
quantifier.fixed_count() == Some(1) && inner_info.anchored_at_end,
)
}
pub const fn min_match_rows(self) -> usize {
self.min_match_rows
}
pub const fn max_match_rows(self) -> Option<usize> {
self.max_match_rows
}
pub const fn has_anchors(self) -> bool {
self.has_anchors
}
pub const fn has_exclusions(self) -> bool {
self.has_exclusions
}
pub const fn anchored_at_end(self) -> bool {
self.anchored_at_end
}
pub const fn can_match_empty(self) -> bool {
self.min_match_rows == 0
}
}
impl Pattern {
pub(crate) fn analysis_summary(&self) -> PatternAnalysisSummary {
PatternAnalysisSummary::analyze(self)
}
pub fn structural_info(&self) -> PatternStructuralInfo {
PatternStructuralInfo::analyze(self)
}
fn flatten_to_elements(&self) -> Option<Vec<PatternElement<'_>>> {
let mut elements = Vec::new();
self.append_elements(&mut elements)?;
Some(elements)
}
fn append_elements<'a>(
&'a self,
elements: &mut Vec<PatternElement<'a>>,
) -> Option<()> {
match self {
Pattern::Symbol(Symbol::Named(name)) => {
elements.push(PatternElement::Fixed(name, 1));
}
Pattern::Symbol(Symbol::Start | Symbol::End)
| Pattern::Exclude(_)
| Pattern::Permute(_)
| Pattern::Alternation(_) => return None,
Pattern::Group(inner) => inner.append_elements(elements)?,
Pattern::Concat(patterns) => {
for pattern in patterns {
pattern.append_elements(elements)?;
}
}
Pattern::Repetition(inner, quantifier) => {
let name = inner.get_single_named_symbol()?;
let quantifier = quantifier.normalized();
if quantifier.is_reluctant() && quantifier.fixed_count().is_none() {
return None;
}
let element = if let Some(count) = quantifier.fixed_count() {
PatternElement::Fixed(name, count as usize)
} else if quantifier.max_repetitions().is_none() {
PatternElement::Variable(name, quantifier.min_repetitions() as usize)
} else {
return None;
};
elements.push(element);
}
}
Some(())
}
}
impl PatternAnalysisSummary {
fn analyze(pattern: &Pattern) -> Self {
Self {
structural_info: pattern.structural_info(),
compact_single_symbol_name: pattern.single_symbol_name().map(str::to_string),
fixed_prefix_suffix: pattern
.flatten_to_elements()
.as_deref()
.and_then(fixed_prefix_suffix_from_elements),
}
}
pub const fn structural_info(&self) -> PatternStructuralInfo {
self.structural_info
}
pub fn compact_single_symbol_name(&self) -> Option<&str> {
self.compact_single_symbol_name.as_deref()
}
pub fn fixed_prefix_suffix_structure(&self) -> Option<&FixedPrefixSuffixInfo> {
self.fixed_prefix_suffix.as_ref()
}
}
fn fixed_prefix_suffix_from_elements(
elements: &[PatternElement<'_>],
) -> Option<FixedPrefixSuffixInfo> {
let (variable_idx, middle_name, middle_min_rows) = elements
.iter()
.enumerate()
.find_map(|(index, element)| match *element {
PatternElement::Variable(name, min_rows) => Some((index, name, min_rows)),
PatternElement::Fixed(_, _) => None,
})?;
let fixed_runs = |elements: &[PatternElement<'_>]| {
let mut runs = Vec::new();
let mut rows = 0usize;
for element in elements {
let PatternElement::Fixed(name, count) = *element else {
return None;
};
rows = rows.checked_add(count)?;
runs.push((name.to_string(), count));
}
Some((runs, rows))
};
let (prefix, prefix_rows) = fixed_runs(&elements[..variable_idx])?;
let (suffix, suffix_rows) = fixed_runs(&elements[variable_idx + 1..])?;
Some(FixedPrefixSuffixInfo {
prefix,
middle: middle_name.to_string(),
suffix,
prefix_rows,
suffix_rows,
middle_min_rows,
})
}