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
352pub 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
379fn 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
407fn 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
424pub 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 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
472pub 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
487pub 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 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
538pub 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
584fn 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
612fn 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;