Skip to main content

datafusion_match_recognize/core/pattern/
properties.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//! Pattern queries for symbols, anchors, exclusions, and compact paths.
17
18use std::collections::BTreeSet;
19
20use super::{Pattern, Symbol};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum SingleNamedSymbolMode {
24    Exact,
25    CompactPath,
26    FixedWidth,
27}
28
29impl Pattern {
30    /// Returns `true` when a repetition can choose to exit before continuing.
31    /// Fixed-count reluctant spellings have no such choice.
32    pub fn has_reluctant_choice(&self) -> bool {
33        match self {
34            Self::Repetition(inner, quantifier) => {
35                (quantifier.is_reluctant() && quantifier.fixed_count().is_none())
36                    || inner.has_reluctant_choice()
37            }
38            Self::Concat(parts) | Self::Alternation(parts) => {
39                parts.iter().any(Self::has_reluctant_choice)
40            }
41            Self::Group(inner) => inner.has_reluctant_choice(),
42            Self::Symbol(_) | Self::Exclude(_) | Self::Permute(_) => false,
43        }
44    }
45
46    /// Return sorted, distinct named symbols with their exact spelling.
47    ///
48    /// Includes excluded and permuted symbols; anchors are omitted.
49    pub fn symbol_names(&self) -> BTreeSet<String> {
50        fn collect(pattern: &Pattern, output: &mut BTreeSet<String>) {
51            match pattern {
52                Pattern::Symbol(Symbol::Named(name))
53                | Pattern::Exclude(Symbol::Named(name)) => {
54                    output.insert(name.clone());
55                }
56                Pattern::Permute(permuted) => {
57                    for symbol in permuted {
58                        if let Symbol::Named(name) = symbol {
59                            output.insert(name.clone());
60                        }
61                    }
62                }
63                Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
64                    for pattern in patterns {
65                        collect(pattern, output);
66                    }
67                }
68                Pattern::Group(pattern) | Pattern::Repetition(pattern, _) => {
69                    collect(pattern, output);
70                }
71                Pattern::Symbol(Symbol::Start | Symbol::End)
72                | Pattern::Exclude(Symbol::Start | Symbol::End) => {}
73            }
74        }
75
76        let mut symbols = BTreeSet::new();
77        collect(self, &mut symbols);
78        symbols
79    }
80
81    /// Returns `true` if this pattern contains any anchors (^ or $).
82    pub fn has_anchors(&self) -> bool {
83        self.structural_info().has_anchors()
84    }
85
86    /// Returns `true` if any branch contains an end-of-partition anchor.
87    pub fn has_end_anchor(&self) -> bool {
88        match self {
89            Self::Symbol(Symbol::End) | Self::Exclude(Symbol::End) => true,
90            Self::Symbol(_) | Self::Exclude(_) => false,
91            Self::Permute(symbols) => symbols.contains(&Symbol::End),
92            Self::Concat(patterns) | Self::Alternation(patterns) => {
93                patterns.iter().any(Self::has_end_anchor)
94            }
95            Self::Group(inner) | Self::Repetition(inner, _) => inner.has_end_anchor(),
96        }
97    }
98
99    /// Returns `true` if this pattern contains any exclusion constructs ({- ... -}).
100    pub fn has_exclusions(&self) -> bool {
101        self.structural_info().has_exclusions()
102    }
103
104    /// Identify the symbol in a repetition whose preference follows its endpoint.
105    ///
106    /// The outer repetition is fixed-count or prefers continuation. Its body is
107    /// a named symbol, optionally wrapped in groups and fixed-count repetitions.
108    pub fn single_symbol_name(&self) -> Option<&str> {
109        self.single_named_symbol_name(SingleNamedSymbolMode::CompactPath)
110    }
111
112    fn single_named_symbol_name(&self, mode: SingleNamedSymbolMode) -> Option<&str> {
113        match self {
114            Pattern::Symbol(Symbol::Named(name)) => {
115                (mode != SingleNamedSymbolMode::CompactPath).then_some(name)
116            }
117            Pattern::Repetition(inner, quantifier) => {
118                let fixed_count = quantifier.fixed_count().is_some();
119                let eligible = match mode {
120                    SingleNamedSymbolMode::Exact => false,
121                    SingleNamedSymbolMode::CompactPath => {
122                        fixed_count || !quantifier.is_reluctant()
123                    }
124                    SingleNamedSymbolMode::FixedWidth => fixed_count,
125                };
126                // Endpoints alone preserve the outer continuation order only
127                // when each copy consumes the same number of rows. For example,
128                // (A{2,3})+ can prefer three rows over two copies of two.
129                if eligible {
130                    inner.single_named_symbol_name(SingleNamedSymbolMode::FixedWidth)
131                } else {
132                    None
133                }
134            }
135            Pattern::Group(inner) => inner.single_named_symbol_name(mode),
136            _ => None,
137        }
138    }
139
140    /// Returns the symbol name if this pattern is exactly a single named symbol.
141    pub(crate) fn get_single_named_symbol(&self) -> Option<&str> {
142        self.single_named_symbol_name(SingleNamedSymbolMode::Exact)
143    }
144}