datafusion_match_recognize/core/pattern/
analysis.rs1use super::{Pattern, RepetitionQuantifier, Symbol};
20
21#[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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41pub struct FixedPrefixSuffixInfo {
42 pub prefix: Vec<(String, usize)>,
44 pub middle: String,
46 pub suffix: Vec<(String, usize)>,
48 pub prefix_rows: usize,
50 pub suffix_rows: usize,
52 pub middle_min_rows: usize,
54}
55
56#[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 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 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 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 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 pub const fn min_match_rows(self) -> usize {
216 self.min_match_rows
217 }
218
219 pub const fn max_match_rows(self) -> Option<usize> {
221 self.max_match_rows
222 }
223
224 pub const fn has_anchors(self) -> bool {
226 self.has_anchors
227 }
228
229 pub const fn has_exclusions(self) -> bool {
231 self.has_exclusions
232 }
233
234 pub const fn anchored_at_end(self) -> bool {
236 self.anchored_at_end
237 }
238
239 pub const fn can_match_empty(self) -> bool {
241 self.min_match_rows == 0
242 }
243}
244
245impl Pattern {
246 pub(crate) fn analysis_summary(&self) -> PatternAnalysisSummary {
251 PatternAnalysisSummary::analyze(self)
252 }
253
254 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 pub const fn structural_info(&self) -> PatternStructuralInfo {
321 self.structural_info
322 }
323
324 pub fn compact_single_symbol_name(&self) -> Option<&str> {
327 self.compact_single_symbol_name.as_deref()
328 }
329
330 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}