datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Quantifier optimization passes.
//!
//! Normalization covers fixed and nested repetitions. An unbounded repeat becomes
//! possessive only when it cannot consume a row needed by a later symbol; a
//! terminal repeat instead requires its own symbols to be pairwise disjoint.

use crate::core::{NormalizedPattern, Pattern, RepetitionQuantifier};

use crate::nfa::pattern_optimizer::optimizer::PatternOptimizer;
use crate::nfa::pattern_optimizer::types::RowsConsumed;

impl<'a> PatternOptimizer<'a> {
    /// Optimize a repetition pattern.
    pub(crate) fn optimize_repetition(
        &self,
        pat: &Pattern,
        quant: &RepetitionQuantifier,
        following_symbols: &[String],
        suffix_can_match_empty: bool,
        rows_before: RowsConsumed,
    ) -> NormalizedPattern {
        // === Phase 1: Quantifier Normalization ===
        let quant = quant.normalized();

        // === Phase 2: Idempotent Quantifier Simplification ===

        if let Pattern::Repetition(inner_inner, inner_quant) = pat
            && !inner_inner.has_reluctant_choice()
            && let Some(simplified_quant) =
                Self::simplify_nested_quantifiers(inner_quant, &quant)
        {
            return self.optimize_repetition(
                inner_inner,
                &simplified_quant,
                following_symbols,
                suffix_can_match_empty,
                rows_before,
            );
        }

        // === Phase 3: Inner Pattern Optimization ===

        let inner_following_symbols =
            self.repetition_inner_following_symbols(pat, &quant, following_symbols);
        let optimized_inner = self.optimize_with_context(
            pat,
            &inner_following_symbols,
            suffix_can_match_empty,
            rows_before,
        );

        match optimized_inner {
            NormalizedPattern::Never => {
                if quant.min_repetitions() == 0 {
                    NormalizedPattern::Epsilon
                } else {
                    NormalizedPattern::Never
                }
            }
            NormalizedPattern::Epsilon => NormalizedPattern::Epsilon,
            NormalizedPattern::Ast(p) => {
                // === Phase 4: Possessive Promotion ===
                // A row-consuming continuation must be disjoint from the repeated
                // inner pattern. Terminal repetitions can still use pairwise
                // inner-symbol disjointness.
                let quant = self
                    .try_promote_repetition(
                        &p,
                        &quant,
                        following_symbols,
                        suffix_can_match_empty,
                    )
                    .unwrap_or(quant);
                NormalizedPattern::Ast(Pattern::Repetition(Box::new(p), quant))
            }
        }
    }

    fn repetition_inner_following_symbols(
        &self,
        pat: &Pattern,
        quant: &RepetitionQuantifier,
        following_symbols: &[String],
    ) -> Vec<String> {
        let mut symbols = Vec::new();
        if quant.max_repetitions().is_none_or(|max| max > 1) {
            symbols.extend(self.pattern_facts.fact(pat).leading_symbols);
        }
        symbols.extend_from_slice(following_symbols);
        symbols
    }

    /// Simplify nested quantifiers.
    ///
    /// Some quantifier combinations can be simplified:
    /// - `(A*)* → A*` (idempotent)
    /// - `(A?)* → A*` (any number of optional matches)
    /// - `(A+)? → A*` (an optional one-or-more match)
    pub(crate) fn simplify_nested_quantifiers(
        inner: &RepetitionQuantifier,
        outer: &RepetitionQuantifier,
    ) -> Option<RepetitionQuantifier> {
        use RepetitionQuantifier::{AtMostOne, OneOrMore, ZeroOrMore};

        // Each level orders its own continuation and exit. Combining their
        // bounds can lose that order when either level prefers its exit or
        // suppresses it. The structural symbol-run pass handles the separately
        // proven homogeneous greedy/reluctant cases before this general rule.
        match (inner.normalized(), outer.normalized()) {
            (AtMostOne, AtMostOne) => Some(AtMostOne),
            (OneOrMore, OneOrMore) => Some(OneOrMore),
            (ZeroOrMore | OneOrMore | AtMostOne, ZeroOrMore | OneOrMore | AtMostOne) => {
                Some(ZeroOrMore)
            }
            _ => None,
        }
    }
}