1use anyhow::{Result, bail};
10
11use crate::diagnostics as dsl_diag;
12use oxdock_diagnostics::Diagnostic;
13use std::collections::HashMap;
14use std::sync::{Arc, Mutex, OnceLock};
15
16use crate::{TypeDescriptor, Value, constants::VAR_SIGIL};
17
18pub const MAX_GENERIC_DEPTH: usize = 8;
23
24#[macro_export]
32macro_rules! union_tag {
33 ($($member:ident),+ $(,)?) => {
34 $crate::TypeTag::union(vec![$($crate::TypeTag::$member),+])
35 };
36}
37
38#[derive(Debug, Clone)]
40pub struct Field {
41 pub name: String,
45 pub ty: TypeTag,
47 pub docs: &'static str,
50 pub optional: bool,
56 pub default: Option<Value>,
61 pub alias: Option<String>,
65}
66
67#[derive(Clone)]
79pub enum TypeTag {
80 String,
81 Int,
82 Float,
83 Bool,
84 List,
85 Map,
86 Pipe,
87 Handle,
88 HandleOf(Arc<TypeTag>),
89 Void,
90 Duration,
91 Path,
92 Semaphore,
93 Permit,
94 Any,
98 Custom(&'static TypeDescriptor),
99 ListOf(Arc<TypeTag>),
100 Record(Arc<[Field]>),
101 MapOf(Arc<TypeTag>),
102 Union(Arc<str>, Arc<[TypeTag]>),
110}
111
112pub const ANY_TAG: TypeTag = TypeTag::Any;
115
116pub const MAP_TAG: TypeTag = TypeTag::Map;
119
120pub const LIST_TAG: TypeTag = TypeTag::List;
122
123pub const HANDLE_TYPE_NAME: &str = "HANDLE";
127
128pub const LIST_TYPE_NAME: &str = "LIST";
131
132pub const MAP_TYPE_NAME: &str = "MAP";
135
136pub const ANY_TYPE_NAME: &str = "ANY";
139
140pub const STRING_TYPE_NAME: &str = "STRING";
142
143pub const INT_TYPE_NAME: &str = "INT";
145
146pub const FLOAT_TYPE_NAME: &str = "FLOAT";
148
149pub const BOOL_TYPE_NAME: &str = "BOOL";
151
152pub const PIPE_TYPE_NAME: &str = "PIPE";
154
155pub const VOID_TYPE_NAME: &str = "VOID";
157
158pub const DURATION_TYPE_NAME: &str = "DURATION";
160
161pub const PATH_TYPE_NAME: &str = "PATH";
163
164pub const SEMAPHORE_TYPE_NAME: &str = "SEMAPHORE";
166
167pub const PERMIT_TYPE_NAME: &str = "PERMIT";
169
170pub const ALIAS_KEYWORD: &str = "ALIAS";
174impl std::fmt::Debug for TypeTag {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 match self {
177 TypeTag::Custom(descriptor) => {
178 write!(f, "Custom({})", descriptor.name)
179 }
180 TypeTag::ListOf(element) => write!(f, "ListOf({element:?})"),
181 TypeTag::HandleOf(inner) => write!(f, "HandleOf({inner:?})"),
182 TypeTag::MapOf(values) => write!(f, "MapOf({values:?})"),
183 TypeTag::Record(fields) => {
184 let names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();
185 write!(f, "Record({})", names.join(", "))
186 }
187 TypeTag::Union(spelling, _) => write!(f, "Union({spelling})"),
192 tag => write!(f, "{}", tag.name()),
193 }
194 }
195}
196
197impl std::fmt::Display for TypeTag {
198 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199 f.write_str(self.name())
200 }
201}
202impl TypeTag {
203 pub fn union(members: Vec<TypeTag>) -> TypeTag {
210 let spelling: Arc<str> = members
211 .iter()
212 .map(render_structural)
213 .collect::<Vec<_>>()
214 .join("|")
215 .into();
216 TypeTag::Union(spelling, Arc::from(members))
217 }
218
219 pub fn name(&self) -> &str {
224 match self {
225 TypeTag::String => STRING_TYPE_NAME,
226 TypeTag::Int => INT_TYPE_NAME,
227 TypeTag::Float => FLOAT_TYPE_NAME,
228 TypeTag::Bool => BOOL_TYPE_NAME,
229 TypeTag::List => LIST_TYPE_NAME,
230 TypeTag::Map => MAP_TYPE_NAME,
231 TypeTag::Pipe => PIPE_TYPE_NAME,
232 TypeTag::Handle => HANDLE_TYPE_NAME,
233 TypeTag::HandleOf(_) => HANDLE_TYPE_NAME,
234 TypeTag::Void => VOID_TYPE_NAME,
235 TypeTag::Duration => DURATION_TYPE_NAME,
236 TypeTag::Path => PATH_TYPE_NAME,
237 TypeTag::Semaphore => SEMAPHORE_TYPE_NAME,
238 TypeTag::Permit => PERMIT_TYPE_NAME,
239 TypeTag::Any => ANY_TYPE_NAME,
240 TypeTag::Union(spelling, _) => spelling,
243 TypeTag::Custom(descriptor) => descriptor.name,
244 TypeTag::ListOf(_) => LIST_TYPE_NAME,
245 TypeTag::MapOf(_) => MAP_TYPE_NAME,
246 TypeTag::Record(_) => MAP_TYPE_NAME,
247 }
248 }
249
250 pub fn builtin(name: &str) -> Option<TypeTag> {
254 match name {
255 STRING_TYPE_NAME => Some(TypeTag::String),
256 INT_TYPE_NAME => Some(TypeTag::Int),
257 FLOAT_TYPE_NAME => Some(TypeTag::Float),
258 BOOL_TYPE_NAME => Some(TypeTag::Bool),
259 LIST_TYPE_NAME => Some(TypeTag::List),
260 MAP_TYPE_NAME => Some(TypeTag::Map),
261 PIPE_TYPE_NAME => Some(TypeTag::Pipe),
262 HANDLE_TYPE_NAME => Some(TypeTag::Handle),
263 VOID_TYPE_NAME => Some(TypeTag::Void),
264 DURATION_TYPE_NAME => Some(TypeTag::Duration),
265 PATH_TYPE_NAME => Some(TypeTag::Path),
266 SEMAPHORE_TYPE_NAME => Some(TypeTag::Semaphore),
267 PERMIT_TYPE_NAME => Some(TypeTag::Permit),
268 ANY_TYPE_NAME => Some(TypeTag::Any),
269 _ => None,
270 }
271 }
272
273 pub fn fields(&self) -> Option<&[Field]> {
278 match self {
279 TypeTag::Record(fields) => Some(fields),
280 TypeTag::String
281 | TypeTag::Int
282 | TypeTag::Float
283 | TypeTag::Bool
284 | TypeTag::List
285 | TypeTag::Map
286 | TypeTag::Pipe
287 | TypeTag::Handle
288 | TypeTag::HandleOf(_)
289 | TypeTag::Void
290 | TypeTag::Duration
291 | TypeTag::Path
292 | TypeTag::Semaphore
293 | TypeTag::Permit
294 | TypeTag::Any
295 | TypeTag::Custom(_)
296 | TypeTag::ListOf(_)
297 | TypeTag::MapOf(_)
298 | TypeTag::Union(..) => None,
299 }
300 }
301}
302
303pub fn render_structural(tag: &TypeTag) -> String {
308 match tag {
309 TypeTag::ListOf(inner) => format!("{LIST_TYPE_NAME}<{}>", render_structural(inner)),
310 TypeTag::HandleOf(inner) => format!("{HANDLE_TYPE_NAME}<{}>", render_structural(inner)),
311 TypeTag::MapOf(values) => format!("{MAP_TYPE_NAME}<{}>", render_structural(values)),
312 TypeTag::Record(fields) => {
313 let field_list = fields
314 .iter()
315 .map(|field| {
316 format!(
317 "{}{}: {}{}{}",
318 field.name,
319 if field.optional { "?" } else { "" },
320 render_structural(&field.ty),
321 field
322 .alias
323 .as_ref()
324 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
325 .unwrap_or_default(),
326 field
327 .default
328 .as_ref()
329 .map(|d| format!(" = {}", render_default_value(d)))
330 .unwrap_or_default(),
331 )
332 })
333 .collect::<Vec<_>>()
334 .join(", ");
335 format!("{MAP_TYPE_NAME}<{field_list}>")
336 }
337 tag => tag.name().to_string(),
338 }
339}
340
341#[derive(Debug, Clone, PartialEq, Eq)]
349pub enum Spelled {
350 Named(String),
351 Generic {
352 name: String,
353 args: Vec<SpelledField>,
354 },
355 Union(Vec<Spelled>),
356}
357
358#[derive(Debug, Clone, PartialEq, Eq)]
364pub struct SpelledField {
365 pub name: Option<String>,
366 pub optional: bool,
367 pub ty: Spelled,
368 pub alias: Option<String>,
369 pub default: Option<SpelledDefault>,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
378pub enum SpelledDefault {
379 Str(String),
380 Int(i64),
381 Float(u64),
382 Bool(bool),
383}
384
385impl SpelledDefault {
386 pub fn to_value(&self) -> Value {
389 match self {
390 SpelledDefault::Str(s) => Value::string(s.clone()),
391 SpelledDefault::Int(n) => Value::int(*n),
392 SpelledDefault::Float(bits) => Value::float(f64::from_bits(*bits)),
393 SpelledDefault::Bool(b) => Value::bool(*b),
394 }
395 }
396
397 pub fn render(&self) -> String {
401 match self {
402 SpelledDefault::Str(s) => format!("\"{s}\""),
403 SpelledDefault::Int(n) => format!("{n}"),
404 SpelledDefault::Float(bits) => format!("{:?}", f64::from_bits(*bits)),
405 SpelledDefault::Bool(b) => format!("{b}"),
406 }
407 }
408}
409
410pub fn render_default_value(value: &Value) -> String {
418 if let Some(n) = value.as_i64() {
419 return format!("{n}");
420 }
421 if let Some(f) = value.as_f64() {
422 return format!("{f:?}");
423 }
424 if let Some(b) = value.as_bool() {
425 return format!("{b}");
426 }
427 if let Some(s) = value.as_str() {
428 return format!("\"{s}\"");
429 }
430 format!("{value:?}")
431}
432
433pub fn canonicalize_spelling(s: &str) -> String {
441 match parse_spelling(s) {
442 Ok(spelled) => render_spelled(&spelled),
443 Err(_) => s.trim().to_string(),
444 }
445}
446
447pub fn render_spelled(spelled: &Spelled) -> String {
451 match spelled {
452 Spelled::Named(name) => name.clone(),
453 Spelled::Union(members) => members
454 .iter()
455 .map(render_spelled)
456 .collect::<Vec<_>>()
457 .join("|"),
458 Spelled::Generic { name, args } => {
459 let rendered: Vec<String> = args
460 .iter()
461 .map(|field| match &field.name {
462 Some(field_name) => format!(
463 "{}{}: {}{}{}",
464 field_name,
465 if field.optional { "?" } else { "" },
466 render_spelled(&field.ty),
467 field
468 .alias
469 .as_ref()
470 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
471 .unwrap_or_default(),
472 field
473 .default
474 .as_ref()
475 .map(|d| format!(" = {}", d.render()))
476 .unwrap_or_default(),
477 ),
478 None => render_spelled(&field.ty),
479 })
480 .collect();
481 format!("{name}<{}>", rendered.join(", "))
482 }
483 }
484}
485
486pub fn parse_spelling(s: &str) -> Result<Spelled, Diagnostic> {
492 let text: String = strip_spelling_whitespace(s);
493 let (spelled, rest) = parse_spelled_one(&text, 0)?;
494 if !rest.is_empty() {
495 return Err(dsl_diag::spelling_trailing_text(
496 &dsl_diag::decode_spelling_fragment(rest),
497 ));
498 }
499 Ok(spelled)
500}
501
502fn decode_spelling_fragment(raw: &str) -> String {
506 dsl_diag::decode_spelling_fragment(raw)
507}
508
509pub(crate) const WS_SENTINEL: char = '\u{1f}';
515
516fn is_spelling_word_char(ch: char) -> bool {
519 ch.is_ascii_alphanumeric() || ch == '_'
520}
521
522fn strip_spelling_whitespace(s: &str) -> String {
529 let mut out = String::with_capacity(s.len());
530 let mut quoted = false;
531 let mut pending_space = false;
532 let mut prev_word = false;
533 for ch in s.chars() {
534 if ch == '"' {
535 pending_space = false;
536 out.push(ch);
537 quoted = !quoted;
538 prev_word = false;
539 continue;
540 }
541 if !quoted && ch.is_whitespace() {
542 pending_space = true;
543 continue;
544 }
545 if pending_space && prev_word && !quoted && is_spelling_word_char(ch) {
546 out.push(WS_SENTINEL);
547 }
548 pending_space = false;
549 out.push(ch);
550 prev_word = !quoted && is_spelling_word_char(ch);
551 }
552 out
553}
554
555fn parse_spelled_one(text: &str, depth: usize) -> Result<(Spelled, &str), Diagnostic> {
556 let (first, mut rest) = parse_spelled_shape(text, depth)?;
557 if !rest.starts_with('|') {
558 return Ok((first, rest));
559 }
560 let mut members = vec![first];
565 while let Some(tail) = rest.strip_prefix('|') {
566 let (next, after) = parse_spelled_shape(tail, depth)?;
567 members.push(next);
568 rest = after;
569 }
570 Ok((Spelled::Union(members), rest))
571}
572
573fn parse_spelled_shape(text: &str, depth: usize) -> Result<(Spelled, &str), Diagnostic> {
574 if depth > MAX_GENERIC_DEPTH {
575 return Err(dsl_diag::spelling_max_depth(
576 MAX_GENERIC_DEPTH,
577 &decode_spelling_fragment(text),
578 ));
579 }
580 let mut chars = text.char_indices();
581 let Some((_, first)) = chars.next() else {
582 return Err(dsl_diag::spelling_expected_type_name());
583 };
584 if !first.is_ascii_uppercase() {
585 return Err(dsl_diag::spelling_expected_uppercase(&first.to_string()));
586 }
587 let mut end = first.len_utf8();
588 for (idx, ch) in chars {
589 if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
590 end = idx + ch.len_utf8();
591 } else {
592 break;
593 }
594 }
595 let (name, mut rest) = text.split_at(end);
596 let name = name.to_string();
597 if !rest.starts_with('<') {
598 return Ok((Spelled::Named(name), rest));
599 }
600 rest = &rest[1..];
601 let mut args = Vec::new();
602 loop {
603 let (field_name, optional, after_name) = parse_spelled_field_name(rest);
604 let (arg, after_arg) = parse_spelled_one(after_name, depth + 1)?;
605 let (alias, after_alias) = parse_spelled_alias(after_arg)?;
606 if alias.is_some() && field_name.is_none() {
609 return Err(dsl_diag::alias_needs_field(&decode_spelling_fragment(rest)));
610 }
611 if let Some(second) = peek_second_alias(after_alias) {
615 let field = field_name.as_deref().unwrap_or("<bare>");
616 let first = alias.as_deref().unwrap_or("<unknown>");
617 return Err(dsl_diag::alias_duplicate_on_field(field, first, &second));
618 }
619 let (default, after_default) = parse_spelled_default(after_alias)?;
620 args.push(SpelledField {
621 name: field_name,
622 optional,
623 ty: arg,
624 alias,
625 default,
626 });
627 rest = after_default;
628 if let Some(tail) = rest.strip_prefix(',') {
629 rest = tail;
630 continue;
631 }
632 if let Some(tail) = rest.strip_prefix('>') {
633 rest = tail;
634 break;
635 }
636 return Err(dsl_diag::spelling_expected_delimiter(
637 &decode_spelling_fragment(rest),
638 ));
639 }
640 Ok((Spelled::Generic { name, args }, rest))
641}
642
643fn peek_second_alias(after: &str) -> Option<String> {
649 let text = after.strip_prefix(WS_SENTINEL).unwrap_or(after);
650 let after_keyword = text.strip_prefix(ALIAS_KEYWORD)?;
651 let after_keyword = after_keyword
652 .strip_prefix(WS_SENTINEL)
653 .unwrap_or(after_keyword);
654 if after_keyword.is_empty() {
655 return Some("<missing>".to_string());
656 }
657 let mut end = 0usize;
658 for (idx, ch) in after_keyword.char_indices() {
659 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
660 end = idx + ch.len_utf8();
661 } else {
662 break;
663 }
664 }
665 if end == 0 {
666 let token: String = after_keyword
667 .chars()
668 .take_while(|c| {
669 !matches!(c, ',' | '>' | '=') && *c != WS_SENTINEL && !c.is_whitespace()
670 })
671 .collect();
672 if token.is_empty() {
673 return Some("<invalid>".to_string());
674 }
675 return Some(dsl_diag::decode_spelling_fragment(&token));
676 }
677 Some(after_keyword[..end].to_string())
678}
679
680fn parse_spelled_field_name(text: &str) -> (Option<String>, bool, &str) {
685 let mut chars = text.char_indices();
686 let Some((_, first)) = chars.next() else {
687 return (None, false, text);
688 };
689 if !first.is_ascii_lowercase() {
690 return (None, false, text);
691 };
692 let mut end = first.len_utf8();
693 for (idx, ch) in chars {
694 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
695 end = idx + ch.len_utf8();
696 } else {
697 break;
698 }
699 }
700 let (candidate, rest) = text.split_at(end);
701 let (optional, rest) = match rest.strip_prefix('?') {
702 Some(after) => (true, after),
703 None => (false, rest),
704 };
705 match rest.strip_prefix(':') {
706 Some(after) => (Some(candidate.to_string()), optional, after),
707 None => (None, false, text),
708 }
709}
710
711fn parse_spelled_alias(text: &str) -> Result<(Option<String>, &str), Diagnostic> {
718 let text = text.strip_prefix(WS_SENTINEL).unwrap_or(text);
719 let Some(after_keyword) = text.strip_prefix(ALIAS_KEYWORD) else {
720 return Ok((None, text));
721 };
722 let after_keyword = after_keyword
723 .strip_prefix(WS_SENTINEL)
724 .unwrap_or(after_keyword);
725 if after_keyword.is_empty() {
726 return Err(dsl_diag::alias_needs_name());
727 }
728 let mut chars = after_keyword.char_indices();
729 let Some((_, first)) = chars.next() else {
730 return Err(dsl_diag::alias_needs_name());
731 };
732 if !first.is_ascii_lowercase() {
733 if !first.is_ascii_alphabetic() {
734 return Err(dsl_diag::alias_needs_name());
735 }
736 return Err(dsl_diag::alias_name_lowercase(
737 &first.to_string(),
738 &decode_spelling_fragment(after_keyword),
739 ));
740 }
741 let mut end = first.len_utf8();
742 for (idx, ch) in chars {
743 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
744 end = idx + ch.len_utf8();
745 } else {
746 break;
747 }
748 }
749 let (alias, rest) = after_keyword.split_at(end);
750 if alias.is_empty() {
751 return Err(dsl_diag::alias_needs_name());
752 }
753 Ok((Some(alias.to_string()), rest))
754}
755
756fn parse_spelled_default(text: &str) -> Result<(Option<SpelledDefault>, &str), Diagnostic> {
762 let Some(after_eq) = text.strip_prefix('=') else {
763 return Ok((None, text));
764 };
765 let (lit, rest) = parse_spelled_literal(after_eq)?;
766 Ok((Some(lit), rest))
767}
768
769fn parse_spelled_literal(text: &str) -> Result<(SpelledDefault, &str), Diagnostic> {
774 if let Some(after) = text.strip_prefix('"') {
775 match after.find('"') {
776 Some(end) => {
777 let (body, rest) = after.split_at(end);
778 return Ok((SpelledDefault::Str(body.to_string()), &rest[1..]));
779 }
780 None => {
781 return Err(dsl_diag::spelling_unterminated_string(
782 &decode_spelling_fragment(text),
783 ));
784 }
785 }
786 }
787 if let Some(rest) = text.strip_prefix("true") {
788 return Ok((SpelledDefault::Bool(true), rest));
789 }
790 if let Some(rest) = text.strip_prefix("false") {
791 return Ok((SpelledDefault::Bool(false), rest));
792 }
793 let bytes = text.as_bytes();
794 let mut i = 0;
795 if bytes.first() == Some(&b'-') {
796 i += 1;
797 }
798 let int_start = i;
799 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
800 i += 1;
801 }
802 if i == int_start {
803 return Err(dsl_diag::spelling_expected_literal(
804 &decode_spelling_fragment(text),
805 ));
806 }
807 let mut is_float = false;
808 if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(|b| b.is_ascii_digit()) {
809 is_float = true;
810 i += 1;
811 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
812 i += 1;
813 }
814 }
815 let (num, rest) = text.split_at(i);
816 if is_float {
817 match num.parse::<f64>() {
818 Ok(f) if f.is_finite() => Ok((SpelledDefault::Float(f.to_bits()), rest)),
819 _ => Err(dsl_diag::spelling_invalid_float(&decode_spelling_fragment(
820 num,
821 ))),
822 }
823 } else {
824 match num.parse::<i64>() {
825 Ok(n) => Ok((SpelledDefault::Int(n), rest)),
826 Err(_) => Err(dsl_diag::spelling_invalid_int(&decode_spelling_fragment(
827 num,
828 ))),
829 }
830 }
831}
832
833static RENDERD_TAGS: OnceLock<Mutex<HashMap<String, TypeTag>>> = OnceLock::new();
838
839fn rendered_table() -> &'static Mutex<HashMap<String, TypeTag>> {
840 RENDERD_TAGS.get_or_init(|| Mutex::new(HashMap::new()))
841}
842
843pub fn lookup_rendered(canonical: &str) -> Option<TypeTag> {
847 rendered_table()
848 .lock()
849 .unwrap_or_else(|poisoned| poisoned.into_inner())
850 .get(canonical)
851 .cloned()
852}
853
854pub fn intern_rendered(canonical: String, tag: TypeTag) -> TypeTag {
860 let mut table = rendered_table()
861 .lock()
862 .unwrap_or_else(|poisoned| poisoned.into_inner());
863 if let Some(hit) = table.get(&canonical) {
864 return hit.clone();
865 }
866 table.insert(canonical, tag.clone());
867 tag
868}
869
870pub fn check_value(tag: &TypeTag, value: &Value) -> Result<()> {
876 check_value_at(tag, value, VAR_SIGIL)
877}
878
879pub fn check_value_at(tag: &TypeTag, value: &Value, path: &str) -> Result<()> {
885 match tag {
886 TypeTag::Any => Ok(()),
887 TypeTag::String if value.as_str().is_some() => Ok(()),
888 TypeTag::Int if value.as_i64().is_some() => Ok(()),
889 TypeTag::Float if value.as_f64().is_some() => Ok(()),
890 TypeTag::Bool if value.as_bool().is_some() => Ok(()),
891 TypeTag::Pipe if value.as_pipe_handle().is_some() => Ok(()),
892 TypeTag::Handle if value.as_handle().is_some() => Ok(()),
893 TypeTag::HandleOf(_) if value.as_handle().is_some() => Ok(()),
894 TypeTag::Void => bail!(
895 "{path}: expected {VOID_TYPE_NAME}, got {}",
896 value.type_name()
897 ),
898 TypeTag::Duration if value.as_duration().is_some() => Ok(()),
899 TypeTag::Path if value.as_path().is_some() => Ok(()),
900 TypeTag::Semaphore if value.as_semaphore().is_some() => Ok(()),
901 TypeTag::Permit if value.as_permit().is_some() => Ok(()),
902 TypeTag::List => match value.as_list() {
903 Some(_) => Ok(()),
904 None => bail!(
905 "{path}: expected {LIST_TYPE_NAME}, got {}",
906 value.type_name()
907 ),
908 },
909 TypeTag::Map => match value.as_map() {
910 Some(_) => Ok(()),
911 None => bail!(
912 "{path}: expected {MAP_TYPE_NAME}, got {}",
913 value.type_name()
914 ),
915 },
916 TypeTag::ListOf(element) => match value.as_list() {
917 Some(items) => {
918 for (idx, item) in items.iter().enumerate() {
919 check_value_at(element, item, &format!("{path}[{idx}]"))?;
920 }
921 Ok(())
922 }
923 None => bail!(
924 "{path}: expected {LIST_TYPE_NAME}, got {}",
925 value.type_name()
926 ),
927 },
928 TypeTag::MapOf(values) => match value.as_map() {
929 Some(map) => {
930 for (key, item) in map.iter() {
931 check_value_at(values, item, &format!("{path}.{key}"))?;
932 }
933 Ok(())
934 }
935 None => bail!(
936 "{path}: expected {}, got {}",
937 render_structural(tag),
938 value.type_name()
939 ),
940 },
941 TypeTag::Record(fields) => match value.as_map() {
942 Some(map) => {
943 for field in fields.iter() {
944 match map.get(field.name.as_str()) {
945 Some(item) => {
946 check_value_at(&field.ty, item, &format!("{path}.{}", field.name))?;
947 }
948 None if field.optional || field.default.is_some() => {}
953 None => bail!(
954 "{path}: missing field '{}'; expected fields: {}",
955 field.name,
956 field_list(fields),
957 ),
958 }
959 }
960 for key in map.keys() {
961 if !fields.iter().any(|field| field.name == *key) {
962 bail!(
963 "{path}: unknown field '{key}'; expected fields: {}",
964 field_list(fields),
965 );
966 }
967 }
968 Ok(())
969 }
970 None => bail!(
971 "{path}: expected {MAP_TYPE_NAME}, got {}",
972 value.type_name()
973 ),
974 },
975 TypeTag::Custom(descriptor) => {
976 if value.type_name() == descriptor.name {
977 Ok(())
978 } else {
979 bail!(
980 "{path}: expected {}, got {}",
981 descriptor.name,
982 value.type_name(),
983 )
984 }
985 }
986 TypeTag::Union(_, members) => {
990 if members
991 .iter()
992 .any(|member| check_value(member, value).is_ok())
993 {
994 Ok(())
995 } else {
996 bail!(
997 "{path}: expected {}, got {}",
998 render_structural(tag),
999 value.type_name()
1000 )
1001 }
1002 }
1003 TypeTag::String
1007 | TypeTag::Int
1008 | TypeTag::Float
1009 | TypeTag::Bool
1010 | TypeTag::Pipe
1011 | TypeTag::Handle
1012 | TypeTag::HandleOf(_)
1013 | TypeTag::Duration
1014 | TypeTag::Path
1015 | TypeTag::Semaphore
1016 | TypeTag::Permit => bail!("{path}: expected {}, got {}", tag.name(), value.type_name()),
1017 }
1018}
1019
1020fn field_list(fields: &[Field]) -> String {
1021 fields
1022 .iter()
1023 .map(|field| field.name.as_str())
1024 .collect::<Vec<_>>()
1025 .join(", ")
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030 use super::*;
1031 use std::collections::BTreeMap;
1032 use std::sync::Arc;
1033
1034 fn map(entries: &[(&str, Value)]) -> Value {
1035 Value::map(
1036 entries
1037 .iter()
1038 .map(|(k, v)| ((*k).to_string(), v.clone()))
1039 .collect::<BTreeMap<_, _>>(),
1040 )
1041 }
1042
1043 #[test]
1044 fn builtin_round_trips_through_names() {
1045 for name in [
1046 "STRING",
1047 "INT",
1048 "FLOAT",
1049 "BOOL",
1050 "LIST",
1051 "MAP",
1052 "PIPE",
1053 "HANDLE",
1054 "DURATION",
1055 "PATH",
1056 "SEMAPHORE",
1057 "PERMIT",
1058 ] {
1059 let tag = TypeTag::builtin(name).expect("builtin");
1060 assert_eq!(tag.name(), name);
1061 }
1062 assert!(TypeTag::builtin("NOPE").is_none());
1063 assert!(TypeTag::builtin("string").is_none());
1064 }
1065
1066 #[test]
1067 fn scalars_conform_by_discriminant() {
1068 assert!(check_value(&TypeTag::String, &Value::string("x".to_string())).is_ok());
1069 assert!(check_value(&TypeTag::Int, &Value::int(1)).is_ok());
1070 assert!(check_value(&TypeTag::String, &Value::int(1)).is_err());
1071 assert!(check_value(&TypeTag::Int, &Value::float(3.0)).is_err());
1073 }
1074
1075 #[test]
1076 fn record_rejects_missing_and_extra_fields() {
1077 let fields: Arc<[Field]> = Arc::from([
1078 Field {
1079 name: "a".to_string(),
1080 ty: TypeTag::String,
1081 docs: "",
1082 optional: false,
1083 default: None,
1084
1085 alias: None,
1086 },
1087 Field {
1088 name: "b".to_string(),
1089 ty: TypeTag::Int,
1090 docs: "",
1091 optional: false,
1092 default: None,
1093
1094 alias: None,
1095 },
1096 ]);
1097 let tag = TypeTag::Record(fields);
1098 let good = map(&[("a", Value::string("x".to_string())), ("b", Value::int(1))]);
1099 assert!(check_value(&tag, &good).is_ok());
1100 let missing = map(&[("a", Value::string("x".to_string()))]);
1101 let err = check_value(&tag, &missing).expect_err("missing must fail");
1102 assert!(format!("{err:#}").contains('b'), "names the field: {err:#}");
1103 let extra = map(&[
1104 ("a", Value::string("x".to_string())),
1105 ("b", Value::int(1)),
1106 ("c", Value::int(2)),
1107 ]);
1108 let err = check_value(&tag, &extra).expect_err("extra must fail");
1109 assert!(format!("{err:#}").contains('c'), "names the field: {err:#}");
1110 let mistyped = map(&[
1111 ("a", Value::string("x".to_string())),
1112 ("b", Value::string("nope".to_string())),
1113 ]);
1114 assert!(check_value(&tag, &mistyped).is_err());
1115 }
1116
1117 #[test]
1118 fn record_optional_fields_may_be_absent() {
1119 let fields: Arc<[Field]> = Arc::from([
1122 Field {
1123 name: "held".to_string(),
1124 ty: TypeTag::Int,
1125 docs: "",
1126 optional: false,
1127 default: None,
1128
1129 alias: None,
1130 },
1131 Field {
1132 name: "permit".to_string(),
1133 ty: TypeTag::String,
1134 docs: "",
1135 optional: true,
1136 default: None,
1137
1138 alias: None,
1139 },
1140 ]);
1141 let tag = TypeTag::Record(fields);
1142 let full = map(&[
1143 ("held", Value::int(1)),
1144 ("permit", Value::string("p".to_string())),
1145 ]);
1146 assert!(check_value(&tag, &full).is_ok());
1147 let missing_optional = map(&[("held", Value::int(0))]);
1148 assert!(check_value(&tag, &missing_optional).is_ok());
1149 let missing_required = map(&[("permit", Value::string("p".to_string()))]);
1150 let err = check_value(&tag, &missing_required).expect_err("missing required must fail");
1151 assert!(
1152 format!("{err:#}").contains("held"),
1153 "names the field: {err:#}"
1154 );
1155 let mistyped_optional = map(&[("held", Value::int(1)), ("permit", Value::int(2))]);
1156 assert!(check_value(&tag, &mistyped_optional).is_err());
1157 }
1158
1159 #[test]
1160 fn list_of_checks_elements_with_index() {
1161 let tag = TypeTag::ListOf(Arc::new(TypeTag::Int));
1162 let good = Value::list(vec![Value::int(1), Value::int(2)]);
1163 assert!(check_value(&tag, &good).is_ok());
1164 let bad = Value::list(vec![Value::int(1), Value::string("x".to_string())]);
1165 let err = check_value(&tag, &bad).expect_err("bad element must fail");
1166 assert!(
1167 format!("{err:#}").contains("[1]"),
1168 "names the index: {err:#}"
1169 );
1170 }
1171
1172 #[test]
1173 fn canonicalization_unifies_input_spacing() {
1174 assert_eq!(canonicalize_spelling("LIST<MAP>"), "LIST<MAP>");
1177 assert_eq!(canonicalize_spelling("LIST< MAP >"), "LIST<MAP>");
1178 assert_eq!(
1179 canonicalize_spelling("MAP<name:STRING,age:INT>"),
1180 "MAP<name: STRING, age: INT>"
1181 );
1182 assert_eq!(
1183 canonicalize_spelling("MAP<name : STRING>"),
1184 "MAP<name: STRING>"
1185 );
1186 }
1187
1188 #[test]
1189 fn spellings_parse_to_shapes() {
1190 assert_eq!(
1191 parse_spelling("LIST<MAP>").expect("parses"),
1192 Spelled::Generic {
1193 name: "LIST".to_string(),
1194 args: vec![SpelledField {
1195 name: None,
1196 optional: false,
1197 ty: Spelled::Named("MAP".to_string()),
1198 default: None,
1199
1200 alias: None,
1201 }],
1202 }
1203 );
1204 assert_eq!(
1205 parse_spelling("MAP<name: STRING>").expect("parses"),
1206 Spelled::Generic {
1207 name: "MAP".to_string(),
1208 args: vec![SpelledField {
1209 name: Some("name".to_string()),
1210 optional: false,
1211 ty: Spelled::Named("STRING".to_string()),
1212 default: None,
1213
1214 alias: None,
1215 }],
1216 }
1217 );
1218 assert!(parse_spelling("LIST<A, B>").is_ok());
1221 assert!(parse_spelling("MAP<STRING>").is_ok());
1222 }
1223
1224 #[test]
1225 fn optional_field_spelling_parses_and_renders() {
1226 assert_eq!(
1229 parse_spelling("MAP<permit?: PERMIT>").expect("parses"),
1230 Spelled::Generic {
1231 name: "MAP".to_string(),
1232 args: vec![SpelledField {
1233 name: Some("permit".to_string()),
1234 optional: true,
1235 ty: Spelled::Named("PERMIT".to_string()),
1236 default: None,
1237
1238 alias: None,
1239 }],
1240 }
1241 );
1242 assert_eq!(
1243 canonicalize_spelling("MAP<permit ? : PERMIT>"),
1244 "MAP<permit?: PERMIT>"
1245 );
1246 }
1247
1248 #[test]
1249 fn default_spellings_parse_render_and_materialize() {
1250 for (spelling, canonical, value) in [
1254 (
1255 "MAP<retries: INT = 2>",
1256 "MAP<retries: INT = 2>",
1257 Value::int(2),
1258 ),
1259 (
1260 "MAP<retries: INT=-2>",
1261 "MAP<retries: INT = -2>",
1262 Value::int(-2),
1263 ),
1264 (
1265 "MAP<ratio: FLOAT = 2.5>",
1266 "MAP<ratio: FLOAT = 2.5>",
1267 Value::float(2.5),
1268 ),
1269 (
1270 "MAP<on: BOOL = true>",
1271 "MAP<on: BOOL = true>",
1272 Value::bool(true),
1273 ),
1274 (
1275 "MAP<model: STRING = \"gpt-4\">",
1276 "MAP<model: STRING = \"gpt-4\">",
1277 Value::string("gpt-4".to_string()),
1278 ),
1279 (
1280 "MAP<msg: STRING = \"hello world\">",
1281 "MAP<msg: STRING = \"hello world\">",
1282 Value::string("hello world".to_string()),
1283 ),
1284 ] {
1285 let spelled = parse_spelling(spelling).expect("parses");
1286 assert_eq!(render_spelled(&spelled), canonical, "canonical: {spelling}");
1287 assert_eq!(canonicalize_spelling(spelling), canonical);
1288 match spelled {
1289 Spelled::Generic { args, .. } => {
1290 let found = args.iter().find(|f| f.default.is_some()).expect("default");
1291 let lit = found.default.as_ref().expect("lit");
1292 assert_eq!(lit.to_value(), value);
1293 assert!(
1294 canonical.contains(&format!("= {}", lit.render())),
1295 "canonical carries the default: {canonical}"
1296 );
1297 }
1298 other => panic!("expected generic, got {other:?}"),
1299 }
1300 }
1301 let tag = TypeTag::Record(Arc::from([Field {
1303 name: "retries".to_string(),
1304 ty: TypeTag::Int,
1305 docs: "",
1306 optional: false,
1307 default: Some(Value::int(2)),
1308
1309 alias: None,
1310 }]));
1311 assert_eq!(
1312 render_structural(&tag),
1313 "MAP<retries: INT = 2>",
1314 "tag renders defaults canonically"
1315 );
1316 assert_eq!(
1317 render_default_value(&Value::float(2.5)),
1318 "2.5",
1319 "float keeps its point"
1320 );
1321 for bad in [
1324 "MAP<a: INT = >",
1325 "MAP<a: INT = x>",
1326 "MAP<a: INT = 1.2.3>",
1327 "MAP<a: INT = \"x>",
1328 "MAP<a: INT = 9999999999999999999999>",
1329 ] {
1330 assert!(parse_spelling(bad).is_err(), "must fail: {bad}");
1331 }
1332 }
1333
1334 #[test]
1335 fn unknown_map_spelling_parses_and_renders() {
1336 assert_eq!(
1339 parse_spelling("MAP<ANY>").expect("parses"),
1340 Spelled::Generic {
1341 name: "MAP".to_string(),
1342 args: vec![SpelledField {
1343 name: None,
1344 optional: false,
1345 ty: Spelled::Named("ANY".to_string()),
1346 default: None,
1347
1348 alias: None,
1349 }],
1350 }
1351 );
1352 assert_eq!(canonicalize_spelling("MAP< ANY >"), "MAP<ANY>");
1353 assert_eq!(
1354 render_structural(&TypeTag::MapOf(Arc::new(TypeTag::Any))),
1355 "MAP<ANY>"
1356 );
1357 }
1358
1359 #[test]
1360 fn map_of_checks_values_with_paths() {
1361 let tag = TypeTag::MapOf(Arc::new(TypeTag::Int));
1364 let good = map(&[("a", Value::int(1))]);
1365 assert!(check_value(&tag, &good).is_ok());
1366 let bad = map(&[("a", Value::string("x".to_string()))]);
1367 let err = check_value(&tag, &bad).expect_err("bad value must fail");
1368 assert!(format!("{err:#}").contains(".a"), "names the key: {err:#}");
1369 let not_map = Value::list(vec![Value::int(1)]);
1370 let err = check_value(&tag, ¬_map).expect_err("non-map must fail");
1371 assert!(format!("{err:#}").contains("MAP<INT>"), "{err:#}");
1372 }
1373
1374 #[test]
1375 fn spellings_reject_malformed_input() {
1376 for bad in [
1377 "",
1378 "LIST<>",
1379 "LIST<A,>",
1380 "MAP<name:>",
1381 "LIST<A",
1382 "list<MAP>",
1383 "LIST<A>>",
1384 ] {
1385 assert!(parse_spelling(bad).is_err(), "{bad:?} must fail");
1386 }
1387 let mut deep = "INT".to_string();
1389 for _ in 0..MAX_GENERIC_DEPTH + 1 {
1390 deep = format!("LIST<{deep}>");
1391 }
1392 let err = parse_spelling(&deep).expect_err("over-deep spelling must fail");
1393 assert!(err.message().contains("generic depth"), "{err}");
1394 assert_eq!(err.key(), "dsl.spelling.max_depth");
1395 }
1396
1397 #[test]
1398 fn second_alias_on_same_field_fails_with_both_names() {
1399 let err =
1400 parse_spelling("MAP<h: BOOL ALIAS help ALIAS h2>").expect_err("second ALIAS must fail");
1401 assert_eq!(err.key(), "dsl.alias.duplicate_on_field");
1402 assert!(err.message().contains("`h`"), "{err}");
1403 assert!(err.message().contains("`help`"), "{err}");
1404 assert!(err.message().contains("`h2`"), "{err}");
1405 assert!(err.message().contains("only one `ALIAS`"), "{err}");
1406 assert!(!err.message().contains('\u{1f}'), "{err}");
1408 }
1409
1410 #[test]
1411 fn second_alias_with_bad_name_is_bounded() {
1412 let err = parse_spelling("MAP<h: BOOL ALIAS help ALIAS Bad, x: INT>")
1413 .expect_err("second ALIAS with bad name must fail");
1414 assert_eq!(err.key(), "dsl.alias.duplicate_on_field");
1415 assert!(!err.message().contains('>'), "{err}");
1416 assert!(!err.message().contains("x: INT"), "{err}");
1417 assert!(!err.message().contains('\u{1f}'), "{err}");
1418 }
1419
1420 #[test]
1421 fn identical_spellings_share_one_interned_payload() {
1422 let first = intern_rendered(
1423 "LIST<MAP>".to_string(),
1424 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1425 );
1426 let second = intern_rendered(
1427 "LIST<MAP>".to_string(),
1428 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1429 );
1430 let (TypeTag::ListOf(a), TypeTag::ListOf(b)) = (first, second) else {
1431 panic!("rendered tags keep their shape");
1432 };
1433 assert!(
1434 Arc::ptr_eq(&a, &b),
1435 "same canonical spelling shares one payload"
1436 );
1437 }
1438
1439 #[test]
1440 fn structural_rendering_names_contents() {
1441 let fields: Arc<[Field]> = Arc::from([Field {
1442 name: "name".to_string(),
1443 ty: TypeTag::String,
1444 docs: "",
1445 optional: false,
1446 default: None,
1447
1448 alias: None,
1449 }]);
1450 let record = TypeTag::Record(fields);
1451 let list = TypeTag::ListOf(Arc::new(record));
1452 assert_eq!(render_structural(&list), "LIST<MAP<name: STRING>>");
1453 assert_eq!(render_structural(&TypeTag::Int), "INT");
1454 }
1455}