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.

//! Shared repetition wire mapping and shape-specific bound validation.

use crate::core::{
    RepetitionPreference as Preference, RepetitionQuantifier as Quantifier,
};
use datafusion::common::{DataFusionError, Result, plan_err};

use super::payload::RepetitionQuantifier as WireQuantifier;

#[derive(Clone, Copy)]
enum Shape {
    ZeroOrMore,
    OneOrMore,
    AtMostOne,
    Exactly,
    AtLeast,
    AtMost,
    Range,
}

impl Shape {
    const ALL: [Self; 7] = [
        Self::ZeroOrMore,
        Self::OneOrMore,
        Self::AtMostOne,
        Self::Exactly,
        Self::AtLeast,
        Self::AtMost,
        Self::Range,
    ];

    // Both directions use these explicit wire variants. Their numeric values
    // are a compatibility contract, independent of the core enum's ordering.
    fn wire_variants(self) -> [WireQuantifier; 3] {
        use WireQuantifier as W;
        match self {
            Self::ZeroOrMore => [
                W::ZeroOrMore,
                W::ZeroOrMorePossessive,
                W::ZeroOrMoreReluctant,
            ],
            Self::OneOrMore => {
                [W::OneOrMore, W::OneOrMorePossessive, W::OneOrMoreReluctant]
            }
            Self::AtMostOne => {
                [W::AtMostOne, W::AtMostOnePossessive, W::AtMostOneReluctant]
            }
            Self::Exactly => [W::Exactly, W::ExactlyPossessive, W::ExactlyReluctant],
            Self::AtLeast => [W::AtLeast, W::AtLeastPossessive, W::AtLeastReluctant],
            Self::AtMost => [W::AtMost, W::AtMostPossessive, W::AtMostReluctant],
            Self::Range => [W::Range, W::RangePossessive, W::RangeReluctant],
        }
    }

    fn decode(self, wire: WireQuantifier, lower: u32, upper: u32) -> Result<Quantifier> {
        let unused = match self {
            Self::ZeroOrMore | Self::OneOrMore | Self::AtMostOne
                if lower != 0 || upper != 0 =>
            {
                Some("lower/upper bounds")
            }
            Self::Exactly | Self::AtLeast if upper != 0 => Some("upper"),
            Self::AtMost if lower != 0 => Some("lower"),
            Self::Range if lower > upper => {
                return plan_err!(
                    "repetition quantifier {wire:?} lower bound {lower} exceeds upper bound {upper}"
                );
            }
            _ => None,
        };
        if let Some(unused) = unused {
            return plan_err!("repetition quantifier {wire:?} must not set {unused}");
        }
        Ok(match self {
            Self::ZeroOrMore => Quantifier::ZeroOrMore,
            Self::OneOrMore => Quantifier::OneOrMore,
            Self::AtMostOne => Quantifier::AtMostOne,
            Self::Exactly => Quantifier::Exactly(lower),
            Self::AtLeast => Quantifier::AtLeast(lower),
            Self::AtMost => Quantifier::AtMost(upper),
            Self::Range => Quantifier::Range(lower, upper),
        })
    }
}

pub(super) fn encode(quantifier: &Quantifier) -> (i32, u32, u32) {
    use Quantifier as Q;
    // Preserve the source family: bounds alone cannot distinguish `+` from
    // `{1,}`, `?` from `{,1}`, or `{2}` from `{2,2}`.
    let (shape, lower, upper) = match quantifier {
        Q::ZeroOrMore | Q::ZeroOrMorePossessive | Q::ZeroOrMoreReluctant => {
            (Shape::ZeroOrMore, 0, 0)
        }
        Q::OneOrMore | Q::OneOrMorePossessive | Q::OneOrMoreReluctant => {
            (Shape::OneOrMore, 0, 0)
        }
        Q::AtMostOne | Q::AtMostOnePossessive | Q::AtMostOneReluctant => {
            (Shape::AtMostOne, 0, 0)
        }
        Q::Exactly(n) | Q::ExactlyPossessive(n) | Q::ExactlyReluctant(n) => {
            (Shape::Exactly, *n, 0)
        }
        Q::AtLeast(n) | Q::AtLeastPossessive(n) | Q::AtLeastReluctant(n) => {
            (Shape::AtLeast, *n, 0)
        }
        Q::AtMost(n) | Q::AtMostPossessive(n) | Q::AtMostReluctant(n) => {
            (Shape::AtMost, 0, *n)
        }
        Q::Range(lower, upper)
        | Q::RangePossessive(lower, upper)
        | Q::RangeReluctant(lower, upper) => (Shape::Range, *lower, *upper),
    };
    let [greedy, possessive, reluctant] = shape.wire_variants();
    let wire = match quantifier.bounds().preference {
        Preference::Greedy => greedy,
        Preference::Possessive => possessive,
        Preference::Reluctant => reluctant,
    };
    (wire as i32, lower, upper)
}

pub(super) fn decode(quantifier: i32, lower: u32, upper: u32) -> Result<Quantifier> {
    let wire = WireQuantifier::try_from(quantifier).map_err(|_| {
        DataFusionError::Plan(format!("unknown repetition quantifier {quantifier}"))
    })?;
    if wire == WireQuantifier::Unspecified {
        return plan_err!("repetition quantifier is unspecified");
    }
    for shape in Shape::ALL {
        let [greedy, possessive, reluctant] = shape.wire_variants();
        if wire == greedy || wire == possessive || wire == reluctant {
            let quantifier = shape.decode(wire, lower, upper)?;
            return Ok(if wire == possessive {
                quantifier
                    .possessive_variant()
                    .expect("decoded shape is greedy")
            } else if wire == reluctant {
                quantifier
                    .reluctant_variant()
                    .expect("decoded shape is greedy")
            } else {
                quantifier
            });
        }
    }
    plan_err!("unknown repetition quantifier {quantifier}")
}