datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Helpers for compiling concatenation (`...`) and alternation (`|`) patterns
//! into fragments of the NFA under construction.

use crate::core::Pattern;
use datafusion_common::{DataFusionError, Result};

use super::super::compiler::NfaBuilder;

/// Compile a concatenation pattern into the given builder.
pub(crate) fn compile_concat(
    b: &mut NfaBuilder,
    parts: &[Pattern],
) -> Result<(usize, usize)> {
    let Some((first, rest)) = parts.split_first() else {
        // Epsilon – represents an empty match. Build a single state so callers
        // can still connect to both the start and end of this fragment.
        let s = b.new_state(false)?;
        return Ok((s, s));
    };

    let (start, mut end) = b.build_pattern(first)?;
    for p in rest {
        let (s, e) = b.build_pattern(p)?;
        b.add_epsilon(end, s);
        end = e;
    }
    Ok((start, end))
}

/// Compile an alternation pattern (`A | B | ...`) into the builder.
pub(crate) fn compile_alternation(
    b: &mut NfaBuilder,
    alts: &[Pattern],
) -> Result<(usize, usize)> {
    if alts.is_empty() {
        return Err(DataFusionError::Plan(
            "MATCH_RECOGNIZE pattern alternation must contain at least one branch".into(),
        ));
    }

    // Preserve preference-sensitive routing even for a singleton alternative,
    // matching the compiler's established construction metadata.
    b.record_choice();
    let start = b.new_state(false)?;
    let mut ends = Vec::new();
    for sub in alts {
        let (s, e) = b.build_pattern(sub)?;

        b.add_epsilon(start, s);
        ends.push(e);
    }

    let end = b.new_state(false)?;
    for e in ends {
        b.add_epsilon(e, end);
    }
    Ok((start, end))
}