1use std::cmp::Ordering;
23
24use crate::ast::{PredefinedKind, TypeExpr, VectorCoordKind};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct CanonType {
29 pub kind: CanonKind,
30 pub not_null: bool,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum CanonKind {
39 Predefined(PredefinedKind),
40 List(Box<CanonType>),
41 Vector {
48 coord: Option<VectorCoordKind>,
49 dimension: Option<i64>,
50 },
51 Union(Vec<CanonType>),
54}
55
56fn vector_coord_name(k: VectorCoordKind) -> &'static str {
61 k.canonical_name()
62}
63
64fn vector_coord_kind_from_name(name: &str) -> Option<VectorCoordKind> {
66 VectorCoordKind::from_canonical_name(name)
67}
68
69impl CanonType {
70 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
97fn 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
122fn rank(kind: &CanonKind) -> u8 {
131 match kind {
132 CanonKind::Predefined(k) => match k {
133 PredefinedKind::Nothing => 0,
134 PredefinedKind::Null => 1,
135 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
161pub 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
195fn 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
232fn is_nullable_trigger(t: &CanonType) -> bool {
237 !t.not_null && !matches!(t.kind, CanonKind::Predefined(PredefinedKind::Nothing))
238}
239
240fn 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 return i > j;
253 }
254 is_subtype(item, other)
255 });
256 if !redundant {
257 result.push(item.clone());
258 }
259 }
260 result
261}
262
263fn 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
280fn 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 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
312pub 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 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
377pub 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
404fn 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
432fn 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
449pub 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 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
497pub 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
512pub 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 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
563pub 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
609fn 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
637fn 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;