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.

//! Backward reachability metadata computed during NFA finalization.

use crate::nfa::types::NFA;

/// Propagate reachable symbol bitmaps to affected predecessor states.
///
/// The consuming seal admits only symbol domains that fit a u64. Closure rows
/// and state flags are its scratch, with one entry per state.
pub(super) fn compute_reachable_symbols(
    nfa: &NFA,
    num_symbols: usize,
    mut predecessors: Vec<Vec<usize>>,
    mut queued: Vec<bool>,
) -> Vec<u64> {
    let num_states = nfa.state_count();
    let mut reachable: Vec<u64> = vec![0; num_states];
    let mut pending = Vec::with_capacity(num_states);
    for row in &mut predecessors {
        row.clear();
    }

    for (state_index, state) in nfa.states().enumerate() {
        let mut bitmap = 0u64;
        for (symbol_index, targets) in
            state.transition_slots().enumerate().take(num_symbols)
        {
            if !targets.is_empty() {
                bitmap |= 1 << symbol_index;
            }
            for target in targets {
                predecessors[target.index()].push(state_index);
            }
        }
        for transition in state.epsilon_transitions() {
            predecessors[transition.target().index()].push(state_index);
        }
        reachable[state_index] = bitmap;
        queued[state_index] = bitmap != 0;
        if queued[state_index] {
            pending.push(state_index);
        }
    }

    // Each state can gain at most 64 bits. Queue membership prevents duplicate
    // pending entries, so the work stack never exceeds the state count.
    while let Some(state) = pending.pop() {
        queued[state] = false;
        for &predecessor in &predecessors[state] {
            let combined = reachable[predecessor] | reachable[state];
            if combined != reachable[predecessor] {
                reachable[predecessor] = combined;
                if !queued[predecessor] {
                    queued[predecessor] = true;
                    pending.push(predecessor);
                }
            }
        }
    }
    reachable
}