Skip to main content

datafusion_match_recognize/core/pattern/
mod.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16//! Parser-independent row-pattern syntax, output policy, and derived
17//! structural facts shared by planning and NFA compilation.
18
19use 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/// A pattern for matching in MATCH_RECOGNIZE.
32#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
33pub enum Pattern {
34    /// A single symbol
35    Symbol(Symbol),
36    /// An excluded symbol
37    Exclude(Symbol),
38    /// A permutation of symbols
39    Permute(Vec<Symbol>),
40    /// A concatenation of patterns
41    Concat(Vec<Pattern>),
42    /// A grouped pattern
43    Group(Box<Pattern>),
44    /// An alternation of patterns
45    Alternation(Vec<Pattern>),
46    /// A pattern with repetition
47    Repetition(Box<Pattern>, RepetitionQuantifier),
48}
49
50/// Result of simplifying a pattern before NFA compilation.
51///
52/// Separate variants represent impossible and empty matches, so callers do not
53/// need to encode either case as a synthetic pattern node.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum NormalizedPattern {
56    /// Pattern can never match.
57    Never,
58    /// Pattern matches the empty string.
59    Epsilon,
60    /// Pattern still needs standard matching/compilation.
61    Ast(Pattern),
62}
63
64/// A symbol in a MATCH_RECOGNIZE pattern.
65#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
66pub enum Symbol {
67    /// A named symbol
68    Named(String),
69    /// Start of partition symbol
70    Start,
71    /// End of partition symbol
72    End,
73}
74
75/// Quantifier for pattern repetition.
76///
77/// Source planning and public logical-node construction accept greedy and
78/// reluctant forms. Possessive variants are internal optimizer markers whose
79/// row-local exit suppression requires a proof that it preserves match results.
80/// They do not define general atomic repetition for arbitrary pattern bodies,
81/// and programmatic or Substrait source requests cannot supply them.
82#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
83pub enum RepetitionQuantifier {
84    /// Zero or more (*)
85    ZeroOrMore,
86    /// One or more (+)
87    OneOrMore,
88    /// At most one (?)
89    AtMostOne,
90    /// Exactly n occurrences
91    Exactly(u32),
92    /// At least n occurrences
93    AtLeast(u32),
94    /// At most n occurrences
95    AtMost(u32),
96    /// Between n and m occurrences
97    Range(u32, u32),
98    /// Zero or more, preferring fewer occurrences (*?).
99    ZeroOrMoreReluctant,
100    /// One or more, preferring fewer occurrences (+?).
101    OneOrMoreReluctant,
102    /// At most one, preferring zero occurrences (??).
103    AtMostOneReluctant,
104    /// Exactly n occurrences ({n}?). There is no repetition choice.
105    ExactlyReluctant(u32),
106    /// At least n occurrences, preferring fewer occurrences ({n,}?).
107    AtLeastReluctant(u32),
108    /// At most n occurrences, preferring fewer occurrences ({,n}?).
109    AtMostReluctant(u32),
110    /// Between n and m occurrences, preferring fewer occurrences ({n,m}?).
111    RangeReluctant(u32, u32),
112    /// Internal possessive marker for zero or more (*+).
113    ZeroOrMorePossessive,
114    /// Internal possessive marker for one or more (++).
115    OneOrMorePossessive,
116    /// Internal possessive marker for at most one (?+).
117    AtMostOnePossessive,
118    /// Internal possessive marker for exactly n occurrences ({n}+).
119    ///
120    /// Semantically equivalent to `Exactly(n)` because a fixed-count repetition
121    /// offers no backtracking choice (it either matches n times or fails).
122    /// Included to preserve the optimizer's intent and for consistency in AST transformations.
123    ExactlyPossessive(u32),
124    /// Internal possessive marker for at least n occurrences ({n,}+).
125    AtLeastPossessive(u32),
126    /// Internal possessive marker for at most n occurrences ({,m}+).
127    AtMostPossessive(u32),
128    /// Internal possessive marker for between n and m occurrences ({n,m}+).
129    RangePossessive(u32, u32),
130}
131
132/// Preference at a repetition's continuation/exit choice.
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub enum RepetitionPreference {
135    /// Prefer another occurrence before trying the following pattern.
136    Greedy,
137    /// Prefer the following pattern before trying another occurrence.
138    Reluctant,
139    /// Optimizer-proven row-local continuation/exit suppression.
140    Possessive,
141}
142
143/// Shared repetition bounds and preference used by planning and compilation.
144#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
145pub struct QuantifierBounds {
146    /// Minimum number of repetitions required.
147    pub min: u32,
148    /// Maximum number of repetitions allowed. `None` means unbounded.
149    pub max: Option<u32>,
150    /// How to choose between continuing and exiting the repetition.
151    pub preference: RepetitionPreference,
152}
153
154impl QuantifierBounds {
155    /// Returns `true` when the quantifier suppresses backtracking.
156    pub const fn is_possessive(self) -> bool {
157        matches!(self.preference, RepetitionPreference::Possessive)
158    }
159
160    /// Returns `true` when the quantifier prefers fewer repetitions.
161    pub const fn is_reluctant(self) -> bool {
162        matches!(self.preference, RepetitionPreference::Reluctant)
163    }
164
165    /// Returns the exact repetition count when the quantifier is fixed.
166    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    /// Return this quantifier's bounds and repetition preference.
176    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    /// Returns `true` when the quantifier is possessive.
225    pub const fn is_possessive(&self) -> bool {
226        self.bounds().is_possessive()
227    }
228
229    /// Returns `true` when the quantifier prefers fewer repetitions.
230    pub const fn is_reluctant(&self) -> bool {
231        self.bounds().is_reluctant()
232    }
233
234    /// Returns the exact repetition count when the quantifier is fixed.
235    pub const fn fixed_count(&self) -> Option<u32> {
236        self.bounds().fixed_count()
237    }
238
239    /// Returns the minimum number of repetitions required.
240    pub const fn min_repetitions(&self) -> u32 {
241        self.bounds().min
242    }
243
244    /// Returns the maximum number of repetitions allowed, if bounded.
245    pub const fn max_repetitions(&self) -> Option<u32> {
246        self.bounds().max
247    }
248
249    /// Return an equivalent standard spelling, such as `?` for `{0,1}`, while
250    /// preserving repetition preference.
251    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    /// Returns the reluctant counterpart when this quantifier is greedy.
286    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    /// Return the internal possessive marker when this quantifier is greedy.
300    /// The optimizer must establish that its exit suppression preserves results.
301    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
315// Display implementations
316
317impl 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
360// Pattern tokens need delimiters around identifiers that could change the
361// displayed syntax. Symbol itself still displays the stored name.
362fn 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                    // Normalization need not retain explicit Group nodes.
405                    // Alternation binds less tightly than concatenation; an
406                    // excluded atom also needs parentheses here so SQL parsers
407                    // do not read its opening brace as the previous atom's bound.
408                    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;