use std::fmt::{self, Display, Formatter};
mod analysis;
mod bounds;
mod output;
mod properties;
#[cfg(test)]
pub use analysis::FixedPrefixSuffixInfo;
pub use analysis::{PatternAnalysisSummary, PatternStructuralInfo};
pub use output::{AfterMatchSkip, EmptyMatchesMode, RowsPerMatch};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum Pattern {
Symbol(Symbol),
Exclude(Symbol),
Permute(Vec<Symbol>),
Concat(Vec<Pattern>),
Group(Box<Pattern>),
Alternation(Vec<Pattern>),
Repetition(Box<Pattern>, RepetitionQuantifier),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizedPattern {
Never,
Epsilon,
Ast(Pattern),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum Symbol {
Named(String),
Start,
End,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum RepetitionQuantifier {
ZeroOrMore,
OneOrMore,
AtMostOne,
Exactly(u32),
AtLeast(u32),
AtMost(u32),
Range(u32, u32),
ZeroOrMoreReluctant,
OneOrMoreReluctant,
AtMostOneReluctant,
ExactlyReluctant(u32),
AtLeastReluctant(u32),
AtMostReluctant(u32),
RangeReluctant(u32, u32),
ZeroOrMorePossessive,
OneOrMorePossessive,
AtMostOnePossessive,
ExactlyPossessive(u32),
AtLeastPossessive(u32),
AtMostPossessive(u32),
RangePossessive(u32, u32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RepetitionPreference {
Greedy,
Reluctant,
Possessive,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct QuantifierBounds {
pub min: u32,
pub max: Option<u32>,
pub preference: RepetitionPreference,
}
impl QuantifierBounds {
pub const fn is_possessive(self) -> bool {
matches!(self.preference, RepetitionPreference::Possessive)
}
pub const fn is_reluctant(self) -> bool {
matches!(self.preference, RepetitionPreference::Reluctant)
}
pub const fn fixed_count(self) -> Option<u32> {
match self.max {
Some(max) if max == self.min => Some(self.min),
_ => None,
}
}
}
impl RepetitionQuantifier {
pub(crate) const fn bounds(&self) -> QuantifierBounds {
let (min, max) = match self {
Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
(0, None)
}
Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
(1, None)
}
Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
(0, Some(1))
}
Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
(*n, Some(*n))
}
Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
(*n, None)
}
Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
(0, Some(*n))
}
Self::Range(min, max)
| Self::RangeReluctant(min, max)
| Self::RangePossessive(min, max) => (*min, Some(*max)),
};
let preference = match self {
Self::ZeroOrMoreReluctant
| Self::OneOrMoreReluctant
| Self::AtMostOneReluctant
| Self::ExactlyReluctant(_)
| Self::AtLeastReluctant(_)
| Self::AtMostReluctant(_)
| Self::RangeReluctant(_, _) => RepetitionPreference::Reluctant,
Self::ZeroOrMorePossessive
| Self::OneOrMorePossessive
| Self::AtMostOnePossessive
| Self::ExactlyPossessive(_)
| Self::AtLeastPossessive(_)
| Self::AtMostPossessive(_)
| Self::RangePossessive(_, _) => RepetitionPreference::Possessive,
_ => RepetitionPreference::Greedy,
};
QuantifierBounds {
min,
max,
preference,
}
}
pub const fn is_possessive(&self) -> bool {
self.bounds().is_possessive()
}
pub const fn is_reluctant(&self) -> bool {
self.bounds().is_reluctant()
}
pub const fn fixed_count(&self) -> Option<u32> {
self.bounds().fixed_count()
}
pub const fn min_repetitions(&self) -> u32 {
self.bounds().min
}
pub const fn max_repetitions(&self) -> Option<u32> {
self.bounds().max
}
pub fn normalized(&self) -> Self {
let greedy = match self {
Self::Range(min, max)
| Self::RangeReluctant(min, max)
| Self::RangePossessive(min, max)
if min == max =>
{
Self::Exactly(*min)
}
Self::AtLeast(0) | Self::AtLeastReluctant(0) | Self::AtLeastPossessive(0) => {
Self::ZeroOrMore
}
Self::AtLeast(1) | Self::AtLeastReluctant(1) | Self::AtLeastPossessive(1) => {
Self::OneOrMore
}
Self::AtMost(1)
| Self::Range(0, 1)
| Self::AtMostReluctant(1)
| Self::RangeReluctant(0, 1)
| Self::AtMostPossessive(1)
| Self::RangePossessive(0, 1) => Self::AtMostOne,
_ => return self.clone(),
};
match self.bounds().preference {
RepetitionPreference::Greedy => greedy,
RepetitionPreference::Reluctant => greedy
.reluctant_variant()
.expect("normalized spelling is greedy"),
RepetitionPreference::Possessive => greedy
.possessive_variant()
.expect("normalized spelling is greedy"),
}
}
pub fn reluctant_variant(&self) -> Option<Self> {
match self {
Self::ZeroOrMore => Some(Self::ZeroOrMoreReluctant),
Self::OneOrMore => Some(Self::OneOrMoreReluctant),
Self::AtMostOne => Some(Self::AtMostOneReluctant),
Self::Exactly(n) => Some(Self::ExactlyReluctant(*n)),
Self::AtLeast(n) => Some(Self::AtLeastReluctant(*n)),
Self::AtMost(n) => Some(Self::AtMostReluctant(*n)),
Self::Range(min, max) => Some(Self::RangeReluctant(*min, *max)),
_ => None,
}
}
pub fn possessive_variant(&self) -> Option<Self> {
match self {
Self::ZeroOrMore => Some(Self::ZeroOrMorePossessive),
Self::OneOrMore => Some(Self::OneOrMorePossessive),
Self::AtMostOne => Some(Self::AtMostOnePossessive),
Self::Exactly(n) => Some(Self::ExactlyPossessive(*n)),
Self::AtLeast(n) => Some(Self::AtLeastPossessive(*n)),
Self::AtMost(n) => Some(Self::AtMostPossessive(*n)),
Self::Range(min, max) => Some(Self::RangePossessive(*min, *max)),
_ => None,
}
}
}
impl Display for Symbol {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Symbol::Named(name) => write!(f, "{name}"),
Symbol::Start => write!(f, "^"),
Symbol::End => write!(f, "$"),
}
}
}
impl Display for RepetitionQuantifier {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
write!(f, "*")
}
Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
write!(f, "+")
}
Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
write!(f, "?")
}
Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
write!(f, "{{{n}}}")
}
Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
write!(f, "{{{n},}}")
}
Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
write!(f, "{{,{n}}}")
}
Self::Range(min, max)
| Self::RangeReluctant(min, max)
| Self::RangePossessive(min, max) => write!(f, "{{{min},{max}}}"),
}?;
f.write_str(match self.bounds().preference {
RepetitionPreference::Greedy => "",
RepetitionPreference::Reluctant => "?",
RepetitionPreference::Possessive => "+",
})
}
}
fn fmt_pattern_symbol(symbol: &Symbol, f: &mut Formatter<'_>) -> fmt::Result {
let Symbol::Named(name) = symbol else {
return Display::fmt(symbol, f);
};
let mut bytes = name.bytes();
let bare_name = bytes
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
if bare_name && !name.eq_ignore_ascii_case("PERMUTE") {
f.write_str(name)
} else {
write!(f, "\"{}\"", name.replace('"', "\"\""))
}
}
impl Display for Pattern {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Pattern::Symbol(symbol) => fmt_pattern_symbol(symbol, f),
Pattern::Exclude(symbol) => {
f.write_str("{- ")?;
fmt_pattern_symbol(symbol, f)?;
f.write_str(" -}")
}
Pattern::Permute(symbols) => {
f.write_str("PERMUTE(")?;
for (index, symbol) in symbols.iter().enumerate() {
if index > 0 {
f.write_str(",")?;
}
fmt_pattern_symbol(symbol, f)?;
}
f.write_str(")")
}
Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
let is_concat = matches!(self, Pattern::Concat(_));
let separator = if is_concat { " " } else { "|" };
for (index, pattern) in patterns.iter().enumerate() {
if index > 0 {
f.write_str(separator)?;
}
let grouped = is_concat
&& match pattern {
Pattern::Alternation(_) | Pattern::Exclude(_) => true,
Pattern::Repetition(inner, _) => {
matches!(inner.as_ref(), Pattern::Exclude(_))
}
_ => false,
};
if grouped {
write!(f, "({pattern})")?;
} else {
write!(f, "{pattern}")?;
}
}
Ok(())
}
Pattern::Group(pattern) => write!(f, "({pattern})"),
Pattern::Repetition(pattern, quantifier) => {
if matches!(
pattern.as_ref(),
Pattern::Repetition(..)
| Pattern::Concat(_)
| Pattern::Alternation(_)
) {
write!(f, "({pattern}){quantifier}")
} else {
write!(f, "{pattern}{quantifier}")
}
}
}
}
}
#[cfg(test)]
mod tests;