use std::collections::BTreeSet;
use super::{Pattern, Symbol};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SingleNamedSymbolMode {
Exact,
CompactPath,
FixedWidth,
}
impl Pattern {
pub fn has_reluctant_choice(&self) -> bool {
match self {
Self::Repetition(inner, quantifier) => {
(quantifier.is_reluctant() && quantifier.fixed_count().is_none())
|| inner.has_reluctant_choice()
}
Self::Concat(parts) | Self::Alternation(parts) => {
parts.iter().any(Self::has_reluctant_choice)
}
Self::Group(inner) => inner.has_reluctant_choice(),
Self::Symbol(_) | Self::Exclude(_) | Self::Permute(_) => false,
}
}
pub fn symbol_names(&self) -> BTreeSet<String> {
fn collect(pattern: &Pattern, output: &mut BTreeSet<String>) {
match pattern {
Pattern::Symbol(Symbol::Named(name))
| Pattern::Exclude(Symbol::Named(name)) => {
output.insert(name.clone());
}
Pattern::Permute(permuted) => {
for symbol in permuted {
if let Symbol::Named(name) = symbol {
output.insert(name.clone());
}
}
}
Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
for pattern in patterns {
collect(pattern, output);
}
}
Pattern::Group(pattern) | Pattern::Repetition(pattern, _) => {
collect(pattern, output);
}
Pattern::Symbol(Symbol::Start | Symbol::End)
| Pattern::Exclude(Symbol::Start | Symbol::End) => {}
}
}
let mut symbols = BTreeSet::new();
collect(self, &mut symbols);
symbols
}
pub fn has_anchors(&self) -> bool {
self.structural_info().has_anchors()
}
pub fn has_end_anchor(&self) -> bool {
match self {
Self::Symbol(Symbol::End) | Self::Exclude(Symbol::End) => true,
Self::Symbol(_) | Self::Exclude(_) => false,
Self::Permute(symbols) => symbols.contains(&Symbol::End),
Self::Concat(patterns) | Self::Alternation(patterns) => {
patterns.iter().any(Self::has_end_anchor)
}
Self::Group(inner) | Self::Repetition(inner, _) => inner.has_end_anchor(),
}
}
pub fn has_exclusions(&self) -> bool {
self.structural_info().has_exclusions()
}
pub fn single_symbol_name(&self) -> Option<&str> {
self.single_named_symbol_name(SingleNamedSymbolMode::CompactPath)
}
fn single_named_symbol_name(&self, mode: SingleNamedSymbolMode) -> Option<&str> {
match self {
Pattern::Symbol(Symbol::Named(name)) => {
(mode != SingleNamedSymbolMode::CompactPath).then_some(name)
}
Pattern::Repetition(inner, quantifier) => {
let fixed_count = quantifier.fixed_count().is_some();
let eligible = match mode {
SingleNamedSymbolMode::Exact => false,
SingleNamedSymbolMode::CompactPath => {
fixed_count || !quantifier.is_reluctant()
}
SingleNamedSymbolMode::FixedWidth => fixed_count,
};
if eligible {
inner.single_named_symbol_name(SingleNamedSymbolMode::FixedWidth)
} else {
None
}
}
Pattern::Group(inner) => inner.single_named_symbol_name(mode),
_ => None,
}
}
pub(crate) fn get_single_named_symbol(&self) -> Option<&str> {
self.single_named_symbol_name(SingleNamedSymbolMode::Exact)
}
}