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.

//! Symbol-status simplification for symbols, exclusions, and permutations.

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

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

impl<'a> PatternOptimizer<'a> {
    pub(crate) fn optimize_symbol(
        &self,
        sym: &Symbol,
        wrap: impl FnOnce(Symbol) -> Pattern,
    ) -> NormalizedPattern {
        if self.allow_pruning && self.is_false_symbol(sym) {
            NormalizedPattern::Never
        } else {
            NormalizedPattern::Ast(wrap(sym.clone()))
        }
    }

    /// Optimize a permute pattern (match symbols in any order).
    pub(crate) fn optimize_permute(&self, syms: &[Symbol]) -> NormalizedPattern {
        if let [sym] = syms {
            return self.optimize_symbol(sym, Pattern::Symbol);
        }

        if self.allow_pruning && syms.iter().any(|sym| self.is_false_symbol(sym)) {
            return NormalizedPattern::Never;
        }

        NormalizedPattern::Ast(Pattern::Permute(syms.to_vec()))
    }

    fn is_false_symbol(&self, sym: &Symbol) -> bool {
        matches!(
            sym,
            Symbol::Named(name)
                if self.named_symbol_status(name) == Some(SymbolStatus::False)
        )
    }

    fn named_symbol_status(&self, name: &str) -> Option<SymbolStatus> {
        self.symbol_status.get(name).copied().or_else(|| {
            self.normalized_symbol_status
                .get(&name.to_ascii_lowercase())
                .copied()
        })
    }
}