1use anyhow::{Result, bail};
10
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex, OnceLock};
13
14use crate::{TypeDescriptor, Value};
15
16pub const MAX_GENERIC_DEPTH: usize = 8;
21
22#[macro_export]
30macro_rules! union_tag {
31 ($($member:ident),+ $(,)?) => {
32 $crate::TypeTag::union(vec![$($crate::TypeTag::$member),+])
33 };
34}
35
36#[derive(Debug, Clone)]
38pub struct Field {
39 pub name: String,
43 pub ty: TypeTag,
45 pub docs: &'static str,
48 pub optional: bool,
54 pub default: Option<Value>,
59 pub alias: Option<String>,
63}
64
65#[derive(Clone)]
77pub enum TypeTag {
78 String,
79 Int,
80 Float,
81 Bool,
82 List,
83 Map,
84 Pipe,
85 Handle,
86 HandleOf(Arc<TypeTag>),
87 Void,
88 Duration,
89 Path,
90 Semaphore,
91 Permit,
92 Any,
96 Custom(&'static TypeDescriptor),
97 ListOf(Arc<TypeTag>),
98 Record(Arc<[Field]>),
99 MapOf(Arc<TypeTag>),
100 Union(Arc<str>, Arc<[TypeTag]>),
108}
109
110pub const ANY_TAG: TypeTag = TypeTag::Any;
113
114pub const MAP_TAG: TypeTag = TypeTag::Map;
117
118pub const LIST_TAG: TypeTag = TypeTag::List;
120
121pub const HANDLE_TYPE_NAME: &str = "HANDLE";
125
126pub const LIST_TYPE_NAME: &str = "LIST";
129
130pub const MAP_TYPE_NAME: &str = "MAP";
133
134pub const ANY_TYPE_NAME: &str = "ANY";
137
138pub const STRING_TYPE_NAME: &str = "STRING";
140
141pub const INT_TYPE_NAME: &str = "INT";
143
144pub const FLOAT_TYPE_NAME: &str = "FLOAT";
146
147pub const BOOL_TYPE_NAME: &str = "BOOL";
149
150pub const PIPE_TYPE_NAME: &str = "PIPE";
152
153pub const VOID_TYPE_NAME: &str = "VOID";
155
156pub const DURATION_TYPE_NAME: &str = "DURATION";
158
159pub const PATH_TYPE_NAME: &str = "PATH";
161
162pub const SEMAPHORE_TYPE_NAME: &str = "SEMAPHORE";
164
165pub const PERMIT_TYPE_NAME: &str = "PERMIT";
167
168pub const ALIAS_KEYWORD: &str = "ALIAS";
172impl std::fmt::Debug for TypeTag {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 match self {
175 TypeTag::Custom(descriptor) => {
176 write!(f, "Custom({})", descriptor.name)
177 }
178 TypeTag::ListOf(element) => write!(f, "ListOf({element:?})"),
179 TypeTag::HandleOf(inner) => write!(f, "HandleOf({inner:?})"),
180 TypeTag::MapOf(values) => write!(f, "MapOf({values:?})"),
181 TypeTag::Record(fields) => {
182 let names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();
183 write!(f, "Record({})", names.join(", "))
184 }
185 TypeTag::Union(spelling, _) => write!(f, "Union({spelling})"),
190 tag => write!(f, "{}", tag.name()),
191 }
192 }
193}
194
195impl std::fmt::Display for TypeTag {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.write_str(self.name())
198 }
199}
200impl TypeTag {
201 pub fn union(members: Vec<TypeTag>) -> TypeTag {
208 let spelling: Arc<str> = members
209 .iter()
210 .map(render_structural)
211 .collect::<Vec<_>>()
212 .join("|")
213 .into();
214 TypeTag::Union(spelling, Arc::from(members))
215 }
216
217 pub fn name(&self) -> &str {
222 match self {
223 TypeTag::String => STRING_TYPE_NAME,
224 TypeTag::Int => INT_TYPE_NAME,
225 TypeTag::Float => FLOAT_TYPE_NAME,
226 TypeTag::Bool => BOOL_TYPE_NAME,
227 TypeTag::List => LIST_TYPE_NAME,
228 TypeTag::Map => MAP_TYPE_NAME,
229 TypeTag::Pipe => PIPE_TYPE_NAME,
230 TypeTag::Handle => HANDLE_TYPE_NAME,
231 TypeTag::HandleOf(_) => HANDLE_TYPE_NAME,
232 TypeTag::Void => VOID_TYPE_NAME,
233 TypeTag::Duration => DURATION_TYPE_NAME,
234 TypeTag::Path => PATH_TYPE_NAME,
235 TypeTag::Semaphore => SEMAPHORE_TYPE_NAME,
236 TypeTag::Permit => PERMIT_TYPE_NAME,
237 TypeTag::Any => ANY_TYPE_NAME,
238 TypeTag::Union(spelling, _) => spelling,
241 TypeTag::Custom(descriptor) => descriptor.name,
242 TypeTag::ListOf(_) => LIST_TYPE_NAME,
243 TypeTag::MapOf(_) => MAP_TYPE_NAME,
244 TypeTag::Record(_) => MAP_TYPE_NAME,
245 }
246 }
247
248 pub fn builtin(name: &str) -> Option<TypeTag> {
252 match name {
253 STRING_TYPE_NAME => Some(TypeTag::String),
254 INT_TYPE_NAME => Some(TypeTag::Int),
255 FLOAT_TYPE_NAME => Some(TypeTag::Float),
256 BOOL_TYPE_NAME => Some(TypeTag::Bool),
257 LIST_TYPE_NAME => Some(TypeTag::List),
258 MAP_TYPE_NAME => Some(TypeTag::Map),
259 PIPE_TYPE_NAME => Some(TypeTag::Pipe),
260 HANDLE_TYPE_NAME => Some(TypeTag::Handle),
261 VOID_TYPE_NAME => Some(TypeTag::Void),
262 DURATION_TYPE_NAME => Some(TypeTag::Duration),
263 PATH_TYPE_NAME => Some(TypeTag::Path),
264 SEMAPHORE_TYPE_NAME => Some(TypeTag::Semaphore),
265 PERMIT_TYPE_NAME => Some(TypeTag::Permit),
266 ANY_TYPE_NAME => Some(TypeTag::Any),
267 _ => None,
268 }
269 }
270
271 pub fn fields(&self) -> Option<&[Field]> {
276 match self {
277 TypeTag::Record(fields) => Some(fields),
278 TypeTag::String
279 | TypeTag::Int
280 | TypeTag::Float
281 | TypeTag::Bool
282 | TypeTag::List
283 | TypeTag::Map
284 | TypeTag::Pipe
285 | TypeTag::Handle
286 | TypeTag::HandleOf(_)
287 | TypeTag::Void
288 | TypeTag::Duration
289 | TypeTag::Path
290 | TypeTag::Semaphore
291 | TypeTag::Permit
292 | TypeTag::Any
293 | TypeTag::Custom(_)
294 | TypeTag::ListOf(_)
295 | TypeTag::MapOf(_)
296 | TypeTag::Union(..) => None,
297 }
298 }
299}
300
301pub fn render_structural(tag: &TypeTag) -> String {
306 match tag {
307 TypeTag::ListOf(inner) => format!("LIST<{}>", render_structural(inner)),
308 TypeTag::HandleOf(inner) => format!("HANDLE<{}>", render_structural(inner)),
309 TypeTag::MapOf(values) => format!("MAP<{}>", render_structural(values)),
310 TypeTag::Record(fields) => {
311 let field_list = fields
312 .iter()
313 .map(|field| {
314 format!(
315 "{}{}: {}{}{}",
316 field.name,
317 if field.optional { "?" } else { "" },
318 render_structural(&field.ty),
319 field
320 .alias
321 .as_ref()
322 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
323 .unwrap_or_default(),
324 field
325 .default
326 .as_ref()
327 .map(|d| format!(" = {}", render_default_value(d)))
328 .unwrap_or_default(),
329 )
330 })
331 .collect::<Vec<_>>()
332 .join(", ");
333 format!("MAP<{field_list}>")
334 }
335 tag => tag.name().to_string(),
336 }
337}
338
339#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum Spelled {
348 Named(String),
349 Generic {
350 name: String,
351 args: Vec<SpelledField>,
352 },
353 Union(Vec<Spelled>),
354}
355
356#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct SpelledField {
363 pub name: Option<String>,
364 pub optional: bool,
365 pub ty: Spelled,
366 pub alias: Option<String>,
367 pub default: Option<SpelledDefault>,
368}
369
370#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum SpelledDefault {
377 Str(String),
378 Int(i64),
379 Float(u64),
380 Bool(bool),
381}
382
383impl SpelledDefault {
384 pub fn to_value(&self) -> Value {
387 match self {
388 SpelledDefault::Str(s) => Value::string(s.clone()),
389 SpelledDefault::Int(n) => Value::int(*n),
390 SpelledDefault::Float(bits) => Value::float(f64::from_bits(*bits)),
391 SpelledDefault::Bool(b) => Value::bool(*b),
392 }
393 }
394
395 pub fn render(&self) -> String {
399 match self {
400 SpelledDefault::Str(s) => format!("\"{s}\""),
401 SpelledDefault::Int(n) => format!("{n}"),
402 SpelledDefault::Float(bits) => format!("{:?}", f64::from_bits(*bits)),
403 SpelledDefault::Bool(b) => format!("{b}"),
404 }
405 }
406}
407
408pub fn render_default_value(value: &Value) -> String {
416 if let Some(n) = value.as_i64() {
417 return format!("{n}");
418 }
419 if let Some(f) = value.as_f64() {
420 return format!("{f:?}");
421 }
422 if let Some(b) = value.as_bool() {
423 return format!("{b}");
424 }
425 if let Some(s) = value.as_str() {
426 return format!("\"{s}\"");
427 }
428 format!("{value:?}")
429}
430
431pub fn canonicalize_spelling(s: &str) -> String {
439 match parse_spelling(s) {
440 Ok(spelled) => render_spelled(&spelled),
441 Err(_) => s.trim().to_string(),
442 }
443}
444
445pub fn render_spelled(spelled: &Spelled) -> String {
449 match spelled {
450 Spelled::Named(name) => name.clone(),
451 Spelled::Union(members) => members
452 .iter()
453 .map(render_spelled)
454 .collect::<Vec<_>>()
455 .join("|"),
456 Spelled::Generic { name, args } => {
457 let rendered: Vec<String> = args
458 .iter()
459 .map(|field| match &field.name {
460 Some(field_name) => format!(
461 "{}{}: {}{}{}",
462 field_name,
463 if field.optional { "?" } else { "" },
464 render_spelled(&field.ty),
465 field
466 .alias
467 .as_ref()
468 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
469 .unwrap_or_default(),
470 field
471 .default
472 .as_ref()
473 .map(|d| format!(" = {}", d.render()))
474 .unwrap_or_default(),
475 ),
476 None => render_spelled(&field.ty),
477 })
478 .collect();
479 format!("{name}<{}>", rendered.join(", "))
480 }
481 }
482}
483
484pub fn parse_spelling(s: &str) -> Result<Spelled, String> {
490 let text: String = strip_spelling_whitespace(s);
491 let (spelled, rest) = parse_spelled_one(&text, 0)?;
492 if !rest.is_empty() {
493 return Err(format!(
494 "unexpected trailing text in type spelling: {rest:?}"
495 ));
496 }
497 Ok(spelled)
498}
499
500const WS_SENTINEL: char = '\u{1f}';
506
507fn is_spelling_word_char(ch: char) -> bool {
510 ch.is_ascii_alphanumeric() || ch == '_'
511}
512
513fn strip_spelling_whitespace(s: &str) -> String {
520 let mut out = String::with_capacity(s.len());
521 let mut quoted = false;
522 let mut pending_space = false;
523 let mut prev_word = false;
524 for ch in s.chars() {
525 if ch == '"' {
526 pending_space = false;
527 out.push(ch);
528 quoted = !quoted;
529 prev_word = false;
530 continue;
531 }
532 if !quoted && ch.is_whitespace() {
533 pending_space = true;
534 continue;
535 }
536 if pending_space && prev_word && !quoted && is_spelling_word_char(ch) {
537 out.push(WS_SENTINEL);
538 }
539 pending_space = false;
540 out.push(ch);
541 prev_word = !quoted && is_spelling_word_char(ch);
542 }
543 out
544}
545
546fn parse_spelled_one(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
547 let (first, mut rest) = parse_spelled_shape(text, depth)?;
548 if !rest.starts_with('|') {
549 return Ok((first, rest));
550 }
551 let mut members = vec![first];
556 while let Some(tail) = rest.strip_prefix('|') {
557 let (next, after) = parse_spelled_shape(tail, depth)?;
558 members.push(next);
559 rest = after;
560 }
561 Ok((Spelled::Union(members), rest))
562}
563
564fn parse_spelled_shape(text: &str, depth: usize) -> Result<(Spelled, &str), String> {
565 if depth > MAX_GENERIC_DEPTH {
566 return Err(format!(
567 "type spelling exceeds maximum generic depth of {MAX_GENERIC_DEPTH}: {text:?}"
568 ));
569 }
570 let mut chars = text.char_indices();
571 let Some((_, first)) = chars.next() else {
572 return Err("expected type name, found end of spelling".to_string());
573 };
574 if !first.is_ascii_uppercase() {
575 return Err(format!("expected uppercase type name, found {first:?}"));
576 }
577 let mut end = first.len_utf8();
578 for (idx, ch) in chars {
579 if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
580 end = idx + ch.len_utf8();
581 } else {
582 break;
583 }
584 }
585 let (name, mut rest) = text.split_at(end);
586 let name = name.to_string();
587 if !rest.starts_with('<') {
588 return Ok((Spelled::Named(name), rest));
589 }
590 rest = &rest[1..];
591 let mut args = Vec::new();
592 loop {
593 let (field_name, optional, after_name) = parse_spelled_field_name(rest);
594 let (arg, after_arg) = parse_spelled_one(after_name, depth + 1)?;
595 let (alias, after_alias) = parse_spelled_alias(after_arg)?;
596 if alias.is_some() && field_name.is_none() {
599 return Err(format!(
600 "{ALIAS_KEYWORD} needs a named field, found bare {rest:?}"
601 ));
602 }
603 let (default, after_default) = parse_spelled_default(after_alias)?;
604 args.push(SpelledField {
605 name: field_name,
606 optional,
607 ty: arg,
608 alias,
609 default,
610 });
611 rest = after_default;
612 if let Some(tail) = rest.strip_prefix(',') {
613 rest = tail;
614 continue;
615 }
616 if let Some(tail) = rest.strip_prefix('>') {
617 rest = tail;
618 break;
619 }
620 return Err(format!(
621 "expected ',' or '>' in type spelling, found {rest:?}"
622 ));
623 }
624 Ok((Spelled::Generic { name, args }, rest))
625}
626
627fn parse_spelled_field_name(text: &str) -> (Option<String>, bool, &str) {
632 let mut chars = text.char_indices();
633 let Some((_, first)) = chars.next() else {
634 return (None, false, text);
635 };
636 if !first.is_ascii_lowercase() {
637 return (None, false, text);
638 };
639 let mut end = first.len_utf8();
640 for (idx, ch) in chars {
641 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
642 end = idx + ch.len_utf8();
643 } else {
644 break;
645 }
646 }
647 let (candidate, rest) = text.split_at(end);
648 let (optional, rest) = match rest.strip_prefix('?') {
649 Some(after) => (true, after),
650 None => (false, rest),
651 };
652 match rest.strip_prefix(':') {
653 Some(after) => (Some(candidate.to_string()), optional, after),
654 None => (None, false, text),
655 }
656}
657
658fn parse_spelled_alias(text: &str) -> Result<(Option<String>, &str), String> {
665 let text = text.strip_prefix(WS_SENTINEL).unwrap_or(text);
666 let Some(after_keyword) = text.strip_prefix(ALIAS_KEYWORD) else {
667 return Ok((None, text));
668 };
669 let after_keyword = after_keyword
670 .strip_prefix(WS_SENTINEL)
671 .unwrap_or(after_keyword);
672 if after_keyword.is_empty() {
673 return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
674 }
675 let mut chars = after_keyword.char_indices();
676 let Some((_, first)) = chars.next() else {
677 return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
678 };
679 if !first.is_ascii_lowercase() {
680 if !first.is_ascii_alphabetic() {
681 return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
682 }
683 return Err(format!(
684 "{ALIAS_KEYWORD} name must start lowercase, found {first:?} in {after_keyword:?}"
685 ));
686 }
687 let mut end = first.len_utf8();
688 for (idx, ch) in chars {
689 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
690 end = idx + ch.len_utf8();
691 } else {
692 break;
693 }
694 }
695 let (alias, rest) = after_keyword.split_at(end);
696 if alias.is_empty() {
697 return Err(format!("{ALIAS_KEYWORD} needs a lowercase alias name"));
698 }
699 Ok((Some(alias.to_string()), rest))
700}
701
702fn parse_spelled_default(text: &str) -> Result<(Option<SpelledDefault>, &str), String> {
708 let Some(after_eq) = text.strip_prefix('=') else {
709 return Ok((None, text));
710 };
711 let (lit, rest) = parse_spelled_literal(after_eq)?;
712 Ok((Some(lit), rest))
713}
714
715fn parse_spelled_literal(text: &str) -> Result<(SpelledDefault, &str), String> {
720 if let Some(after) = text.strip_prefix('"') {
721 match after.find('"') {
722 Some(end) => {
723 let (body, rest) = after.split_at(end);
724 return Ok((SpelledDefault::Str(body.to_string()), &rest[1..]));
725 }
726 None => {
727 return Err(format!(
728 "unterminated string default in type spelling: {text:?}"
729 ));
730 }
731 }
732 }
733 if let Some(rest) = text.strip_prefix("true") {
734 return Ok((SpelledDefault::Bool(true), rest));
735 }
736 if let Some(rest) = text.strip_prefix("false") {
737 return Ok((SpelledDefault::Bool(false), rest));
738 }
739 let bytes = text.as_bytes();
740 let mut i = 0;
741 if bytes.first() == Some(&b'-') {
742 i += 1;
743 }
744 let int_start = i;
745 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
746 i += 1;
747 }
748 if i == int_start {
749 return Err(format!(
750 "expected default literal (INT, FLOAT, BOOL, or quoted STRING) in type spelling, found {text:?}"
751 ));
752 }
753 let mut is_float = false;
754 if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(|b| b.is_ascii_digit()) {
755 is_float = true;
756 i += 1;
757 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
758 i += 1;
759 }
760 }
761 let (num, rest) = text.split_at(i);
762 if is_float {
763 match num.parse::<f64>() {
764 Ok(f) if f.is_finite() => Ok((SpelledDefault::Float(f.to_bits()), rest)),
765 _ => Err(format!("bad float default in type spelling: {num:?}")),
766 }
767 } else {
768 match num.parse::<i64>() {
769 Ok(n) => Ok((SpelledDefault::Int(n), rest)),
770 Err(_) => Err(format!("bad integer default in type spelling: {num:?}")),
771 }
772 }
773}
774
775static RENDERD_TAGS: OnceLock<Mutex<HashMap<String, TypeTag>>> = OnceLock::new();
780
781fn rendered_table() -> &'static Mutex<HashMap<String, TypeTag>> {
782 RENDERD_TAGS.get_or_init(|| Mutex::new(HashMap::new()))
783}
784
785pub fn lookup_rendered(canonical: &str) -> Option<TypeTag> {
789 rendered_table()
790 .lock()
791 .unwrap_or_else(|poisoned| poisoned.into_inner())
792 .get(canonical)
793 .cloned()
794}
795
796pub fn intern_rendered(canonical: String, tag: TypeTag) -> TypeTag {
802 let mut table = rendered_table()
803 .lock()
804 .unwrap_or_else(|poisoned| poisoned.into_inner());
805 if let Some(hit) = table.get(&canonical) {
806 return hit.clone();
807 }
808 table.insert(canonical, tag.clone());
809 tag
810}
811
812pub fn check_value(tag: &TypeTag, value: &Value) -> Result<()> {
818 check_value_at(tag, value, "$")
819}
820
821pub fn check_value_at(tag: &TypeTag, value: &Value, path: &str) -> Result<()> {
827 match tag {
828 TypeTag::Any => Ok(()),
829 TypeTag::String if value.as_str().is_some() => Ok(()),
830 TypeTag::Int if value.as_i64().is_some() => Ok(()),
831 TypeTag::Float if value.as_f64().is_some() => Ok(()),
832 TypeTag::Bool if value.as_bool().is_some() => Ok(()),
833 TypeTag::Pipe if value.as_pipe_handle().is_some() => Ok(()),
834 TypeTag::Handle if value.as_handle().is_some() => Ok(()),
835 TypeTag::HandleOf(_) if value.as_handle().is_some() => Ok(()),
836 TypeTag::Void => bail!("{path}: expected VOID, got {}", value.type_name()),
837 TypeTag::Duration if value.as_duration().is_some() => Ok(()),
838 TypeTag::Path if value.as_path().is_some() => Ok(()),
839 TypeTag::Semaphore if value.as_semaphore().is_some() => Ok(()),
840 TypeTag::Permit if value.as_permit().is_some() => Ok(()),
841 TypeTag::List => match value.as_list() {
842 Some(_) => Ok(()),
843 None => bail!("{path}: expected LIST, got {}", value.type_name()),
844 },
845 TypeTag::Map => match value.as_map() {
846 Some(_) => Ok(()),
847 None => bail!("{path}: expected MAP, got {}", value.type_name()),
848 },
849 TypeTag::ListOf(element) => match value.as_list() {
850 Some(items) => {
851 for (idx, item) in items.iter().enumerate() {
852 check_value_at(element, item, &format!("{path}[{idx}]"))?;
853 }
854 Ok(())
855 }
856 None => bail!("{path}: expected LIST, got {}", value.type_name()),
857 },
858 TypeTag::MapOf(values) => match value.as_map() {
859 Some(map) => {
860 for (key, item) in map.iter() {
861 check_value_at(values, item, &format!("{path}.{key}"))?;
862 }
863 Ok(())
864 }
865 None => bail!(
866 "{path}: expected {}, got {}",
867 render_structural(tag),
868 value.type_name()
869 ),
870 },
871 TypeTag::Record(fields) => match value.as_map() {
872 Some(map) => {
873 for field in fields.iter() {
874 match map.get(field.name.as_str()) {
875 Some(item) => {
876 check_value_at(&field.ty, item, &format!("{path}.{}", field.name))?;
877 }
878 None if field.optional || field.default.is_some() => {}
883 None => bail!(
884 "{path}: missing field '{}'; expected fields: {}",
885 field.name,
886 field_list(fields),
887 ),
888 }
889 }
890 for key in map.keys() {
891 if !fields.iter().any(|field| field.name == *key) {
892 bail!(
893 "{path}: unknown field '{key}'; expected fields: {}",
894 field_list(fields),
895 );
896 }
897 }
898 Ok(())
899 }
900 None => bail!("{path}: expected MAP, got {}", value.type_name()),
901 },
902 TypeTag::Custom(descriptor) => {
903 if value.type_name() == descriptor.name {
904 Ok(())
905 } else {
906 bail!(
907 "{path}: expected {}, got {}",
908 descriptor.name,
909 value.type_name(),
910 )
911 }
912 }
913 TypeTag::Union(_, members) => {
917 if members
918 .iter()
919 .any(|member| check_value(member, value).is_ok())
920 {
921 Ok(())
922 } else {
923 bail!(
924 "{path}: expected {}, got {}",
925 render_structural(tag),
926 value.type_name()
927 )
928 }
929 }
930 TypeTag::String
934 | TypeTag::Int
935 | TypeTag::Float
936 | TypeTag::Bool
937 | TypeTag::Pipe
938 | TypeTag::Handle
939 | TypeTag::HandleOf(_)
940 | TypeTag::Duration
941 | TypeTag::Path
942 | TypeTag::Semaphore
943 | TypeTag::Permit => bail!("{path}: expected {}, got {}", tag.name(), value.type_name()),
944 }
945}
946
947fn field_list(fields: &[Field]) -> String {
948 fields
949 .iter()
950 .map(|field| field.name.as_str())
951 .collect::<Vec<_>>()
952 .join(", ")
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use std::collections::BTreeMap;
959 use std::sync::Arc;
960
961 fn map(entries: &[(&str, Value)]) -> Value {
962 Value::map(
963 entries
964 .iter()
965 .map(|(k, v)| ((*k).to_string(), v.clone()))
966 .collect::<BTreeMap<_, _>>(),
967 )
968 }
969
970 #[test]
971 fn builtin_round_trips_through_names() {
972 for name in [
973 "STRING",
974 "INT",
975 "FLOAT",
976 "BOOL",
977 "LIST",
978 "MAP",
979 "PIPE",
980 "HANDLE",
981 "DURATION",
982 "PATH",
983 "SEMAPHORE",
984 "PERMIT",
985 ] {
986 let tag = TypeTag::builtin(name).expect("builtin");
987 assert_eq!(tag.name(), name);
988 }
989 assert!(TypeTag::builtin("NOPE").is_none());
990 assert!(TypeTag::builtin("string").is_none());
991 }
992
993 #[test]
994 fn scalars_conform_by_discriminant() {
995 assert!(check_value(&TypeTag::String, &Value::string("x".to_string())).is_ok());
996 assert!(check_value(&TypeTag::Int, &Value::int(1)).is_ok());
997 assert!(check_value(&TypeTag::String, &Value::int(1)).is_err());
998 assert!(check_value(&TypeTag::Int, &Value::float(3.0)).is_err());
1000 }
1001
1002 #[test]
1003 fn record_rejects_missing_and_extra_fields() {
1004 let fields: Arc<[Field]> = Arc::from([
1005 Field {
1006 name: "a".to_string(),
1007 ty: TypeTag::String,
1008 docs: "",
1009 optional: false,
1010 default: None,
1011
1012 alias: None,
1013 },
1014 Field {
1015 name: "b".to_string(),
1016 ty: TypeTag::Int,
1017 docs: "",
1018 optional: false,
1019 default: None,
1020
1021 alias: None,
1022 },
1023 ]);
1024 let tag = TypeTag::Record(fields);
1025 let good = map(&[("a", Value::string("x".to_string())), ("b", Value::int(1))]);
1026 assert!(check_value(&tag, &good).is_ok());
1027 let missing = map(&[("a", Value::string("x".to_string()))]);
1028 let err = check_value(&tag, &missing).expect_err("missing must fail");
1029 assert!(format!("{err:#}").contains('b'), "names the field: {err:#}");
1030 let extra = map(&[
1031 ("a", Value::string("x".to_string())),
1032 ("b", Value::int(1)),
1033 ("c", Value::int(2)),
1034 ]);
1035 let err = check_value(&tag, &extra).expect_err("extra must fail");
1036 assert!(format!("{err:#}").contains('c'), "names the field: {err:#}");
1037 let mistyped = map(&[
1038 ("a", Value::string("x".to_string())),
1039 ("b", Value::string("nope".to_string())),
1040 ]);
1041 assert!(check_value(&tag, &mistyped).is_err());
1042 }
1043
1044 #[test]
1045 fn record_optional_fields_may_be_absent() {
1046 let fields: Arc<[Field]> = Arc::from([
1049 Field {
1050 name: "held".to_string(),
1051 ty: TypeTag::Int,
1052 docs: "",
1053 optional: false,
1054 default: None,
1055
1056 alias: None,
1057 },
1058 Field {
1059 name: "permit".to_string(),
1060 ty: TypeTag::String,
1061 docs: "",
1062 optional: true,
1063 default: None,
1064
1065 alias: None,
1066 },
1067 ]);
1068 let tag = TypeTag::Record(fields);
1069 let full = map(&[
1070 ("held", Value::int(1)),
1071 ("permit", Value::string("p".to_string())),
1072 ]);
1073 assert!(check_value(&tag, &full).is_ok());
1074 let missing_optional = map(&[("held", Value::int(0))]);
1075 assert!(check_value(&tag, &missing_optional).is_ok());
1076 let missing_required = map(&[("permit", Value::string("p".to_string()))]);
1077 let err = check_value(&tag, &missing_required).expect_err("missing required must fail");
1078 assert!(
1079 format!("{err:#}").contains("held"),
1080 "names the field: {err:#}"
1081 );
1082 let mistyped_optional = map(&[("held", Value::int(1)), ("permit", Value::int(2))]);
1083 assert!(check_value(&tag, &mistyped_optional).is_err());
1084 }
1085
1086 #[test]
1087 fn list_of_checks_elements_with_index() {
1088 let tag = TypeTag::ListOf(Arc::new(TypeTag::Int));
1089 let good = Value::list(vec![Value::int(1), Value::int(2)]);
1090 assert!(check_value(&tag, &good).is_ok());
1091 let bad = Value::list(vec![Value::int(1), Value::string("x".to_string())]);
1092 let err = check_value(&tag, &bad).expect_err("bad element must fail");
1093 assert!(
1094 format!("{err:#}").contains("[1]"),
1095 "names the index: {err:#}"
1096 );
1097 }
1098
1099 #[test]
1100 fn canonicalization_unifies_input_spacing() {
1101 assert_eq!(canonicalize_spelling("LIST<MAP>"), "LIST<MAP>");
1104 assert_eq!(canonicalize_spelling("LIST< MAP >"), "LIST<MAP>");
1105 assert_eq!(
1106 canonicalize_spelling("MAP<name:STRING,age:INT>"),
1107 "MAP<name: STRING, age: INT>"
1108 );
1109 assert_eq!(
1110 canonicalize_spelling("MAP<name : STRING>"),
1111 "MAP<name: STRING>"
1112 );
1113 }
1114
1115 #[test]
1116 fn spellings_parse_to_shapes() {
1117 assert_eq!(
1118 parse_spelling("LIST<MAP>").expect("parses"),
1119 Spelled::Generic {
1120 name: "LIST".to_string(),
1121 args: vec![SpelledField {
1122 name: None,
1123 optional: false,
1124 ty: Spelled::Named("MAP".to_string()),
1125 default: None,
1126
1127 alias: None,
1128 }],
1129 }
1130 );
1131 assert_eq!(
1132 parse_spelling("MAP<name: STRING>").expect("parses"),
1133 Spelled::Generic {
1134 name: "MAP".to_string(),
1135 args: vec![SpelledField {
1136 name: Some("name".to_string()),
1137 optional: false,
1138 ty: Spelled::Named("STRING".to_string()),
1139 default: None,
1140
1141 alias: None,
1142 }],
1143 }
1144 );
1145 assert!(parse_spelling("LIST<A, B>").is_ok());
1148 assert!(parse_spelling("MAP<STRING>").is_ok());
1149 }
1150
1151 #[test]
1152 fn optional_field_spelling_parses_and_renders() {
1153 assert_eq!(
1156 parse_spelling("MAP<permit?: PERMIT>").expect("parses"),
1157 Spelled::Generic {
1158 name: "MAP".to_string(),
1159 args: vec![SpelledField {
1160 name: Some("permit".to_string()),
1161 optional: true,
1162 ty: Spelled::Named("PERMIT".to_string()),
1163 default: None,
1164
1165 alias: None,
1166 }],
1167 }
1168 );
1169 assert_eq!(
1170 canonicalize_spelling("MAP<permit ? : PERMIT>"),
1171 "MAP<permit?: PERMIT>"
1172 );
1173 }
1174
1175 #[test]
1176 fn default_spellings_parse_render_and_materialize() {
1177 for (spelling, canonical, value) in [
1181 (
1182 "MAP<retries: INT = 2>",
1183 "MAP<retries: INT = 2>",
1184 Value::int(2),
1185 ),
1186 (
1187 "MAP<retries: INT=-2>",
1188 "MAP<retries: INT = -2>",
1189 Value::int(-2),
1190 ),
1191 (
1192 "MAP<ratio: FLOAT = 2.5>",
1193 "MAP<ratio: FLOAT = 2.5>",
1194 Value::float(2.5),
1195 ),
1196 (
1197 "MAP<on: BOOL = true>",
1198 "MAP<on: BOOL = true>",
1199 Value::bool(true),
1200 ),
1201 (
1202 "MAP<model: STRING = \"gpt-4\">",
1203 "MAP<model: STRING = \"gpt-4\">",
1204 Value::string("gpt-4".to_string()),
1205 ),
1206 (
1207 "MAP<msg: STRING = \"hello world\">",
1208 "MAP<msg: STRING = \"hello world\">",
1209 Value::string("hello world".to_string()),
1210 ),
1211 ] {
1212 let spelled = parse_spelling(spelling).expect("parses");
1213 assert_eq!(render_spelled(&spelled), canonical, "canonical: {spelling}");
1214 assert_eq!(canonicalize_spelling(spelling), canonical);
1215 match spelled {
1216 Spelled::Generic { args, .. } => {
1217 let found = args.iter().find(|f| f.default.is_some()).expect("default");
1218 let lit = found.default.as_ref().expect("lit");
1219 assert_eq!(lit.to_value(), value);
1220 assert!(
1221 canonical.contains(&format!("= {}", lit.render())),
1222 "canonical carries the default: {canonical}"
1223 );
1224 }
1225 other => panic!("expected generic, got {other:?}"),
1226 }
1227 }
1228 let tag = TypeTag::Record(Arc::from([Field {
1230 name: "retries".to_string(),
1231 ty: TypeTag::Int,
1232 docs: "",
1233 optional: false,
1234 default: Some(Value::int(2)),
1235
1236 alias: None,
1237 }]));
1238 assert_eq!(
1239 render_structural(&tag),
1240 "MAP<retries: INT = 2>",
1241 "tag renders defaults canonically"
1242 );
1243 assert_eq!(
1244 render_default_value(&Value::float(2.5)),
1245 "2.5",
1246 "float keeps its point"
1247 );
1248 for bad in [
1251 "MAP<a: INT = >",
1252 "MAP<a: INT = x>",
1253 "MAP<a: INT = 1.2.3>",
1254 "MAP<a: INT = \"x>",
1255 "MAP<a: INT = 9999999999999999999999>",
1256 ] {
1257 assert!(parse_spelling(bad).is_err(), "must fail: {bad}");
1258 }
1259 }
1260
1261 #[test]
1262 fn unknown_map_spelling_parses_and_renders() {
1263 assert_eq!(
1266 parse_spelling("MAP<ANY>").expect("parses"),
1267 Spelled::Generic {
1268 name: "MAP".to_string(),
1269 args: vec![SpelledField {
1270 name: None,
1271 optional: false,
1272 ty: Spelled::Named("ANY".to_string()),
1273 default: None,
1274
1275 alias: None,
1276 }],
1277 }
1278 );
1279 assert_eq!(canonicalize_spelling("MAP< ANY >"), "MAP<ANY>");
1280 assert_eq!(
1281 render_structural(&TypeTag::MapOf(Arc::new(TypeTag::Any))),
1282 "MAP<ANY>"
1283 );
1284 }
1285
1286 #[test]
1287 fn map_of_checks_values_with_paths() {
1288 let tag = TypeTag::MapOf(Arc::new(TypeTag::Int));
1291 let good = map(&[("a", Value::int(1))]);
1292 assert!(check_value(&tag, &good).is_ok());
1293 let bad = map(&[("a", Value::string("x".to_string()))]);
1294 let err = check_value(&tag, &bad).expect_err("bad value must fail");
1295 assert!(format!("{err:#}").contains(".a"), "names the key: {err:#}");
1296 let not_map = Value::list(vec![Value::int(1)]);
1297 let err = check_value(&tag, ¬_map).expect_err("non-map must fail");
1298 assert!(format!("{err:#}").contains("MAP<INT>"), "{err:#}");
1299 }
1300
1301 #[test]
1302 fn spellings_reject_malformed_input() {
1303 for bad in [
1304 "",
1305 "LIST<>",
1306 "LIST<A,>",
1307 "MAP<name:>",
1308 "LIST<A",
1309 "list<MAP>",
1310 "LIST<A>>",
1311 ] {
1312 assert!(parse_spelling(bad).is_err(), "{bad:?} must fail");
1313 }
1314 let mut deep = "INT".to_string();
1316 for _ in 0..MAX_GENERIC_DEPTH + 1 {
1317 deep = format!("LIST<{deep}>");
1318 }
1319 let err = parse_spelling(&deep).expect_err("over-deep spelling must fail");
1320 assert!(err.contains("maximum generic depth"), "{err}");
1321 }
1322
1323 #[test]
1324 fn identical_spellings_share_one_interned_payload() {
1325 let first = intern_rendered(
1326 "LIST<MAP>".to_string(),
1327 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1328 );
1329 let second = intern_rendered(
1330 "LIST<MAP>".to_string(),
1331 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1332 );
1333 let (TypeTag::ListOf(a), TypeTag::ListOf(b)) = (first, second) else {
1334 panic!("rendered tags keep their shape");
1335 };
1336 assert!(
1337 Arc::ptr_eq(&a, &b),
1338 "same canonical spelling shares one payload"
1339 );
1340 }
1341
1342 #[test]
1343 fn structural_rendering_names_contents() {
1344 let fields: Arc<[Field]> = Arc::from([Field {
1345 name: "name".to_string(),
1346 ty: TypeTag::String,
1347 docs: "",
1348 optional: false,
1349 default: None,
1350
1351 alias: None,
1352 }]);
1353 let record = TypeTag::Record(fields);
1354 let list = TypeTag::ListOf(Arc::new(record));
1355 assert_eq!(render_structural(&list), "LIST<MAP<name: STRING>>");
1356 assert_eq!(render_structural(&TypeTag::Int), "INT");
1357 }
1358}