1use std::fmt::{self, Display, Formatter};
20
21mod analysis;
22mod bounds;
23mod output;
24mod properties;
25
26#[cfg(test)]
27pub use analysis::FixedPrefixSuffixInfo;
28pub use analysis::{PatternAnalysisSummary, PatternStructuralInfo};
29pub use output::{AfterMatchSkip, EmptyMatchesMode, RowsPerMatch};
30
31#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
33pub enum Pattern {
34 Symbol(Symbol),
36 Exclude(Symbol),
38 Permute(Vec<Symbol>),
40 Concat(Vec<Pattern>),
42 Group(Box<Pattern>),
44 Alternation(Vec<Pattern>),
46 Repetition(Box<Pattern>, RepetitionQuantifier),
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum NormalizedPattern {
56 Never,
58 Epsilon,
60 Ast(Pattern),
62}
63
64#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
66pub enum Symbol {
67 Named(String),
69 Start,
71 End,
73}
74
75#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
83pub enum RepetitionQuantifier {
84 ZeroOrMore,
86 OneOrMore,
88 AtMostOne,
90 Exactly(u32),
92 AtLeast(u32),
94 AtMost(u32),
96 Range(u32, u32),
98 ZeroOrMoreReluctant,
100 OneOrMoreReluctant,
102 AtMostOneReluctant,
104 ExactlyReluctant(u32),
106 AtLeastReluctant(u32),
108 AtMostReluctant(u32),
110 RangeReluctant(u32, u32),
112 ZeroOrMorePossessive,
114 OneOrMorePossessive,
116 AtMostOnePossessive,
118 ExactlyPossessive(u32),
124 AtLeastPossessive(u32),
126 AtMostPossessive(u32),
128 RangePossessive(u32, u32),
130}
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub enum RepetitionPreference {
135 Greedy,
137 Reluctant,
139 Possessive,
141}
142
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
145pub struct QuantifierBounds {
146 pub min: u32,
148 pub max: Option<u32>,
150 pub preference: RepetitionPreference,
152}
153
154impl QuantifierBounds {
155 pub const fn is_possessive(self) -> bool {
157 matches!(self.preference, RepetitionPreference::Possessive)
158 }
159
160 pub const fn is_reluctant(self) -> bool {
162 matches!(self.preference, RepetitionPreference::Reluctant)
163 }
164
165 pub const fn fixed_count(self) -> Option<u32> {
167 match self.max {
168 Some(max) if max == self.min => Some(self.min),
169 _ => None,
170 }
171 }
172}
173
174impl RepetitionQuantifier {
175 pub(crate) const fn bounds(&self) -> QuantifierBounds {
177 let (min, max) = match self {
178 Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
179 (0, None)
180 }
181 Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
182 (1, None)
183 }
184 Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
185 (0, Some(1))
186 }
187 Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
188 (*n, Some(*n))
189 }
190 Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
191 (*n, None)
192 }
193 Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
194 (0, Some(*n))
195 }
196 Self::Range(min, max)
197 | Self::RangeReluctant(min, max)
198 | Self::RangePossessive(min, max) => (*min, Some(*max)),
199 };
200 let preference = match self {
201 Self::ZeroOrMoreReluctant
202 | Self::OneOrMoreReluctant
203 | Self::AtMostOneReluctant
204 | Self::ExactlyReluctant(_)
205 | Self::AtLeastReluctant(_)
206 | Self::AtMostReluctant(_)
207 | Self::RangeReluctant(_, _) => RepetitionPreference::Reluctant,
208 Self::ZeroOrMorePossessive
209 | Self::OneOrMorePossessive
210 | Self::AtMostOnePossessive
211 | Self::ExactlyPossessive(_)
212 | Self::AtLeastPossessive(_)
213 | Self::AtMostPossessive(_)
214 | Self::RangePossessive(_, _) => RepetitionPreference::Possessive,
215 _ => RepetitionPreference::Greedy,
216 };
217 QuantifierBounds {
218 min,
219 max,
220 preference,
221 }
222 }
223
224 pub const fn is_possessive(&self) -> bool {
226 self.bounds().is_possessive()
227 }
228
229 pub const fn is_reluctant(&self) -> bool {
231 self.bounds().is_reluctant()
232 }
233
234 pub const fn fixed_count(&self) -> Option<u32> {
236 self.bounds().fixed_count()
237 }
238
239 pub const fn min_repetitions(&self) -> u32 {
241 self.bounds().min
242 }
243
244 pub const fn max_repetitions(&self) -> Option<u32> {
246 self.bounds().max
247 }
248
249 pub fn normalized(&self) -> Self {
252 let greedy = match self {
253 Self::Range(min, max)
254 | Self::RangeReluctant(min, max)
255 | Self::RangePossessive(min, max)
256 if min == max =>
257 {
258 Self::Exactly(*min)
259 }
260 Self::AtLeast(0) | Self::AtLeastReluctant(0) | Self::AtLeastPossessive(0) => {
261 Self::ZeroOrMore
262 }
263 Self::AtLeast(1) | Self::AtLeastReluctant(1) | Self::AtLeastPossessive(1) => {
264 Self::OneOrMore
265 }
266 Self::AtMost(1)
267 | Self::Range(0, 1)
268 | Self::AtMostReluctant(1)
269 | Self::RangeReluctant(0, 1)
270 | Self::AtMostPossessive(1)
271 | Self::RangePossessive(0, 1) => Self::AtMostOne,
272 _ => return self.clone(),
273 };
274 match self.bounds().preference {
275 RepetitionPreference::Greedy => greedy,
276 RepetitionPreference::Reluctant => greedy
277 .reluctant_variant()
278 .expect("normalized spelling is greedy"),
279 RepetitionPreference::Possessive => greedy
280 .possessive_variant()
281 .expect("normalized spelling is greedy"),
282 }
283 }
284
285 pub fn reluctant_variant(&self) -> Option<Self> {
287 match self {
288 Self::ZeroOrMore => Some(Self::ZeroOrMoreReluctant),
289 Self::OneOrMore => Some(Self::OneOrMoreReluctant),
290 Self::AtMostOne => Some(Self::AtMostOneReluctant),
291 Self::Exactly(n) => Some(Self::ExactlyReluctant(*n)),
292 Self::AtLeast(n) => Some(Self::AtLeastReluctant(*n)),
293 Self::AtMost(n) => Some(Self::AtMostReluctant(*n)),
294 Self::Range(min, max) => Some(Self::RangeReluctant(*min, *max)),
295 _ => None,
296 }
297 }
298
299 pub fn possessive_variant(&self) -> Option<Self> {
302 match self {
303 Self::ZeroOrMore => Some(Self::ZeroOrMorePossessive),
304 Self::OneOrMore => Some(Self::OneOrMorePossessive),
305 Self::AtMostOne => Some(Self::AtMostOnePossessive),
306 Self::Exactly(n) => Some(Self::ExactlyPossessive(*n)),
307 Self::AtLeast(n) => Some(Self::AtLeastPossessive(*n)),
308 Self::AtMost(n) => Some(Self::AtMostPossessive(*n)),
309 Self::Range(min, max) => Some(Self::RangePossessive(*min, *max)),
310 _ => None,
311 }
312 }
313}
314
315impl Display for Symbol {
318 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
319 match self {
320 Symbol::Named(name) => write!(f, "{name}"),
321 Symbol::Start => write!(f, "^"),
322 Symbol::End => write!(f, "$"),
323 }
324 }
325}
326
327impl Display for RepetitionQuantifier {
328 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
329 match self {
330 Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
331 write!(f, "*")
332 }
333 Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
334 write!(f, "+")
335 }
336 Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
337 write!(f, "?")
338 }
339 Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
340 write!(f, "{{{n}}}")
341 }
342 Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
343 write!(f, "{{{n},}}")
344 }
345 Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
346 write!(f, "{{,{n}}}")
347 }
348 Self::Range(min, max)
349 | Self::RangeReluctant(min, max)
350 | Self::RangePossessive(min, max) => write!(f, "{{{min},{max}}}"),
351 }?;
352 f.write_str(match self.bounds().preference {
353 RepetitionPreference::Greedy => "",
354 RepetitionPreference::Reluctant => "?",
355 RepetitionPreference::Possessive => "+",
356 })
357 }
358}
359
360fn fmt_pattern_symbol(symbol: &Symbol, f: &mut Formatter<'_>) -> fmt::Result {
363 let Symbol::Named(name) = symbol else {
364 return Display::fmt(symbol, f);
365 };
366 let mut bytes = name.bytes();
367 let bare_name = bytes
368 .next()
369 .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
370 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
371 if bare_name && !name.eq_ignore_ascii_case("PERMUTE") {
372 f.write_str(name)
373 } else {
374 write!(f, "\"{}\"", name.replace('"', "\"\""))
375 }
376}
377
378impl Display for Pattern {
379 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
380 match self {
381 Pattern::Symbol(symbol) => fmt_pattern_symbol(symbol, f),
382 Pattern::Exclude(symbol) => {
383 f.write_str("{- ")?;
384 fmt_pattern_symbol(symbol, f)?;
385 f.write_str(" -}")
386 }
387 Pattern::Permute(symbols) => {
388 f.write_str("PERMUTE(")?;
389 for (index, symbol) in symbols.iter().enumerate() {
390 if index > 0 {
391 f.write_str(",")?;
392 }
393 fmt_pattern_symbol(symbol, f)?;
394 }
395 f.write_str(")")
396 }
397 Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
398 let is_concat = matches!(self, Pattern::Concat(_));
399 let separator = if is_concat { " " } else { "|" };
400 for (index, pattern) in patterns.iter().enumerate() {
401 if index > 0 {
402 f.write_str(separator)?;
403 }
404 let grouped = is_concat
409 && match pattern {
410 Pattern::Alternation(_) | Pattern::Exclude(_) => true,
411 Pattern::Repetition(inner, _) => {
412 matches!(inner.as_ref(), Pattern::Exclude(_))
413 }
414 _ => false,
415 };
416 if grouped {
417 write!(f, "({pattern})")?;
418 } else {
419 write!(f, "{pattern}")?;
420 }
421 }
422 Ok(())
423 }
424 Pattern::Group(pattern) => write!(f, "({pattern})"),
425 Pattern::Repetition(pattern, quantifier) => {
426 if matches!(
427 pattern.as_ref(),
428 Pattern::Repetition(..)
429 | Pattern::Concat(_)
430 | Pattern::Alternation(_)
431 ) {
432 write!(f, "({pattern}){quantifier}")
433 } else {
434 write!(f, "{pattern}{quantifier}")
435 }
436 }
437 }
438 }
439}
440
441#[cfg(test)]
442mod tests;