Skip to main content

datafusion_match_recognize/core/pattern/
analysis.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//! Calculates row-count bounds, anchor and exclusion flags, and compact-path
17//! information from a pattern.
18
19use super::{Pattern, RepetitionQuantifier, Symbol};
20
21/// Row bounds and flags derived from one recursive walk over a pattern AST.
22///
23/// This bundles the planner-side properties that are otherwise frequently
24/// recomputed independently by row-bounds, anchor checks, exclusion checks,
25/// and downstream compilation metadata extraction.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct PatternStructuralInfo {
28    min_match_rows: usize,
29    max_match_rows: Option<usize>,
30    has_anchors: bool,
31    has_exclusions: bool,
32    anchored_at_end: bool,
33}
34
35/// Information about a pattern with fixed prefix/suffix and a variable middle.
36///
37/// This enables compact path reconstruction from `(start_row, end_row)` when a
38/// pattern has one unbounded middle symbol surrounded by fixed-width prefix and
39/// suffix segments.
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41pub struct FixedPrefixSuffixInfo {
42    /// Fixed named-symbol runs before the variable middle, in pattern order.
43    pub prefix: Vec<(String, usize)>,
44    /// Name of the single unbounded middle symbol.
45    pub middle: String,
46    /// Fixed named-symbol runs after the variable middle, in pattern order.
47    pub suffix: Vec<(String, usize)>,
48    /// Total rows consumed by `prefix`.
49    pub prefix_rows: usize,
50    /// Total rows consumed by `suffix`.
51    pub suffix_rows: usize,
52    /// Minimum rows consumed by the variable middle.
53    pub middle_min_rows: usize,
54}
55
56/// Combined result of the structural and compact-path analyses.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct PatternAnalysisSummary {
59    structural_info: PatternStructuralInfo,
60    compact_single_symbol_name: Option<String>,
61    fixed_prefix_suffix: Option<FixedPrefixSuffixInfo>,
62}
63
64enum PatternElement<'a> {
65    Fixed(&'a str, usize),
66    Variable(&'a str, usize),
67}
68
69impl PatternStructuralInfo {
70    const fn new(
71        min_match_rows: usize,
72        max_match_rows: Option<usize>,
73        has_anchors: bool,
74        has_exclusions: bool,
75        anchored_at_end: bool,
76    ) -> Self {
77        Self {
78            min_match_rows,
79            max_match_rows,
80            has_anchors,
81            has_exclusions,
82            anchored_at_end,
83        }
84    }
85
86    fn analyze(pattern: &Pattern) -> Self {
87        match pattern {
88            Pattern::Symbol(symbol) => Self::symbol_info(symbol, false),
89            Pattern::Exclude(symbol) => Self::symbol_info(symbol, true),
90            Pattern::Permute(symbols) => Self::for_permute(symbols),
91            Pattern::Concat(patterns) => {
92                let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
93                Self::from_concat_children(&child_info)
94            }
95            Pattern::Group(inner) => Self::analyze(inner),
96            Pattern::Alternation(patterns) => {
97                let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
98                Self::from_alternation_children(&child_info)
99            }
100            Pattern::Repetition(inner, quantifier) => {
101                Self::from_repetition_child(Self::analyze(inner), quantifier)
102            }
103        }
104    }
105
106    const fn symbol_info(symbol: &Symbol, is_excluded: bool) -> Self {
107        match symbol {
108            Symbol::Named(_) => Self::new(1, Some(1), false, is_excluded, false),
109            Symbol::Start => Self::new(0, Some(0), true, is_excluded, false),
110            Symbol::End => Self::new(0, Some(0), true, is_excluded, !is_excluded),
111        }
112    }
113
114    /// Structural facts for a `PERMUTE(...)` sequence.
115    pub fn for_permute(symbols: &[Symbol]) -> Self {
116        let mut named_count = 0usize;
117        let mut has_anchors = false;
118        for symbol in symbols {
119            match symbol {
120                Symbol::Named(_) => named_count += 1,
121                Symbol::Start | Symbol::End => has_anchors = true,
122            }
123        }
124        Self::new(named_count, Some(named_count), has_anchors, false, false)
125    }
126
127    /// Structural facts for a concatenation computed from child summaries.
128    pub fn from_concat_children(child_info: &[Self]) -> Self {
129        let mut min_match_rows = 0usize;
130        let mut max_match_rows = Some(0usize);
131        let mut has_anchors = false;
132        let mut has_exclusions = false;
133        let mut anchored_at_end = false;
134
135        for info in child_info {
136            min_match_rows = min_match_rows.saturating_add(info.min_match_rows);
137            max_match_rows = match (max_match_rows, info.max_match_rows) {
138                (Some(lhs), Some(rhs)) => lhs.checked_add(rhs),
139                _ => None,
140            };
141            has_anchors |= info.has_anchors;
142            has_exclusions |= info.has_exclusions;
143            anchored_at_end = if info.can_match_empty() {
144                anchored_at_end || info.anchored_at_end
145            } else {
146                info.anchored_at_end
147            };
148        }
149
150        Self::new(
151            min_match_rows,
152            max_match_rows,
153            has_anchors,
154            has_exclusions,
155            anchored_at_end,
156        )
157    }
158
159    /// Structural facts for an alternation computed from child summaries.
160    pub fn from_alternation_children(child_info: &[Self]) -> Self {
161        let mut min_match_rows: Option<usize> = None;
162        let mut max_match_rows = Some(0usize);
163        let mut has_anchors = false;
164        let mut has_exclusions = false;
165        let mut anchored_at_end = !child_info.is_empty();
166
167        for info in child_info {
168            min_match_rows =
169                Some(min_match_rows.map_or(info.min_match_rows, |current| {
170                    current.min(info.min_match_rows)
171                }));
172            max_match_rows = match (max_match_rows, info.max_match_rows) {
173                (Some(lhs), Some(rhs)) => Some(lhs.max(rhs)),
174                _ => None,
175            };
176            has_anchors |= info.has_anchors;
177            has_exclusions |= info.has_exclusions;
178            anchored_at_end &= info.anchored_at_end;
179        }
180
181        Self::new(
182            min_match_rows.unwrap_or(0),
183            max_match_rows,
184            has_anchors,
185            has_exclusions,
186            anchored_at_end,
187        )
188    }
189
190    /// Structural facts for a repetition computed from the inner child summary.
191    pub fn from_repetition_child(
192        inner_info: Self,
193        quantifier: &RepetitionQuantifier,
194    ) -> Self {
195        let min_match_rows = inner_info
196            .min_match_rows
197            .saturating_mul(quantifier.min_repetitions() as usize);
198        let max_match_rows =
199            match (inner_info.max_match_rows, quantifier.max_repetitions()) {
200                (Some(0), _) | (_, Some(0)) => Some(0),
201                (Some(inner_max), Some(count)) => inner_max.checked_mul(count as usize),
202                _ => None,
203            };
204
205        Self::new(
206            min_match_rows,
207            max_match_rows,
208            inner_info.has_anchors,
209            inner_info.has_exclusions,
210            quantifier.fixed_count() == Some(1) && inner_info.anchored_at_end,
211        )
212    }
213
214    /// Return the structural minimum, saturating at `usize::MAX` on overflow.
215    pub const fn min_match_rows(self) -> usize {
216        self.min_match_rows
217    }
218
219    /// Return a structural upper bound, or `None` if unbounded or larger than `usize`.
220    pub const fn max_match_rows(self) -> Option<usize> {
221        self.max_match_rows
222    }
223
224    /// Returns `true` when the pattern contains any anchors.
225    pub const fn has_anchors(self) -> bool {
226        self.has_anchors
227    }
228
229    /// Returns `true` when the pattern contains any exclusions.
230    pub const fn has_exclusions(self) -> bool {
231        self.has_exclusions
232    }
233
234    /// Returns `true` when the pattern is structurally anchored at the end.
235    pub const fn anchored_at_end(self) -> bool {
236        self.anchored_at_end
237    }
238
239    /// Returns `true` when the pattern can match without consuming any rows.
240    pub const fn can_match_empty(self) -> bool {
241        self.min_match_rows == 0
242    }
243}
244
245impl Pattern {
246    /// Returns the shared pattern-analysis summary for this pattern.
247    ///
248    /// Use this when a caller needs an owned bundle of structural and
249    /// compact-path facts from the same AST.
250    pub(crate) fn analysis_summary(&self) -> PatternAnalysisSummary {
251        PatternAnalysisSummary::analyze(self)
252    }
253
254    /// Returns shared structural facts for this pattern.
255    ///
256    /// This calculates the pattern properties commonly needed by planning,
257    /// optimization, and compilation in one traversal.
258    pub fn structural_info(&self) -> PatternStructuralInfo {
259        PatternStructuralInfo::analyze(self)
260    }
261
262    fn flatten_to_elements(&self) -> Option<Vec<PatternElement<'_>>> {
263        let mut elements = Vec::new();
264        self.append_elements(&mut elements)?;
265        Some(elements)
266    }
267
268    fn append_elements<'a>(
269        &'a self,
270        elements: &mut Vec<PatternElement<'a>>,
271    ) -> Option<()> {
272        match self {
273            Pattern::Symbol(Symbol::Named(name)) => {
274                elements.push(PatternElement::Fixed(name, 1));
275            }
276            Pattern::Symbol(Symbol::Start | Symbol::End)
277            | Pattern::Exclude(_)
278            | Pattern::Permute(_)
279            | Pattern::Alternation(_) => return None,
280            Pattern::Group(inner) => inner.append_elements(elements)?,
281            Pattern::Concat(patterns) => {
282                for pattern in patterns {
283                    pattern.append_elements(elements)?;
284                }
285            }
286            Pattern::Repetition(inner, quantifier) => {
287                let name = inner.get_single_named_symbol()?;
288                let quantifier = quantifier.normalized();
289
290                if quantifier.is_reluctant() && quantifier.fixed_count().is_none() {
291                    return None;
292                }
293                let element = if let Some(count) = quantifier.fixed_count() {
294                    PatternElement::Fixed(name, count as usize)
295                } else if quantifier.max_repetitions().is_none() {
296                    PatternElement::Variable(name, quantifier.min_repetitions() as usize)
297                } else {
298                    return None;
299                };
300                elements.push(element);
301            }
302        }
303        Some(())
304    }
305}
306
307impl PatternAnalysisSummary {
308    fn analyze(pattern: &Pattern) -> Self {
309        Self {
310            structural_info: pattern.structural_info(),
311            compact_single_symbol_name: pattern.single_symbol_name().map(str::to_string),
312            fixed_prefix_suffix: pattern
313                .flatten_to_elements()
314                .as_deref()
315                .and_then(fixed_prefix_suffix_from_elements),
316        }
317    }
318
319    /// Return the pattern's row limits and structural flags.
320    pub const fn structural_info(&self) -> PatternStructuralInfo {
321        self.structural_info
322    }
323
324    /// Returns the compact-path single-symbol name, if the pattern can be
325    /// reduced to a single named symbol with repetition.
326    pub fn compact_single_symbol_name(&self) -> Option<&str> {
327        self.compact_single_symbol_name.as_deref()
328    }
329
330    /// Returns the fixed prefix/suffix structure, if present.
331    pub fn fixed_prefix_suffix_structure(&self) -> Option<&FixedPrefixSuffixInfo> {
332        self.fixed_prefix_suffix.as_ref()
333    }
334}
335
336fn fixed_prefix_suffix_from_elements(
337    elements: &[PatternElement<'_>],
338) -> Option<FixedPrefixSuffixInfo> {
339    let (variable_idx, middle_name, middle_min_rows) = elements
340        .iter()
341        .enumerate()
342        .find_map(|(index, element)| match *element {
343            PatternElement::Variable(name, min_rows) => Some((index, name, min_rows)),
344            PatternElement::Fixed(_, _) => None,
345        })?;
346
347    let fixed_runs = |elements: &[PatternElement<'_>]| {
348        let mut runs = Vec::new();
349        let mut rows = 0usize;
350        for element in elements {
351            let PatternElement::Fixed(name, count) = *element else {
352                return None;
353            };
354            rows = rows.checked_add(count)?;
355            runs.push((name.to_string(), count));
356        }
357        Some((runs, rows))
358    };
359    let (prefix, prefix_rows) = fixed_runs(&elements[..variable_idx])?;
360    let (suffix, suffix_rows) = fixed_runs(&elements[variable_idx + 1..])?;
361
362    Some(FixedPrefixSuffixInfo {
363        prefix,
364        middle: middle_name.to_string(),
365        suffix,
366        prefix_rows,
367        suffix_rows,
368        middle_min_rows,
369    })
370}