Skip to main content

substrait/parse/text/simple_extensions/
scalar_functions.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Scalar function definitions parsed from extension YAML.
4
5use std::collections::HashMap;
6
7use crate::text::simple_extensions::{
8    ArgumentsItem as RawArgumentsItem, NullabilityHandling as RawNullabilityHandling,
9    Options as RawOptions, ScalarFunction as RawScalarFunction, ScalarFunctionImplsItem as RawImpl,
10    Type as RawType, VariadicBehavior as RawVariadicBehavior, VariadicBehaviorParameterConsistency,
11};
12
13use super::argument::{ArgumentsItem, ArgumentsItemError};
14use super::extensions::TypeContext;
15use super::return_type::ReturnType;
16use super::type_parser::TypeParseError;
17use super::types::ExtensionTypeError;
18use crate::parse::Parse;
19use thiserror::Error;
20
21/// Errors that can occur when parsing scalar functions
22#[derive(Debug, Error)]
23pub enum ScalarFunctionError {
24    /// Scalar function has no implementations
25    #[error("Scalar function '{name}' must have at least one implementation")]
26    NoImplementations {
27        /// The function name
28        name: String,
29    },
30    /// Invalid variadic behavior
31    #[error("Variadic behavior {field} must be a non-negative integer, got {value}")]
32    InvalidVariadicBehavior {
33        /// The field that was invalid (min or max)
34        field: String,
35        /// The invalid value
36        value: f64,
37    },
38    /// Variadic min is greater than max
39    #[error("Variadic min ({min}) must be less than or equal to max ({max})")]
40    VariadicMinGreaterThanMax {
41        /// The minimum value
42        min: u32,
43        /// The maximum value
44        max: u32,
45    },
46    /// Error parsing function argument
47    #[error("Argument error: {0}")]
48    ArgumentError(#[from] ArgumentsItemError),
49    /// Error parsing type in function signature
50    #[error("Type error: {0}")]
51    TypeError(#[from] ExtensionTypeError),
52    /// Error parsing type expression
53    #[error("Type parse error: {0}")]
54    TypeParseError(#[from] TypeParseError),
55    /// Feature not yet implemented
56    #[error("Not yet implemented: {0}")]
57    NotYetImplemented(String),
58}
59
60/// A scalar function implementation (overload), identified by its [signature](Self::signature).
61#[derive(Clone, Debug, PartialEq)]
62pub struct ScalarFunctionVariant {
63    /// Function name
64    pub name: String,
65    /// Human-readable description of the function
66    pub description: Option<String>,
67    /// Function arguments with types and optional names/descriptions
68    pub args: Vec<ArgumentsItem>,
69    /// Configurable function options (e.g., overflow behavior, rounding modes)
70    pub options: Options,
71    /// Variadic argument behavior.
72    ///
73    /// `None` indicates the function is not variadic.
74    pub variadic: Option<VariadicBehavior>,
75    /// Whether the function output depends on session state (e.g., timezone, locale).
76    ///
77    /// Defaults to `false` per the Substrait spec.
78    pub session_dependent: bool,
79    /// Whether the function is deterministic (same inputs always produce same output).
80    ///
81    /// Defaults to `true` per the Substrait spec.
82    pub deterministic: bool,
83    /// How the function handles null inputs and produces nullable outputs.
84    ///
85    /// Defaults to [`NullabilityHandling::Mirror`] per the Substrait spec.
86    pub nullability: NullabilityHandling,
87    /// The return declaration, including any ordered numeric assignments.
88    ///
89    /// Variables are not bound and derivations are not evaluated during parsing.
90    pub return_type: ReturnType,
91    /// Language-specific implementation code (e.g., SQL, C++, Python)
92    ///
93    /// Maps language identifiers to implementation source code snippets.
94    pub implementation: HashMap<String, String>,
95}
96
97impl ScalarFunctionVariant {
98    /// Parse each implementation of a raw scalar function with the provided type context.
99    pub(super) fn from_raw(
100        raw: RawScalarFunction,
101        ctx: &mut TypeContext,
102    ) -> Result<Vec<Self>, ScalarFunctionError> {
103        if raw.impls.is_empty() {
104            return Err(ScalarFunctionError::NoImplementations { name: raw.name });
105        }
106
107        raw.impls
108            .into_iter()
109            .map(|impl_| Self::from_raw_impl(&raw.name, raw.description.as_deref(), impl_, ctx))
110            .collect()
111    }
112
113    /// This implementation's function signature, such as `add:i32_i32`.
114    ///
115    /// See <https://substrait.io/extensions/#function-signature>.
116    pub fn signature(&self) -> String {
117        let argument_signature = self
118            .args
119            .iter()
120            .map(ArgumentsItem::short_name)
121            .collect::<Vec<_>>()
122            .join("_");
123        format!("{}:{argument_signature}", self.name)
124    }
125
126    /// Parse one implementation from raw YAML with the provided type context.
127    fn from_raw_impl(
128        name: &str,
129        description: Option<&str>,
130        raw: RawImpl,
131        ctx: &mut TypeContext,
132    ) -> Result<Self, ScalarFunctionError> {
133        // Parse and validate the return type
134        let return_type = match raw.return_.0 {
135            RawType::String(s) => {
136                let return_type = match ReturnType::parse(&s) {
137                    Err(ExtensionTypeError::ParseType(
138                        TypeParseError::UnsupportedNumericExpression(_),
139                    )) => {
140                        return Err(ScalarFunctionError::NotYetImplemented(
141                            "Numeric expressions in type parameters - issue #449".to_string(),
142                        ));
143                    }
144                    Err(ExtensionTypeError::ParseType(error)) => return Err(error.into()),
145                    Err(ExtensionTypeError::InvalidAnyTypeVariable { .. })
146                    | Err(ExtensionTypeError::ExpectedConcreteType { .. })
147                    | Err(ExtensionTypeError::InvalidParameter(_)) => {
148                        // Other numeric derivations are not yet supported.
149                        // See: https://github.com/substrait-io/substrait-rs/issues/452
150                        return Err(ScalarFunctionError::NotYetImplemented(
151                            "Type variables in function signatures - issue #452".to_string(),
152                        ));
153                    }
154                    Err(ExtensionTypeError::UnknownTypeName { name }) => {
155                        return Err(ScalarFunctionError::TypeError(
156                            ExtensionTypeError::UnknownTypeName { name },
157                        ));
158                    }
159                    Err(e) => return Err(ScalarFunctionError::TypeError(e)),
160                    Ok(expression) => expression,
161                };
162                return_type
163                    .return_type
164                    .visit_references(&mut |name| ctx.linked(name));
165                return_type
166            }
167            RawType::Object(_) => {
168                // Struct return types (YAML syntactic sugar) are not yet supported
169                // See: https://github.com/substrait-io/substrait-rs/issues/450
170                return Err(ScalarFunctionError::NotYetImplemented(
171                    "Struct return types - issue #450".to_string(),
172                ));
173            }
174        };
175
176        let variadic = raw.variadic.map(|v| v.try_into()).transpose()?;
177
178        let args = match raw.args {
179            Some(a) => {
180                a.0.into_iter()
181                    .map(|raw_arg| parse_argument(raw_arg, ctx))
182                    .collect::<Result<Vec<_>, _>>()?
183            }
184            None => Vec::new(),
185        };
186
187        Ok(ScalarFunctionVariant {
188            name: name.to_string(),
189            description: description.map(str::to_string),
190            args,
191            options: raw.options.as_ref().map(Options::from).unwrap_or_default(),
192            variadic,
193            session_dependent: raw.session_dependent.map(|b| b.0).unwrap_or(false),
194            deterministic: raw.deterministic.map(|b| b.0).unwrap_or(true),
195            nullability: raw
196                .nullability
197                .map(Into::into)
198                .unwrap_or(NullabilityHandling::Mirror),
199            return_type,
200            implementation: raw
201                .implementation
202                .map(|i| i.0.into_iter().collect())
203                .unwrap_or_default(),
204        })
205    }
206}
207
208/// Parse a function argument and record the extension types its type references.
209fn parse_argument(
210    raw: RawArgumentsItem,
211    ctx: &mut TypeContext,
212) -> Result<ArgumentsItem, ScalarFunctionError> {
213    let argument = raw.parse(ctx)?;
214    let argument_type = match &argument {
215        ArgumentsItem::ValueArgument(value) => value.value(),
216        ArgumentsItem::TypeArgument(type_argument) => type_argument.type_(),
217        ArgumentsItem::EnumArgument(_) => return Ok(argument),
218    };
219    argument_type.visit_references(&mut |name| ctx.linked(name));
220    Ok(argument)
221}
222
223/// Validated variadic behavior with min/max constraints
224#[derive(Clone, Debug, PartialEq)]
225pub struct VariadicBehavior {
226    /// Minimum number of arguments
227    pub min: u32,
228    /// Maximum number of arguments (unlimited when None)
229    pub max: Option<u32>,
230    /// Whether all variadic parameters must have the same type.
231    ///
232    /// `None` when the parameter is not specified in the YAML. We cannot assume a default
233    /// because the Substrait spec does not define default behavior for missing values
234    /// (see <https://github.com/substrait-io/substrait/issues/928>).
235    ///
236    /// TODO: Once the spec defines default behavior, apply it and change this to a non-Option
237    /// type (see issue #454).
238    pub parameter_consistency: Option<ParameterConsistency>,
239}
240
241/// Specifies whether variadic parameters must have consistent types.
242///
243/// When a function's last argument is variadic with a type parameter (e.g., `fn(A, B, C...)`),
244/// this controls type binding for the variadic arguments.
245///
246/// See: <https://github.com/substrait-io/substrait/issues/928>
247#[derive(Clone, Debug, PartialEq)]
248pub enum ParameterConsistency {
249    /// All variadic arguments must have the same concrete type.
250    ///
251    /// For example, if `C` binds to `i32`, all variadic arguments must be `i32`.
252    Consistent,
253    /// Each variadic argument can have a different type.
254    ///
255    /// Each instance of the variadic parameter can bind to different types
256    /// within the constraints of the type parameter.
257    Inconsistent,
258}
259
260impl From<VariadicBehaviorParameterConsistency> for ParameterConsistency {
261    fn from(raw: VariadicBehaviorParameterConsistency) -> Self {
262        match raw {
263            VariadicBehaviorParameterConsistency::Consistent => ParameterConsistency::Consistent,
264            VariadicBehaviorParameterConsistency::Inconsistent => {
265                ParameterConsistency::Inconsistent
266            }
267        }
268    }
269}
270
271impl TryFrom<RawVariadicBehavior> for VariadicBehavior {
272    type Error = ScalarFunctionError;
273
274    fn try_from(raw: RawVariadicBehavior) -> Result<Self, Self::Error> {
275        fn parse_bound(value: f64, field: &str) -> Result<u32, ScalarFunctionError> {
276            if value < 0.0 || value.fract() != 0.0 {
277                return Err(ScalarFunctionError::InvalidVariadicBehavior {
278                    field: field.to_string(),
279                    value,
280                });
281            }
282            Ok(value as u32)
283        }
284
285        let min = raw
286            .min
287            .map(|v| parse_bound(v, "min"))
288            .transpose()?
289            .unwrap_or(0);
290        let max = raw.max.map(|v| parse_bound(v, "max")).transpose()?;
291
292        if let Some(max_val) = max
293            && min > max_val
294        {
295            return Err(ScalarFunctionError::VariadicMinGreaterThanMax { min, max: max_val });
296        }
297
298        Ok(VariadicBehavior {
299            min,
300            max,
301            parameter_consistency: raw.parameter_consistency.map(Into::into),
302        })
303    }
304}
305
306/// How a function handles null inputs and produces nullable outputs
307#[derive(Clone, Debug, PartialEq)]
308pub enum NullabilityHandling {
309    /// Nullability of output mirrors the nullability of input(s)
310    Mirror,
311    /// Function explicitly declares the nullability of its output
312    DeclaredOutput,
313    /// Function handles nulls in a custom way per implementation
314    Discrete,
315}
316
317impl From<RawNullabilityHandling> for NullabilityHandling {
318    fn from(raw: RawNullabilityHandling) -> Self {
319        match raw {
320            RawNullabilityHandling::Mirror => NullabilityHandling::Mirror,
321            RawNullabilityHandling::DeclaredOutput => NullabilityHandling::DeclaredOutput,
322            RawNullabilityHandling::Discrete => NullabilityHandling::Discrete,
323        }
324    }
325}
326
327/// Validated function options
328#[derive(Clone, Debug, Default, PartialEq)]
329pub struct Options(pub HashMap<String, Vec<String>>);
330
331impl From<&RawOptions> for Options {
332    fn from(raw: &RawOptions) -> Self {
333        Options(
334            raw.0
335                .iter()
336                .map(|(k, v)| (k.clone(), v.values.clone()))
337                .collect(),
338        )
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    #[test]
347    fn test_variadic_invalid_values() {
348        let invalid_cases = vec![
349            (Some(-1.0), None, "negative min"),
350            (None, Some(-2.5), "negative max"),
351            (Some(7.2), None, "non-integer min"),
352            (None, Some(3.5), "non-integer max"),
353            (Some(5.0), Some(3.0), "min greater than max"),
354        ];
355
356        for (min, max, description) in invalid_cases {
357            let raw = RawVariadicBehavior {
358                min,
359                max,
360                parameter_consistency: None,
361            };
362            assert!(
363                VariadicBehavior::try_from(raw).is_err(),
364                "expected error for {}",
365                description
366            );
367        }
368    }
369
370    #[test]
371    fn test_variadic_valid() {
372        let raw = RawVariadicBehavior {
373            min: Some(1.0),
374            max: Some(5.0),
375            parameter_consistency: None,
376        };
377        let result = VariadicBehavior::try_from(raw).unwrap();
378        assert_eq!(result.min, 1);
379        assert_eq!(result.max, Some(5));
380    }
381
382    #[test]
383    fn test_variadic_none_values() {
384        let raw = RawVariadicBehavior {
385            min: None,
386            max: None,
387            parameter_consistency: None,
388        };
389        let result = VariadicBehavior::try_from(raw).unwrap();
390        assert_eq!(result.min, 0);
391        assert_eq!(result.max, None);
392    }
393
394    #[test]
395    fn test_no_implementations_error() {
396        use crate::text::simple_extensions::ScalarFunction as RawScalarFunction;
397
398        let raw = RawScalarFunction {
399            deprecated: None,
400            name: "empty_function".to_string(),
401            description: None,
402            metadata: Default::default(),
403            impls: vec![],
404        };
405
406        let mut ctx = super::super::extensions::TypeContext::default();
407        let result = ScalarFunctionVariant::from_raw(raw, &mut ctx);
408
409        assert!(matches!(
410            result,
411            Err(ScalarFunctionError::NoImplementations { name })
412            if name == "empty_function"
413        ));
414    }
415
416    #[test]
417    fn test_scalar_function_with_single_impl() {
418        use crate::text::simple_extensions::{
419            ReturnValue, ScalarFunction as RawScalarFunction, ScalarFunctionImplsItem,
420            Type as RawType,
421        };
422
423        let raw = RawScalarFunction {
424            deprecated: None,
425            name: "add".to_string(),
426            description: Some("Addition function".to_string()),
427            metadata: Default::default(),
428            impls: vec![ScalarFunctionImplsItem {
429                args: None,
430                deprecated: None,
431                description: None,
432                options: None,
433                variadic: None,
434                session_dependent: None,
435                deterministic: None,
436                nullability: None,
437                return_: ReturnValue(RawType::String("i32".to_string())),
438                implementation: None,
439            }],
440        };
441
442        let mut ctx = super::super::extensions::TypeContext::default();
443        let result = ScalarFunctionVariant::from_raw(raw, &mut ctx).unwrap();
444        let [result] = result.as_slice() else {
445            panic!("expected one implementation, got {result:?}");
446        };
447
448        assert_eq!(result.name, "add");
449        assert_eq!(result.description, Some("Addition function".to_string()));
450        assert_eq!(result.signature(), "add:");
451
452        use super::super::types::{Type, TypeKind};
453        assert_eq!(result.return_type, Type::new(TypeKind::I32, false).into());
454    }
455
456    #[test]
457    fn test_options_conversion() {
458        use crate::text::simple_extensions::{Options as RawOptions, OptionsValue};
459        use indexmap::IndexMap;
460
461        let mut raw_map = IndexMap::new();
462        raw_map.insert(
463            "overflow".to_string(),
464            OptionsValue {
465                values: vec!["SILENT".to_string(), "ERROR".to_string()],
466                description: None,
467            },
468        );
469
470        let raw = RawOptions(raw_map);
471        let options = Options::from(&raw);
472
473        assert_eq!(options.0.len(), 1);
474        assert_eq!(
475            options.0.get("overflow").unwrap(),
476            &vec!["SILENT".to_string(), "ERROR".to_string()]
477        );
478    }
479}