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