Skip to main content

relate_parser/
type_normalize.rs

1//! CIP-100 canonical type normalization and name rendering.
2//!
3//! `CanonType` is the single normalized form of a Cypher type: default
4//! names (CIP-100 "Type name normalization"), CIP-100's semantic
5//! simplifications (flatten nested unions, drop redundant/subtype members,
6//! combine NULL with NOT NULL types), and the canonical type order all
7//! already applied. Two semantically equivalent types always normalize to
8//! structurally equal `CanonType` trees.
9//!
10//! This is the shared engine behind two features:
11//! - CIP-90's `valueType()`, which renders a *runtime value's* dynamic
12//!   type (built bottom-up from the value's own shape by the engine, see
13//!   `relate-executor`'s `value_type_name`).
14//! - The normalization of a *parsed* `TypeExpr` (property type
15//!   constraints, exposed via `SHOW CONSTRAINTS.propertyType`).
16//!
17//! Note: `TypeExpr` (CIP-86 grammar), the type predicate evaluator, and
18//! this module's `type_expr_to_canon` all live in the parser crate since
19//! normalization is purely a function of the parsed type grammar; nothing
20//! here depends on `CypherValue`.
21
22use std::cmp::Ordering;
23
24use crate::ast::{PredefinedKind, TypeExpr, VectorCoordKind};
25
26/// A fully CIP-100-normalized Cypher type.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct CanonType {
29    pub kind: CanonKind,
30    /// Whether this node is marked NOT NULL. Always `false` for `Nothing`
31    /// (normalized away, see `CanonType::predefined`) and for `Union` (the
32    /// CIP-86 grammar gives closed unions no `NOT NULL` production of
33    /// their own -- nullability is carried per-member instead).
34    pub not_null: bool,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum CanonKind {
39    Predefined(PredefinedKind),
40    List(Box<CanonType>),
41    /// `VECTOR<COORD NOT NULL>(DIM)` (CIP-216). Either half may be absent
42    /// (`coord: None` renders as bare `VECTOR`, `dimension: None` omits the
43    /// `(...)` suffix) -- both are grammatically legal `TypeExpr::Vector`
44    /// shapes, kept around only so `validate_property_type` can render
45    /// them back into Neo4j's own error text for the "need to define both"
46    /// rejection.
47    Vector {
48        coord: Option<VectorCoordKind>,
49        dimension: Option<i64>,
50    },
51    /// Two or more component types, already flattened, deduped, subtype-
52    /// collapsed, and ordered -- the result of `normalize_union`.
53    Union(Vec<CanonType>),
54}
55
56/// CIP-100 "Default type names" table, vector coordinate half: the
57/// canonical coordinate name rendered inside `VECTOR<...>`. `Int64`/
58/// `Float64` render as the plain `INTEGER`/`FLOAT` names (CIP-216 S-6: they
59/// double as ordinary property type aliases), not `INTEGER64`/`FLOAT64`.
60fn vector_coord_name(k: VectorCoordKind) -> &'static str {
61    k.canonical_name()
62}
63
64/// Reverse of `vector_coord_name`.
65fn vector_coord_kind_from_name(name: &str) -> Option<VectorCoordKind> {
66    VectorCoordKind::from_canonical_name(name)
67}
68
69impl CanonType {
70    /// Builds a predefined leaf, applying the "Simplify NULL NOT NULL" /
71    /// "Simplify NOTHING NOT NULL" rules (both normalize to plain
72    /// `NOTHING`) up front so every other rule can assume `not_null` is
73    /// always `false` on `Nothing`.
74    pub fn predefined(kind: PredefinedKind, not_null: bool) -> Self {
75        if matches!(kind, PredefinedKind::Nothing)
76            || (matches!(kind, PredefinedKind::Null) && not_null)
77        {
78            return CanonType {
79                kind: CanonKind::Predefined(PredefinedKind::Nothing),
80                not_null: false,
81            };
82        }
83        CanonType {
84            kind: CanonKind::Predefined(kind),
85            not_null,
86        }
87    }
88
89    pub fn list(element: CanonType, not_null: bool) -> Self {
90        CanonType {
91            kind: CanonKind::List(Box::new(element)),
92            not_null,
93        }
94    }
95}
96
97/// CIP-100 "Default type names" table.
98fn predefined_name(kind: PredefinedKind) -> &'static str {
99    match kind {
100        PredefinedKind::Nothing => "NOTHING",
101        PredefinedKind::Null => "NULL",
102        PredefinedKind::Any => "ANY",
103        PredefinedKind::Boolean => "BOOLEAN",
104        PredefinedKind::String => "STRING",
105        PredefinedKind::Integer => "INTEGER",
106        PredefinedKind::Float => "FLOAT",
107        PredefinedKind::Date => "DATE",
108        PredefinedKind::Duration => "DURATION",
109        PredefinedKind::Point => "POINT",
110        PredefinedKind::LocalTime => "LOCAL TIME",
111        PredefinedKind::ZonedTime => "ZONED TIME",
112        PredefinedKind::LocalDateTime => "LOCAL DATETIME",
113        PredefinedKind::ZonedDateTime => "ZONED DATETIME",
114        PredefinedKind::Node => "NODE",
115        PredefinedKind::Relationship => "RELATIONSHIP",
116        PredefinedKind::Path => "PATH",
117        PredefinedKind::Map => "MAP",
118        PredefinedKind::Uuid => "UUID",
119    }
120}
121
122/// CIP-100 "General order of types" rank; lower sorts first. `List`'s rank
123/// sits between `MAP` and `PATH` per the doc's constructed-types list;
124/// `Vector` (CIP-216, not in the original CIP-100 table) sits directly
125/// before `List` -- the only order relationship pinned down by observed
126/// live-Neo4j behavior (CIP-216 01#5: `VECTOR<...>(...)` sorts before
127/// `LIST<...>` in a union). `Union` is never itself ranked in practice
128/// (nested unions are always flattened away, so a bare `Union` never
129/// appears as a sibling of anything else needing a rank).
130fn rank(kind: &CanonKind) -> u8 {
131    match kind {
132        CanonKind::Predefined(k) => match k {
133            PredefinedKind::Nothing => 0,
134            PredefinedKind::Null => 1,
135            // CIP-246 amendment to the CIP-100 order: UUID sits between
136            // STRING and the numerics.
137            PredefinedKind::Boolean => 2,
138            PredefinedKind::String => 3,
139            PredefinedKind::Uuid => 4,
140            PredefinedKind::Integer => 5,
141            PredefinedKind::Float => 6,
142            PredefinedKind::Date => 7,
143            PredefinedKind::LocalTime => 8,
144            PredefinedKind::ZonedTime => 9,
145            PredefinedKind::LocalDateTime => 10,
146            PredefinedKind::ZonedDateTime => 11,
147            PredefinedKind::Duration => 12,
148            PredefinedKind::Point => 13,
149            PredefinedKind::Node => 14,
150            PredefinedKind::Relationship => 15,
151            PredefinedKind::Map => 16,
152            PredefinedKind::Path => 19,
153            PredefinedKind::Any => 21,
154        },
155        CanonKind::Vector { .. } => 17,
156        CanonKind::List(_) => 18,
157        CanonKind::Union(_) => 20,
158    }
159}
160
161/// Renders a `CanonType` to its CIP-100 canonical string: uppercase,
162/// single-space word separators, no space around `<>`, `|` surrounded by
163/// exactly one space on each side.
164pub fn render_canon(t: &CanonType) -> String {
165    let base = match &t.kind {
166        CanonKind::Predefined(k) => predefined_name(*k).to_string(),
167        CanonKind::List(elem) => format!("LIST<{}>", render_canon(elem)),
168        CanonKind::Vector { coord, dimension } => {
169            let mut s = String::from("VECTOR");
170            if let Some(c) = coord {
171                s.push('<');
172                s.push_str(vector_coord_name(*c));
173                s.push_str(" NOT NULL>");
174            }
175            if let Some(d) = dimension {
176                s.push('(');
177                s.push_str(&d.to_string());
178                s.push(')');
179            }
180            s
181        }
182        CanonKind::Union(members) => members
183            .iter()
184            .map(render_canon)
185            .collect::<Vec<_>>()
186            .join(" | "),
187    };
188    if t.not_null && !matches!(t.kind, CanonKind::Predefined(PredefinedKind::Nothing)) {
189        format!("{base} NOT NULL")
190    } else {
191        base
192    }
193}
194
195/// True if every value of `a` is also a value of `b` (CIP-100 "Simplify
196/// encompassing types"). Used to drop redundant members from a dynamic
197/// union: `NOTHING` is a subtype of everything (including `NULL`), `NULL`
198/// is a subtype of every other nullable type, `ANY` is a supertype of
199/// everything, `T NOT NULL` is a subtype of the nullable `T`, and
200/// `LIST<T1>` is a subtype of `LIST<T2>` when `T1` is a subtype of `T2`.
201fn is_subtype(a: &CanonType, b: &CanonType) -> bool {
202    if a == b {
203        return true;
204    }
205    if matches!(b.kind, CanonKind::Predefined(PredefinedKind::Any)) {
206        return true;
207    }
208    if matches!(a.kind, CanonKind::Predefined(PredefinedKind::Nothing)) {
209        return true;
210    }
211    if let CanonKind::Union(ma) = &a.kind {
212        return ma.iter().all(|m| is_subtype(m, b));
213    }
214    if let CanonKind::Union(mb) = &b.kind {
215        return mb.iter().any(|m| is_subtype(a, m));
216    }
217    if matches!(a.kind, CanonKind::Predefined(PredefinedKind::Null)) {
218        return matches!(b.kind, CanonKind::Predefined(PredefinedKind::Null))
219            || (!b.not_null && !matches!(b.kind, CanonKind::Predefined(PredefinedKind::Nothing)));
220    }
221    match (&a.kind, &b.kind) {
222        (CanonKind::Predefined(ka), CanonKind::Predefined(kb)) => {
223            ka == kb && (a.not_null || !b.not_null)
224        }
225        (CanonKind::List(ea), CanonKind::List(eb)) => {
226            (a.not_null || !b.not_null) && is_subtype(ea, eb)
227        }
228        _ => false,
229    }
230}
231
232/// Whether a member's presence in a union should trigger the "if the
233/// dynamic union contains at least one nullable type, then all types are
234/// nullable" rule. `NOTHING` never triggers it -- it isn't "nullable" in
235/// the sense of containing the null value, it contains no values at all.
236fn is_nullable_trigger(t: &CanonType) -> bool {
237    !t.not_null && !matches!(t.kind, CanonKind::Predefined(PredefinedKind::Nothing))
238}
239
240/// Removes exact duplicates and members that are a strict subtype of a
241/// different member still present (CIP-100 "Remove redundant types from
242/// dynamic unions" + "Simplify encompassing types").
243fn dedup_subtypes(items: Vec<CanonType>) -> Vec<CanonType> {
244    let mut result = Vec::with_capacity(items.len());
245    for (i, item) in items.iter().enumerate() {
246        let redundant = items.iter().enumerate().any(|(j, other)| {
247            if i == j {
248                return false;
249            }
250            if item == other {
251                // Exact duplicate: keep only the first occurrence.
252                return i > j;
253            }
254            is_subtype(item, other)
255        });
256        if !redundant {
257            result.push(item.clone());
258        }
259    }
260    result
261}
262
263/// Cardinality used by the CIP-100 tie-break algorithm: a closed dynamic
264/// union's own component count, or 1 for anything else (a single type is
265/// a "union of one").
266fn cardinality(t: &CanonType) -> usize {
267    match &t.kind {
268        CanonKind::Union(members) => members.len(),
269        _ => 1,
270    }
271}
272
273fn as_members(t: &CanonType) -> Vec<&CanonType> {
274    match &t.kind {
275        CanonKind::Union(members) => members.iter().collect(),
276        _ => vec![t],
277    }
278}
279
280/// CIP-100 total order over normalized types: general type rank first;
281/// for two lists, the closed-dynamic-union tie-break algorithm (fewer
282/// inner types first, then lexicographic by first differing inner type);
283/// NOT NULL ordered directly before the equivalent nullable type.
284fn cmp_canon(a: &CanonType, b: &CanonType) -> Ordering {
285    let ra = rank(&a.kind);
286    let rb = rank(&b.kind);
287    if ra != rb {
288        return ra.cmp(&rb);
289    }
290    match (&a.kind, &b.kind) {
291        (CanonKind::List(ea), CanonKind::List(eb)) => {
292            let ca = cardinality(ea);
293            let cb = cardinality(eb);
294            if ca != cb {
295                return ca.cmp(&cb);
296            }
297            let (ma, mb) = (as_members(ea), as_members(eb));
298            for (x, y) in ma.iter().zip(mb.iter()) {
299                let ord = cmp_canon(x, y);
300                if ord != Ordering::Equal {
301                    return ord;
302                }
303            }
304            // NOT NULL before nullable, at the list level itself.
305            b.not_null.cmp(&a.not_null)
306        }
307        (CanonKind::Predefined(_), CanonKind::Predefined(_)) => b.not_null.cmp(&a.not_null),
308        _ => Ordering::Equal,
309    }
310}
311
312/// Normalizes a set of already-normalized component types into their
313/// single CIP-100 normalized form: flattens nested unions, removes
314/// duplicate/subtype members, applies the "combine NULL and NOT NULL
315/// types" encompassing rule (a union with at least one nullable member
316/// makes every member nullable), and orders what remains. Returns the
317/// single member directly if only one remains once simplified (CIP-100
318/// "Simplify dynamic unions with one type"), or `NOTHING` for an empty
319/// input.
320pub fn normalize_union(components: Vec<CanonType>) -> CanonType {
321    let mut flat = Vec::with_capacity(components.len());
322    for c in components {
323        match c.kind {
324            CanonKind::Union(members) => flat.extend(members),
325            _ => flat.push(c),
326        }
327    }
328
329    flat = dedup_subtypes(flat);
330
331    if flat.iter().any(is_nullable_trigger) {
332        for m in &mut flat {
333            if !matches!(m.kind, CanonKind::Predefined(PredefinedKind::Nothing)) {
334                m.not_null = false;
335            }
336        }
337        flat = dedup_subtypes(flat);
338    }
339
340    flat.sort_by(cmp_canon);
341
342    match flat.len() {
343        0 => CanonType::predefined(PredefinedKind::Nothing, false),
344        1 => flat.into_iter().next().unwrap(),
345        _ => CanonType {
346            kind: CanonKind::Union(flat),
347            not_null: false,
348        },
349    }
350}
351
352impl TypeExpr {
353    /// The declaration form of a normalized type: the inverse of
354    /// [`type_expr_to_canon`](crate::type_normalize::type_expr_to_canon).
355    pub fn from_canon(canon: &CanonType) -> TypeExpr {
356        match &canon.kind {
357            CanonKind::Predefined(kind) => TypeExpr::Predefined {
358                kind: *kind,
359                not_null: canon.not_null,
360            },
361            CanonKind::List(element) => TypeExpr::List {
362                element: Box::new(TypeExpr::from_canon(element)),
363                not_null: canon.not_null,
364            },
365            CanonKind::Vector { coord, dimension } => TypeExpr::Vector {
366                coord: *coord,
367                dimension: *dimension,
368                not_null: canon.not_null,
369            },
370            CanonKind::Union(members) => {
371                TypeExpr::Union(members.iter().map(TypeExpr::from_canon).collect())
372            }
373        }
374    }
375}
376
377/// Converts a parsed `TypeExpr` (CIP-86 grammar) to its CIP-100 canonical
378/// form.
379pub fn type_expr_to_canon(te: &TypeExpr) -> CanonType {
380    match te {
381        TypeExpr::Predefined { kind, not_null } => CanonType::predefined(*kind, *not_null),
382        TypeExpr::List { element, not_null } => {
383            CanonType::list(type_expr_to_canon(element), *not_null)
384        }
385        TypeExpr::PropertyValue { not_null } => property_value_canon(*not_null),
386        TypeExpr::Vector {
387            coord,
388            dimension,
389            not_null,
390        } => CanonType {
391            kind: CanonKind::Vector {
392                coord: *coord,
393                dimension: *dimension,
394            },
395            not_null: *not_null,
396        },
397        TypeExpr::Union(components) => {
398            let converted: Vec<CanonType> = components.iter().map(type_expr_to_canon).collect();
399            normalize_union(converted)
400        }
401    }
402}
403
404/// CIP-100 "Simplify ANY PROPERTY VALUE to the union of all property
405/// types": the 11 property-storable scalar/temporal types plus a
406/// `LIST<T NOT NULL>` of each (list elements are always NOT NULL --
407/// property-storable lists can never contain a null element).
408fn property_value_canon(not_null: bool) -> CanonType {
409    const SCALARS: [PredefinedKind; 11] = [
410        PredefinedKind::Boolean,
411        PredefinedKind::String,
412        PredefinedKind::Integer,
413        PredefinedKind::Float,
414        PredefinedKind::Date,
415        PredefinedKind::LocalTime,
416        PredefinedKind::ZonedTime,
417        PredefinedKind::LocalDateTime,
418        PredefinedKind::ZonedDateTime,
419        PredefinedKind::Duration,
420        PredefinedKind::Point,
421    ];
422    let mut members: Vec<CanonType> = SCALARS
423        .iter()
424        .map(|k| CanonType::predefined(*k, not_null))
425        .collect();
426    for k in SCALARS {
427        members.push(CanonType::list(CanonType::predefined(k, true), not_null));
428    }
429    normalize_union(members)
430}
431
432/// Whether `k` is one of the composite/unbounded kinds CIP-85 disallows as
433/// a property type (or list inner element type): `NOTHING`/`NULL`/`ANY`/
434/// `NODE`/`RELATIONSHIP`/`PATH`/`MAP`. The 11 scalar/temporal property-
435/// storable kinds (plus their `LIST<...>` forms) are the only ones left.
436fn is_disallowed_property_kind(k: PredefinedKind) -> bool {
437    matches!(
438        k,
439        PredefinedKind::Nothing
440            | PredefinedKind::Null
441            | PredefinedKind::Any
442            | PredefinedKind::Node
443            | PredefinedKind::Relationship
444            | PredefinedKind::Path
445            | PredefinedKind::Map
446    )
447}
448
449/// Validates a `LIST<...>` inner element type (CIP-85: "lists cannot have
450/// a union/list/nullable inner type", NOT NULL is mandatory on the
451/// element). Errors are rendered against `list_canon` (the whole
452/// `LIST<...>` type), matching Neo4j's error shape. `pub` (not just used by
453/// `validate_property_type`) because CIP-178/181's graph-type property
454/// types share this exact restriction while allowing top-level `NOT NULL`
455/// (which `validate_property_type` itself forbids -- that rule is specific
456/// to standalone property type *constraints*, not a node/edge type's own
457/// declared properties).
458pub fn validate_list_element(list_canon: &CanonType, elem: &CanonType) -> Result<(), String> {
459    if matches!(elem.kind, CanonKind::Union(_)) {
460        return Err(format!(
461            "Invalid property type `{}`. Lists cannot have a union of types as an inner type.",
462            render_canon(list_canon)
463        ));
464    }
465    if matches!(elem.kind, CanonKind::List(_)) {
466        return Err(format!(
467            "Invalid property type `{}`. Lists cannot have a list as an inner type.",
468            render_canon(list_canon)
469        ));
470    }
471    // CIP-216 Negative 4: a list of vectors is not a supported property
472    // type, regardless of the vector's own NOT NULL/coordinate/dimension.
473    if matches!(elem.kind, CanonKind::Vector { .. }) {
474        return Err(format!(
475            "{} is not supported in property type constraints. A list in this position \
476             cannot have VECTOR as an inner type.",
477            render_canon(list_canon)
478        ));
479    }
480    if !elem.not_null {
481        return Err(format!(
482            "Invalid property type `{}`. Lists cannot have a nullable inner type.",
483            render_canon(list_canon)
484        ));
485    }
486    if let CanonKind::Predefined(k) = &elem.kind {
487        if is_disallowed_property_kind(*k) {
488            return Err(format!(
489                "{} is not supported in property type constraints.",
490                render_canon(list_canon)
491            ));
492        }
493    }
494    Ok(())
495}
496
497/// The `<value type>` expression form of [`validate_property_type`], for
498/// callers that still hold the parsed type: `PROPERTY VALUE` canonicalizes
499/// into an open union of every storable scalar, so the canonical form alone
500/// cannot tell it apart from an explicitly written union -- and Neo4j
501/// rejects it as a property type constraint while accepting the union
502/// (live corpus: `Create*PropertyTypeConstraintCommands`). One entry point
503/// for both call sites, so the expression-level rule cannot drift from the
504/// canonical one.
505pub fn validate_property_type_expr(te: &TypeExpr) -> Result<(), String> {
506    if matches!(te, TypeExpr::PropertyValue { .. }) {
507        return Err("PROPERTY VALUE is not supported in property type constraints.".to_string());
508    }
509    validate_property_type(&type_expr_to_canon(te))
510}
511
512/// Validates a normalized type against Relate's property type
513/// constraint restrictions (CIP-85): no top-level `NOT NULL` (on a scalar
514/// or on the list itself -- Neo4j 2026.05 does not implement `TYPE NOT
515/// NULL` for property type constraints), no `NOTHING`/`NULL`/`ANY`/`NODE`/
516/// `RELATIONSHIP`/`PATH`/`MAP`, and -- inside a `LIST<...>` -- no union,
517/// no nested list, and no nullable inner type (NOT NULL is mandatory
518/// there).
519pub fn validate_property_type(canon: &CanonType) -> Result<(), String> {
520    if canon.not_null {
521        return Err(format!(
522            "{} is not supported in property type constraints.",
523            render_canon(canon)
524        ));
525    }
526    match &canon.kind {
527        CanonKind::Predefined(k) => {
528            if is_disallowed_property_kind(*k) {
529                Err(format!(
530                    "{} is not supported in property type constraints.",
531                    render_canon(canon)
532                ))
533            } else {
534                Ok(())
535            }
536        }
537        CanonKind::List(elem) => validate_list_element(canon, elem),
538        // CIP-216 Negative 1/2: both coordinate type and dimension are
539        // mandatory for a vector property type constraint; either omitted
540        // makes the whole constraint creation fail (the type itself
541        // parses fine -- this is a runtime rejection, not a syntax error).
542        CanonKind::Vector { coord, dimension } => {
543            if coord.is_none() || dimension.is_none() {
544                Err(format!(
545                    "{} is not supported in property type constraints. Property type \
546                     constraints for vectors need to define both coordinate type and \
547                     dimension.",
548                    render_canon(canon)
549                ))
550            } else {
551                Ok(())
552            }
553        }
554        CanonKind::Union(members) => {
555            for m in members {
556                validate_property_type(m)?;
557            }
558            Ok(())
559        }
560    }
561}
562
563/// Reverse of `render_canon` for a property type constraint's stored
564/// canonical string: reconstructs a `TypeExpr` a caller can feed to a
565/// value-type matcher. Only understands the shape `render_canon` actually
566/// produces for a `validate_property_type`-accepted type (predefined
567/// names, `LIST<...>`, a trailing ` NOT NULL`, and `" | "`-separated
568/// unions) -- not general Cypher type syntax. Used to re-derive a runtime
569/// type matcher for a constraint loaded back from storage (CIP-85
570/// enforcement), where only the rendered string persists. Returns `None`
571/// if `s` doesn't match that shape (should not happen for a string this
572/// module itself produced).
573pub fn parse_canon_type_str(s: &str) -> Option<TypeExpr> {
574    if s.contains(" | ") {
575        let members = s
576            .split(" | ")
577            .map(parse_single_canon_type_str)
578            .collect::<Option<Vec<_>>>()?;
579        return Some(TypeExpr::Union(members));
580    }
581    parse_single_canon_type_str(s)
582}
583
584fn parse_single_canon_type_str(s: &str) -> Option<TypeExpr> {
585    let (base, not_null) = match s.strip_suffix(" NOT NULL") {
586        Some(b) => (b, true),
587        None => (s, false),
588    };
589    if let Some(inner) = base.strip_prefix("LIST<").and_then(|x| x.strip_suffix('>')) {
590        return Some(TypeExpr::List {
591            element: Box::new(parse_single_canon_type_str(inner)?),
592            not_null,
593        });
594    }
595    if let Some(rest) = base.strip_prefix("VECTOR") {
596        let (coord, dimension) = parse_vector_canon_tail(rest)?;
597        return Some(TypeExpr::Vector {
598            coord,
599            dimension,
600            not_null,
601        });
602    }
603    Some(TypeExpr::Predefined {
604        kind: predefined_kind_from_name(base)?,
605        not_null,
606    })
607}
608
609/// Parses the part of a rendered vector type string after the `VECTOR`
610/// prefix (and after any outer ` NOT NULL` has already been stripped by
611/// the caller): an optional `<COORD NOT NULL>` and an optional `(DIM)`,
612/// in that order, and nothing else. Reverse of the `CanonKind::Vector`
613/// branch of `render_canon`.
614fn parse_vector_canon_tail(rest: &str) -> Option<(Option<VectorCoordKind>, Option<i64>)> {
615    let mut s = rest;
616    let mut coord = None;
617    if let Some(after_lt) = s.strip_prefix('<') {
618        let end = after_lt.find('>')?;
619        let inner = after_lt[..end].strip_suffix(" NOT NULL")?;
620        coord = Some(vector_coord_kind_from_name(inner)?);
621        s = &after_lt[end + 1..];
622    }
623    let dimension = if let Some(after_paren) = s.strip_prefix('(') {
624        let end = after_paren.find(')')?;
625        let dim = after_paren[..end].parse::<i64>().ok()?;
626        s = &after_paren[end + 1..];
627        Some(dim)
628    } else {
629        None
630    };
631    if !s.is_empty() {
632        return None;
633    }
634    Some((coord, dimension))
635}
636
637/// Reverse of `predefined_name`.
638fn predefined_kind_from_name(name: &str) -> Option<PredefinedKind> {
639    Some(match name {
640        "NOTHING" => PredefinedKind::Nothing,
641        "NULL" => PredefinedKind::Null,
642        "ANY" => PredefinedKind::Any,
643        "BOOLEAN" => PredefinedKind::Boolean,
644        "STRING" => PredefinedKind::String,
645        "INTEGER" => PredefinedKind::Integer,
646        "FLOAT" => PredefinedKind::Float,
647        "UUID" => PredefinedKind::Uuid,
648        "DATE" => PredefinedKind::Date,
649        "DURATION" => PredefinedKind::Duration,
650        "POINT" => PredefinedKind::Point,
651        "LOCAL TIME" => PredefinedKind::LocalTime,
652        "ZONED TIME" => PredefinedKind::ZonedTime,
653        "LOCAL DATETIME" => PredefinedKind::LocalDateTime,
654        "ZONED DATETIME" => PredefinedKind::ZonedDateTime,
655        "NODE" => PredefinedKind::Node,
656        "RELATIONSHIP" => PredefinedKind::Relationship,
657        "PATH" => PredefinedKind::Path,
658        "MAP" => PredefinedKind::Map,
659        _ => return None,
660    })
661}
662
663#[cfg(test)]
664mod tests;