Skip to main content

substrait/parse/text/simple_extensions/
types.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Owned type expressions used by the extension registry.
4
5use super::argument::{
6    EnumOptions as ParsedEnumOptions, EnumOptionsError as ParsedEnumOptionsError,
7};
8use super::boolean_expr::BooleanExpr;
9use super::extensions::TypeContext;
10use super::type_parser::TypeParseError;
11use crate::parse::Parse;
12use crate::text::simple_extensions::{
13    EnumOptions as RawEnumOptions, SimpleExtensionsTypesItem, Type as RawType, TypeParamDefs,
14    TypeParamDefsItem, TypeParamDefsItemType,
15};
16use indexmap::IndexMap;
17use serde_json::Value;
18use std::convert::TryFrom;
19use std::fmt;
20use std::ops::RangeInclusive;
21use thiserror::Error;
22
23/// Write a sequence of items separated by a separator, with a start and end
24/// delimiter.
25///
26/// Start and end are only included in the output if there is at least one item.
27fn write_separated<I, T>(
28    f: &mut fmt::Formatter<'_>,
29    iter: I,
30    start: &str,
31    end: &str,
32    sep: &str,
33) -> fmt::Result
34where
35    I: IntoIterator<Item = T>,
36    T: fmt::Display,
37{
38    let mut it = iter.into_iter();
39    if let Some(first) = it.next() {
40        f.write_str(start)?;
41        write!(f, "{first}")?;
42        for item in it {
43            f.write_str(sep)?;
44            write!(f, "{item}")?;
45        }
46        f.write_str(end)
47    } else {
48        Ok(())
49    }
50}
51
52/// A pair of a key and a value, separated by a separator. For display purposes.
53struct KeyValueDisplay<K, V>(K, V, &'static str);
54
55impl<K, V> fmt::Display for KeyValueDisplay<K, V>
56where
57    K: fmt::Display,
58    V: fmt::Display,
59{
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "{}{}{}", self.0, self.2, self.1)
62    }
63}
64
65/// The structure of a type expression, without its nullability.
66#[derive(Clone, Debug, PartialEq)]
67pub enum TypeKind {
68    /// Boolean type - `boolean`
69    Boolean,
70    /// 8-bit signed integer - `i8`
71    I8,
72    /// 16-bit signed integer - `i16`
73    I16,
74    /// 32-bit signed integer - `i32`
75    I32,
76    /// 64-bit signed integer - `i64`
77    I64,
78    /// 32-bit floating point - `fp32`
79    Fp32,
80    /// 64-bit floating point - `fp64`
81    Fp64,
82    /// Variable-length string - `string`
83    String,
84    /// Variable-length binary data - `binary`
85    Binary,
86    /// Calendar date - `date`
87    Date,
88    /// Year-month interval - `interval_year`
89    IntervalYear,
90    /// 128-bit UUID - `uuid`
91    Uuid,
92    /// Fixed-length character string: `fixedchar<L>`
93    FixedChar {
94        /// Length (number of characters), must be >= 1
95        length: IntegerParameter,
96    },
97    /// Variable-length character string: `varchar<L>`
98    VarChar {
99        /// Maximum length (number of characters), must be >= 1
100        length: IntegerParameter,
101    },
102    /// Fixed-length binary data: `fixedbinary<L>`
103    FixedBinary {
104        /// Length (number of bytes), must be >= 1
105        length: IntegerParameter,
106    },
107    /// Fixed-point decimal: `decimal<P, S>`
108    Decimal {
109        /// Precision (total digits), <= 38
110        precision: IntegerParameter,
111        /// Scale (digits after decimal point), 0 <= S <= P
112        scale: IntegerParameter,
113    },
114    /// Time with sub-second precision: `precision_time<P>`
115    PrecisionTime {
116        /// Sub-second precision digits (0-12: seconds to picoseconds)
117        precision: IntegerParameter,
118    },
119    /// Timestamp with sub-second precision: `precision_timestamp<P>`
120    PrecisionTimestamp {
121        /// Sub-second precision digits (0-12: seconds to picoseconds)
122        precision: IntegerParameter,
123    },
124    /// Timezone-aware timestamp with precision: `precision_timestamp_tz<P>`
125    PrecisionTimestampTz {
126        /// Sub-second precision digits (0-12: seconds to picoseconds)
127        precision: IntegerParameter,
128    },
129    /// Day-time interval: `interval_day<P>`
130    IntervalDay {
131        /// Sub-second precision digits (0-9: seconds to nanoseconds)
132        precision: IntegerParameter,
133    },
134    /// Compound interval: `interval_compound<P>`
135    IntervalCompound {
136        /// Sub-second precision digits
137        precision: IntegerParameter,
138    },
139    /// Extension type with optional parameters
140    Extension {
141        /// Extension type name
142        name: String,
143        /// Type parameters
144        parameters: Vec<TypeParameter>,
145    },
146    /// List type with element type
147    List(Box<Type>),
148    /// Map type with key and value types
149    Map {
150        /// Key type
151        key: Box<Type>,
152        /// Value type
153        value: Box<Type>,
154    },
155    /// Struct type (ordered fields without names)
156    Struct(Vec<Type>),
157    /// Named struct type (nstruct - ordered fields with names)
158    NamedStruct {
159        /// Ordered field names and types. They are in the order they should
160        /// appear in the struct - hence the use of [`IndexMap`].
161        fields: IndexMap<String, Type>,
162    },
163    /// A function type: `func<(P1, P2) -> R>`
164    Func {
165        /// Parameter types in declaration order
166        parameters: Vec<Type>,
167        /// The return type
168        return_type: Box<Type>,
169    },
170    /// An unnumbered wildcard, such as `any`.
171    Any,
172    /// A numbered type variable, such as `any1`.
173    Variable {
174        /// The variable identifier shared within a function signature.
175        id: u32,
176    },
177}
178
179impl TypeKind {
180    /// Check if a string is a valid name for a builtin scalar type
181    pub fn is_name(name: &str) -> bool {
182        let lower = name.to_ascii_lowercase();
183        primitive_builtin(&lower).is_some()
184            || matches!(
185                lower.as_str(),
186                "fixedchar"
187                    | "varchar"
188                    | "fixedbinary"
189                    | "decimal"
190                    | "precision_time"
191                    | "precision_timestamp"
192                    | "precision_timestamp_tz"
193                    | "interval_day"
194                    | "interval_compound"
195            )
196    }
197
198    /// The short name of this type in a function signature, such as `vchar` for
199    /// `varchar<L1>` or `any` for `any1`.
200    ///
201    /// See <https://substrait.io/extensions/#type-short-names>.
202    pub fn short_name(&self) -> String {
203        let short_name = match self {
204            TypeKind::Boolean => "bool",
205            TypeKind::I8 => "i8",
206            TypeKind::I16 => "i16",
207            TypeKind::I32 => "i32",
208            TypeKind::I64 => "i64",
209            TypeKind::Fp32 => "fp32",
210            TypeKind::Fp64 => "fp64",
211            TypeKind::String => "str",
212            TypeKind::Binary => "vbin",
213            TypeKind::Date => "date",
214            TypeKind::IntervalYear => "iyear",
215            TypeKind::Uuid => "uuid",
216            TypeKind::FixedChar { .. } => "fchar",
217            TypeKind::VarChar { .. } => "vchar",
218            TypeKind::FixedBinary { .. } => "fbin",
219            TypeKind::Decimal { .. } => "dec",
220            TypeKind::PrecisionTime { .. } => "pt",
221            TypeKind::PrecisionTimestamp { .. } => "pts",
222            TypeKind::PrecisionTimestampTz { .. } => "ptstz",
223            TypeKind::IntervalDay { .. } => "iday",
224            TypeKind::IntervalCompound { .. } => "icompound",
225            TypeKind::Extension { name, .. } => return format!("u!{name}"),
226            TypeKind::List(_) => "list",
227            TypeKind::Map { .. } => "map",
228            TypeKind::Struct(_) | TypeKind::NamedStruct { .. } => "struct",
229            TypeKind::Func { .. } => "func",
230            TypeKind::Any | TypeKind::Variable { .. } => "any",
231        };
232        short_name.to_string()
233    }
234
235    fn fmt_with_nullability(&self, f: &mut fmt::Formatter<'_>, nullable: bool) -> fmt::Result {
236        let nullability = if nullable { "?" } else { "" };
237        let name = match self {
238            Self::Boolean => "boolean",
239            Self::I8 => "i8",
240            Self::I16 => "i16",
241            Self::I32 => "i32",
242            Self::I64 => "i64",
243            Self::Fp32 => "fp32",
244            Self::Fp64 => "fp64",
245            Self::String => "string",
246            Self::Binary => "binary",
247            Self::Date => "date",
248            Self::IntervalYear => "interval_year",
249            Self::Uuid => "uuid",
250            Self::FixedChar { .. } => "fixedchar",
251            Self::VarChar { .. } => "varchar",
252            Self::FixedBinary { .. } => "fixedbinary",
253            Self::Decimal { .. } => "decimal",
254            Self::PrecisionTime { .. } => "precision_time",
255            Self::PrecisionTimestamp { .. } => "precision_timestamp",
256            Self::PrecisionTimestampTz { .. } => "precision_timestamp_tz",
257            Self::IntervalDay { .. } => "interval_day",
258            Self::IntervalCompound { .. } => "interval_compound",
259            Self::List(_) => "list",
260            Self::Map { .. } => "map",
261            Self::Struct(_) => "struct",
262            Self::Func { .. } => "func",
263            Self::Extension { name, parameters } => {
264                write!(f, "u!{name}{nullability}")?;
265                return write_separated(f, parameters.iter(), "<", ">", ", ");
266            }
267            Self::NamedStruct { fields } => {
268                let fields = fields
269                    .iter()
270                    .map(|(name, field)| KeyValueDisplay(name, field, ": "));
271                write_separated(f, fields, "{", "}", ", ")?;
272                return f.write_str(nullability);
273            }
274            Self::Any => return write!(f, "any{nullability}"),
275            Self::Variable { id } => return write!(f, "any{id}{nullability}"),
276        };
277        write!(f, "{name}{nullability}")?;
278        match self {
279            Self::FixedChar { length }
280            | Self::VarChar { length }
281            | Self::FixedBinary { length } => {
282                write!(f, "<{length}>")
283            }
284            Self::Decimal { precision, scale } => write!(f, "<{precision}, {scale}>"),
285            Self::PrecisionTime { precision }
286            | Self::PrecisionTimestamp { precision }
287            | Self::PrecisionTimestampTz { precision }
288            | Self::IntervalDay { precision }
289            | Self::IntervalCompound { precision } => write!(f, "<{precision}>"),
290            Self::List(element) => write!(f, "<{element}>"),
291            Self::Map { key, value } => write!(f, "<{key}, {value}>"),
292            Self::Struct(fields) => {
293                f.write_str("<")?;
294                write_separated(f, fields.iter(), "", "", ", ")?;
295                f.write_str(">")
296            }
297            Self::Func {
298                parameters,
299                return_type,
300            } => {
301                if parameters.len() == 1 {
302                    write!(f, "<{} -> {return_type}>", parameters[0])
303                } else {
304                    f.write_str("<(")?;
305                    write_separated(f, parameters.iter(), "", "", ", ")?;
306                    write!(f, ") -> {return_type}>")
307                }
308            }
309            _ => Ok(()),
310        }
311    }
312}
313
314/// Formats the full type spelling used in extension YAML, not the short name
315/// used in function signatures (e.g., `precision_timestamp<3>`, not `pts`).
316impl fmt::Display for TypeKind {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        self.fmt_with_nullability(f, false)
319    }
320}
321
322/// A binary operator in an unevaluated numeric expression.
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324pub enum BinaryOp {
325    /// Integer addition.
326    Add,
327    /// Integer subtraction.
328    Subtract,
329    /// Integer multiplication.
330    Multiply,
331    /// Integer division.
332    Divide,
333}
334
335impl BinaryOp {
336    fn precedence(self) -> u8 {
337        match self {
338            Self::Add | Self::Subtract => 3,
339            Self::Multiply | Self::Divide => 4,
340        }
341    }
342}
343
344impl fmt::Display for BinaryOp {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        match self {
347            Self::Add => f.write_str("+"),
348            Self::Subtract => f.write_str("-"),
349            Self::Multiply => f.write_str("*"),
350            Self::Divide => f.write_str("/"),
351        }
352    }
353}
354
355/// A supported numeric function in an unevaluated type derivation.
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub enum NumericFunction {
358    /// The minimum of two integers.
359    Min,
360    /// The maximum of two integers.
361    Max,
362}
363
364impl fmt::Display for NumericFunction {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        match self {
367            Self::Min => f.write_str("min"),
368            Self::Max => f.write_str("max"),
369        }
370    }
371}
372
373/// An integer literal, named parameter, or unevaluated numeric expression.
374#[derive(Clone, Debug, PartialEq)]
375pub enum IntegerParameter {
376    /// A known integer value.
377    Literal(i64),
378    /// A name whose value depends on a function call.
379    Variable(String),
380    /// An integer supplied by the value of a named function argument.
381    ValueArgumentReference {
382        /// The argument name passed to `integer_parameter`.
383        name: String,
384    },
385    /// A binary expression, retained without evaluation.
386    BinaryExpression {
387        /// The operator applied to the operands.
388        op: BinaryOp,
389        /// The left operand.
390        left: Box<Self>,
391        /// The right operand.
392        right: Box<Self>,
393    },
394    /// A ternary conditional, retained without selecting a branch.
395    Conditional {
396        /// The condition to test when evaluating the derivation.
397        condition: Box<BooleanExpr>,
398        /// The value when the condition is true.
399        then_value: Box<Self>,
400        /// The value when the condition is false.
401        else_value: Box<Self>,
402    },
403    /// A supported numeric function call, retained without evaluation.
404    Call {
405        /// The numeric function being called.
406        function: NumericFunction,
407        /// Ordered numeric arguments.
408        arguments: Vec<Self>,
409    },
410}
411
412impl IntegerParameter {
413    /// Returns whether this parameter is a literal rather than an unresolved expression.
414    pub fn is_concrete(&self) -> bool {
415        matches!(self, Self::Literal(_))
416    }
417}
418
419impl IntegerParameter {
420    fn precedence(&self) -> u8 {
421        match self {
422            Self::Conditional { .. } => 1,
423            Self::BinaryExpression { op, .. } => op.precedence(),
424            _ => 5,
425        }
426    }
427
428    fn fmt_with_precedence(&self, f: &mut fmt::Formatter<'_>, minimum: u8) -> fmt::Result {
429        let precedence = self.precedence();
430        let needs_parentheses = precedence < minimum;
431        if needs_parentheses {
432            f.write_str("(")?;
433        }
434        match self {
435            Self::Literal(value) => write!(f, "{value}"),
436            Self::Variable(name) => f.write_str(name),
437            Self::ValueArgumentReference { name } => write!(f, "integer_parameter({name})"),
438            Self::Call {
439                function,
440                arguments,
441            } => {
442                write!(f, "{function}(")?;
443                for (index, argument) in arguments.iter().enumerate() {
444                    if index > 0 {
445                        f.write_str(", ")?;
446                    }
447                    write!(f, "{argument}")?;
448                }
449                f.write_str(")")
450            }
451            Self::BinaryExpression { op, left, right } => {
452                left.fmt_with_precedence(f, precedence)?;
453                write!(f, " {op} ")?;
454                right.fmt_with_precedence(f, precedence + 1)
455            }
456            Self::Conditional {
457                condition,
458                then_value,
459                else_value,
460            } => {
461                write!(f, "({condition})")?;
462                write!(f, " ? {then_value} : ")?;
463                else_value.fmt_with_precedence(f, precedence + 1)
464            }
465        }?;
466        if needs_parentheses {
467            f.write_str(")")?;
468        }
469        Ok(())
470    }
471}
472
473impl fmt::Display for IntegerParameter {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        self.fmt_with_precedence(f, 0)
476    }
477}
478
479/// A parameter, used in parameterized types
480#[derive(Clone, Debug, PartialEq)]
481pub enum TypeParameter {
482    /// Integer parameter (e.g., precision, scale)
483    Integer(IntegerParameter),
484    /// Type parameter (nested type)
485    Type(Type),
486    /// A name whose parameter kind depends on the user-defined type declaration.
487    Name(String),
488    // TODO: Add support for other type parameters, as described in
489    // https://github.com/substrait-io/substrait/blob/35101020d961eda48f8dd1aafbc794c9e5cac077/proto/substrait/type.proto#L250-L265
490}
491
492impl TypeParameter {
493    /// Returns whether this parameter contains no unresolved variables.
494    pub fn is_concrete(&self) -> bool {
495        match self {
496            Self::Integer(parameter) => parameter.is_concrete(),
497            Self::Type(type_) => type_.is_concrete(),
498            Self::Name(_) => false,
499        }
500    }
501}
502
503impl fmt::Display for TypeParameter {
504    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505        match self {
506            TypeParameter::Integer(i) => write!(f, "{i}"),
507            TypeParameter::Type(t) => write!(f, "{t}"),
508            TypeParameter::Name(name) => f.write_str(name),
509        }
510    }
511}
512
513/// Parse a primitive (no type parameters) builtin type name
514pub(super) fn primitive_builtin(lower_name: &str) -> Option<TypeKind> {
515    match lower_name {
516        "bool" | "boolean" => Some(TypeKind::Boolean),
517        "i8" => Some(TypeKind::I8),
518        "i16" => Some(TypeKind::I16),
519        "i32" => Some(TypeKind::I32),
520        "i64" => Some(TypeKind::I64),
521        "fp32" => Some(TypeKind::Fp32),
522        "fp64" => Some(TypeKind::Fp64),
523        "string" => Some(TypeKind::String),
524        "binary" => Some(TypeKind::Binary),
525        "date" => Some(TypeKind::Date),
526        "interval_year" => Some(TypeKind::IntervalYear),
527        "uuid" => Some(TypeKind::Uuid),
528        _ => None,
529    }
530}
531
532/// Parameter type information for type definitions
533#[derive(Clone, Debug, PartialEq)]
534pub enum ParameterConstraint {
535    /// Data type parameter
536    DataType,
537    /// Integer parameter with range constraints
538    Integer {
539        /// Minimum value (inclusive), if specified
540        min: Option<i64>,
541        /// Maximum value (inclusive), if specified
542        max: Option<i64>,
543    },
544    /// Enumeration parameter
545    Enumeration {
546        /// Valid enumeration values (validated, deduplicated)
547        options: ParsedEnumOptions,
548    },
549    /// Boolean parameter
550    Boolean,
551    /// String parameter
552    String,
553}
554
555impl ParameterConstraint {
556    /// Convert back to raw TypeParamDefsItemType
557    fn raw_type(&self) -> TypeParamDefsItemType {
558        match self {
559            ParameterConstraint::DataType => TypeParamDefsItemType::DataType,
560            ParameterConstraint::Boolean => TypeParamDefsItemType::Boolean,
561            ParameterConstraint::Integer { .. } => TypeParamDefsItemType::Integer,
562            ParameterConstraint::Enumeration { .. } => TypeParamDefsItemType::Enumeration,
563            ParameterConstraint::String => TypeParamDefsItemType::String,
564        }
565    }
566
567    /// Extract raw bounds for integer parameters (min, max)
568    fn raw_bounds(&self) -> (Option<f64>, Option<f64>) {
569        match self {
570            ParameterConstraint::Integer { min, max } => {
571                (min.map(|i| i as f64), max.map(|i| i as f64))
572            }
573            _ => (None, None),
574        }
575    }
576
577    /// Extract raw enum options for enumeration parameters
578    fn raw_options(&self) -> Option<RawEnumOptions> {
579        match self {
580            ParameterConstraint::Enumeration { options } => Some(options.clone().into()),
581            _ => None,
582        }
583    }
584
585    /// Check if a parameter value is valid for this parameter type
586    pub fn is_valid_value(&self, value: &Value) -> bool {
587        match (self, value) {
588            (ParameterConstraint::DataType, Value::String(_)) => true,
589            (ParameterConstraint::Integer { min, max }, Value::Number(n)) => {
590                if let Some(i) = n.as_i64() {
591                    min.is_none_or(|min_val| i >= min_val) && max.is_none_or(|max_val| i <= max_val)
592                } else {
593                    false
594                }
595            }
596            (ParameterConstraint::Enumeration { options }, Value::String(s)) => options.contains(s),
597            (ParameterConstraint::Boolean, Value::Bool(_)) => true,
598            (ParameterConstraint::String, Value::String(_)) => true,
599            _ => false,
600        }
601    }
602
603    fn from_raw(
604        t: TypeParamDefsItemType,
605        opts: Option<RawEnumOptions>,
606        min: Option<f64>,
607        max: Option<f64>,
608    ) -> Result<Self, TypeParamError> {
609        Ok(match t {
610            TypeParamDefsItemType::DataType => Self::DataType,
611            TypeParamDefsItemType::Boolean => Self::Boolean,
612            TypeParamDefsItemType::Integer => {
613                match (min, max) {
614                    (Some(min_f), _) if min_f.fract() != 0.0 => {
615                        return Err(TypeParamError::InvalidIntegerBounds { min, max });
616                    }
617                    (_, Some(max_f)) if max_f.fract() != 0.0 => {
618                        return Err(TypeParamError::InvalidIntegerBounds { min, max });
619                    }
620                    _ => (),
621                }
622
623                let min_i = min.map(|v| v as i64);
624                let max_i = max.map(|v| v as i64);
625                Self::Integer {
626                    min: min_i,
627                    max: max_i,
628                }
629            }
630            TypeParamDefsItemType::Enumeration => {
631                let options: ParsedEnumOptions =
632                    opts.ok_or(TypeParamError::MissingEnumOptions)?.try_into()?;
633                Self::Enumeration { options }
634            }
635            TypeParamDefsItemType::String => Self::String,
636        })
637    }
638}
639
640/// A validated type parameter with name and constraints
641#[derive(Clone, Debug, PartialEq)]
642pub struct TypeParam {
643    /// Parameter name (e.g., "K" for a type variable)
644    pub name: String,
645    /// Parameter type constraints
646    pub param_type: ParameterConstraint,
647    /// Human-readable description
648    pub description: Option<String>,
649}
650
651impl TypeParam {
652    /// Create a new type parameter
653    pub fn new(name: String, param_type: ParameterConstraint, description: Option<String>) -> Self {
654        Self {
655            name,
656            param_type,
657            description,
658        }
659    }
660
661    /// Check if a parameter value is valid
662    pub fn is_valid_value(&self, value: &Value) -> bool {
663        self.param_type.is_valid_value(value)
664    }
665}
666
667impl TryFrom<TypeParamDefsItem> for TypeParam {
668    type Error = TypeParamError;
669
670    fn try_from(item: TypeParamDefsItem) -> Result<Self, Self::Error> {
671        let name = item.name.ok_or(TypeParamError::MissingName)?;
672        let param_type =
673            ParameterConstraint::from_raw(item.type_, item.options, item.min, item.max)?;
674
675        Ok(Self {
676            name,
677            param_type,
678            description: item.description,
679        })
680    }
681}
682
683/// Error types for extension type validation
684#[derive(Debug, Error, PartialEq)]
685pub enum ExtensionTypeError {
686    /// Extension type name is invalid
687    #[error("{0}")]
688    InvalidName(#[from] InvalidTypeName),
689    /// Any type variable is invalid for concrete types
690    #[error("Any type variable is invalid for concrete types: any{}{}", id, nullability.then_some("?").unwrap_or(""))]
691    InvalidAnyTypeVariable {
692        /// The type variable name
693        id: u32,
694        /// Whether the type variable is nullable
695        nullability: bool,
696    },
697    /// Type variables or named numeric parameters are not supported in this context.
698    #[error("Type '{type_string}' must be concrete in this context")]
699    ExpectedConcreteType {
700        /// The type expression containing unresolved parameters.
701        type_string: String,
702    },
703    /// Unknown type name (not a builtin, missing u! prefix for extension types)
704    #[error("Unknown type name: '{name}'. Extension types must use the u! prefix (e.g., u!{name})")]
705    UnknownTypeName {
706        /// The unknown type name
707        name: String,
708    },
709    /// Parameter validation failed
710    #[error("Invalid parameter: {0}")]
711    InvalidParameter(#[from] TypeParamError),
712    /// Field type is invalid
713    #[error("Invalid structure field type: {0}")]
714    InvalidFieldType(String),
715    /// Duplicate struct field name
716    #[error("Duplicate struct field '{field_name}'")]
717    DuplicateFieldName {
718        /// The duplicated field name
719        field_name: String,
720    },
721    /// Type parameter count is invalid for the given type name
722    #[error("Type '{type_name}' expects {expected} parameters, got {actual}")]
723    InvalidParameterCount {
724        /// The type name being validated
725        type_name: String,
726        /// Expected number of parameters
727        expected: usize,
728        /// The actual number of parameters provided
729        actual: usize,
730    },
731    /// Type parameter is of the wrong kind for the given position
732    #[error("Type '{type_name}' parameter {index} must be {expected}")]
733    InvalidParameterKind {
734        /// The type name being validated
735        type_name: String,
736        /// Zero-based index of the offending parameter
737        index: usize,
738        /// Expected parameter kind (e.g., integer, type)
739        expected: &'static str,
740    },
741    /// Provided parameter value does not fit within the expected bounds
742    #[error("Type '{type_name}' parameter {index} value {value} is not within {expected}")]
743    InvalidParameterValue {
744        /// The type name being validated
745        type_name: String,
746        /// Zero-based index of the offending parameter
747        index: usize,
748        /// Provided parameter value
749        value: i64,
750        /// Description of the expected range or type
751        expected: &'static str,
752    },
753    /// Provided parameter value does not fit within the expected bounds
754    #[error("Type '{type_name}' parameter {index} value {value} is out of range {expected:?}")]
755    InvalidParameterRange {
756        /// The type name being validated
757        type_name: String,
758        /// Zero-based index of the offending parameter
759        index: usize,
760        /// Provided parameter value
761        value: i64,
762        /// Description of the expected range or type
763        expected: RangeInclusive<i32>,
764    },
765    /// Structure representation cannot be nullable
766    #[error("Structure representation cannot be nullable: {type_string}")]
767    StructureCannotBeNullable {
768        /// The type string that was nullable
769        type_string: String,
770    },
771    /// Error parsing type
772    #[error("Error parsing type: {0}")]
773    ParseType(#[from] TypeParseError),
774}
775
776/// Error types for TypeParam validation
777#[derive(Debug, Error, PartialEq)]
778pub enum TypeParamError {
779    /// Parameter name is missing
780    #[error("Parameter name is required")]
781    MissingName,
782    /// Integer parameter has non-integer min/max values
783    #[error("Integer parameter has invalid min/max values: min={min:?}, max={max:?}")]
784    InvalidIntegerBounds {
785        /// The invalid minimum value
786        min: Option<f64>,
787        /// The invalid maximum value
788        max: Option<f64>,
789    },
790    /// Enumeration parameter is missing options
791    #[error("Enumeration parameter is missing options")]
792    MissingEnumOptions,
793    /// Enumeration parameter has invalid options
794    #[error("Enumeration parameter has invalid options: {0}")]
795    InvalidEnumOptions(#[from] ParsedEnumOptionsError),
796}
797
798/// A validated Simple Extension type definition
799#[derive(Clone, Debug, PartialEq)]
800pub struct CustomType {
801    /// Type name
802    pub name: String,
803    /// Type parameters (e.g., for generic types)
804    pub parameters: Vec<TypeParam>,
805    /// Structure definition, if any
806    pub structure: Option<Type>,
807    /// Whether this type can have variadic parameters
808    pub variadic: Option<bool>,
809    /// Human-readable description
810    pub description: Option<String>,
811}
812
813impl CustomType {
814    /// Check if this type name is valid according to Substrait naming rules
815    /// (see the `Identifier` rule in `substrait/grammar/SubstraitLexer.g4`).
816    /// Identifiers are case-insensitive and must start with a an ASCII letter,
817    /// `_`, or `$`, followed by ASCII letters, digits, `_`, or `$`.
818    //
819    // Note: I'm not sure if `$` is actually something we want to allow, or if
820    // `_` is, but it's in the grammar so I'm allowing it here.
821    pub fn validate_name(name: &str) -> Result<(), InvalidTypeName> {
822        let mut chars = name.chars();
823        let first = chars
824            .next()
825            .ok_or_else(|| InvalidTypeName(name.to_string()))?;
826        if !(first.is_ascii_alphabetic() || first == '_' || first == '$') {
827            return Err(InvalidTypeName(name.to_string()));
828        }
829
830        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') {
831            return Err(InvalidTypeName(name.to_string()));
832        }
833
834        Ok(())
835    }
836
837    /// Create a new custom type with validation
838    pub fn new(
839        name: String,
840        parameters: Vec<TypeParam>,
841        structure: Option<Type>,
842        variadic: Option<bool>,
843        description: Option<String>,
844    ) -> Result<Self, ExtensionTypeError> {
845        Self::validate_name(&name)?;
846
847        Ok(Self {
848            name,
849            parameters,
850            structure,
851            variadic,
852            description,
853        })
854    }
855}
856
857impl From<CustomType> for SimpleExtensionsTypesItem {
858    fn from(value: CustomType) -> Self {
859        // Convert parameters back to TypeParamDefs if any
860        let parameters = if value.parameters.is_empty() {
861            None
862        } else {
863            Some(TypeParamDefs(
864                value
865                    .parameters
866                    .into_iter()
867                    .map(|param| {
868                        let (min, max) = param.param_type.raw_bounds();
869                        TypeParamDefsItem {
870                            name: Some(param.name),
871                            description: param.description,
872                            type_: param.param_type.raw_type(),
873                            min,
874                            max,
875                            options: param.param_type.raw_options(),
876                            // TODO: add this to TypeParamDefsItem parsing, and
877                            // follow it through here. I'm not entirely sure
878                            // when/if it is used.
879                            optional: None,
880                        }
881                    })
882                    .collect(),
883            ))
884        };
885
886        // Convert structure back to Type if any
887        let structure = value.structure.map(Into::into);
888
889        SimpleExtensionsTypesItem {
890            name: value.name,
891            description: value.description,
892            metadata: Default::default(),
893            parameters,
894            structure,
895            variadic: value.variadic,
896            // Not tracked by `CustomType`; default to no deprecation.
897            deprecated: None,
898        }
899    }
900}
901
902impl Parse<TypeContext> for SimpleExtensionsTypesItem {
903    type Parsed = CustomType;
904    type Error = ExtensionTypeError;
905
906    fn parse(self, ctx: &mut TypeContext) -> Result<Self::Parsed, Self::Error> {
907        let name = self.name;
908        CustomType::validate_name(&name)?;
909
910        // Register this type as found
911        ctx.found(&name);
912
913        let parameters = if let Some(param_defs) = self.parameters {
914            param_defs
915                .0
916                .into_iter()
917                .map(TypeParam::try_from)
918                .collect::<Result<Vec<_>, _>>()?
919        } else {
920            Vec::new()
921        };
922
923        // Parse structure with context, so referenced extension types are recorded as linked
924        let structure = match self.structure {
925            Some(structure_data) => {
926                let parsed = Parse::parse(structure_data, ctx)?;
927                // TODO: check that the structure is valid. The `Type::Object`
928                // form of `structure_data` is by definition a non-nullable `NSTRUCT`; however,
929                // what types allowed under the `Type::String` form is less clear in the spec:
930                // See https://github.com/substrait-io/substrait/issues/920.
931                Some(parsed)
932            }
933            None => None,
934        };
935
936        Ok(CustomType {
937            name,
938            parameters,
939            structure,
940            variadic: self.variadic,
941            description: self.description,
942        })
943    }
944}
945
946impl Parse<TypeContext> for RawType {
947    type Parsed = Type;
948    type Error = ExtensionTypeError;
949
950    fn parse(self, ctx: &mut TypeContext) -> Result<Self::Parsed, Self::Error> {
951        match self {
952            RawType::String(type_string) => {
953                let parsed_type = expect_concrete_type(Type::parse(&type_string)?)?;
954                let mut link = |name: &str| ctx.linked(name);
955                parsed_type.visit_references(&mut link);
956                Ok(parsed_type)
957            }
958            RawType::Object(field_map) => {
959                let structure = expect_concrete_type(parse_struct_type(field_map)?)?;
960                structure.visit_references(&mut |name| ctx.linked(name));
961                Ok(structure)
962            }
963        }
964    }
965}
966
967/// Invalid type name error
968#[derive(Debug, Error, PartialEq)]
969#[error("invalid type name `{0}`")]
970pub struct InvalidTypeName(String);
971
972/// A type expression with nullability.
973#[derive(Clone, Debug, PartialEq)]
974pub struct Type {
975    /// The type expression
976    pub kind: TypeKind,
977    /// Whether this type is nullable
978    pub nullable: bool,
979}
980
981impl Type {
982    /// Parse a type declaration, retaining variables and derivations without evaluation.
983    pub fn parse(source: &str) -> Result<Self, ExtensionTypeError> {
984        super::type_parser::parse(source)
985    }
986
987    /// Visit extension type references, including those nested in parameters.
988    pub fn visit_references(&self, on_ext: &mut impl FnMut(&str)) {
989        match &self.kind {
990            TypeKind::Extension { name, parameters } => {
991                on_ext(name);
992                for parameter in parameters {
993                    if let TypeParameter::Type(ty) = parameter {
994                        ty.visit_references(on_ext);
995                    }
996                }
997            }
998            TypeKind::List(element) => element.visit_references(on_ext),
999            TypeKind::Map { key, value } => {
1000                key.visit_references(on_ext);
1001                value.visit_references(on_ext);
1002            }
1003            TypeKind::Struct(fields) => {
1004                for field in fields {
1005                    field.visit_references(on_ext);
1006                }
1007            }
1008            TypeKind::NamedStruct { fields } => {
1009                for field in fields.values() {
1010                    field.visit_references(on_ext);
1011                }
1012            }
1013            TypeKind::Func {
1014                parameters,
1015                return_type,
1016            } => {
1017                for parameter in parameters {
1018                    parameter.visit_references(on_ext);
1019                }
1020                return_type.visit_references(on_ext);
1021            }
1022            _ => {}
1023        }
1024    }
1025
1026    /// Create a type expression with the given nullability.
1027    pub fn new(kind: TypeKind, nullable: bool) -> Type {
1028        Type { kind, nullable }
1029    }
1030
1031    /// Create a new extension type reference (without parameters)
1032    pub fn extension(name: String, nullable: bool) -> Type {
1033        Type {
1034            kind: TypeKind::Extension {
1035                name,
1036                parameters: Vec::new(),
1037            },
1038            nullable,
1039        }
1040    }
1041
1042    /// Create a new parameterized extension type
1043    pub fn extension_with_params(
1044        name: String,
1045        parameters: Vec<TypeParameter>,
1046        nullable: bool,
1047    ) -> Type {
1048        Type {
1049            kind: TypeKind::Extension { name, parameters },
1050            nullable,
1051        }
1052    }
1053
1054    /// Create a new list type
1055    pub fn list(element_type: Type, nullable: bool) -> Type {
1056        Type {
1057            kind: TypeKind::List(Box::new(element_type)),
1058            nullable,
1059        }
1060    }
1061
1062    /// Create a new struct type (ordered fields without names)
1063    pub fn r#struct(field_types: Vec<Type>, nullable: bool) -> Type {
1064        Type {
1065            kind: TypeKind::Struct(field_types),
1066            nullable,
1067        }
1068    }
1069
1070    /// Create a new map type
1071    pub fn map(key_type: Type, value_type: Type, nullable: bool) -> Type {
1072        Type {
1073            kind: TypeKind::Map {
1074                key: Box::new(key_type),
1075                value: Box::new(value_type),
1076            },
1077            nullable,
1078        }
1079    }
1080
1081    /// Create a new named struct type (nstruct - ordered fields with names)
1082    pub fn named_struct(fields: IndexMap<String, Type>, nullable: bool) -> Type {
1083        Type {
1084            kind: TypeKind::NamedStruct { fields },
1085            nullable,
1086        }
1087    }
1088
1089    /// Returns whether this type contains no unresolved variables.
1090    pub fn is_concrete(&self) -> bool {
1091        match &self.kind {
1092            TypeKind::Any | TypeKind::Variable { .. } => false,
1093            TypeKind::FixedChar { length }
1094            | TypeKind::VarChar { length }
1095            | TypeKind::FixedBinary { length } => length.is_concrete(),
1096            TypeKind::Decimal { precision, scale } => {
1097                precision.is_concrete() && scale.is_concrete()
1098            }
1099            TypeKind::PrecisionTime { precision }
1100            | TypeKind::PrecisionTimestamp { precision }
1101            | TypeKind::PrecisionTimestampTz { precision }
1102            | TypeKind::IntervalDay { precision }
1103            | TypeKind::IntervalCompound { precision } => precision.is_concrete(),
1104            TypeKind::List(element) => element.is_concrete(),
1105            TypeKind::Map { key, value } => key.is_concrete() && value.is_concrete(),
1106            TypeKind::Struct(fields) => fields.iter().all(Type::is_concrete),
1107            TypeKind::NamedStruct { fields } => fields.values().all(Type::is_concrete),
1108            TypeKind::Func {
1109                parameters,
1110                return_type,
1111            } => parameters.iter().all(Type::is_concrete) && return_type.is_concrete(),
1112            TypeKind::Extension { parameters, .. } => {
1113                parameters.iter().all(TypeParameter::is_concrete)
1114            }
1115            _ => true,
1116        }
1117    }
1118
1119    /// Check if this type (as a function argument) is compatible with another
1120    /// type (as an input).
1121    ///
1122    /// Does not bind type variables or symbolic parameters.
1123    /// Mainly checks nullability:
1124    ///   - `i64?` is compatible with `i64` and `i64?` - both can be passed as
1125    ///     arguments
1126    ///   - `i64` is compatible with `i64` but NOT `i64?` - you can't pass a
1127    ///     nullable type to a function that only accepts non-nullable arguments
1128    pub fn is_compatible_with(&self, other: &Type) -> bool {
1129        // Types must match exactly, but nullable types can accept non-nullable values
1130        self.kind == other.kind && (self.nullable || !other.nullable)
1131    }
1132}
1133
1134/// Formats full extension-YAML spellings, not function-signature short names.
1135impl fmt::Display for Type {
1136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1137        self.kind.fmt_with_nullability(f, self.nullable)
1138    }
1139}
1140
1141impl From<Type> for RawType {
1142    fn from(val: Type) -> Self {
1143        match val.kind {
1144            TypeKind::NamedStruct { fields } => RawType::Object(
1145                fields
1146                    .into_iter()
1147                    .map(|(name, ty)| (name, serde_json::Value::String(ty.to_string())))
1148                    .collect(),
1149            ),
1150            _ => RawType::String(val.to_string()),
1151        }
1152    }
1153}
1154
1155/// Validate a built-in numeric parameter, retaining symbolic expressions unchanged.
1156pub(super) fn validate_integer_parameter(
1157    type_name: &str,
1158    index: usize,
1159    parameter: IntegerParameter,
1160    range: Option<RangeInclusive<i32>>,
1161) -> Result<IntegerParameter, ExtensionTypeError> {
1162    let IntegerParameter::Literal(value) = parameter else {
1163        return Ok(parameter);
1164    };
1165    let value = i32::try_from(value).map_err(|_| ExtensionTypeError::InvalidParameterValue {
1166        type_name: type_name.to_string(),
1167        index,
1168        value,
1169        expected: "an i32",
1170    })?;
1171
1172    if let Some(range) = range {
1173        if range.contains(&value) {
1174            return Ok(IntegerParameter::Literal(i64::from(value)));
1175        }
1176        return Err(ExtensionTypeError::InvalidParameterRange {
1177            type_name: type_name.to_string(),
1178            index,
1179            value: i64::from(value),
1180            expected: range,
1181        });
1182    }
1183
1184    Ok(IntegerParameter::Literal(i64::from(value)))
1185}
1186
1187/// Parse an inline struct such as `{x: i32, y: i32}`.
1188pub(super) fn parse_struct_type(
1189    field_map: IndexMap<String, serde_json::Value>,
1190) -> Result<Type, ExtensionTypeError> {
1191    // Type structure in Substrait must preserve field order (see
1192    // substrait-io/substrait#915). The typify generation uses
1193    // IndexMap to retain the YAML order so that the order of the
1194    // fields in the structure matches that of the extensions file.
1195    let mut fields = IndexMap::new();
1196
1197    for (field_name, field_type_value) in field_map {
1198        let type_string = match field_type_value {
1199            serde_json::Value::String(s) => s,
1200            _ => {
1201                return Err(ExtensionTypeError::InvalidFieldType(
1202                    "Struct field types must be strings".to_string(),
1203                ));
1204            }
1205        };
1206
1207        let field_type = Type::parse(&type_string)?;
1208
1209        if fields.insert(field_name.clone(), field_type).is_some() {
1210            return Err(ExtensionTypeError::DuplicateFieldName { field_name });
1211        }
1212    }
1213
1214    Ok(Type {
1215        kind: TypeKind::NamedStruct { fields },
1216        nullable: false,
1217    })
1218}
1219
1220/// Require a concrete type for extension structures.
1221fn expect_concrete_type(parsed: Type) -> Result<Type, ExtensionTypeError> {
1222    if let TypeKind::Variable { id } = parsed.kind {
1223        return Err(ExtensionTypeError::InvalidAnyTypeVariable {
1224            id,
1225            nullability: parsed.nullable,
1226        });
1227    }
1228    if !parsed.is_concrete() {
1229        return Err(ExtensionTypeError::ExpectedConcreteType {
1230            type_string: parsed.to_string(),
1231        });
1232    }
1233    Ok(parsed)
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238    use super::super::extensions::TypeContext;
1239    use super::super::type_parser::parse_integer_parameter as parse_integer_expression;
1240    use super::*;
1241    use crate::parse::text::simple_extensions::argument::EnumOptions as ParsedEnumOptions;
1242    use crate::text::simple_extensions;
1243    use std::iter::FromIterator;
1244
1245    /// Wrap a type kind without a nullable annotation.
1246    fn required_type(kind: TypeKind) -> Type {
1247        Type::new(kind, false)
1248    }
1249
1250    /// Parse a string into a [Type]
1251    fn parse_type(expr: &str) -> Type {
1252        Type::parse(expr).unwrap()
1253    }
1254
1255    /// Parse a string into a [Type], returning the result
1256    fn parse_type_result(expr: &str) -> Result<Type, ExtensionTypeError> {
1257        Type::parse(expr)
1258    }
1259
1260    /// Parse a string into a builtin [Type], with no unresolved
1261    /// extension references
1262    fn parse_simple(s: &str) -> Type {
1263        let parsed = parse_type(s);
1264
1265        let mut refs = Vec::new();
1266        parsed.visit_references(&mut |name| refs.push(name.to_string()));
1267        assert!(refs.is_empty(), "{s} should not add an extension reference");
1268
1269        parsed
1270    }
1271
1272    #[test]
1273    fn test_visit_references_builtin_case_insensitive() {
1274        let cases = vec![
1275            ("DECIMAL<10,2>", Vec::<String>::new()),
1276            ("List<string>", Vec::<String>::new()),
1277            ("u!custom<i32>", vec!["custom".to_string()]),
1278            ("u!Geo<string>", vec!["Geo".to_string()]),
1279        ];
1280
1281        for (expr, expected_refs) in cases {
1282            let mut refs = Vec::new();
1283            parse_type(expr).visit_references(&mut |name| refs.push(name.to_string()));
1284            assert_eq!(refs, expected_refs, "unexpected references for {expr}");
1285        }
1286    }
1287
1288    #[test]
1289    fn test_visit_references_function_types() {
1290        let mut refs = Vec::new();
1291        parse_type("func<(u!point, any1) -> u!edge?>")
1292            .visit_references(&mut |name| refs.push(name.to_string()));
1293        assert_eq!(refs, vec!["point".to_string(), "edge".to_string()]);
1294    }
1295
1296    #[test]
1297    fn test_visit_references_nested_parameters() {
1298        for (source, expected) in [
1299            (
1300                "u!Box<map<u!Key, list<u!Value>>, P, 2, any1, u!Key>",
1301                vec!["Box", "Key", "Value", "Key"],
1302            ),
1303            ("struct<u!Left, u!Right>", vec!["Left", "Right"]),
1304            (
1305                "func<list<u!Input> -> map<string, u!Output>>",
1306                vec!["Input", "Output"],
1307            ),
1308        ] {
1309            let mut references = Vec::new();
1310            parse_type(source).visit_references(&mut |name| references.push(name.to_string()));
1311            assert_eq!(references, expected, "{source}");
1312        }
1313    }
1314
1315    #[test]
1316    fn test_visit_references_programmatically_constructed_named_struct() {
1317        let ty = Type::named_struct(
1318            IndexMap::from([
1319                (
1320                    "z".to_string(),
1321                    Type::r#struct(vec![Type::extension("First".to_string(), false)], false),
1322                ),
1323                (
1324                    "a".to_string(),
1325                    Type::list(Type::extension("Second".to_string(), true), false),
1326                ),
1327            ]),
1328            false,
1329        );
1330        let mut references = Vec::new();
1331        ty.visit_references(&mut |name| references.push(name.to_string()));
1332        assert_eq!(references, vec!["First", "Second"]);
1333    }
1334
1335    #[test]
1336    fn grouped_additions_preserve_the_type_on_roundtrip() {
1337        for source in [
1338            "varchar<L + (M + 1)>",
1339            "varchar<L + (M + (N + 1))>",
1340            "list<decimal<P + (Q + 1), S>>",
1341        ] {
1342            let original = parse_type(source);
1343            assert_eq!(parse_type(&original.to_string()), original, "{source}");
1344        }
1345    }
1346
1347    #[test]
1348    fn parenthesized_extension_parameter_names_preserve_their_kind() {
1349        let original = parse_type("u!foo<(P)>");
1350        assert_eq!(
1351            original,
1352            Type::extension_with_params("foo".into(), vec![TypeParameter::Name("P".into())], false)
1353        );
1354        assert_eq!(parse_type(&original.to_string()), original);
1355    }
1356
1357    #[test]
1358    fn multiplication_and_division_display_roundtrips() {
1359        for source in [
1360            "P + S * 2",
1361            "P * S + 2",
1362            "(P + S) * 2",
1363            "P * (S + 2)",
1364            "P / S / 2",
1365            "P / (S / 2)",
1366            "P / (S * 2)",
1367            "P * (S / 2)",
1368            "P - S / 2",
1369            "(P - S) / 2",
1370            "P / -2",
1371            "P * -2",
1372            "P / 0",
1373            "9223372036854775807 * 2",
1374        ] {
1375            let original = parse_type(&format!("varchar<{source}>"));
1376            assert_eq!(original.to_string(), format!("varchar<{source}>"));
1377            assert_eq!(parse_type(&original.to_string()), original, "{source}");
1378        }
1379    }
1380
1381    #[test]
1382    fn integer_expression_display_roundtrips() {
1383        for source in [
1384            "P + S + 1",
1385            "P + (S + 1)",
1386            "P - (S + 1)",
1387            "P + (S - 1)",
1388            "P - (S - 1)",
1389            "P - -1",
1390            "min(P, 38)",
1391            "max(S1, S2)",
1392            "integer_parameter(precision)",
1393            "min(max(P1 - S1, P2 - S2) + 1, 38)",
1394            "P + S + (1 + (T + 2))",
1395            "$P + _S",
1396            "P + -2",
1397            "9223372036854775807 + 1",
1398        ] {
1399            let expression = parse_integer_expression(source).unwrap();
1400            assert_eq!(expression.to_string(), source);
1401        }
1402    }
1403
1404    #[test]
1405    fn conditional_expression_display_roundtrips() {
1406        for source in [
1407            "(P > 38 ? 38 : P) + 1",
1408            "P * 2 > S / 2 ? P / 2 : S * 2",
1409            "(P > 38 ? 38 : P) * 2",
1410            "P / (S > 1 ? S : 1)",
1411            "P - (S > 38 ? 38 : S)",
1412            "P > 1 ? (S > 1 ? 1 : 2) : 3",
1413            "P > 1 ? 1 : (S > 1 ? 2 : 3)",
1414            "min(P > 38 ? 38 : P, 10)",
1415        ] {
1416            let expression = parse_integer_expression(source).unwrap();
1417            assert_eq!(
1418                parse_integer_expression(&expression.to_string()).unwrap(),
1419                expression
1420            );
1421        }
1422    }
1423
1424    #[test]
1425    fn integer_expression_display_normalizes_whitespace() {
1426        for (source, expected) in [("L+1", "L + 1"), (" $P + _S ", "$P + _S")] {
1427            let expression = parse_integer_expression(source).unwrap();
1428            assert_eq!(expression.to_string(), expected, "{source}");
1429        }
1430    }
1431
1432    #[test]
1433    fn test_numeric_parameter_expressions() {
1434        assert_eq!(
1435            parse_type("decimal<P1 + P2, S>"),
1436            required_type(TypeKind::Decimal {
1437                precision: IntegerParameter::BinaryExpression {
1438                    op: BinaryOp::Add,
1439                    left: Box::new(IntegerParameter::Variable("P1".into())),
1440                    right: Box::new(IntegerParameter::Variable("P2".into())),
1441                },
1442                scale: IntegerParameter::Variable("S".into()),
1443            })
1444        );
1445    }
1446
1447    #[test]
1448    fn test_expression_literals_still_validate_ranges() {
1449        for source in ["decimal<(0), 0>", "decimal<(39), 0>", "decimal<10, (11)>"] {
1450            assert!(
1451                matches!(
1452                    parse_type_result(source),
1453                    Err(ExtensionTypeError::InvalidParameterRange { .. })
1454                ),
1455                "{source}"
1456            );
1457        }
1458    }
1459
1460    #[test]
1461    fn test_numeric_expression_type_display() {
1462        for (source, expected) in [
1463            ("varchar<L+1>", "varchar<L + 1>"),
1464            ("varchar<L + (M + 1)>", "varchar<L + (M + 1)>"),
1465            ("varchar<(L)>", "varchar<L>"),
1466            ("decimal<(P1 + P2), (S + 1)>", "decimal<P1 + P2, S + 1>"),
1467            ("list<decimal<P + 1, S>>", "list<decimal<P + 1, S>>"),
1468            (
1469                "func<varchar<L + 1> -> decimal<P, S + 1>>",
1470                "func<varchar<L + 1> -> decimal<P, S + 1>>",
1471            ),
1472        ] {
1473            assert_eq!(parse_type(source).to_string(), expected, "{source}");
1474        }
1475    }
1476
1477    #[test]
1478    fn test_numeric_expression_types_are_not_concrete() {
1479        for source in [
1480            "varchar<L + 1>",
1481            "varchar<1 + 2>",
1482            "list<decimal<P + 1, S>>",
1483            "func<varchar<L + 1> -> decimal<P, S + 1>>",
1484        ] {
1485            assert!(!parse_type(source).is_concrete(), "{source}");
1486        }
1487    }
1488
1489    #[test]
1490    fn test_numeric_expressions_are_not_type_arguments() {
1491        for source in ["list<P + 1>", "map<i32, P + 1>", "func<P + 1 -> i32>"] {
1492            assert!(parse_type_result(source).is_err(), "{source}");
1493        }
1494    }
1495
1496    #[test]
1497    fn test_numeric_expressions_are_not_concrete_structure_fields() {
1498        let expression = Type::parse("varchar<L + 1>").unwrap();
1499        assert!(matches!(
1500            expect_concrete_type(expression),
1501            Err(ExtensionTypeError::ExpectedConcreteType { .. })
1502        ));
1503    }
1504
1505    #[test]
1506    fn test_literal_and_symbolic_lengths_share_a_type_kind() {
1507        for (length, expected, is_concrete) in [
1508            (IntegerParameter::Literal(20), "varchar<20>", true),
1509            (IntegerParameter::Variable("L".into()), "varchar<L>", false),
1510        ] {
1511            let type_ = Type::new(
1512                TypeKind::VarChar {
1513                    length: length.clone(),
1514                },
1515                false,
1516            );
1517            assert_eq!(type_.to_string(), expected);
1518            assert_eq!(type_.is_concrete(), is_concrete);
1519
1520            let extension = Type::extension_with_params(
1521                "sized".into(),
1522                vec![TypeParameter::Integer(length)],
1523                false,
1524            );
1525            assert_eq!(extension.is_concrete(), is_concrete);
1526        }
1527    }
1528
1529    #[test]
1530    fn test_concreteness_is_recursive() {
1531        let variable = parse_type("any1?");
1532        assert_eq!(variable.to_string(), "any1?");
1533        for field in [
1534            parse_type("i32"),
1535            variable,
1536            Type::new(
1537                TypeKind::VarChar {
1538                    length: IntegerParameter::Variable("L".into()),
1539                },
1540                false,
1541            ),
1542        ] {
1543            let expected = field.is_concrete();
1544            for nested in [
1545                Type::list(field.clone(), false),
1546                Type::map(parse_type("string"), field.clone(), false),
1547                Type::r#struct(vec![field.clone()], false),
1548                Type::named_struct(IndexMap::from([("field".into(), field.clone())]), false),
1549                Type::extension_with_params(
1550                    "wrapper".into(),
1551                    vec![TypeParameter::Type(field)],
1552                    false,
1553                ),
1554            ] {
1555                assert_eq!(
1556                    nested.is_concrete(),
1557                    expected,
1558                    "unexpected concreteness for {nested}"
1559                );
1560            }
1561        }
1562    }
1563
1564    #[test]
1565    fn test_concreteness_does_not_replace_value_validation() {
1566        let type_ = Type::new(
1567            TypeKind::Decimal {
1568                precision: IntegerParameter::Literal(10),
1569                scale: IntegerParameter::Literal(20),
1570            },
1571            false,
1572        );
1573        assert!(type_.is_concrete());
1574        assert!(matches!(
1575            parse_type_result(&type_.to_string()),
1576            Err(ExtensionTypeError::InvalidParameterRange { .. })
1577        ));
1578    }
1579
1580    #[test]
1581    fn test_structure_parsing_still_requires_concrete_types() {
1582        assert!(matches!(
1583            RawType::String("any1?".into()).parse(&mut TypeContext::default()),
1584            Err(ExtensionTypeError::InvalidAnyTypeVariable {
1585                id: 1,
1586                nullability: true
1587            })
1588        ));
1589
1590        let raw = RawType::Object(IndexMap::from([(
1591            "field".into(),
1592            Value::String("any1?".into()),
1593        )]));
1594        assert!(matches!(
1595            raw.parse(&mut TypeContext::default()),
1596            Err(ExtensionTypeError::ExpectedConcreteType { type_string })
1597                if type_string == "{field: any1?}"
1598        ));
1599    }
1600
1601    #[test]
1602    fn test_named_numeric_parameters_remain_unsupported_in_type_structures() {
1603        for raw in [
1604            RawType::String("varchar<L>".into()),
1605            RawType::Object(IndexMap::from([(
1606                "field".into(),
1607                Value::String("decimal<P, S>".into()),
1608            )])),
1609        ] {
1610            assert!(matches!(
1611                raw.parse(&mut TypeContext::default()),
1612                Err(ExtensionTypeError::ExpectedConcreteType { .. })
1613            ));
1614        }
1615    }
1616
1617    #[test]
1618    fn test_extension_integer_parameters_preserve_i64_range() {
1619        let input = format!("u!wide<{}>", i64::MAX);
1620        let parsed = parse_type(&input);
1621        assert!(parsed.is_concrete());
1622        assert_eq!(parsed.to_string(), input);
1623        assert!(matches!(
1624            parse_type_result(&format!("varchar<{}>", i64::MAX)),
1625            Err(ExtensionTypeError::InvalidParameterValue { .. })
1626        ));
1627    }
1628
1629    /// Create a type parameter from a type expression string
1630    fn type_param(expr: &str) -> TypeParameter {
1631        TypeParameter::Type(parse_type(expr))
1632    }
1633
1634    /// Create an extension type
1635    fn extension(name: &str, parameters: Vec<TypeParameter>, nullable: bool) -> Type {
1636        Type::extension_with_params(name.to_string(), parameters, nullable)
1637    }
1638
1639    /// Convert a custom type to raw and back, ensuring round-trip consistency
1640    fn round_trip(custom: &CustomType) {
1641        let item: simple_extensions::SimpleExtensionsTypesItem = custom.clone().into();
1642        let mut ctx = TypeContext::default();
1643        let parsed = Parse::parse(item, &mut ctx).unwrap();
1644        assert_eq!(&parsed, custom);
1645    }
1646
1647    /// Create a raw named struct (e.g. straight from YAML) from field name and
1648    /// type pairs
1649    fn raw_named_struct(fields: &[(&str, &str)]) -> RawType {
1650        RawType::Object(
1651            fields
1652                .iter()
1653                .map(|(name, ty)| ((*name).into(), serde_json::Value::String((*ty).into())))
1654                .collect(),
1655        )
1656    }
1657
1658    #[test]
1659    fn test_builtin_scalar_parsing() {
1660        let cases = vec![
1661            ("bool", Some(TypeKind::Boolean)),
1662            ("i8", Some(TypeKind::I8)),
1663            ("i16", Some(TypeKind::I16)),
1664            ("i32", Some(TypeKind::I32)),
1665            ("i64", Some(TypeKind::I64)),
1666            ("fp32", Some(TypeKind::Fp32)),
1667            ("fp64", Some(TypeKind::Fp64)),
1668            ("STRING", Some(TypeKind::String)),
1669            ("binary", Some(TypeKind::Binary)),
1670            ("uuid", Some(TypeKind::Uuid)),
1671            ("date", Some(TypeKind::Date)),
1672            ("interval_year", Some(TypeKind::IntervalYear)),
1673            ("invalid", None),
1674        ];
1675
1676        for (input, expected) in cases {
1677            let result = primitive_builtin(&input.to_ascii_lowercase());
1678            match expected {
1679                Some(expected_type) => {
1680                    assert_eq!(
1681                        result,
1682                        Some(expected_type),
1683                        "expected builtin type for {input}"
1684                    );
1685                }
1686                None => {
1687                    assert!(result.is_none(), "expected parsing {input} to fail");
1688                }
1689            }
1690        }
1691    }
1692
1693    #[test]
1694    fn test_nested_symbolic_types() {
1695        assert_eq!(
1696            parse_type("List<any>"),
1697            Type::list(required_type(TypeKind::Any), false)
1698        );
1699        assert_eq!(
1700            parse_type("Map<string, any?>"),
1701            Type::map(parse_type("string"), Type::new(TypeKind::Any, true), false)
1702        );
1703        assert_eq!(
1704            parse_type("List?<DECIMAL<P, S>>"),
1705            Type::list(parse_type("decimal<P, S>"), true)
1706        );
1707        assert_eq!(
1708            parse_type("Map<string, precision_timestamp<P>>"),
1709            Type::map(
1710                parse_type("string"),
1711                parse_type("precision_timestamp<P>"),
1712                false
1713            )
1714        );
1715        assert_eq!(
1716            parse_type("Struct?<any1, List<Map<string, VARCHAR<L>>>>"),
1717            Type::r#struct(
1718                vec![
1719                    parse_type("any1"),
1720                    parse_type("List<Map<string, VARCHAR<L>>>")
1721                ],
1722                true
1723            )
1724        );
1725        assert_eq!(parse_type("any").to_string(), "any");
1726        assert_eq!(parse_type("Any?").to_string(), "any?");
1727    }
1728
1729    #[test]
1730    fn test_nested_type_concreteness_follows_elements() {
1731        assert!(parse_type("list<decimal<10, 2>>").is_concrete());
1732        assert!(!parse_type("list<any>").is_concrete());
1733    }
1734
1735    #[test]
1736    fn test_function_types() {
1737        for (input, expected) in [
1738            ("func<i32 -> i64>", "func<i32 -> i64>"),
1739            ("FUNC?<any1 -> any2>", "func?<any1 -> any2>"),
1740            (
1741                "func<(i32, list<any1>) -> i64?>",
1742                "func<(i32, list<any1>) -> i64?>",
1743            ),
1744            (
1745                "func<i32 -> func<i64 -> boolean?>>",
1746                "func<i32 -> func<i64 -> boolean?>>",
1747            ),
1748        ] {
1749            let ty = parse_type(input);
1750            assert_eq!(ty.to_string(), expected, "unexpected spelling for {input}");
1751            assert_eq!(
1752                parse_type(&ty.to_string()),
1753                ty,
1754                "round trip failed for {input}"
1755            );
1756        }
1757
1758        assert!(parse_type("func<i32 -> i64>").is_concrete());
1759        assert!(!parse_type("func<any1 -> i64>").is_concrete());
1760        assert!(!parse_type("func<i32 -> any1>").is_concrete());
1761    }
1762
1763    #[test]
1764    fn test_function_parameter_can_be_a_function() {
1765        assert_eq!(
1766            parse_type("func<func<i32 -> i64> -> boolean>"),
1767            required_type(TypeKind::Func {
1768                parameters: vec![parse_type("func<i32 -> i64>")],
1769                return_type: Box::new(parse_type("boolean")),
1770            }),
1771        );
1772    }
1773
1774    #[test]
1775    fn test_list_elements_can_be_functions() {
1776        assert_eq!(
1777            parse_type("list<func<i32 -> i64>>"),
1778            Type::list(parse_type("func<i32 -> i64>"), false),
1779        );
1780    }
1781
1782    #[test]
1783    fn test_function_type_validation() {
1784        for input in ["func<5 -> i64>", "func<i32 -> missing>"] {
1785            assert!(
1786                parse_type_result(input).is_err(),
1787                "{input} should not be accepted as a signature type"
1788            );
1789        }
1790    }
1791
1792    #[test]
1793    fn test_symbolic_user_defined_type_parameters() {
1794        let ty = parse_type("u!Box?<List<decimal<P, S>>, 5, N>");
1795        assert_eq!(
1796            ty,
1797            Type::extension_with_params(
1798                "Box".to_string(),
1799                vec![
1800                    TypeParameter::Type(parse_type("List<decimal<P, S>>")),
1801                    TypeParameter::Integer(IntegerParameter::Literal(5)),
1802                    TypeParameter::Name("N".to_string()),
1803                ],
1804                true,
1805            )
1806        );
1807        assert!(!ty.is_concrete());
1808        assert!(!parse_type("u!Box<5, N>").is_concrete());
1809        assert_eq!(ty.to_string(), "u!Box?<list<decimal<P, S>>, 5, N>");
1810    }
1811
1812    #[test]
1813    fn test_invalid_nested_signature_types() {
1814        for input in [
1815            "List<any1, any2>",
1816            "Map<any1>",
1817            "Struct<1, any1>",
1818            "List<missing_type?>",
1819            "List<decimal<any1>>",
1820            "List<i32<P>>",
1821        ] {
1822            assert!(
1823                parse_type_result(input).is_err(),
1824                "{input} should not be accepted as a signature type"
1825            );
1826        }
1827    }
1828
1829    #[test]
1830    fn reserved_type_names_are_not_integer_parameters() {
1831        for name in [
1832            "i32",
1833            "boolean",
1834            "varchar",
1835            "decimal",
1836            "precision_time",
1837            "list",
1838            "map",
1839            "struct",
1840            "func",
1841            "any",
1842        ] {
1843            for spelling in [name.to_string(), name.to_ascii_uppercase()] {
1844                for source in [
1845                    format!("varchar<{spelling}>"),
1846                    format!("decimal<{spelling}, S>"),
1847                    format!("decimal<P, {spelling}>"),
1848                ] {
1849                    assert!(parse_type_result(&source).is_err(), "{source}");
1850                }
1851            }
1852        }
1853    }
1854
1855    #[test]
1856    fn test_named_integer_parameters() {
1857        let parameter = IntegerParameter::Variable("N".to_string());
1858        for (name, expected) in [
1859            (
1860                "fixedchar",
1861                TypeKind::FixedChar {
1862                    length: parameter.clone(),
1863                },
1864            ),
1865            (
1866                "varchar",
1867                TypeKind::VarChar {
1868                    length: parameter.clone(),
1869                },
1870            ),
1871            (
1872                "fixedbinary",
1873                TypeKind::FixedBinary {
1874                    length: parameter.clone(),
1875                },
1876            ),
1877            (
1878                "precision_time",
1879                TypeKind::PrecisionTime {
1880                    precision: parameter.clone(),
1881                },
1882            ),
1883            (
1884                "precision_timestamp",
1885                TypeKind::PrecisionTimestamp {
1886                    precision: parameter.clone(),
1887                },
1888            ),
1889            (
1890                "precision_timestamp_tz",
1891                TypeKind::PrecisionTimestampTz {
1892                    precision: parameter.clone(),
1893                },
1894            ),
1895            (
1896                "interval_day",
1897                TypeKind::IntervalDay {
1898                    precision: parameter.clone(),
1899                },
1900            ),
1901            (
1902                "interval_compound",
1903                TypeKind::IntervalCompound {
1904                    precision: parameter,
1905                },
1906            ),
1907        ] {
1908            let input = format!("{}?<N>", name.to_ascii_uppercase());
1909            let expression = Type::parse(&input).unwrap();
1910            assert_eq!(
1911                expression,
1912                Type::new(expected, true),
1913                "unexpected type for {input}"
1914            );
1915        }
1916
1917        for (input, precision, scale) in [
1918            (
1919                "decimal<P, S>",
1920                IntegerParameter::Variable("P".into()),
1921                IntegerParameter::Variable("S".into()),
1922            ),
1923            (
1924                "decimal<10, S>",
1925                IntegerParameter::Literal(10),
1926                IntegerParameter::Variable("S".into()),
1927            ),
1928            (
1929                "decimal<P, 2>",
1930                IntegerParameter::Variable("P".into()),
1931                IntegerParameter::Literal(2),
1932            ),
1933        ] {
1934            assert_eq!(
1935                Type::parse(input).unwrap(),
1936                Type::new(TypeKind::Decimal { precision, scale }, false)
1937            );
1938        }
1939    }
1940
1941    #[test]
1942    fn test_named_numeric_parameters_preserve_builtin_validation() {
1943        for input in [
1944            "i32<P>",
1945            "varchar<L, 2>",
1946            "decimal<any1, S>",
1947            "decimal<P?, S>",
1948            "decimal<P<1>, S>",
1949            "decimal<u!P, S>",
1950            "decimal<39, S>",
1951            "decimal<P, 39>",
1952            "precisiontime<P>",
1953            "missing<P>",
1954        ] {
1955            assert!(
1956                parse_type_result(input).is_err(),
1957                "{input} should not be accepted as a signature type"
1958            );
1959        }
1960    }
1961
1962    #[test]
1963    fn test_parameterized_builtin_types() {
1964        let cases = vec![
1965            (
1966                "precision_time<2>",
1967                required_type(TypeKind::PrecisionTime {
1968                    precision: IntegerParameter::Literal(2),
1969                }),
1970            ),
1971            (
1972                "precision_timestamp<1>",
1973                required_type(TypeKind::PrecisionTimestamp {
1974                    precision: IntegerParameter::Literal(1),
1975                }),
1976            ),
1977            (
1978                "precision_timestamp_tz<5>",
1979                required_type(TypeKind::PrecisionTimestampTz {
1980                    precision: IntegerParameter::Literal(5),
1981                }),
1982            ),
1983            (
1984                "DECIMAL<10,2>",
1985                required_type(TypeKind::Decimal {
1986                    precision: IntegerParameter::Literal(10),
1987                    scale: IntegerParameter::Literal(2),
1988                }),
1989            ),
1990            (
1991                "fixedchar<12>",
1992                required_type(TypeKind::FixedChar {
1993                    length: IntegerParameter::Literal(12),
1994                }),
1995            ),
1996            (
1997                "VarChar<42>",
1998                required_type(TypeKind::VarChar {
1999                    length: IntegerParameter::Literal(42),
2000                }),
2001            ),
2002            (
2003                "fixedbinary<8>",
2004                required_type(TypeKind::FixedBinary {
2005                    length: IntegerParameter::Literal(8),
2006                }),
2007            ),
2008            (
2009                "interval_day<7>",
2010                required_type(TypeKind::IntervalDay {
2011                    precision: IntegerParameter::Literal(7),
2012                }),
2013            ),
2014            (
2015                "interval_compound<6>",
2016                required_type(TypeKind::IntervalCompound {
2017                    precision: IntegerParameter::Literal(6),
2018                }),
2019            ),
2020        ];
2021
2022        for (expr, expected) in cases {
2023            let found = parse_simple(expr);
2024            assert_eq!(found, expected, "unexpected type for {expr}");
2025        }
2026    }
2027
2028    #[test]
2029    fn short_names_match_the_spec() {
2030        for (source, short_name) in [
2031            ("boolean", "bool"),
2032            ("i8", "i8"),
2033            ("i16", "i16"),
2034            ("i32?", "i32"),
2035            ("i64", "i64"),
2036            ("fp32", "fp32"),
2037            ("fp64", "fp64"),
2038            ("string", "str"),
2039            ("binary", "vbin"),
2040            ("date", "date"),
2041            ("interval_year", "iyear"),
2042            ("uuid", "uuid"),
2043            ("fixedchar<L1>", "fchar"),
2044            ("varchar<10>", "vchar"),
2045            ("fixedbinary<L1>", "fbin"),
2046            ("decimal<P1, S1>", "dec"),
2047            ("precision_time<P>", "pt"),
2048            ("precision_timestamp<P>", "pts"),
2049            ("precision_timestamp_tz<P>", "ptstz"),
2050            ("interval_day<P>", "iday"),
2051            ("interval_compound<P>", "icompound"),
2052            ("u!point?", "u!point"),
2053            ("list<any1>", "list"),
2054            ("map<string, i32>", "map"),
2055            ("struct<i32, string>", "struct"),
2056            ("func<any1 -> any2>", "func"),
2057            ("any", "any"),
2058            ("any1?", "any"),
2059        ] {
2060            assert_eq!(
2061                Type::parse(source).unwrap().kind.short_name(),
2062                short_name,
2063                "{source}"
2064            );
2065        }
2066    }
2067
2068    #[test]
2069    fn test_parameterized_builtin_range_errors() {
2070        use ExtensionTypeError::InvalidParameterRange;
2071
2072        let cases = vec![
2073            ("precision_time<13>", "precision_time", 0, 13, 0..=12),
2074            ("precision_time<-1>", "precision_time", 0, -1, 0..=12),
2075            (
2076                "precision_timestamp<13>",
2077                "precision_timestamp",
2078                0,
2079                13,
2080                0..=12,
2081            ),
2082            (
2083                "precision_timestamp<-1>",
2084                "precision_timestamp",
2085                0,
2086                -1,
2087                0..=12,
2088            ),
2089            (
2090                "precision_timestamp_tz<20>",
2091                "precision_timestamp_tz",
2092                0,
2093                20,
2094                0..=12,
2095            ),
2096            ("interval_day<10>", "interval_day", 0, 10, 0..=9),
2097            ("DECIMAL<39,0>", "DECIMAL", 0, 39, 1..=38),
2098            ("DECIMAL<0,0>", "DECIMAL", 0, 0, 1..=38),
2099            ("DECIMAL<10,-1>", "DECIMAL", 1, -1, 0..=10),
2100            ("DECIMAL<10,12>", "DECIMAL", 1, 12, 0..=10),
2101        ];
2102
2103        for (expr, expected_type, expected_index, expected_value, expected_range) in cases {
2104            match parse_type_result(expr) {
2105                Ok(value) => panic!("expected error parsing {expr}, got {value:?}"),
2106                Err(InvalidParameterRange {
2107                    type_name,
2108                    index,
2109                    value,
2110                    expected,
2111                }) => {
2112                    assert_eq!(type_name, expected_type, "unexpected type for {expr}");
2113                    assert_eq!(index, expected_index, "unexpected index for {expr}");
2114                    assert_eq!(
2115                        value,
2116                        i64::from(expected_value),
2117                        "unexpected value for {expr}"
2118                    );
2119                    assert_eq!(expected, expected_range, "unexpected range for {expr}");
2120                }
2121                Err(other) => panic!("expected InvalidParameterRange for {expr}, got {other:?}"),
2122            }
2123        }
2124    }
2125
2126    #[test]
2127    fn test_container_types() {
2128        let cases = vec![
2129            (
2130                "List<i32>",
2131                Type::list(Type::new(TypeKind::I32, false), false),
2132            ),
2133            (
2134                "List<fp64?>",
2135                Type::list(Type::new(TypeKind::Fp64, true), false),
2136            ),
2137            (
2138                "Map?<i64, string?>",
2139                Type::map(
2140                    Type::new(TypeKind::I64, false),
2141                    Type::new(TypeKind::String, true),
2142                    true,
2143                ),
2144            ),
2145            (
2146                "Struct?<i8, string?>",
2147                Type::r#struct(
2148                    vec![
2149                        Type::new(TypeKind::I8, false),
2150                        Type::new(TypeKind::String, true),
2151                    ],
2152                    true,
2153                ),
2154            ),
2155        ];
2156
2157        for (expr, expected) in cases {
2158            assert_eq!(parse_type(expr), expected, "unexpected parse for {expr}");
2159        }
2160    }
2161
2162    #[test]
2163    fn test_extension_types() {
2164        let cases = vec![
2165            (
2166                "u!geo<List<i32>, 10>",
2167                extension(
2168                    "geo",
2169                    vec![
2170                        type_param("List<i32>"),
2171                        TypeParameter::Integer(IntegerParameter::Literal(10)),
2172                    ],
2173                    false,
2174                ),
2175            ),
2176            (
2177                "u!Geo?<List<i32?>>",
2178                extension("Geo", vec![type_param("List<i32?>")], true),
2179            ),
2180            (
2181                "u!Custom<string?, boolean>",
2182                extension(
2183                    "Custom",
2184                    vec![
2185                        type_param("string?"),
2186                        TypeParameter::Type(Type::new(TypeKind::Boolean, false)),
2187                    ],
2188                    false,
2189                ),
2190            ),
2191        ];
2192
2193        for (expr, expected) in cases {
2194            assert_eq!(
2195                parse_type(expr),
2196                expected,
2197                "unexpected extension for {expr}"
2198            );
2199        }
2200    }
2201
2202    #[test]
2203    fn test_parameter_type_validation() {
2204        let int_param = ParameterConstraint::Integer {
2205            min: Some(1),
2206            max: Some(10),
2207        };
2208        let enum_param = ParameterConstraint::Enumeration {
2209            options: ParsedEnumOptions::try_from(simple_extensions::EnumOptions(vec![
2210                "OVERFLOW".to_string(),
2211                "ERROR".to_string(),
2212            ]))
2213            .unwrap(),
2214        };
2215
2216        let cases = vec![
2217            (&int_param, Value::Number(5.into()), true),
2218            (&int_param, Value::Number(0.into()), false),
2219            (&int_param, Value::Number(11.into()), false),
2220            (&int_param, Value::String("not a number".into()), false),
2221            (&enum_param, Value::String("OVERFLOW".into()), true),
2222            (&enum_param, Value::String("INVALID".into()), false),
2223        ];
2224
2225        for (param, value, expected) in cases {
2226            assert_eq!(
2227                param.is_valid_value(&value),
2228                expected,
2229                "unexpected validation result for {value:?}"
2230            );
2231        }
2232    }
2233
2234    #[test]
2235    fn test_builtin_type_display_lowercase() {
2236        for input in [
2237            "I32",
2238            "FIXEDCHAR<5>",
2239            "VARCHAR<10>",
2240            "FIXEDBINARY<8>",
2241            "DeCiMaL<10, 2>",
2242            "PRECISION_TIME<3>",
2243            "PRECISION_TIMESTAMP<3>",
2244            "PRECISION_TIMESTAMP_TZ<3>",
2245            "INTERVAL_DAY<3>",
2246            "INTERVAL_COMPOUND<3>",
2247        ] {
2248            let concrete = parse_type(input);
2249            assert_eq!(parse_type(&input.to_ascii_lowercase()), concrete);
2250
2251            let output = concrete.to_string();
2252            assert_eq!(output, output.to_ascii_lowercase(), "display for {input}");
2253        }
2254    }
2255
2256    #[test]
2257    fn test_precision_types_require_underscores() {
2258        for name in [
2259            "precisiontime",
2260            "precisiontimestamp",
2261            "precisiontimestamptz",
2262        ] {
2263            for spelling in [name.to_string(), name.to_ascii_uppercase()] {
2264                assert!(!TypeKind::is_name(&spelling));
2265                assert!(parse_type_result(&format!("{spelling}<3>")).is_err());
2266            }
2267        }
2268    }
2269
2270    #[test]
2271    fn test_precision_type_round_trip_display() {
2272        for (input, expected) in [
2273            ("PRECISION_TIME<3>", "precision_time<3>"),
2274            ("PRECISION_TIMESTAMP<3>", "precision_timestamp<3>"),
2275            ("PRECISION_TIMESTAMP_TZ<3>", "precision_timestamp_tz<3>"),
2276        ] {
2277            let concrete = parse_type(input);
2278            let output = concrete.to_string();
2279            assert_eq!(output, expected);
2280            assert_eq!(parse_type(&output), concrete);
2281
2282            let raw: RawType = concrete.clone().into();
2283            let mut ctx = TypeContext::default();
2284            assert_eq!(raw.parse(&mut ctx).unwrap(), concrete);
2285        }
2286    }
2287
2288    #[test]
2289    fn test_type_round_trip_display() {
2290        // (example, canonical form)
2291        let cases = vec![
2292            ("i32", "i32"),
2293            ("I64?", "i64?"),
2294            ("list<string>", "list<string>"),
2295            ("List<STRING?>", "list<string?>"),
2296            ("map<i32, list<string>>", "map<i32, list<string>>"),
2297            ("struct<i8, string?>", "struct<i8, string?>"),
2298            (
2299                "Struct<List<i32>, Map<string, list<i64?>>>",
2300                "struct<list<i32>, map<string, list<i64?>>>",
2301            ),
2302            (
2303                "Map<List<I32?>, Struct<string, list<i64?>>>",
2304                "map<list<i32?>, struct<string, list<i64?>>>",
2305            ),
2306            ("List?<i32>", "list?<i32>"),
2307            ("Map?<string, List?<i32?>>", "map?<string, list?<i32?>>"),
2308            ("Struct?<i32, string?>", "struct?<i32, string?>"),
2309            ("FIXEDCHAR?<5>", "fixedchar?<5>"),
2310            ("VARCHAR?<10>", "varchar?<10>"),
2311            ("FIXEDBINARY?<8>", "fixedbinary?<8>"),
2312            ("DeCiMaL?<10,2>", "decimal?<10, 2>"),
2313            ("precision_time?<3>", "precision_time?<3>"),
2314            ("precision_timestamp?<3>", "precision_timestamp?<3>"),
2315            ("precision_timestamp_tz?<3>", "precision_timestamp_tz?<3>"),
2316            ("InTeRvAl_DaY?<3>", "interval_day?<3>"),
2317            ("INTERVAL_COMPOUND?<3>", "interval_compound?<3>"),
2318            ("u!geometry?", "u!geometry?"),
2319            ("u!CustomType?<i32>", "u!CustomType?<i32>"),
2320            ("u!custom<i32>", "u!custom<i32>"),
2321            ("u!custom?<i32, 5>", "u!custom?<i32, 5>"),
2322            ("list?<u!geometry?>", "list?<u!geometry?>"),
2323        ];
2324
2325        for (input, expected) in cases {
2326            let concrete = Type::parse(input).unwrap();
2327            let actual = concrete.to_string();
2328
2329            assert_eq!(actual, expected, "unexpected display for {input}");
2330            assert_eq!(
2331                parse_type(&actual),
2332                concrete,
2333                "round trip failed for {input}"
2334            );
2335
2336            let raw: RawType = concrete.clone().into();
2337            let mut ctx = TypeContext::default();
2338            assert_eq!(
2339                raw.parse(&mut ctx).unwrap(),
2340                concrete,
2341                "raw type round trip failed for {input}"
2342            );
2343        }
2344    }
2345
2346    /// Test that named struct field order preserves the structure order when
2347    /// round-tripping through RawType (Substrait #915).
2348    #[test]
2349    fn test_named_struct_field_order_stability() -> Result<(), ExtensionTypeError> {
2350        let raw = RawType::Object(
2351            [("beta", "i32"), ("alpha", "string?")]
2352                .into_iter()
2353                .map(|(name, ty)| (name.to_string(), Value::String(ty.to_string())))
2354                .collect(),
2355        );
2356        let mut ctx = TypeContext::default();
2357        let concrete = Parse::parse(raw, &mut ctx)?;
2358
2359        let round_tripped: RawType = concrete.into();
2360        match round_tripped {
2361            RawType::Object(result_map) => {
2362                let keys: Vec<_> = result_map.keys().collect();
2363                assert_eq!(
2364                    keys,
2365                    vec!["beta", "alpha"],
2366                    "field order should be preserved"
2367                );
2368            }
2369            other => panic!("expected Object, got {other:?}"),
2370        }
2371
2372        Ok(())
2373    }
2374
2375    #[test]
2376    fn test_integer_param_bounds_round_trip() {
2377        let cases = vec![
2378            (
2379                "bounded",
2380                simple_extensions::TypeParamDefsItem {
2381                    name: Some("K".to_string()),
2382                    description: None,
2383                    type_: simple_extensions::TypeParamDefsItemType::Integer,
2384                    min: Some(1.0),
2385                    max: Some(10.0),
2386                    options: None,
2387                    optional: None,
2388                },
2389                Ok((Some(1), Some(10))),
2390            ),
2391            (
2392                "fractional_min",
2393                simple_extensions::TypeParamDefsItem {
2394                    name: Some("K".to_string()),
2395                    description: None,
2396                    type_: simple_extensions::TypeParamDefsItemType::Integer,
2397                    min: Some(1.5),
2398                    max: None,
2399                    options: None,
2400                    optional: None,
2401                },
2402                Err(TypeParamError::InvalidIntegerBounds {
2403                    min: Some(1.5),
2404                    max: None,
2405                }),
2406            ),
2407            (
2408                "fractional_max",
2409                simple_extensions::TypeParamDefsItem {
2410                    name: Some("K".to_string()),
2411                    description: None,
2412                    type_: simple_extensions::TypeParamDefsItemType::Integer,
2413                    min: None,
2414                    max: Some(9.9),
2415                    options: None,
2416                    optional: None,
2417                },
2418                Err(TypeParamError::InvalidIntegerBounds {
2419                    min: None,
2420                    max: Some(9.9),
2421                }),
2422            ),
2423        ];
2424
2425        for (label, item, expected) in cases {
2426            match (TypeParam::try_from(item), expected) {
2427                (Ok(tp), Ok((expected_min, expected_max))) => match tp.param_type {
2428                    ParameterConstraint::Integer { min, max } => {
2429                        assert_eq!(min, expected_min, "min mismatch for {label}");
2430                        assert_eq!(max, expected_max, "max mismatch for {label}");
2431                    }
2432                    _ => panic!("expected integer param type for {label}"),
2433                },
2434                (Err(actual_err), Err(expected_err)) => {
2435                    assert_eq!(actual_err, expected_err, "unexpected error for {label}");
2436                }
2437                (result, expected) => {
2438                    panic!("unexpected result for {label}: got {result:?}, expected {expected:?}")
2439                }
2440            }
2441        }
2442    }
2443
2444    #[test]
2445    fn test_custom_type_round_trip() -> Result<(), ExtensionTypeError> {
2446        let fields = IndexMap::from_iter([
2447            ("x".to_string(), Type::new(TypeKind::Fp64, false)),
2448            ("y".to_string(), Type::new(TypeKind::Fp64, false)),
2449        ]);
2450
2451        let cases = vec![
2452            CustomType::new(
2453                "AliasType".to_string(),
2454                vec![],
2455                Some(Type::new(TypeKind::I32, false)),
2456                None,
2457                Some("a test alias type".to_string()),
2458            )?,
2459            CustomType::new(
2460                "Point".to_string(),
2461                vec![TypeParam::new(
2462                    "T".to_string(),
2463                    ParameterConstraint::DataType,
2464                    Some("a numeric value".to_string()),
2465                )],
2466                Some(Type::named_struct(fields, false)),
2467                None,
2468                None,
2469            )?,
2470        ];
2471
2472        for custom in cases {
2473            round_trip(&custom);
2474        }
2475
2476        Ok(())
2477    }
2478
2479    #[test]
2480    fn test_invalid_type_names() {
2481        let cases = vec![
2482            ("", false),
2483            ("bad name", false),
2484            ("9bad", false),
2485            ("bad-name", false),
2486            ("bad.name", false),
2487            ("GoodName", true),
2488            ("also_good", true),
2489            ("_underscore", true),
2490            ("$dollar", true),
2491            ("CamelCase123", true),
2492        ];
2493
2494        for (name, expected_ok) in cases {
2495            let result = CustomType::validate_name(name);
2496            assert_eq!(
2497                result.is_ok(),
2498                expected_ok,
2499                "unexpected validation for {name}"
2500            );
2501        }
2502    }
2503
2504    #[test]
2505    fn test_ext_type_to_concrete_type() -> Result<(), ExtensionTypeError> {
2506        let cases = vec![
2507            (
2508                "alias",
2509                RawType::String("i32".to_string()),
2510                Type::new(TypeKind::I32, false),
2511            ),
2512            (
2513                "named_struct",
2514                raw_named_struct(&[("field1", "fp64"), ("field2", "i32?")]),
2515                Type::named_struct(
2516                    IndexMap::from_iter([
2517                        ("field1".to_string(), Type::new(TypeKind::Fp64, false)),
2518                        ("field2".to_string(), Type::new(TypeKind::I32, true)),
2519                    ]),
2520                    false,
2521                ),
2522            ),
2523        ];
2524
2525        for (label, raw, expected) in cases {
2526            let mut ctx = TypeContext::default();
2527            let parsed = Parse::parse(raw, &mut ctx)?;
2528            assert_eq!(parsed, expected, "unexpected type for {label}");
2529        }
2530
2531        Ok(())
2532    }
2533
2534    #[test]
2535    fn test_custom_type_parsing() -> Result<(), ExtensionTypeError> {
2536        let cases = vec![
2537            (
2538                "alias",
2539                simple_extensions::SimpleExtensionsTypesItem {
2540                    deprecated: None,
2541                    name: "Alias".to_string(),
2542                    description: Some("Alias type".to_string()),
2543                    metadata: Default::default(),
2544                    parameters: None,
2545                    structure: Some(RawType::String("BINARY".to_string())),
2546                    variadic: None,
2547                },
2548                "Alias",
2549                Some("Alias type"),
2550                Some(Type::new(TypeKind::Binary, false)),
2551            ),
2552            (
2553                "named_struct",
2554                simple_extensions::SimpleExtensionsTypesItem {
2555                    deprecated: None,
2556                    name: "Point".to_string(),
2557                    description: Some("A 2D point".to_string()),
2558                    metadata: Default::default(),
2559                    parameters: None,
2560                    structure: Some(raw_named_struct(&[("x", "fp64"), ("y", "fp64?")])),
2561                    variadic: None,
2562                },
2563                "Point",
2564                Some("A 2D point"),
2565                Some(Type::named_struct(
2566                    IndexMap::from_iter([
2567                        ("x".to_string(), Type::new(TypeKind::Fp64, false)),
2568                        ("y".to_string(), Type::new(TypeKind::Fp64, true)),
2569                    ]),
2570                    false,
2571                )),
2572            ),
2573            (
2574                "no_structure",
2575                simple_extensions::SimpleExtensionsTypesItem {
2576                    deprecated: None,
2577                    name: "Opaque".to_string(),
2578                    description: None,
2579                    metadata: Default::default(),
2580                    parameters: None,
2581                    structure: None,
2582                    variadic: Some(true),
2583                },
2584                "Opaque",
2585                None,
2586                None,
2587            ),
2588        ];
2589
2590        for (label, item, expected_name, expected_description, expected_structure) in cases {
2591            let mut ctx = TypeContext::default();
2592            let parsed = Parse::parse(item, &mut ctx)?;
2593            assert_eq!(parsed.name, expected_name);
2594            assert_eq!(
2595                parsed.description.as_deref(),
2596                expected_description,
2597                "description mismatch for {label}"
2598            );
2599            assert_eq!(
2600                parsed.structure, expected_structure,
2601                "structure mismatch for {label}"
2602            );
2603        }
2604
2605        Ok(())
2606    }
2607}