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::{
16 TypeDescriptor, Value,
17 constants::{MODULE_SEPARATOR, VAR_SIGIL},
18};
19
20pub const MAX_GENERIC_DEPTH: usize = 8;
25
26#[macro_export]
34macro_rules! union_tag {
35 ($($member:ident),+ $(,)?) => {
36 $crate::TypeTag::union(vec![$($crate::TypeTag::$member),+])
37 };
38}
39
40#[derive(Debug, Clone)]
42pub struct Field {
43 pub name: String,
47 pub ty: TypeTag,
49 pub docs: &'static str,
52 pub optional: bool,
58 pub default: Option<Value>,
63 pub alias: Option<String>,
67}
68
69#[derive(Clone)]
81pub enum TypeTag {
82 String,
83 Int,
84 Float,
85 Bool,
86 List,
87 Map,
88 Pipe,
89 Handle,
90 HandleOf(Arc<TypeTag>),
91 Void,
92 Duration,
93 Path,
94 Semaphore,
95 Permit,
96 Any,
100 Custom(&'static TypeDescriptor),
101 ListOf(Arc<TypeTag>),
102 Record(Arc<[Field]>),
103 MapOf(Arc<TypeTag>),
104 Union(Arc<str>, Arc<[TypeTag]>),
112}
113
114pub const ANY_TAG: TypeTag = TypeTag::Any;
117
118pub const MAP_TAG: TypeTag = TypeTag::Map;
121
122pub const LIST_TAG: TypeTag = TypeTag::List;
124
125pub const HANDLE_TYPE_NAME: &str = "HANDLE";
129
130pub const LIST_TYPE_NAME: &str = "LIST";
133
134pub const MAP_TYPE_NAME: &str = "MAP";
137
138pub const ANY_TYPE_NAME: &str = "ANY";
141
142pub const STRING_TYPE_NAME: &str = "STRING";
144
145pub const INT_TYPE_NAME: &str = "INT";
147
148pub const FLOAT_TYPE_NAME: &str = "FLOAT";
150
151pub const BOOL_TYPE_NAME: &str = "BOOL";
153
154pub const PIPE_TYPE_NAME: &str = "PIPE";
156
157pub const VOID_TYPE_NAME: &str = "VOID";
159
160pub const DURATION_TYPE_NAME: &str = "DURATION";
162
163pub const PATH_TYPE_NAME: &str = "PATH";
165
166pub const SEMAPHORE_TYPE_NAME: &str = "SEMAPHORE";
168
169pub const PERMIT_TYPE_NAME: &str = "PERMIT";
171
172pub const ALIAS_KEYWORD: &str = "ALIAS";
176impl std::fmt::Debug for TypeTag {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 match self {
179 TypeTag::Custom(descriptor) => {
180 write!(f, "Custom({})", descriptor.name)
181 }
182 TypeTag::ListOf(element) => write!(f, "ListOf({element:?})"),
183 TypeTag::HandleOf(inner) => write!(f, "HandleOf({inner:?})"),
184 TypeTag::MapOf(values) => write!(f, "MapOf({values:?})"),
185 TypeTag::Record(fields) => {
186 let names: Vec<&str> = fields.iter().map(|field| field.name.as_str()).collect();
187 write!(f, "Record({})", names.join(", "))
188 }
189 TypeTag::Union(spelling, _) => write!(f, "Union({spelling})"),
194 tag => write!(f, "{}", tag.name()),
195 }
196 }
197}
198
199impl std::fmt::Display for TypeTag {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 f.write_str(self.name())
202 }
203}
204impl TypeTag {
205 pub fn union(members: Vec<TypeTag>) -> TypeTag {
212 let spelling: Arc<str> = members
213 .iter()
214 .map(render_structural)
215 .collect::<Vec<_>>()
216 .join("|")
217 .into();
218 TypeTag::Union(spelling, Arc::from(members))
219 }
220
221 pub fn name(&self) -> &str {
226 match self {
227 TypeTag::String => STRING_TYPE_NAME,
228 TypeTag::Int => INT_TYPE_NAME,
229 TypeTag::Float => FLOAT_TYPE_NAME,
230 TypeTag::Bool => BOOL_TYPE_NAME,
231 TypeTag::List => LIST_TYPE_NAME,
232 TypeTag::Map => MAP_TYPE_NAME,
233 TypeTag::Pipe => PIPE_TYPE_NAME,
234 TypeTag::Handle => HANDLE_TYPE_NAME,
235 TypeTag::HandleOf(_) => HANDLE_TYPE_NAME,
236 TypeTag::Void => VOID_TYPE_NAME,
237 TypeTag::Duration => DURATION_TYPE_NAME,
238 TypeTag::Path => PATH_TYPE_NAME,
239 TypeTag::Semaphore => SEMAPHORE_TYPE_NAME,
240 TypeTag::Permit => PERMIT_TYPE_NAME,
241 TypeTag::Any => ANY_TYPE_NAME,
242 TypeTag::Union(spelling, _) => spelling,
245 TypeTag::Custom(descriptor) => descriptor.name,
246 TypeTag::ListOf(_) => LIST_TYPE_NAME,
247 TypeTag::MapOf(_) => MAP_TYPE_NAME,
248 TypeTag::Record(_) => MAP_TYPE_NAME,
249 }
250 }
251
252 pub fn builtin(name: &str) -> Option<TypeTag> {
256 match name {
257 STRING_TYPE_NAME => Some(TypeTag::String),
258 INT_TYPE_NAME => Some(TypeTag::Int),
259 FLOAT_TYPE_NAME => Some(TypeTag::Float),
260 BOOL_TYPE_NAME => Some(TypeTag::Bool),
261 LIST_TYPE_NAME => Some(TypeTag::List),
262 MAP_TYPE_NAME => Some(TypeTag::Map),
263 PIPE_TYPE_NAME => Some(TypeTag::Pipe),
264 HANDLE_TYPE_NAME => Some(TypeTag::Handle),
265 VOID_TYPE_NAME => Some(TypeTag::Void),
266 DURATION_TYPE_NAME => Some(TypeTag::Duration),
267 PATH_TYPE_NAME => Some(TypeTag::Path),
268 SEMAPHORE_TYPE_NAME => Some(TypeTag::Semaphore),
269 PERMIT_TYPE_NAME => Some(TypeTag::Permit),
270 ANY_TYPE_NAME => Some(TypeTag::Any),
271 _ => None,
272 }
273 }
274
275 pub fn fields(&self) -> Option<&[Field]> {
280 match self {
281 TypeTag::Record(fields) => Some(fields),
282 TypeTag::String
283 | TypeTag::Int
284 | TypeTag::Float
285 | TypeTag::Bool
286 | TypeTag::List
287 | TypeTag::Map
288 | TypeTag::Pipe
289 | TypeTag::Handle
290 | TypeTag::HandleOf(_)
291 | TypeTag::Void
292 | TypeTag::Duration
293 | TypeTag::Path
294 | TypeTag::Semaphore
295 | TypeTag::Permit
296 | TypeTag::Any
297 | TypeTag::Custom(_)
298 | TypeTag::ListOf(_)
299 | TypeTag::MapOf(_)
300 | TypeTag::Union(..) => None,
301 }
302 }
303}
304
305pub fn render_structural(tag: &TypeTag) -> String {
310 match tag {
311 TypeTag::ListOf(inner) => format!("{LIST_TYPE_NAME}<{}>", render_structural(inner)),
312 TypeTag::HandleOf(inner) => format!("{HANDLE_TYPE_NAME}<{}>", render_structural(inner)),
313 TypeTag::MapOf(values) => format!("{MAP_TYPE_NAME}<{}>", render_structural(values)),
314 TypeTag::Record(fields) => {
315 let field_list = fields
316 .iter()
317 .map(|field| {
318 format!(
319 "{}{}: {}{}{}",
320 field.name,
321 if field.optional { "?" } else { "" },
322 render_structural(&field.ty),
323 field
324 .alias
325 .as_ref()
326 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
327 .unwrap_or_default(),
328 field
329 .default
330 .as_ref()
331 .map(|d| format!(" = {}", render_default_value(d)))
332 .unwrap_or_default(),
333 )
334 })
335 .collect::<Vec<_>>()
336 .join(", ");
337 format!("{MAP_TYPE_NAME}<{field_list}>")
338 }
339 tag => tag.name().to_string(),
340 }
341}
342
343#[derive(Debug, Clone, PartialEq, Eq)]
351pub enum Spelled {
352 Named(String),
353 Generic {
354 name: String,
355 args: Vec<SpelledField>,
356 },
357 Union(Vec<Spelled>),
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
366pub struct SpelledField {
367 pub name: Option<String>,
368 pub optional: bool,
369 pub ty: Spelled,
370 pub alias: Option<String>,
371 pub default: Option<SpelledDefault>,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq)]
380pub enum SpelledDefault {
381 Str(String),
382 Int(i64),
383 Float(u64),
384 Bool(bool),
385}
386
387impl SpelledDefault {
388 pub fn to_value(&self) -> Value {
391 match self {
392 SpelledDefault::Str(s) => Value::string(s.clone()),
393 SpelledDefault::Int(n) => Value::int(*n),
394 SpelledDefault::Float(bits) => Value::float(f64::from_bits(*bits)),
395 SpelledDefault::Bool(b) => Value::bool(*b),
396 }
397 }
398
399 pub fn render(&self) -> String {
403 match self {
404 SpelledDefault::Str(s) => format!("\"{s}\""),
405 SpelledDefault::Int(n) => format!("{n}"),
406 SpelledDefault::Float(bits) => format!("{:?}", f64::from_bits(*bits)),
407 SpelledDefault::Bool(b) => format!("{b}"),
408 }
409 }
410}
411
412pub fn render_default_value(value: &Value) -> String {
420 if let Some(n) = value.as_i64() {
421 return format!("{n}");
422 }
423 if let Some(f) = value.as_f64() {
424 return format!("{f:?}");
425 }
426 if let Some(b) = value.as_bool() {
427 return format!("{b}");
428 }
429 if let Some(s) = value.as_str() {
430 return format!("\"{s}\"");
431 }
432 format!("{value:?}")
433}
434
435pub fn canonicalize_spelling(s: &str) -> String {
443 match parse_spelling(s) {
444 Ok(spelled) => render_spelled(&spelled),
445 Err(_) => s.trim().to_string(),
446 }
447}
448
449pub fn render_spelled(spelled: &Spelled) -> String {
453 match spelled {
454 Spelled::Named(name) => name.clone(),
455 Spelled::Union(members) => members
456 .iter()
457 .map(render_spelled)
458 .collect::<Vec<_>>()
459 .join("|"),
460 Spelled::Generic { name, args } => {
461 let rendered: Vec<String> = args
462 .iter()
463 .map(|field| match &field.name {
464 Some(field_name) => format!(
465 "{}{}: {}{}{}",
466 field_name,
467 if field.optional { "?" } else { "" },
468 render_spelled(&field.ty),
469 field
470 .alias
471 .as_ref()
472 .map(|a| format!(" {ALIAS_KEYWORD} {a}"))
473 .unwrap_or_default(),
474 field
475 .default
476 .as_ref()
477 .map(|d| format!(" = {}", d.render()))
478 .unwrap_or_default(),
479 ),
480 None => render_spelled(&field.ty),
481 })
482 .collect();
483 format!("{name}<{}>", rendered.join(", "))
484 }
485 }
486}
487
488pub fn parse_spelling(s: &str) -> Result<Spelled, Diagnostic> {
494 let text: String = strip_spelling_whitespace(s);
495 let (spelled, rest) = parse_spelled_one(&text, 0)?;
496 if !rest.is_empty() {
497 return Err(dsl_diag::spelling_trailing_text(
498 &dsl_diag::decode_spelling_fragment(rest),
499 ));
500 }
501 Ok(spelled)
502}
503
504fn decode_spelling_fragment(raw: &str) -> String {
508 dsl_diag::decode_spelling_fragment(raw)
509}
510
511pub(crate) const WS_SENTINEL: char = '\u{1f}';
517
518fn is_spelling_word_char(ch: char) -> bool {
521 ch.is_ascii_alphanumeric() || ch == '_'
522}
523
524fn strip_spelling_whitespace(s: &str) -> String {
531 let mut out = String::with_capacity(s.len());
532 let mut quoted = false;
533 let mut pending_space = false;
534 let mut prev_word = false;
535 for ch in s.chars() {
536 if ch == '"' {
537 pending_space = false;
538 out.push(ch);
539 quoted = !quoted;
540 prev_word = false;
541 continue;
542 }
543 if !quoted && ch.is_whitespace() {
544 pending_space = true;
545 continue;
546 }
547 if pending_space && prev_word && !quoted && is_spelling_word_char(ch) {
548 out.push(WS_SENTINEL);
549 }
550 pending_space = false;
551 out.push(ch);
552 prev_word = !quoted && is_spelling_word_char(ch);
553 }
554 out
555}
556
557fn parse_spelled_one(text: &str, depth: usize) -> Result<(Spelled, &str), Diagnostic> {
558 let (first, mut rest) = parse_spelled_shape(text, depth)?;
559 if !rest.starts_with('|') {
560 return Ok((first, rest));
561 }
562 let mut members = vec![first];
567 while let Some(tail) = rest.strip_prefix('|') {
568 let (next, after) = parse_spelled_shape(tail, depth)?;
569 members.push(next);
570 rest = after;
571 }
572 Ok((Spelled::Union(members), rest))
573}
574
575fn parse_spelled_shape(text: &str, depth: usize) -> Result<(Spelled, &str), Diagnostic> {
576 if depth > MAX_GENERIC_DEPTH {
577 return Err(dsl_diag::spelling_max_depth(
578 MAX_GENERIC_DEPTH,
579 &decode_spelling_fragment(text),
580 ));
581 }
582 let mut chars = text.char_indices();
583 let Some((_, first)) = chars.next() else {
584 return Err(dsl_diag::spelling_expected_type_name());
585 };
586 if !first.is_ascii_uppercase() {
587 return Err(dsl_diag::spelling_expected_uppercase(&first.to_string()));
588 }
589 let mut end = first.len_utf8();
590 for (idx, ch) in chars {
591 if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
592 end = idx + ch.len_utf8();
593 } else {
594 break;
595 }
596 }
597 let (first_name, mut rest) = text.split_at(end);
598 let mut owned = first_name.to_string();
599 if let Some(after_colons) = rest.strip_prefix(MODULE_SEPARATOR) {
603 let mut tail_chars = after_colons.char_indices();
604 let Some((_, tail_first)) = tail_chars.next() else {
605 return Err(dsl_diag::spelling_expected_type_name());
606 };
607 if !tail_first.is_ascii_uppercase() {
608 return Err(dsl_diag::spelling_expected_uppercase(
609 &tail_first.to_string(),
610 ));
611 }
612 let mut tail_end = tail_first.len_utf8();
613 for (idx, ch) in tail_chars {
614 if ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_' {
615 tail_end = idx + ch.len_utf8();
616 } else {
617 break;
618 }
619 }
620 let (tail_name, tail_rest) = after_colons.split_at(tail_end);
621 owned = format!("{owned}{MODULE_SEPARATOR}{tail_name}");
622 rest = tail_rest;
623 }
624 let name = owned;
625 if !rest.starts_with('<') {
626 return Ok((Spelled::Named(name), rest));
627 }
628 rest = &rest[1..];
629 let mut args = Vec::new();
630 loop {
631 let (field_name, optional, after_name) = parse_spelled_field_name(rest);
632 let (arg, after_arg) = parse_spelled_one(after_name, depth + 1)?;
633 let (alias, after_alias) = parse_spelled_alias(after_arg)?;
634 if alias.is_some() && field_name.is_none() {
637 return Err(dsl_diag::alias_needs_field(&decode_spelling_fragment(rest)));
638 }
639 if let Some(second) = peek_second_alias(after_alias) {
643 let field = field_name.as_deref().unwrap_or("<bare>");
644 let first = alias.as_deref().unwrap_or("<unknown>");
645 return Err(dsl_diag::alias_duplicate_on_field(field, first, &second));
646 }
647 let (default, after_default) = parse_spelled_default(after_alias)?;
648 args.push(SpelledField {
649 name: field_name,
650 optional,
651 ty: arg,
652 alias,
653 default,
654 });
655 rest = after_default;
656 if let Some(tail) = rest.strip_prefix(',') {
657 rest = tail;
658 continue;
659 }
660 if let Some(tail) = rest.strip_prefix('>') {
661 rest = tail;
662 break;
663 }
664 return Err(dsl_diag::spelling_expected_delimiter(
665 &decode_spelling_fragment(rest),
666 ));
667 }
668 Ok((Spelled::Generic { name, args }, rest))
669}
670
671fn peek_second_alias(after: &str) -> Option<String> {
677 let text = after.strip_prefix(WS_SENTINEL).unwrap_or(after);
678 let after_keyword = text.strip_prefix(ALIAS_KEYWORD)?;
679 let after_keyword = after_keyword
680 .strip_prefix(WS_SENTINEL)
681 .unwrap_or(after_keyword);
682 if after_keyword.is_empty() {
683 return Some("<missing>".to_string());
684 }
685 let mut end = 0usize;
686 for (idx, ch) in after_keyword.char_indices() {
687 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
688 end = idx + ch.len_utf8();
689 } else {
690 break;
691 }
692 }
693 if end == 0 {
694 let token: String = after_keyword
695 .chars()
696 .take_while(|c| {
697 !matches!(c, ',' | '>' | '=') && *c != WS_SENTINEL && !c.is_whitespace()
698 })
699 .collect();
700 if token.is_empty() {
701 return Some("<invalid>".to_string());
702 }
703 return Some(dsl_diag::decode_spelling_fragment(&token));
704 }
705 Some(after_keyword[..end].to_string())
706}
707
708fn parse_spelled_field_name(text: &str) -> (Option<String>, bool, &str) {
713 let mut chars = text.char_indices();
714 let Some((_, first)) = chars.next() else {
715 return (None, false, text);
716 };
717 if !first.is_ascii_lowercase() {
718 return (None, false, text);
719 };
720 let mut end = first.len_utf8();
721 for (idx, ch) in chars {
722 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
723 end = idx + ch.len_utf8();
724 } else {
725 break;
726 }
727 }
728 let (candidate, rest) = text.split_at(end);
729 let (optional, rest) = match rest.strip_prefix('?') {
730 Some(after) => (true, after),
731 None => (false, rest),
732 };
733 match rest.strip_prefix(':') {
734 Some(after) => (Some(candidate.to_string()), optional, after),
735 None => (None, false, text),
736 }
737}
738
739fn parse_spelled_alias(text: &str) -> Result<(Option<String>, &str), Diagnostic> {
746 let text = text.strip_prefix(WS_SENTINEL).unwrap_or(text);
747 let Some(after_keyword) = text.strip_prefix(ALIAS_KEYWORD) else {
748 return Ok((None, text));
749 };
750 let after_keyword = after_keyword
751 .strip_prefix(WS_SENTINEL)
752 .unwrap_or(after_keyword);
753 if after_keyword.is_empty() {
754 return Err(dsl_diag::alias_needs_name());
755 }
756 let mut chars = after_keyword.char_indices();
757 let Some((_, first)) = chars.next() else {
758 return Err(dsl_diag::alias_needs_name());
759 };
760 if !first.is_ascii_lowercase() {
761 if !first.is_ascii_alphabetic() {
762 return Err(dsl_diag::alias_needs_name());
763 }
764 return Err(dsl_diag::alias_name_lowercase(
765 &first.to_string(),
766 &decode_spelling_fragment(after_keyword),
767 ));
768 }
769 let mut end = first.len_utf8();
770 for (idx, ch) in chars {
771 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' {
772 end = idx + ch.len_utf8();
773 } else {
774 break;
775 }
776 }
777 let (alias, rest) = after_keyword.split_at(end);
778 if alias.is_empty() {
779 return Err(dsl_diag::alias_needs_name());
780 }
781 Ok((Some(alias.to_string()), rest))
782}
783
784fn parse_spelled_default(text: &str) -> Result<(Option<SpelledDefault>, &str), Diagnostic> {
790 let Some(after_eq) = text.strip_prefix('=') else {
791 return Ok((None, text));
792 };
793 let (lit, rest) = parse_spelled_literal(after_eq)?;
794 Ok((Some(lit), rest))
795}
796
797fn parse_spelled_literal(text: &str) -> Result<(SpelledDefault, &str), Diagnostic> {
802 if let Some(after) = text.strip_prefix('"') {
803 match after.find('"') {
804 Some(end) => {
805 let (body, rest) = after.split_at(end);
806 return Ok((SpelledDefault::Str(body.to_string()), &rest[1..]));
807 }
808 None => {
809 return Err(dsl_diag::spelling_unterminated_string(
810 &decode_spelling_fragment(text),
811 ));
812 }
813 }
814 }
815 if let Some(rest) = text.strip_prefix("true") {
816 return Ok((SpelledDefault::Bool(true), rest));
817 }
818 if let Some(rest) = text.strip_prefix("false") {
819 return Ok((SpelledDefault::Bool(false), rest));
820 }
821 let bytes = text.as_bytes();
822 let mut i = 0;
823 if bytes.first() == Some(&b'-') {
824 i += 1;
825 }
826 let int_start = i;
827 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
828 i += 1;
829 }
830 if i == int_start {
831 return Err(dsl_diag::spelling_expected_literal(
832 &decode_spelling_fragment(text),
833 ));
834 }
835 let mut is_float = false;
836 if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(|b| b.is_ascii_digit()) {
837 is_float = true;
838 i += 1;
839 while bytes.get(i).is_some_and(|b| b.is_ascii_digit()) {
840 i += 1;
841 }
842 }
843 let (num, rest) = text.split_at(i);
844 if is_float {
845 match num.parse::<f64>() {
846 Ok(f) if f.is_finite() => Ok((SpelledDefault::Float(f.to_bits()), rest)),
847 _ => Err(dsl_diag::spelling_invalid_float(&decode_spelling_fragment(
848 num,
849 ))),
850 }
851 } else {
852 match num.parse::<i64>() {
853 Ok(n) => Ok((SpelledDefault::Int(n), rest)),
854 Err(_) => Err(dsl_diag::spelling_invalid_int(&decode_spelling_fragment(
855 num,
856 ))),
857 }
858 }
859}
860
861static RENDERD_TAGS: OnceLock<Mutex<HashMap<String, TypeTag>>> = OnceLock::new();
866
867fn rendered_table() -> &'static Mutex<HashMap<String, TypeTag>> {
868 RENDERD_TAGS.get_or_init(|| Mutex::new(HashMap::new()))
869}
870
871pub fn lookup_rendered(canonical: &str) -> Option<TypeTag> {
875 rendered_table()
876 .lock()
877 .unwrap_or_else(|poisoned| poisoned.into_inner())
878 .get(canonical)
879 .cloned()
880}
881
882pub fn intern_rendered(canonical: String, tag: TypeTag) -> TypeTag {
888 let mut table = rendered_table()
889 .lock()
890 .unwrap_or_else(|poisoned| poisoned.into_inner());
891 if let Some(hit) = table.get(&canonical) {
892 return hit.clone();
893 }
894 table.insert(canonical, tag.clone());
895 tag
896}
897
898pub fn check_value(tag: &TypeTag, value: &Value) -> DiagnosticResult<()> {
904 check_value_at(tag, value, VAR_SIGIL)
905}
906
907pub fn check_value_at(tag: &TypeTag, value: &Value, path: &str) -> DiagnosticResult<()> {
913 match tag {
914 TypeTag::Any => Ok(()),
915 TypeTag::String if value.as_str().is_some() => Ok(()),
916 TypeTag::Int if value.as_i64().is_some() => Ok(()),
917 TypeTag::Float if value.as_f64().is_some() => Ok(()),
918 TypeTag::Bool if value.as_bool().is_some() => Ok(()),
919 TypeTag::Pipe if value.as_pipe_handle().is_some() => Ok(()),
920 TypeTag::Handle if value.as_handle().is_some() => Ok(()),
921 TypeTag::HandleOf(_) if value.as_handle().is_some() => Ok(()),
922 TypeTag::Void => Err(dsl_diag::type_mismatch_at(
923 path,
924 VOID_TYPE_NAME,
925 value.type_name(),
926 )),
927 TypeTag::Duration if value.as_duration().is_some() => Ok(()),
928 TypeTag::Path if value.as_path().is_some() => Ok(()),
929 TypeTag::Semaphore if value.as_semaphore().is_some() => Ok(()),
930 TypeTag::Permit if value.as_permit().is_some() => Ok(()),
931 TypeTag::List => match value.as_list() {
932 Some(_) => Ok(()),
933 None => Err(dsl_diag::type_mismatch_at(
934 path,
935 LIST_TYPE_NAME,
936 value.type_name(),
937 )),
938 },
939 TypeTag::Map => match value.as_map() {
940 Some(_) => Ok(()),
941 None => Err(dsl_diag::type_mismatch_at(
942 path,
943 MAP_TYPE_NAME,
944 value.type_name(),
945 )),
946 },
947 TypeTag::ListOf(element) => match value.as_list() {
948 Some(items) => {
949 for (idx, item) in items.iter().enumerate() {
950 check_value_at(element, item, &format!("{path}[{idx}]"))?;
951 }
952 Ok(())
953 }
954 None => Err(dsl_diag::type_mismatch_at(
955 path,
956 LIST_TYPE_NAME,
957 value.type_name(),
958 )),
959 },
960 TypeTag::MapOf(values) => match value.as_map() {
961 Some(map) => {
962 for (key, item) in map.iter() {
963 check_value_at(values, item, &format!("{path}.{key}"))?;
964 }
965 Ok(())
966 }
967 None => Err(dsl_diag::type_mismatch_at(
968 path,
969 &render_structural(tag),
970 value.type_name(),
971 )),
972 },
973 TypeTag::Record(fields) => match value.as_map() {
974 Some(map) => {
975 for field in fields.iter() {
976 match map.get(field.name.as_str()) {
977 Some(item) => {
978 check_value_at(&field.ty, item, &format!("{path}.{}", field.name))?;
979 }
980 None if field.optional || field.default.is_some() => {}
985 None => {
986 return Err(dsl_diag::record_missing_field(
987 path,
988 &field.name,
989 &field_list(fields),
990 ));
991 }
992 }
993 }
994 for key in map.keys() {
995 if !fields.iter().any(|field| field.name == *key) {
996 return Err(dsl_diag::record_unknown_field(
997 path,
998 key,
999 &field_list(fields),
1000 ));
1001 }
1002 }
1003 Ok(())
1004 }
1005 None => Err(dsl_diag::type_mismatch_at(
1006 path,
1007 MAP_TYPE_NAME,
1008 value.type_name(),
1009 )),
1010 },
1011 TypeTag::Custom(descriptor) => {
1012 if value.type_name() == descriptor.name {
1013 Ok(())
1014 } else {
1015 Err(dsl_diag::type_mismatch_at(
1016 path,
1017 descriptor.name,
1018 value.type_name(),
1019 ))
1020 }
1021 }
1022 TypeTag::Union(_, members) => {
1026 if members
1027 .iter()
1028 .any(|member| check_value(member, value).is_ok())
1029 {
1030 Ok(())
1031 } else {
1032 Err(dsl_diag::type_mismatch_at(
1033 path,
1034 &render_structural(tag),
1035 value.type_name(),
1036 ))
1037 }
1038 }
1039 TypeTag::String
1043 | TypeTag::Int
1044 | TypeTag::Float
1045 | TypeTag::Bool
1046 | TypeTag::Pipe
1047 | TypeTag::Handle
1048 | TypeTag::HandleOf(_)
1049 | TypeTag::Duration
1050 | TypeTag::Path
1051 | TypeTag::Semaphore
1052 | TypeTag::Permit => Err(dsl_diag::type_mismatch_at(
1053 path,
1054 tag.name(),
1055 value.type_name(),
1056 )),
1057 }
1058}
1059
1060fn field_list(fields: &[Field]) -> String {
1061 fields
1062 .iter()
1063 .map(|field| field.name.as_str())
1064 .collect::<Vec<_>>()
1065 .join(", ")
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use super::*;
1071 use std::collections::BTreeMap;
1072 use std::sync::Arc;
1073
1074 fn map(entries: &[(&str, Value)]) -> Value {
1075 Value::map(
1076 entries
1077 .iter()
1078 .map(|(k, v)| ((*k).to_string(), v.clone()))
1079 .collect::<BTreeMap<_, _>>(),
1080 )
1081 }
1082
1083 #[test]
1084 fn builtin_round_trips_through_names() {
1085 for name in [
1086 "STRING",
1087 "INT",
1088 "FLOAT",
1089 "BOOL",
1090 "LIST",
1091 "MAP",
1092 "PIPE",
1093 "HANDLE",
1094 "DURATION",
1095 "PATH",
1096 "SEMAPHORE",
1097 "PERMIT",
1098 ] {
1099 let tag = TypeTag::builtin(name).expect("builtin");
1100 assert_eq!(tag.name(), name);
1101 }
1102 assert!(TypeTag::builtin("NOPE").is_none());
1103 assert!(TypeTag::builtin("string").is_none());
1104 }
1105
1106 #[test]
1107 fn scalars_conform_by_discriminant() {
1108 assert!(check_value(&TypeTag::String, &Value::string("x".to_string())).is_ok());
1109 assert!(check_value(&TypeTag::Int, &Value::int(1)).is_ok());
1110 assert!(check_value(&TypeTag::String, &Value::int(1)).is_err());
1111 assert!(check_value(&TypeTag::Int, &Value::float(3.0)).is_err());
1113 }
1114
1115 #[test]
1116 fn record_rejects_missing_and_extra_fields() {
1117 let fields: Arc<[Field]> = Arc::from([
1118 Field {
1119 name: "a".to_string(),
1120 ty: TypeTag::String,
1121 docs: "",
1122 optional: false,
1123 default: None,
1124
1125 alias: None,
1126 },
1127 Field {
1128 name: "b".to_string(),
1129 ty: TypeTag::Int,
1130 docs: "",
1131 optional: false,
1132 default: None,
1133
1134 alias: None,
1135 },
1136 ]);
1137 let tag = TypeTag::Record(fields);
1138 let good = map(&[("a", Value::string("x".to_string())), ("b", Value::int(1))]);
1139 assert!(check_value(&tag, &good).is_ok());
1140 let missing = map(&[("a", Value::string("x".to_string()))]);
1141 let err = check_value(&tag, &missing).expect_err("missing must fail");
1142 assert!(format!("{err:#}").contains('b'), "names the field: {err:#}");
1143 let extra = map(&[
1144 ("a", Value::string("x".to_string())),
1145 ("b", Value::int(1)),
1146 ("c", Value::int(2)),
1147 ]);
1148 let err = check_value(&tag, &extra).expect_err("extra must fail");
1149 assert!(format!("{err:#}").contains('c'), "names the field: {err:#}");
1150 let mistyped = map(&[
1151 ("a", Value::string("x".to_string())),
1152 ("b", Value::string("nope".to_string())),
1153 ]);
1154 assert!(check_value(&tag, &mistyped).is_err());
1155 }
1156
1157 #[test]
1158 fn record_optional_fields_may_be_absent() {
1159 let fields: Arc<[Field]> = Arc::from([
1162 Field {
1163 name: "held".to_string(),
1164 ty: TypeTag::Int,
1165 docs: "",
1166 optional: false,
1167 default: None,
1168
1169 alias: None,
1170 },
1171 Field {
1172 name: "permit".to_string(),
1173 ty: TypeTag::String,
1174 docs: "",
1175 optional: true,
1176 default: None,
1177
1178 alias: None,
1179 },
1180 ]);
1181 let tag = TypeTag::Record(fields);
1182 let full = map(&[
1183 ("held", Value::int(1)),
1184 ("permit", Value::string("p".to_string())),
1185 ]);
1186 assert!(check_value(&tag, &full).is_ok());
1187 let missing_optional = map(&[("held", Value::int(0))]);
1188 assert!(check_value(&tag, &missing_optional).is_ok());
1189 let missing_required = map(&[("permit", Value::string("p".to_string()))]);
1190 let err = check_value(&tag, &missing_required).expect_err("missing required must fail");
1191 assert!(
1192 format!("{err:#}").contains("held"),
1193 "names the field: {err:#}"
1194 );
1195 let mistyped_optional = map(&[("held", Value::int(1)), ("permit", Value::int(2))]);
1196 assert!(check_value(&tag, &mistyped_optional).is_err());
1197 }
1198
1199 #[test]
1200 fn list_of_checks_elements_with_index() {
1201 let tag = TypeTag::ListOf(Arc::new(TypeTag::Int));
1202 let good = Value::list(vec![Value::int(1), Value::int(2)]);
1203 assert!(check_value(&tag, &good).is_ok());
1204 let bad = Value::list(vec![Value::int(1), Value::string("x".to_string())]);
1205 let err = check_value(&tag, &bad).expect_err("bad element must fail");
1206 assert!(
1207 format!("{err:#}").contains("[1]"),
1208 "names the index: {err:#}"
1209 );
1210 }
1211
1212 #[test]
1213 fn canonicalization_unifies_input_spacing() {
1214 assert_eq!(canonicalize_spelling("LIST<MAP>"), "LIST<MAP>");
1217 assert_eq!(canonicalize_spelling("LIST< MAP >"), "LIST<MAP>");
1218 assert_eq!(
1219 canonicalize_spelling("MAP<name:STRING,age:INT>"),
1220 "MAP<name: STRING, age: INT>"
1221 );
1222 assert_eq!(
1223 canonicalize_spelling("MAP<name : STRING>"),
1224 "MAP<name: STRING>"
1225 );
1226 }
1227
1228 #[test]
1229 fn spellings_parse_to_shapes() {
1230 assert_eq!(
1231 parse_spelling("LIST<MAP>").expect("parses"),
1232 Spelled::Generic {
1233 name: "LIST".to_string(),
1234 args: vec![SpelledField {
1235 name: None,
1236 optional: false,
1237 ty: Spelled::Named("MAP".to_string()),
1238 default: None,
1239
1240 alias: None,
1241 }],
1242 }
1243 );
1244 assert_eq!(
1245 parse_spelling("MAP<name: STRING>").expect("parses"),
1246 Spelled::Generic {
1247 name: "MAP".to_string(),
1248 args: vec![SpelledField {
1249 name: Some("name".to_string()),
1250 optional: false,
1251 ty: Spelled::Named("STRING".to_string()),
1252 default: None,
1253
1254 alias: None,
1255 }],
1256 }
1257 );
1258 assert!(parse_spelling("LIST<A, B>").is_ok());
1261 assert!(parse_spelling("MAP<STRING>").is_ok());
1262 }
1263
1264 #[test]
1265 fn optional_field_spelling_parses_and_renders() {
1266 assert_eq!(
1269 parse_spelling("MAP<permit?: PERMIT>").expect("parses"),
1270 Spelled::Generic {
1271 name: "MAP".to_string(),
1272 args: vec![SpelledField {
1273 name: Some("permit".to_string()),
1274 optional: true,
1275 ty: Spelled::Named("PERMIT".to_string()),
1276 default: None,
1277
1278 alias: None,
1279 }],
1280 }
1281 );
1282 assert_eq!(
1283 canonicalize_spelling("MAP<permit ? : PERMIT>"),
1284 "MAP<permit?: PERMIT>"
1285 );
1286 }
1287
1288 #[test]
1289 fn default_spellings_parse_render_and_materialize() {
1290 for (spelling, canonical, value) in [
1294 (
1295 "MAP<retries: INT = 2>",
1296 "MAP<retries: INT = 2>",
1297 Value::int(2),
1298 ),
1299 (
1300 "MAP<retries: INT=-2>",
1301 "MAP<retries: INT = -2>",
1302 Value::int(-2),
1303 ),
1304 (
1305 "MAP<ratio: FLOAT = 2.5>",
1306 "MAP<ratio: FLOAT = 2.5>",
1307 Value::float(2.5),
1308 ),
1309 (
1310 "MAP<on: BOOL = true>",
1311 "MAP<on: BOOL = true>",
1312 Value::bool(true),
1313 ),
1314 (
1315 "MAP<model: STRING = \"gpt-4\">",
1316 "MAP<model: STRING = \"gpt-4\">",
1317 Value::string("gpt-4".to_string()),
1318 ),
1319 (
1320 "MAP<msg: STRING = \"hello world\">",
1321 "MAP<msg: STRING = \"hello world\">",
1322 Value::string("hello world".to_string()),
1323 ),
1324 ] {
1325 let spelled = parse_spelling(spelling).expect("parses");
1326 assert_eq!(render_spelled(&spelled), canonical, "canonical: {spelling}");
1327 assert_eq!(canonicalize_spelling(spelling), canonical);
1328 match spelled {
1329 Spelled::Generic { args, .. } => {
1330 let found = args.iter().find(|f| f.default.is_some()).expect("default");
1331 let lit = found.default.as_ref().expect("lit");
1332 assert_eq!(lit.to_value(), value);
1333 assert!(
1334 canonical.contains(&format!("= {}", lit.render())),
1335 "canonical carries the default: {canonical}"
1336 );
1337 }
1338 other => panic!("expected generic, got {other:?}"),
1339 }
1340 }
1341 let tag = TypeTag::Record(Arc::from([Field {
1343 name: "retries".to_string(),
1344 ty: TypeTag::Int,
1345 docs: "",
1346 optional: false,
1347 default: Some(Value::int(2)),
1348
1349 alias: None,
1350 }]));
1351 assert_eq!(
1352 render_structural(&tag),
1353 "MAP<retries: INT = 2>",
1354 "tag renders defaults canonically"
1355 );
1356 assert_eq!(
1357 render_default_value(&Value::float(2.5)),
1358 "2.5",
1359 "float keeps its point"
1360 );
1361 for bad in [
1364 "MAP<a: INT = >",
1365 "MAP<a: INT = x>",
1366 "MAP<a: INT = 1.2.3>",
1367 "MAP<a: INT = \"x>",
1368 "MAP<a: INT = 9999999999999999999999>",
1369 ] {
1370 assert!(parse_spelling(bad).is_err(), "must fail: {bad}");
1371 }
1372 }
1373
1374 #[test]
1375 fn unknown_map_spelling_parses_and_renders() {
1376 assert_eq!(
1379 parse_spelling("MAP<ANY>").expect("parses"),
1380 Spelled::Generic {
1381 name: "MAP".to_string(),
1382 args: vec![SpelledField {
1383 name: None,
1384 optional: false,
1385 ty: Spelled::Named("ANY".to_string()),
1386 default: None,
1387
1388 alias: None,
1389 }],
1390 }
1391 );
1392 assert_eq!(canonicalize_spelling("MAP< ANY >"), "MAP<ANY>");
1393 assert_eq!(
1394 render_structural(&TypeTag::MapOf(Arc::new(TypeTag::Any))),
1395 "MAP<ANY>"
1396 );
1397 }
1398
1399 #[test]
1400 fn map_of_checks_values_with_paths() {
1401 let tag = TypeTag::MapOf(Arc::new(TypeTag::Int));
1404 let good = map(&[("a", Value::int(1))]);
1405 assert!(check_value(&tag, &good).is_ok());
1406 let bad = map(&[("a", Value::string("x".to_string()))]);
1407 let err = check_value(&tag, &bad).expect_err("bad value must fail");
1408 assert!(format!("{err:#}").contains(".a"), "names the key: {err:#}");
1409 let not_map = Value::list(vec![Value::int(1)]);
1410 let err = check_value(&tag, ¬_map).expect_err("non-map must fail");
1411 assert!(format!("{err:#}").contains("MAP<INT>"), "{err:#}");
1412 }
1413
1414 #[test]
1415 fn spellings_reject_malformed_input() {
1416 for bad in [
1417 "",
1418 "LIST<>",
1419 "LIST<A,>",
1420 "MAP<name:>",
1421 "LIST<A",
1422 "list<MAP>",
1423 "LIST<A>>",
1424 ] {
1425 assert!(parse_spelling(bad).is_err(), "{bad:?} must fail");
1426 }
1427 let mut deep = "INT".to_string();
1429 for _ in 0..MAX_GENERIC_DEPTH + 1 {
1430 deep = format!("LIST<{deep}>");
1431 }
1432 let err = parse_spelling(&deep).expect_err("over-deep spelling must fail");
1433 assert!(err.message().contains("generic depth"), "{err}");
1434 assert_eq!(err.key(), "dsl.spelling.max_depth");
1435 }
1436
1437 #[test]
1438 fn second_alias_on_same_field_fails_with_both_names() {
1439 let err =
1440 parse_spelling("MAP<h: BOOL ALIAS help ALIAS h2>").expect_err("second ALIAS must fail");
1441 assert_eq!(err.key(), "dsl.alias.duplicate_on_field");
1442 assert!(err.message().contains("`h`"), "{err}");
1443 assert!(err.message().contains("`help`"), "{err}");
1444 assert!(err.message().contains("`h2`"), "{err}");
1445 assert!(err.message().contains("only one `ALIAS`"), "{err}");
1446 assert!(!err.message().contains('\u{1f}'), "{err}");
1448 }
1449
1450 #[test]
1451 fn second_alias_with_bad_name_is_bounded() {
1452 let err = parse_spelling("MAP<h: BOOL ALIAS help ALIAS Bad, x: INT>")
1453 .expect_err("second ALIAS with bad name must fail");
1454 assert_eq!(err.key(), "dsl.alias.duplicate_on_field");
1455 assert!(!err.message().contains('>'), "{err}");
1456 assert!(!err.message().contains("x: INT"), "{err}");
1457 assert!(!err.message().contains('\u{1f}'), "{err}");
1458 }
1459
1460 #[test]
1461 fn identical_spellings_share_one_interned_payload() {
1462 let first = intern_rendered(
1463 "LIST<MAP>".to_string(),
1464 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1465 );
1466 let second = intern_rendered(
1467 "LIST<MAP>".to_string(),
1468 TypeTag::ListOf(Arc::new(TypeTag::Map)),
1469 );
1470 let (TypeTag::ListOf(a), TypeTag::ListOf(b)) = (first, second) else {
1471 panic!("rendered tags keep their shape");
1472 };
1473 assert!(
1474 Arc::ptr_eq(&a, &b),
1475 "same canonical spelling shares one payload"
1476 );
1477 }
1478
1479 #[test]
1480 fn structural_rendering_names_contents() {
1481 let fields: Arc<[Field]> = Arc::from([Field {
1482 name: "name".to_string(),
1483 ty: TypeTag::String,
1484 docs: "",
1485 optional: false,
1486 default: None,
1487
1488 alias: None,
1489 }]);
1490 let record = TypeTag::Record(fields);
1491 let list = TypeTag::ListOf(Arc::new(record));
1492 assert_eq!(render_structural(&list), "LIST<MAP<name: STRING>>");
1493 assert_eq!(render_structural(&TypeTag::Int), "INT");
1494 }
1495}