Skip to main content

substrait/parse/text/simple_extensions/
registry.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Substrait Extension Registry
4//!
5//! This module provides registries for Substrait extensions:
6//! - **Global Registry**: Immutable, reusable across plans, URI+name based lookup
7//! - **Local Registry**: Per-plan, anchor-based, references Global Registry (TODO)
8//!
9//! Currently only type definitions are supported. Function parsing will be added in a future update.
10//!
11//! This module is only available when the `parse` feature is enabled.
12
13use std::collections::{HashMap, hash_map::Entry};
14
15use super::{ExtensionFile, SimpleExtensions, SimpleExtensionsError, types::CustomType};
16use crate::urn::Urn;
17
18/// Extension Registry that manages Substrait extensions
19///
20/// This registry is immutable and reusable across multiple plans.
21/// It provides URN + name based lookup for extension types. Function parsing will be added in a future update.
22#[derive(Debug)]
23pub struct Registry {
24    /// Pre-validated extension files
25    extensions: HashMap<Urn, SimpleExtensions>,
26}
27
28impl Registry {
29    /// Create a new Global Registry from validated extension files.
30    ///
31    /// Any duplicate URNs will raise an error.
32    pub fn new<I: IntoIterator<Item = ExtensionFile>>(
33        extensions: I,
34    ) -> Result<Self, SimpleExtensionsError> {
35        let mut map = HashMap::new();
36        for ExtensionFile { urn, extension } in extensions {
37            match map.entry(urn.clone()) {
38                Entry::Occupied(_) => return Err(SimpleExtensionsError::DuplicateUrn(urn)),
39                Entry::Vacant(entry) => {
40                    entry.insert(extension);
41                }
42            }
43        }
44        Ok(Self { extensions: map })
45    }
46
47    /// Get an iterator over all extension files in this registry
48    pub fn extensions(&self) -> impl Iterator<Item = (&Urn, &SimpleExtensions)> {
49        self.extensions.iter()
50    }
51
52    /// Create a Global Registry from the built-in core extensions.
53    #[cfg(feature = "extensions")]
54    pub fn from_core_extensions() -> Self {
55        use crate::extensions::EXTENSIONS;
56
57        // Parse the core extensions from the raw extensions format to the parsed format
58        let extensions: HashMap<Urn, SimpleExtensions> = EXTENSIONS
59            .iter()
60            .map(|(orig_urn, simple_extensions)| {
61                let ExtensionFile { urn, extension } = ExtensionFile::create(simple_extensions.clone())
62                    .unwrap_or_else(|err| panic!("Core extensions should be valid, but failed to create extension file for {orig_urn}: {err}"));
63                debug_assert_eq!(orig_urn, &urn);
64                (urn, extension)
65            })
66            .collect();
67
68        Self { extensions }
69    }
70
71    fn get_extension(&self, urn: &Urn) -> Option<&SimpleExtensions> {
72        self.extensions.get(urn)
73    }
74
75    /// Get a type by URN and name
76    pub fn get_type(&self, urn: &Urn, name: &str) -> Option<&CustomType> {
77        self.get_extension(urn)?.get_type(name)
78    }
79
80    /// Get a scalar function implementation by URN and function signature,
81    /// such as `add:i32_i32`.
82    pub fn get_scalar_function(
83        &self,
84        urn: &Urn,
85        signature: &str,
86    ) -> Option<&super::ScalarFunctionVariant> {
87        self.get_extension(urn)?.get_scalar_function(signature)
88    }
89
90    /// Get an iterator over the implementations of a scalar function by URN and name.
91    pub fn scalar_function_overloads<'a>(
92        &'a self,
93        urn: &Urn,
94        name: &'a str,
95    ) -> impl Iterator<Item = &'a super::ScalarFunctionVariant> {
96        self.get_extension(urn)
97            .into_iter()
98            .flat_map(move |extension| extension.scalar_function_overloads(name))
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::{ExtensionFile, Registry};
105    use crate::parse::text::simple_extensions::{
106        SimpleExtensionsError, argument::ArgumentsItemError, scalar_functions::ScalarFunctionError,
107        types::ExtensionTypeError,
108    };
109    use crate::text::simple_extensions::{SimpleExtensions, SimpleExtensionsTypesItem};
110    use crate::urn::Urn;
111    use std::str::FromStr;
112
113    fn extension_file(urn: &str, type_names: &[&str]) -> ExtensionFile {
114        let types = type_names
115            .iter()
116            .map(|name| SimpleExtensionsTypesItem {
117                name: (*name).to_string(),
118                deprecated: None,
119                description: None,
120                metadata: Default::default(),
121                parameters: None,
122                structure: None,
123                variadic: None,
124            })
125            .collect();
126
127        let raw = SimpleExtensions {
128            scalar_functions: vec![],
129            aggregate_functions: vec![],
130            window_functions: vec![],
131            table_functions: vec![],
132            dependencies: Default::default(),
133            description: None,
134            metadata: Default::default(),
135            type_variations: vec![],
136            types,
137            urn: urn.to_string(),
138        };
139
140        ExtensionFile::create(raw).expect("valid extension file")
141    }
142
143    #[test]
144    fn test_registry_iteration() {
145        let urns = vec![
146            "extension:example.com:first",
147            "extension:example.com:second",
148        ];
149        let registry =
150            Registry::new(urns.iter().map(|&urn| extension_file(urn, &["type"]))).unwrap();
151
152        let collected: Vec<&Urn> = registry.extensions().map(|(urn, _)| urn).collect();
153        assert_eq!(collected.len(), 2);
154        for urn in urns {
155            assert!(
156                collected
157                    .iter()
158                    .any(|candidate| candidate.to_string() == urn)
159            );
160        }
161    }
162
163    #[test]
164    fn test_type_lookup() {
165        let urn = Urn::from_str("extension:example.com:test").unwrap();
166        let registry =
167            Registry::new(vec![extension_file(&urn.to_string(), &["test_type"])]).unwrap();
168        let other_urn = Urn::from_str("extension:example.com:other").unwrap();
169
170        let cases = vec![
171            (&urn, "test_type", true),
172            (&urn, "missing", false),
173            (&other_urn, "test_type", false),
174        ];
175
176        for (query_urn, type_name, expected) in cases {
177            assert_eq!(
178                registry.get_type(query_urn, type_name).is_some(),
179                expected,
180                "unexpected lookup result for {query_urn}:{type_name}"
181            );
182        }
183    }
184
185    #[cfg(feature = "extensions")]
186    #[test]
187    fn test_from_core_extensions() {
188        let registry = Registry::from_core_extensions();
189        assert!(registry.extensions().count() > 0);
190
191        // Test that functions_geometry.yaml loaded correctly with its geometry type
192        let urn = Urn::from_str("extension:io.substrait:functions_geometry").unwrap();
193        let core_extension = registry
194            .get_extension(&urn)
195            .expect("Should find functions_geometry extension");
196
197        let geometry_type = core_extension.get_type("geometry");
198        assert!(
199            geometry_type.is_some(),
200            "Should find 'geometry' type in functions_geometry extension"
201        );
202
203        // Also test the registry's get_type method with the actual URN
204        let type_via_registry = registry.get_type(&urn, "geometry");
205        assert!(type_via_registry.is_some());
206
207        // `unsigned_integers` was added to the catalog in Substrait v0.101.0.
208        let unsigned_integers_urn =
209            Urn::from_str("extension:io.substrait:unsigned_integers").unwrap();
210        assert!(
211            registry.get_extension(&unsigned_integers_urn).is_some(),
212            "unsigned_integers should be a core extension"
213        );
214    }
215
216    #[test]
217    fn test_unknown_type_without_prefix_fails() {
218        use crate::text::simple_extensions;
219
220        // Function that references a type without u! prefix - should fail with UnknownTypeName
221        let invalid_extension = SimpleExtensions {
222            scalar_functions: vec![simple_extensions::ScalarFunction {
223                name: "bad_function".to_string(),
224                description: None,
225                metadata: Default::default(),
226                deprecated: None,
227                impls: vec![simple_extensions::ScalarFunctionImplsItem {
228                    args: None,
229                    deprecated: None,
230                    description: None,
231                    options: None,
232                    variadic: None,
233                    session_dependent: None,
234                    deterministic: None,
235                    nullability: None,
236                    return_: simple_extensions::ReturnValue(simple_extensions::Type::String(
237                        "point".to_string(), // Missing u! prefix - this is an error, not NYI
238                    )),
239                    implementation: None,
240                }],
241            }],
242            aggregate_functions: vec![],
243            window_functions: vec![],
244            table_functions: vec![],
245            dependencies: Default::default(),
246            description: None,
247            metadata: Default::default(),
248            type_variations: vec![],
249            types: vec![],
250            urn: "extension:example.com:invalid".to_string(),
251        };
252
253        let result = ExtensionFile::create(invalid_extension);
254        assert!(
255            result.is_err(),
256            "Should fail when type is missing u! prefix"
257        );
258
259        match result {
260            Err(SimpleExtensionsError::ScalarFunctionError(ScalarFunctionError::TypeError(
261                ExtensionTypeError::UnknownTypeName { name },
262            ))) => {
263                assert_eq!(name, "point");
264            }
265            other => panic!("Expected UnknownTypeName error, got {:?}", other),
266        }
267    }
268
269    /// Helper to create a minimal extension with a scalar function returning a custom type
270    fn extension_with_custom_type_reference(
271        urn: &str,
272        function_name: &str,
273        return_type: &str,
274        defined_types: Vec<&str>,
275    ) -> SimpleExtensions {
276        use crate::text::simple_extensions;
277
278        SimpleExtensions {
279            scalar_functions: vec![simple_extensions::ScalarFunction {
280                name: function_name.to_string(),
281                description: None,
282                metadata: Default::default(),
283                deprecated: None,
284                impls: vec![simple_extensions::ScalarFunctionImplsItem {
285                    args: None,
286                    deprecated: None,
287                    description: None,
288                    options: None,
289                    variadic: None,
290                    session_dependent: None,
291                    deterministic: None,
292                    nullability: None,
293                    return_: simple_extensions::ReturnValue(simple_extensions::Type::String(
294                        return_type.to_string(),
295                    )),
296                    implementation: None,
297                }],
298            }],
299            aggregate_functions: vec![],
300            window_functions: vec![],
301            table_functions: vec![],
302            dependencies: Default::default(),
303            description: None,
304            metadata: Default::default(),
305            type_variations: vec![],
306            types: defined_types
307                .into_iter()
308                .map(|name| SimpleExtensionsTypesItem {
309                    name: name.to_string(),
310                    deprecated: None,
311                    description: None,
312                    metadata: Default::default(),
313                    parameters: None,
314                    structure: None,
315                    variadic: None,
316                })
317                .collect(),
318            urn: urn.to_string(),
319        }
320    }
321
322    #[test]
323    fn test_custom_type_reference_valid() {
324        let extension = extension_with_custom_type_reference(
325            "extension:example.com:valid",
326            "get_point",
327            "u!point",
328            vec!["point"],
329        );
330
331        let result = ExtensionFile::create(extension);
332        assert!(
333            result.is_ok(),
334            "Should succeed when referenced type exists with u! prefix"
335        );
336    }
337
338    #[test]
339    fn test_custom_type_reference_missing() {
340        let extension = extension_with_custom_type_reference(
341            "extension:example.com:invalid",
342            "get_rectangle",
343            "u!rectangle",
344            vec![], // rectangle type not defined
345        );
346
347        let result = ExtensionFile::create(extension);
348        assert!(
349            result.is_err(),
350            "Should fail when referenced type doesn't exist"
351        );
352
353        match result {
354            Err(SimpleExtensionsError::UnresolvedTypeReference { type_name }) => {
355                assert_eq!(type_name, "rectangle");
356            }
357            other => panic!("Expected UnresolvedTypeReference error, got {:?}", other),
358        }
359    }
360
361    #[cfg(feature = "extensions")]
362    #[test]
363    fn test_core_functions_with_variable_returns() {
364        let registry = Registry::from_core_extensions();
365        let urn = Urn::from_str("extension:io.substrait:functions_comparison").unwrap();
366        for name in ["coalesce", "nullif"] {
367            assert!(
368                registry
369                    .scalar_function_overloads(&urn, name)
370                    .next()
371                    .is_some(),
372                "{name} should not be skipped because of its variable return type"
373            );
374        }
375    }
376
377    #[test]
378    fn test_numbered_variable_returns() {
379        use super::super::{Type, TypeKind, argument::ArgumentsItem};
380
381        for (return_type, id, nullable) in [("any1", 1, false), ("any2?", 2, true)] {
382            let yaml = format!(
383                r#"urn: extension:example.com:variables
384scalar_functions:
385  - name: identity
386    impls:
387      - args:
388          - value: {return_type}
389        return: {return_type}
390"#
391            );
392            let file = ExtensionFile::read_from_str(yaml).unwrap();
393            let urn = file.urn().clone();
394            let registry = Registry::new(vec![file]).unwrap();
395            let function = registry
396                .scalar_function_overloads(&urn, "identity")
397                .next()
398                .unwrap();
399            assert_eq!(
400                function.return_type,
401                Type {
402                    kind: TypeKind::Variable { id },
403                    nullable
404                }
405                .into()
406            );
407
408            let ArgumentsItem::ValueArgument(argument) = function.args[0].clone() else {
409                panic!("expected value argument");
410            };
411            let raw: crate::text::simple_extensions::ValueArg = argument.into();
412            assert_eq!(
413                raw.value,
414                crate::text::simple_extensions::Type::String(return_type.to_string())
415            );
416        }
417    }
418
419    #[cfg(feature = "extensions")]
420    #[test]
421    fn test_core_functions_with_numeric_parameter_returns() {
422        let registry = Registry::from_core_extensions();
423        let urn = Urn::from_str("extension:io.substrait:functions_string").unwrap();
424        for name in ["lower", "upper"] {
425            assert!(
426                registry
427                    .scalar_function_overloads(&urn, name)
428                    .next()
429                    .is_some(),
430                "{name} should not be skipped because of its named numeric parameters"
431            );
432        }
433    }
434
435    #[test]
436    fn test_numeric_parameter_returns() {
437        use super::super::{IntegerParameter, Type, TypeKind};
438
439        let yaml = r#"urn: extension:example.com:numeric_parameters
440scalar_functions:
441  - name: upper
442    impls:
443      - args:
444          - value: varchar<L>
445        return: varchar<L>
446"#;
447        let file = ExtensionFile::read_from_str(yaml).unwrap();
448        let urn = file.urn().clone();
449        let registry = Registry::new(vec![file]).unwrap();
450        let function = registry
451            .scalar_function_overloads(&urn, "upper")
452            .next()
453            .unwrap();
454        assert_eq!(
455            function.return_type,
456            Type::new(
457                TypeKind::VarChar {
458                    length: IntegerParameter::Variable("L".to_string()),
459                },
460                false
461            )
462            .into()
463        );
464    }
465
466    /// The grammar only lexes single-digit `anyN` as a type variable, so
467    /// `any12` is an ordinary named parameter like `P`. This changes if
468    /// https://github.com/substrait-io/substrait/issues/1335 is adopted.
469    #[test]
470    fn test_multi_digit_any_names_are_named_numeric_parameters() {
471        use super::super::{IntegerParameter, Type, TypeKind};
472
473        for name in ["any12", "ANY12"] {
474            let yaml = format!(
475                r#"urn: extension:example.com:numeric_parameters
476scalar_functions:
477  - name: decimal_identity
478    impls:
479      - return: decimal<{name}, 0>
480"#
481            );
482            let file = ExtensionFile::read_from_str(yaml).unwrap();
483            let urn = file.urn().clone();
484            let registry = Registry::new(vec![file]).unwrap();
485            let function = registry
486                .scalar_function_overloads(&urn, "decimal_identity")
487                .next()
488                .unwrap();
489            assert_eq!(
490                function.return_type,
491                Type::new(
492                    TypeKind::Decimal {
493                        precision: IntegerParameter::Variable(name.to_string()),
494                        scale: IntegerParameter::Literal(0),
495                    },
496                    false
497                )
498                .into(),
499                "{name}"
500            );
501        }
502    }
503
504    #[cfg(feature = "extensions")]
505    #[test]
506    fn test_core_function_with_nested_symbolic_return() {
507        use super::super::{IntegerParameter, Type, TypeKind};
508
509        let registry = Registry::from_core_extensions();
510        let urn = Urn::from_str("extension:io.substrait:functions_string").unwrap();
511        let function = registry
512            .get_scalar_function(&urn, "regexp_match_substring_all:vchar_vchar_i64_i64")
513            .expect("regexp_match_substring_all should not be skipped because it returns List<varchar<L1>>");
514        assert_eq!(
515            function.return_type,
516            Type::list(
517                Type::new(
518                    TypeKind::VarChar {
519                        length: IntegerParameter::Variable("L1".to_string()),
520                    },
521                    false,
522                ),
523                false,
524            )
525            .into()
526        );
527    }
528
529    #[test]
530    fn test_function_type_returns() {
531        use super::super::{Type, TypeKind};
532
533        let yaml = r#"urn: extension:example.com:function_types
534scalar_functions:
535  - name: transform_values
536    impls:
537      - args:
538          - value: func<any1 -> any2>
539            name: transformer
540        return: func<any1 -> any2>
541"#;
542        let file = ExtensionFile::read_from_str(yaml).unwrap();
543        let urn = file.urn().clone();
544        let registry = Registry::new(vec![file]).unwrap();
545        let function = registry
546            .scalar_function_overloads(&urn, "transform_values")
547            .next()
548            .unwrap();
549        assert_eq!(
550            function.return_type,
551            Type::new(
552                TypeKind::Func {
553                    parameters: vec![Type::new(TypeKind::Variable { id: 1 }, false)],
554                    return_type: Box::new(Type::new(TypeKind::Variable { id: 2 }, false)),
555                },
556                false,
557            )
558            .into()
559        );
560    }
561
562    #[test]
563    fn test_nested_return_preserves_object_arguments() {
564        use super::super::{Type, TypeKind, argument::ArgumentsItem};
565        use crate::text::simple_extensions as raw;
566
567        let yaml = r#"urn: extension:example.com:nested
568scalar_functions:
569  - name: wrap_field
570    impls:
571      - args:
572          - value: {field: any1}
573        return: list<any1>
574"#;
575        let file = ExtensionFile::read_from_str(yaml).unwrap();
576        let urn = file.urn().clone();
577        let registry = Registry::new(vec![file]).unwrap();
578        let function = registry
579            .scalar_function_overloads(&urn, "wrap_field")
580            .next()
581            .unwrap();
582        assert_eq!(
583            function.return_type,
584            Type::list(Type::new(TypeKind::Variable { id: 1 }, false), false).into()
585        );
586        let ArgumentsItem::ValueArgument(argument) = function.args[0].clone() else {
587            panic!("expected value argument");
588        };
589        let argument: raw::ValueArg = argument.into();
590        let raw::Type::Object(fields) = argument.value else {
591            panic!("expected object-form type to be preserved");
592        };
593        assert_eq!(
594            fields["field"],
595            serde_json::Value::String("any1".to_string())
596        );
597    }
598
599    #[test]
600    fn test_missing_symbolic_type_reference() {
601        let raw = extension_with_custom_type_reference(
602            "extension:example.com:missing",
603            "wrap",
604            "list<u!missing<any1>>",
605            vec![],
606        );
607        assert!(matches!(
608            ExtensionFile::create(raw),
609            Err(SimpleExtensionsError::UnresolvedTypeReference { type_name }) if type_name == "missing"
610        ));
611    }
612
613    #[test]
614    fn test_get_scalar_function_by_signature() {
615        let yaml = r#"urn: extension:example.com:signatures
616scalar_functions:
617  - name: example
618    impls:
619      - args:
620          - options: [FIRST, SECOND]
621          - type: any1
622          - value: decimal?<P1, S1>
623          - value: {field: i32}
624        return: i32
625      - args:
626          - value: varchar<L1>
627        variadic:
628          min: 1
629        return: i64
630      - return: boolean
631"#;
632        let file = ExtensionFile::read_from_str(yaml).unwrap();
633        let urn = file.urn().clone();
634        let registry = Registry::new(vec![file]).unwrap();
635        let return_type = |signature| {
636            registry
637                .get_scalar_function(&urn, signature)
638                .map(|function| function.return_type.to_string())
639        };
640
641        assert_eq!(
642            return_type("example:req_type_dec_struct").as_deref(),
643            Some("i32")
644        );
645        assert_eq!(return_type("example:vchar").as_deref(), Some("i64"));
646        assert_eq!(return_type("example:").as_deref(), Some("boolean"));
647        assert_eq!(return_type("example"), None);
648        assert_eq!(return_type("example:vchar_vchar"), None);
649        assert_eq!(return_type("missing:vchar"), None);
650        assert_eq!(
651            registry.scalar_function_overloads(&urn, "example").count(),
652            3
653        );
654    }
655
656    #[test]
657    fn test_duplicate_scalar_function_signatures_are_rejected() {
658        let same_function = r#"urn: extension:example.com:duplicates
659scalar_functions:
660  - name: example
661    impls:
662      - args:
663          - value: varchar<L1>
664        return: i32
665      - args:
666          - value: varchar<10>
667        return: i64
668"#;
669        let repeated_name = r#"urn: extension:example.com:duplicates
670scalar_functions:
671  - name: example
672    impls:
673      - args:
674          - value: i32
675        return: i32
676  - name: example
677    impls:
678      - args:
679          - value: i32?
680        return: i32
681"#;
682        for yaml in [same_function, repeated_name] {
683            assert!(matches!(
684                ExtensionFile::read_from_str(yaml),
685                Err(SimpleExtensionsError::DuplicateFunctionSignature { signature })
686                    if signature == "example:vchar" || signature == "example:i32"
687            ));
688        }
689    }
690
691    #[cfg(feature = "extensions")]
692    #[test]
693    fn test_core_scalar_function_signatures() {
694        let registry = Registry::from_core_extensions();
695        for (urn, signature) in [
696            ("functions_arithmetic", "add:i32_i32"),
697            ("functions_string", "concat:vchar"),
698            ("functions_datetime", "extract:req_pts"),
699            ("functions_geometry", "make_line:u!geometry_u!geometry"),
700        ] {
701            let urn = Urn::from_str(&format!("extension:io.substrait:{urn}")).unwrap();
702            assert!(
703                registry.get_scalar_function(&urn, signature).is_some(),
704                "{signature}"
705            );
706        }
707    }
708
709    #[test]
710    fn test_missing_argument_type_reference() {
711        for argument in [
712            "value: u!missing",
713            "value: list<u!missing>",
714            "value: {field: u!missing}",
715            "type: u!missing",
716        ] {
717            let yaml = format!(
718                r#"urn: extension:example.com:missing_argument
719scalar_functions:
720  - name: example
721    impls:
722      - args:
723          - {argument}
724        return: i32
725"#
726            );
727            assert!(
728                matches!(
729                    ExtensionFile::read_from_str(&yaml),
730                    Err(SimpleExtensionsError::UnresolvedTypeReference { type_name }) if type_name == "missing"
731                ),
732                "{argument}"
733            );
734        }
735    }
736
737    #[test]
738    fn invalid_argument_type_is_reported() {
739        let yaml = r#"urn: extension:example.com:invalid_argument
740scalar_functions:
741  - name: example
742    impls:
743      - args:
744          - value: varchr<L1>
745        return: i32
746"#;
747        assert!(matches!(
748            ExtensionFile::read_from_str(yaml),
749            Err(SimpleExtensionsError::ScalarFunctionError(
750                ScalarFunctionError::ArgumentError(ArgumentsItemError::InvalidType(_))
751            ))
752        ));
753    }
754
755    #[test]
756    fn invalid_return_parameter_is_reported_even_with_a_valid_overload() {
757        use super::super::type_parser::TypeParseError;
758
759        for return_type in ["varchar<i32>", "list<1>"] {
760            let yaml = format!(
761                r#"urn: extension:example.com:invalid_overload
762scalar_functions:
763  - name: example
764    impls:
765      - return: i32
766      - return: {return_type}
767"#
768            );
769            assert!(
770                matches!(
771                    ExtensionFile::read_from_str(&yaml),
772                    Err(SimpleExtensionsError::ScalarFunctionError(
773                        ScalarFunctionError::TypeError(
774                            ExtensionTypeError::InvalidParameterKind { .. }
775                        ) | ScalarFunctionError::TypeParseError(TypeParseError::ExpectedInteger(_))
776                    ))
777                ),
778                "{return_type}"
779            );
780        }
781    }
782
783    #[test]
784    fn test_unsupported_numeric_returns_are_still_skipped() {
785        for return_type in [
786            "varchar<unknown(L, 1)>",
787            "decimal<P = 2, S>",
788            "varchar<L + unknown(S, 6)>",
789        ] {
790            let raw = extension_with_custom_type_reference(
791                "extension:example.com:unsupported",
792                "unsupported",
793                return_type,
794                vec![],
795            );
796            let file = ExtensionFile::create(raw).unwrap();
797            assert!(
798                file.extension()
799                    .scalar_function_overloads("unsupported")
800                    .next()
801                    .is_none()
802            );
803        }
804    }
805
806    #[test]
807    fn functions_with_calls_after_addition_are_retained() {
808        let source = "varchar<L + min(S, 6)>";
809        let raw = extension_with_custom_type_reference(
810            "extension:example.com:numeric_calls",
811            "append",
812            source,
813            vec![],
814        );
815        let file = ExtensionFile::create(raw).unwrap();
816        let function = file
817            .extension()
818            .scalar_function_overloads("append")
819            .next()
820            .unwrap();
821        assert_eq!(function.return_type.to_string(), source);
822    }
823
824    #[test]
825    fn multiplication_and_division_returns_are_retained() {
826        for return_type in [
827            "varchar<L * 2>",
828            "decimal<(P + 1) / 2, S>",
829            "varchar<L / 0>",
830        ] {
831            let raw = extension_with_custom_type_reference(
832                "extension:example.com:arithmetic",
833                "arithmetic",
834                return_type,
835                vec![],
836            );
837            let file = ExtensionFile::create(raw).unwrap();
838            let function = file
839                .extension()
840                .scalar_function_overloads("arithmetic")
841                .next()
842                .unwrap();
843            assert_eq!(function.return_type.to_string(), return_type);
844        }
845    }
846
847    #[test]
848    fn integer_parameter_requires_an_argument_name() {
849        use super::super::type_parser::TypeParseError;
850        use super::super::{IntegerParameter, ReturnType, Type, TypeKind};
851
852        let raw = extension_with_custom_type_reference(
853            "extension:example.com:argument_reference",
854            "argument_reference",
855            "varchar<integer_parameter(length)>",
856            vec![],
857        );
858        let file = ExtensionFile::create(raw).unwrap();
859        let function = file
860            .extension()
861            .scalar_function_overloads("argument_reference")
862            .next()
863            .unwrap();
864        assert_eq!(
865            function.return_type,
866            ReturnType {
867                assignments: vec![],
868                return_type: Type::new(
869                    TypeKind::VarChar {
870                        length: IntegerParameter::ValueArgumentReference {
871                            name: "length".into()
872                        },
873                    },
874                    false,
875                ),
876            },
877        );
878
879        let raw = extension_with_custom_type_reference(
880            "extension:example.com:invalid_argument_reference",
881            "invalid_argument_reference",
882            "varchar<integer_parameter(3)>",
883            vec![],
884        );
885        assert!(matches!(
886            ExtensionFile::create(raw),
887            Err(SimpleExtensionsError::ScalarFunctionError(
888                ScalarFunctionError::TypeParseError(TypeParseError::ExpectedArgumentName(_))
889            ))
890        ));
891    }
892
893    #[test]
894    fn incorrect_numeric_call_argument_counts_are_reported() {
895        use super::super::type_parser::TypeParseError;
896
897        let raw = extension_with_custom_type_reference(
898            "extension:example.com:invalid_call",
899            "invalid_call",
900            "varchar<min(L)>",
901            vec![],
902        );
903        assert!(matches!(
904            ExtensionFile::create(raw),
905            Err(SimpleExtensionsError::ScalarFunctionError(
906                ScalarFunctionError::TypeParseError(TypeParseError::InvalidArgumentCount {
907                    function,
908                    expected: 2,
909                    actual: 1,
910                })
911            )) if function == "min"
912        ));
913    }
914
915    #[test]
916    fn malformed_addition_returns_are_reported() {
917        use super::super::type_parser::TypeParseError;
918
919        let raw = extension_with_custom_type_reference(
920            "extension:example.com:malformed",
921            "malformed",
922            "varchar<L +>",
923            vec![],
924        );
925        assert!(matches!(
926            ExtensionFile::create(raw),
927            Err(SimpleExtensionsError::ScalarFunctionError(
928                ScalarFunctionError::TypeParseError(TypeParseError::Syntax { .. })
929            ))
930        ));
931    }
932
933    #[test]
934    fn test_function_with_addition_in_return_type_is_retained() {
935        use super::super::{BinaryOp, IntegerParameter, Type, TypeKind};
936
937        let yaml = r#"urn: extension:example.com:numeric_expressions
938scalar_functions:
939  - name: append_space
940    impls:
941      - args:
942          - name: input
943            value: varchar<L>
944        return: varchar<L + 1>
945"#;
946        let file = ExtensionFile::read_from_str(yaml).unwrap();
947        let function = file
948            .extension()
949            .scalar_function_overloads("append_space")
950            .next()
951            .unwrap();
952        let expected = Type::new(
953            TypeKind::VarChar {
954                length: IntegerParameter::BinaryExpression {
955                    op: BinaryOp::Add,
956                    left: Box::new(IntegerParameter::Variable("L".into())),
957                    right: Box::new(IntegerParameter::Literal(1)),
958                },
959            },
960            false,
961        );
962
963        assert_eq!(function.return_type, expected.into());
964    }
965
966    #[test]
967    fn test_multiline_return_validates_type_references() {
968        let raw = extension_with_custom_type_reference(
969            "extension:example.com:derivations",
970            "derive",
971            "precision = min(P + 1, 38)\nmap<varchar<precision>, u!missing>",
972            vec![],
973        );
974        assert!(matches!(ExtensionFile::create(raw),
975            Err(SimpleExtensionsError::UnresolvedTypeReference { type_name }) if type_name == "missing"
976        ));
977    }
978
979    #[test]
980    fn nullable_type_assignments_do_not_discard_supported_functions() {
981        for return_type in ["T = point?\nlist<T>", "T = (point?)\nlist<T>"] {
982            let mut raw = extension_with_custom_type_reference(
983                "extension:example.com:unsupported",
984                "unsupported",
985                return_type,
986                vec![],
987            );
988            let mut supported = raw.scalar_functions[0].clone();
989            supported.name = "supported".into();
990            supported.impls[0].return_ = crate::text::simple_extensions::ReturnValue(
991                crate::text::simple_extensions::Type::String("i32".into()),
992            );
993            raw.scalar_functions.push(supported);
994
995            let file = ExtensionFile::create(raw).unwrap();
996            assert!(
997                file.extension()
998                    .scalar_function_overloads("unsupported")
999                    .next()
1000                    .is_none(),
1001                "{return_type}"
1002            );
1003            assert!(
1004                file.extension()
1005                    .scalar_function_overloads("supported")
1006                    .next()
1007                    .is_some(),
1008                "{return_type}"
1009            );
1010        }
1011    }
1012
1013    #[test]
1014    fn unsupported_derivations_do_not_discard_supported_functions() {
1015        for return_type in [
1016            "1 > 0 ? i32 : i64",
1017            "(1 > 0 ? i32 : i64)",
1018            "T = i32\nlist<T>",
1019            "T = 1 > 0 ? i32 : i64\nlist<T>",
1020            "T = 1 > 0 ? (1 > 0 ? i32 : i64) : i64\nlist<T>",
1021            "T = IF 1 > 0 THEN i32 ELSE i64\nlist<T>",
1022            "T = IF 1 > 0 THEN (IF 1 > 0 THEN i32 ELSE i64) ELSE i64\nlist<T>",
1023            "1 > 0 ? (1 > 0 ? i32 : i64) : i64",
1024            "1 > 0 ? i32 : (1 > 0 ? i32 : i64)",
1025            "IF 1 > 0 THEN i32 ELSE i64",
1026            "IF 1 > 0 THEN (IF 1 > 0 THEN i32 ELSE i64) ELSE i64",
1027            "is_wide = P > 18\ndecimal<18, 0>",
1028        ] {
1029            let mut raw = extension_with_custom_type_reference(
1030                "extension:example.com:unsupported",
1031                "unsupported",
1032                return_type,
1033                vec![],
1034            );
1035            let mut supported = raw.scalar_functions[0].clone();
1036            supported.name = "supported".into();
1037            supported.impls[0].return_ = crate::text::simple_extensions::ReturnValue(
1038                crate::text::simple_extensions::Type::String("i32".into()),
1039            );
1040            raw.scalar_functions.push(supported);
1041
1042            let file = ExtensionFile::create(raw).unwrap();
1043            assert!(
1044                file.extension()
1045                    .scalar_function_overloads("unsupported")
1046                    .next()
1047                    .is_none(),
1048                "{return_type}"
1049            );
1050            assert!(
1051                file.extension()
1052                    .scalar_function_overloads("supported")
1053                    .next()
1054                    .is_some(),
1055                "{return_type}"
1056            );
1057        }
1058    }
1059
1060    #[test]
1061    fn test_multiline_return_is_retained() {
1062        use super::super::{
1063            Assignment, AssignmentValue, IntegerParameter, NumericFunction, ReturnType, Type,
1064            TypeKind,
1065        };
1066
1067        let raw = extension_with_custom_type_reference(
1068            "extension:example.com:derivations",
1069            "derive",
1070            "precision = min(P, 38)\ndecimal<precision, 0>",
1071            vec![],
1072        );
1073        let file = ExtensionFile::create(raw).unwrap();
1074        let function = file
1075            .extension()
1076            .scalar_function_overloads("derive")
1077            .next()
1078            .unwrap();
1079        let ReturnType {
1080            assignments,
1081            return_type,
1082        } = &function.return_type;
1083        let precision = IntegerParameter::Call {
1084            function: NumericFunction::Min,
1085            arguments: vec![
1086                IntegerParameter::Variable("P".into()),
1087                IntegerParameter::Literal(38),
1088            ],
1089        };
1090        assert_eq!(
1091            assignments,
1092            &vec![Assignment {
1093                name: "precision".into(),
1094                value: AssignmentValue::Integer(precision)
1095            }]
1096        );
1097        assert_eq!(
1098            return_type,
1099            &Type::new(
1100                TypeKind::Decimal {
1101                    precision: IntegerParameter::Variable("precision".into()),
1102                    scale: IntegerParameter::Literal(0),
1103                },
1104                false,
1105            )
1106        );
1107    }
1108
1109    #[cfg(feature = "extensions")]
1110    #[test]
1111    fn test_core_scalar_declarations_parse_without_skipping() {
1112        use super::super::{ReturnType, Type};
1113        use crate::text::simple_extensions::{ArgumentsItem, Type as RawType};
1114        use std::collections::HashMap;
1115
1116        for (urn, raw) in crate::extensions::EXTENSIONS.iter() {
1117            let file = ExtensionFile::create(raw.clone()).unwrap();
1118            let mut expected_counts = HashMap::new();
1119            for function in &raw.scalar_functions {
1120                *expected_counts.entry(&function.name).or_insert(0) += function.impls.len();
1121                for implementation in &function.impls {
1122                    let RawType::String(source) = &implementation.return_.0 else {
1123                        panic!("unsupported object return in {urn}/{}", function.name);
1124                    };
1125                    ReturnType::parse(source)
1126                        .unwrap_or_else(|error| panic!("{urn}/{} return: {error}", function.name));
1127                    for argument in implementation.args.iter().flat_map(|args| &args.0) {
1128                        let source = match argument {
1129                            ArgumentsItem::ValueArg(argument) => {
1130                                let RawType::String(source) = &argument.value else {
1131                                    panic!(
1132                                        "unsupported object argument in {urn}/{}",
1133                                        function.name
1134                                    );
1135                                };
1136                                source
1137                            }
1138                            ArgumentsItem::TypeArg(argument) => &argument.type_,
1139                            ArgumentsItem::EnumerationArg(_) => continue,
1140                        };
1141                        Type::parse(source).unwrap_or_else(|error| {
1142                            panic!("{urn}/{} argument: {error}", function.name)
1143                        });
1144                    }
1145                }
1146            }
1147            assert_eq!(
1148                file.extension().scalar_functions().count(),
1149                expected_counts.values().sum::<usize>(),
1150                "{urn}"
1151            );
1152            for (name, expected) in expected_counts {
1153                assert_eq!(
1154                    file.extension().scalar_function_overloads(name).count(),
1155                    expected,
1156                    "{urn}/{name}"
1157                );
1158            }
1159        }
1160    }
1161
1162    #[cfg(feature = "extensions")]
1163    #[test]
1164    fn test_scalar_function_parses_completely() {
1165        use super::super::{
1166            argument::ArgumentsItem,
1167            scalar_functions::{NullabilityHandling, Options, ScalarFunctionVariant},
1168            types::*,
1169        };
1170        use crate::parse::Parse;
1171        use crate::text::simple_extensions;
1172        use std::collections::HashMap;
1173
1174        let registry = Registry::from_core_extensions();
1175        let functions_arithmetic_urn =
1176            Urn::from_str("extension:io.substrait:functions_arithmetic").unwrap();
1177
1178        let add = registry
1179            .get_scalar_function(&functions_arithmetic_urn, "add:i8_i8")
1180            .expect("add:i8_i8 should exist");
1181
1182        let mut ctx = super::super::extensions::TypeContext::default();
1183        let expected = ScalarFunctionVariant {
1184            name: "add".to_string(),
1185            description: Some("Add two values.".to_string()),
1186            args: vec![
1187                ArgumentsItem::ValueArgument(
1188                    simple_extensions::ValueArg {
1189                        name: Some("x".to_string()),
1190                        description: None,
1191                        value: simple_extensions::Type::String("i8".to_string()),
1192                        constant: None,
1193                    }
1194                    .parse(&mut ctx)
1195                    .unwrap(),
1196                ),
1197                ArgumentsItem::ValueArgument(
1198                    simple_extensions::ValueArg {
1199                        name: Some("y".to_string()),
1200                        description: None,
1201                        value: simple_extensions::Type::String("i8".to_string()),
1202                        constant: None,
1203                    }
1204                    .parse(&mut ctx)
1205                    .unwrap(),
1206                ),
1207            ],
1208            options: Options({
1209                let mut map = HashMap::new();
1210                map.insert(
1211                    "overflow".to_string(),
1212                    vec![
1213                        "SILENT".to_string(),
1214                        "SATURATE".to_string(),
1215                        "ERROR".to_string(),
1216                    ],
1217                );
1218                map
1219            }),
1220            variadic: None,
1221            session_dependent: false,
1222            deterministic: true,
1223            nullability: NullabilityHandling::Mirror,
1224            return_type: Type::new(TypeKind::I8, false).into(),
1225            implementation: HashMap::new(),
1226        };
1227
1228        assert_eq!(add, &expected);
1229    }
1230}