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//! - CIP-100's own 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
352/// Converts a parsed `TypeExpr` (CIP-86 grammar) to its CIP-100 canonical
353/// form.
354pub fn type_expr_to_canon(te: &TypeExpr) -> CanonType {
355    match te {
356        TypeExpr::Predefined { kind, not_null } => CanonType::predefined(*kind, *not_null),
357        TypeExpr::List { element, not_null } => {
358            CanonType::list(type_expr_to_canon(element), *not_null)
359        }
360        TypeExpr::PropertyValue { not_null } => property_value_canon(*not_null),
361        TypeExpr::Vector {
362            coord,
363            dimension,
364            not_null,
365        } => CanonType {
366            kind: CanonKind::Vector {
367                coord: *coord,
368                dimension: *dimension,
369            },
370            not_null: *not_null,
371        },
372        TypeExpr::Union(components) => {
373            let converted: Vec<CanonType> = components.iter().map(type_expr_to_canon).collect();
374            normalize_union(converted)
375        }
376    }
377}
378
379/// CIP-100 "Simplify ANY PROPERTY VALUE to the union of all property
380/// types": the 11 property-storable scalar/temporal types plus a
381/// `LIST<T NOT NULL>` of each (list elements are always NOT NULL --
382/// property-storable lists can never contain a null element).
383fn property_value_canon(not_null: bool) -> CanonType {
384    const SCALARS: [PredefinedKind; 11] = [
385        PredefinedKind::Boolean,
386        PredefinedKind::String,
387        PredefinedKind::Integer,
388        PredefinedKind::Float,
389        PredefinedKind::Date,
390        PredefinedKind::LocalTime,
391        PredefinedKind::ZonedTime,
392        PredefinedKind::LocalDateTime,
393        PredefinedKind::ZonedDateTime,
394        PredefinedKind::Duration,
395        PredefinedKind::Point,
396    ];
397    let mut members: Vec<CanonType> = SCALARS
398        .iter()
399        .map(|k| CanonType::predefined(*k, not_null))
400        .collect();
401    for k in SCALARS {
402        members.push(CanonType::list(CanonType::predefined(k, true), not_null));
403    }
404    normalize_union(members)
405}
406
407/// Whether `k` is one of the composite/unbounded kinds CIP-85 disallows as
408/// a property type (or list inner element type): `NOTHING`/`NULL`/`ANY`/
409/// `NODE`/`RELATIONSHIP`/`PATH`/`MAP`. The 11 scalar/temporal property-
410/// storable kinds (plus their `LIST<...>` forms) are the only ones left.
411fn is_disallowed_property_kind(k: PredefinedKind) -> bool {
412    matches!(
413        k,
414        PredefinedKind::Nothing
415            | PredefinedKind::Null
416            | PredefinedKind::Any
417            | PredefinedKind::Node
418            | PredefinedKind::Relationship
419            | PredefinedKind::Path
420            | PredefinedKind::Map
421    )
422}
423
424/// Validates a `LIST<...>` inner element type (CIP-85: "lists cannot have
425/// a union/list/nullable inner type", NOT NULL is mandatory on the
426/// element). Errors are rendered against `list_canon` (the whole
427/// `LIST<...>` type), matching Neo4j's error shape. `pub` (not just used by
428/// `validate_property_type`) because CIP-178/181's graph-type property
429/// types share this exact restriction while allowing top-level `NOT NULL`
430/// (which `validate_property_type` itself forbids -- that rule is specific
431/// to standalone property type *constraints*, not a node/edge type's own
432/// declared properties).
433pub fn validate_list_element(list_canon: &CanonType, elem: &CanonType) -> Result<(), String> {
434    if matches!(elem.kind, CanonKind::Union(_)) {
435        return Err(format!(
436            "Invalid property type `{}`. Lists cannot have a union of types as an inner type.",
437            render_canon(list_canon)
438        ));
439    }
440    if matches!(elem.kind, CanonKind::List(_)) {
441        return Err(format!(
442            "Invalid property type `{}`. Lists cannot have a list as an inner type.",
443            render_canon(list_canon)
444        ));
445    }
446    // CIP-216 Negative 4: a list of vectors is not a supported property
447    // type, regardless of the vector's own NOT NULL/coordinate/dimension.
448    if matches!(elem.kind, CanonKind::Vector { .. }) {
449        return Err(format!(
450            "{} is not supported in property type constraints. A list in this position \
451             cannot have VECTOR as an inner type.",
452            render_canon(list_canon)
453        ));
454    }
455    if !elem.not_null {
456        return Err(format!(
457            "Invalid property type `{}`. Lists cannot have a nullable inner type.",
458            render_canon(list_canon)
459        ));
460    }
461    if let CanonKind::Predefined(k) = &elem.kind {
462        if is_disallowed_property_kind(*k) {
463            return Err(format!(
464                "{} is not supported in property type constraints.",
465                render_canon(list_canon)
466            ));
467        }
468    }
469    Ok(())
470}
471
472/// The `<value type>` expression form of [`validate_property_type`], for
473/// callers that still hold the parsed type: `PROPERTY VALUE` canonicalizes
474/// into an open union of every storable scalar, so the canonical form alone
475/// cannot tell it apart from an explicitly written union -- and Neo4j
476/// rejects it as a property type constraint while accepting the union
477/// (live corpus: `Create*PropertyTypeConstraintCommands`). One entry point
478/// for both call sites, so the expression-level rule cannot drift from the
479/// canonical one.
480pub fn validate_property_type_expr(te: &TypeExpr) -> Result<(), String> {
481    if matches!(te, TypeExpr::PropertyValue { .. }) {
482        return Err("PROPERTY VALUE is not supported in property type constraints.".to_string());
483    }
484    validate_property_type(&type_expr_to_canon(te))
485}
486
487/// Validates a normalized type against Relate's property type
488/// constraint restrictions (CIP-85): no top-level `NOT NULL` (on a scalar
489/// or on the list itself -- Neo4j 2026.05 does not implement `TYPE NOT
490/// NULL` for property type constraints), no `NOTHING`/`NULL`/`ANY`/`NODE`/
491/// `RELATIONSHIP`/`PATH`/`MAP`, and -- inside a `LIST<...>` -- no union,
492/// no nested list, and no nullable inner type (NOT NULL is mandatory
493/// there).
494pub fn validate_property_type(canon: &CanonType) -> Result<(), String> {
495    if canon.not_null {
496        return Err(format!(
497            "{} is not supported in property type constraints.",
498            render_canon(canon)
499        ));
500    }
501    match &canon.kind {
502        CanonKind::Predefined(k) => {
503            if is_disallowed_property_kind(*k) {
504                Err(format!(
505                    "{} is not supported in property type constraints.",
506                    render_canon(canon)
507                ))
508            } else {
509                Ok(())
510            }
511        }
512        CanonKind::List(elem) => validate_list_element(canon, elem),
513        // CIP-216 Negative 1/2: both coordinate type and dimension are
514        // mandatory for a vector property type constraint; either omitted
515        // makes the whole constraint creation fail (the type itself
516        // parses fine -- this is a runtime rejection, not a syntax error).
517        CanonKind::Vector { coord, dimension } => {
518            if coord.is_none() || dimension.is_none() {
519                Err(format!(
520                    "{} is not supported in property type constraints. Property type \
521                     constraints for vectors need to define both coordinate type and \
522                     dimension.",
523                    render_canon(canon)
524                ))
525            } else {
526                Ok(())
527            }
528        }
529        CanonKind::Union(members) => {
530            for m in members {
531                validate_property_type(m)?;
532            }
533            Ok(())
534        }
535    }
536}
537
538/// Reverse of `render_canon` for a property type constraint's stored
539/// canonical string: reconstructs a `TypeExpr` a caller can feed to a
540/// value-type matcher. Only understands the shape `render_canon` actually
541/// produces for a `validate_property_type`-accepted type (predefined
542/// names, `LIST<...>`, a trailing ` NOT NULL`, and `" | "`-separated
543/// unions) -- not general Cypher type syntax. Used to re-derive a runtime
544/// type matcher for a constraint loaded back from storage (CIP-85
545/// enforcement), where only the rendered string persists. Returns `None`
546/// if `s` doesn't match that shape (should not happen for a string this
547/// module itself produced).
548pub fn parse_canon_type_str(s: &str) -> Option<TypeExpr> {
549    if s.contains(" | ") {
550        let members = s
551            .split(" | ")
552            .map(parse_single_canon_type_str)
553            .collect::<Option<Vec<_>>>()?;
554        return Some(TypeExpr::Union(members));
555    }
556    parse_single_canon_type_str(s)
557}
558
559fn parse_single_canon_type_str(s: &str) -> Option<TypeExpr> {
560    let (base, not_null) = match s.strip_suffix(" NOT NULL") {
561        Some(b) => (b, true),
562        None => (s, false),
563    };
564    if let Some(inner) = base.strip_prefix("LIST<").and_then(|x| x.strip_suffix('>')) {
565        return Some(TypeExpr::List {
566            element: Box::new(parse_single_canon_type_str(inner)?),
567            not_null,
568        });
569    }
570    if let Some(rest) = base.strip_prefix("VECTOR") {
571        let (coord, dimension) = parse_vector_canon_tail(rest)?;
572        return Some(TypeExpr::Vector {
573            coord,
574            dimension,
575            not_null,
576        });
577    }
578    Some(TypeExpr::Predefined {
579        kind: predefined_kind_from_name(base)?,
580        not_null,
581    })
582}
583
584/// Parses the part of a rendered vector type string after the `VECTOR`
585/// prefix (and after any outer ` NOT NULL` has already been stripped by
586/// the caller): an optional `<COORD NOT NULL>` and an optional `(DIM)`,
587/// in that order, and nothing else. Reverse of the `CanonKind::Vector`
588/// branch of `render_canon`.
589fn parse_vector_canon_tail(rest: &str) -> Option<(Option<VectorCoordKind>, Option<i64>)> {
590    let mut s = rest;
591    let mut coord = None;
592    if let Some(after_lt) = s.strip_prefix('<') {
593        let end = after_lt.find('>')?;
594        let inner = after_lt[..end].strip_suffix(" NOT NULL")?;
595        coord = Some(vector_coord_kind_from_name(inner)?);
596        s = &after_lt[end + 1..];
597    }
598    let dimension = if let Some(after_paren) = s.strip_prefix('(') {
599        let end = after_paren.find(')')?;
600        let dim = after_paren[..end].parse::<i64>().ok()?;
601        s = &after_paren[end + 1..];
602        Some(dim)
603    } else {
604        None
605    };
606    if !s.is_empty() {
607        return None;
608    }
609    Some((coord, dimension))
610}
611
612/// Reverse of `predefined_name`.
613fn predefined_kind_from_name(name: &str) -> Option<PredefinedKind> {
614    Some(match name {
615        "NOTHING" => PredefinedKind::Nothing,
616        "NULL" => PredefinedKind::Null,
617        "ANY" => PredefinedKind::Any,
618        "BOOLEAN" => PredefinedKind::Boolean,
619        "STRING" => PredefinedKind::String,
620        "INTEGER" => PredefinedKind::Integer,
621        "FLOAT" => PredefinedKind::Float,
622        "UUID" => PredefinedKind::Uuid,
623        "DATE" => PredefinedKind::Date,
624        "DURATION" => PredefinedKind::Duration,
625        "POINT" => PredefinedKind::Point,
626        "LOCAL TIME" => PredefinedKind::LocalTime,
627        "ZONED TIME" => PredefinedKind::ZonedTime,
628        "LOCAL DATETIME" => PredefinedKind::LocalDateTime,
629        "ZONED DATETIME" => PredefinedKind::ZonedDateTime,
630        "NODE" => PredefinedKind::Node,
631        "RELATIONSHIP" => PredefinedKind::Relationship,
632        "PATH" => PredefinedKind::Path,
633        "MAP" => PredefinedKind::Map,
634        _ => return None,
635    })
636}
637
638#[cfg(test)]
639mod tests;