1use crate::{Expr, ExprSpan, OpLookup, ParseError, ResolvedLeafType, ResolvedType, Ty, TypeExpr};
14use serde::{Deserialize, Serialize};
15use std::{
16 any::TypeId,
17 collections::{HashMap, HashSet},
18 fmt,
19 sync::Arc,
20};
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Capabilities {
28 pub default_available: bool,
30 pub cloneable: bool,
32 pub comparable: bool,
34 pub debuggable: bool,
36}
37
38impl Capabilities {
39 fn from_host(leaf: &ResolvedLeafType) -> Self {
41 Self {
42 cloneable: leaf.element_type().can_clone_for_argument(),
43 comparable: leaf.element_type().can_compare(),
44 debuggable: leaf.element_type().can_debug(),
45 default_available: false,
46 }
47 }
48}
49
50#[derive(Clone, Debug)]
52enum Identity {
53 Host(TypeId),
54 Catalog(Arc<()>, u32),
55}
56
57#[derive(Clone, Debug)]
65pub struct NominalLeaf {
66 identity: Identity,
67 name: Arc<str>,
68 pub capabilities: Capabilities,
70}
71
72impl PartialEq for NominalLeaf {
73 fn eq(&self, other: &Self) -> bool {
75 match (&self.identity, &other.identity) {
76 (Identity::Host(a), Identity::Host(b)) => a == b,
77 (Identity::Catalog(a, i), Identity::Catalog(b, j)) => Arc::ptr_eq(a, b) && i == j,
78 _ => false,
79 }
80 }
81}
82impl Eq for NominalLeaf {}
83
84impl NominalLeaf {
85 pub(crate) fn from_host(leaf: &ResolvedLeafType) -> Self {
89 Self {
90 identity: Identity::Host(leaf.type_id()),
91 name: Arc::from(leaf.type_name()),
92 capabilities: Capabilities::from_host(leaf),
93 }
94 }
95
96 pub fn type_name(&self) -> &str {
101 &self.name
102 }
103
104 pub fn type_id(&self) -> Option<TypeId> {
109 match self.identity {
110 Identity::Host(id) => Some(id),
111 Identity::Catalog(..) => None,
112 }
113 }
114}
115
116#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
123pub enum CheckingType {
124 Leaf(u32),
126 Array(Box<CheckingType>),
128 Tuple(Vec<CheckingType>),
130 Callable(Vec<CheckingType>, Box<CheckingType>),
132}
133
134#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
139pub struct TypeDescription {
140 pub id: u32,
142 pub name: String,
144 pub aliases: Vec<String>,
146 pub primitive: Option<String>,
148 pub capabilities: Capabilities,
150 pub range_element: Option<u32>,
152}
153
154#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159pub struct OperationDescription {
160 pub name: String,
162 pub operands: Vec<CheckingType>,
164 pub result: CheckingType,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
173pub struct RecordDescription {
174 pub name: String,
176 pub ty: u32,
178 pub fields: Vec<(String, CheckingType)>,
180}
181
182#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
187pub struct FunctionDescription {
188 pub name: String,
190 pub marker: u32,
192}
193
194#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
205pub struct CheckingDescription {
206 pub builtin_contract: u32,
208 pub types: Vec<TypeDescription>,
210 pub operations: Vec<OperationDescription>,
212 pub records: Vec<RecordDescription>,
214 pub functions: Vec<FunctionDescription>,
216 pub type_functions: Vec<TypeFunctionDescription>,
218}
219
220#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
227pub struct TypeFunctionDescription {
228 pub name: String,
230 pub arguments: Vec<CheckingType>,
232 pub result: CheckingType,
234}
235
236#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct MetadataError(pub String);
242impl fmt::Display for MetadataError {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 self.0.fmt(f)
246 }
247}
248impl std::error::Error for MetadataError {}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
255pub enum MetadataAvailability {
256 Complete,
258 Unavailable,
260}
261
262pub struct CheckingReport<T> {
267 pub value: T,
269 pub diagnostics: Vec<ParseError>,
271 pub incomplete: Vec<ParseError>,
273}
274
275pub struct CheckingEnvironment {
282 owner: Arc<()>,
283 description: CheckingDescription,
284 types: HashMap<u32, Ty>,
285 type_indices: HashMap<u32, usize>,
286 names: HashMap<String, u32>,
287 type_functions: HashMap<String, HashMap<Vec<CheckingType>, u32>>,
288 operations: HashMap<String, Vec<SemanticOperation>>,
289 records: HashMap<String, SemanticRecord>,
290 functions: HashMap<String, Ty>,
291 function_names: HashMap<u32, String>,
292}
293
294pub(crate) struct SemanticOperation {
296 pub(crate) operands: Vec<Ty>,
297 pub(crate) result: Ty,
298}
299pub(crate) struct SemanticRecord {
301 pub(crate) ty: Ty,
302 pub(crate) fields: Vec<(String, Ty)>,
303}
304
305impl CheckingEnvironment {
306 pub fn from_description(description: CheckingDescription) -> Result<Self, MetadataError> {
318 validate(&description)?;
319 Self::from_validated_description(description)
320 }
321
322 fn from_validated_description(description: CheckingDescription) -> Result<Self, MetadataError> {
326 let owner = Arc::new(());
327 let types: HashMap<_, _> = description
328 .types
329 .iter()
330 .map(|leaf| {
331 let ty = leaf
332 .primitive
333 .as_deref()
334 .and_then(Ty::from_name)
335 .unwrap_or_else(|| {
336 Ty::Registered(NominalLeaf {
337 identity: Identity::Catalog(owner.clone(), leaf.id),
338 name: Arc::from(leaf.name.as_str()),
339 capabilities: leaf.capabilities,
340 })
341 });
342 (leaf.id, ty)
343 })
344 .collect();
345 let names = description
346 .types
347 .iter()
348 .flat_map(|leaf| {
349 leaf.aliases
350 .iter()
351 .map(move |alias| (alias.clone(), leaf.id))
352 })
353 .collect();
354 let mut operations: HashMap<String, Vec<SemanticOperation>> = HashMap::new();
355 for operation in &description.operations {
356 operations
357 .entry(operation.name.clone())
358 .or_default()
359 .push(SemanticOperation {
360 operands: operation
361 .operands
362 .iter()
363 .map(|ty| lower(ty, &types))
364 .collect(),
365 result: lower(&operation.result, &types),
366 });
367 }
368 let mut records = HashMap::new();
369 for record in &description.records {
370 records.insert(
371 record.name.clone(),
372 SemanticRecord {
373 ty: types[&record.ty].clone(),
374 fields: record
375 .fields
376 .iter()
377 .map(|(name, ty)| (name.clone(), lower(ty, &types)))
378 .collect(),
379 },
380 );
381 }
382 let functions = description
383 .functions
384 .iter()
385 .map(|function| (function.name.clone(), types[&function.marker].clone()))
386 .collect();
387 let function_names = description
388 .functions
389 .iter()
390 .map(|function| (function.marker, function.name.clone()))
391 .collect();
392 let type_indices = description
393 .types
394 .iter()
395 .enumerate()
396 .map(|(index, ty)| (ty.id, index))
397 .collect();
398 let mut environment = Self {
399 owner,
400 description,
401 types,
402 type_indices,
403 names,
404 type_functions: HashMap::new(),
405 operations,
406 records,
407 functions,
408 function_names,
409 };
410 for signature in &environment.description.type_functions {
411 let CheckingType::Leaf(result) = signature.result else {
412 return Err(MetadataError("type-function result must be nominal".into()));
413 };
414 environment
415 .type_functions
416 .entry(signature.name.clone())
417 .or_default()
418 .insert(signature.arguments.clone(), result);
419 }
420 Ok(environment)
421 }
422
423 pub fn description(&self) -> &CheckingDescription {
428 &self.description
429 }
430
431 pub fn resolve_type(&self, name: &str) -> Option<Ty> {
441 self.names.get(name).map(|id| self.types[id].clone())
442 }
443
444 pub fn capabilities(&self, ty: &Ty) -> Option<Capabilities> {
454 let id = self.nominal_id(ty)?;
455 Some(self.description.types[self.type_indices[&id]].capabilities)
456 }
457
458 pub fn range_element(&self, ty: &Ty) -> Option<Ty> {
469 let id = self.nominal_id(ty)?;
470 self.description.types[self.type_indices[&id]]
471 .range_element
472 .map(|id| self.types[&id].clone())
473 }
474
475 pub fn check_annotation(
500 &self,
501 expr: &TypeExpr,
502 availability: MetadataAvailability,
503 ) -> CheckingReport<Ty> {
504 let (value, errors) = resolve_partial_annotation(expr, &|ty| self.resolve_annotation(ty));
505 let (incomplete, diagnostics) = errors.into_iter().partition(|error| {
506 availability == MetadataAvailability::Unavailable && is_missing(error)
507 });
508 CheckingReport {
509 value,
510 diagnostics,
511 incomplete,
512 }
513 }
514
515 pub(crate) fn operation_signatures(
517 &self,
518 name: &str,
519 ) -> impl Iterator<Item = &SemanticOperation> {
520 self.operations.get(name).into_iter().flatten()
521 }
522 pub(crate) fn record_schema(&self, name: &str) -> Option<&SemanticRecord> {
524 self.records.get(name)
525 }
526 pub(crate) fn registered_function_type(&self, name: &str) -> Option<Ty> {
528 self.functions.get(name).cloned()
529 }
530 pub(crate) fn registered_function_name(&self, marker: &Ty) -> Option<&str> {
532 self.function_names
533 .get(&self.nominal_id(marker)?)
534 .map(String::as_str)
535 }
536
537 pub(crate) fn resolve_annotation(&self, expr: &TypeExpr) -> Result<Ty, ParseError> {
544 match expr {
545 TypeExpr::Array { element, .. } => {
546 Ok(Ty::Array(Box::new(self.resolve_annotation(element)?)))
547 }
548 TypeExpr::Tuple { elements, .. } => Ok(Ty::Tuple(
549 elements
550 .iter()
551 .map(|ty| self.resolve_annotation(ty))
552 .collect::<Result<_, _>>()?,
553 )),
554 TypeExpr::Named { name, args, span } if name == "Fn" => {
555 if let [parameters, result] = args.as_slice()
556 && let Ty::Tuple(parameters) = self.resolve_annotation(parameters)?
557 {
558 return Ok(Ty::Callable(
559 parameters,
560 Box::new(self.resolve_annotation(result)?),
561 ));
562 }
563 Err(ParseError::new_range(
564 "Fn requires a parameter tuple and result type",
565 span.start,
566 span.end,
567 ))
568 }
569 TypeExpr::Named { name, args, span } => {
570 if args.is_empty()
571 && let Some(ty) = self.resolve_type(name)
572 {
573 return Ok(ty);
574 }
575 let arguments = args
576 .iter()
577 .map(|arg| self.resolve_annotation(arg))
578 .collect::<Result<Vec<_>, _>>()?;
579 let keys = arguments
580 .iter()
581 .map(|ty| self.type_reference(ty))
582 .collect::<Option<Vec<_>>>();
583 keys.and_then(|keys| self.type_functions.get(name)?.get(keys.as_slice()))
584 .map(|id| self.types[id].clone())
585 .ok_or_else(|| {
586 missing(
587 if args.is_empty() {
588 format!("unknown type `{name}`")
589 } else {
590 format!(
591 "unknown concrete type `{name}({})`",
592 arguments
593 .iter()
594 .map(Ty::name)
595 .collect::<Vec<_>>()
596 .join(", ")
597 )
598 },
599 *span,
600 )
601 })
602 }
603 }
604 }
605
606 pub fn type_reference(&self, ty: &Ty) -> Option<CheckingType> {
617 Some(match ty {
618 Ty::Array(element) => CheckingType::Array(Box::new(self.type_reference(element)?)),
619 Ty::Tuple(elements) => CheckingType::Tuple(
620 elements
621 .iter()
622 .map(|ty| self.type_reference(ty))
623 .collect::<Option<_>>()?,
624 ),
625 Ty::Callable(parameters, result) => CheckingType::Callable(
626 parameters
627 .iter()
628 .map(|ty| self.type_reference(ty))
629 .collect::<Option<_>>()?,
630 Box::new(self.type_reference(result)?),
631 ),
632 Ty::Any => return None,
633 nominal => CheckingType::Leaf(self.nominal_id(nominal)?),
634 })
635 }
636
637 fn nominal_id(&self, ty: &Ty) -> Option<u32> {
639 match ty {
640 Ty::Registered(leaf) => {
641 let Identity::Catalog(_, id) = leaf.identity else {
642 return None;
643 };
644 (self.types.get(&id) == Some(ty)).then_some(id)
645 }
646 Ty::Array(_) | Ty::Tuple(_) | Ty::Callable(..) | Ty::Any => None,
647 primitive => self.names.get(primitive.name().as_ref()).copied(),
648 }
649 }
650}
651
652pub struct CheckingBuilder {
659 description: CheckingDescription,
660 bindings: HashMap<TypeId, u32>,
661}
662
663#[derive(Clone)]
677pub struct HostTypeBinding {
678 owner: Arc<()>,
679 types: HashMap<TypeId, Ty>,
680}
681
682impl HostTypeBinding {
683 pub fn new(environment: &CheckingEnvironment) -> Self {
688 Self {
689 owner: environment.owner.clone(),
690 types: HashMap::new(),
691 }
692 }
693
694 pub fn bind<T: 'static>(
703 &mut self,
704 environment: &CheckingEnvironment,
705 ty: Ty,
706 ) -> Result<(), MetadataError> {
707 if !Arc::ptr_eq(&self.owner, &environment.owner) || environment.nominal_id(&ty).is_none() {
708 return Err(MetadataError(
709 "native binding requires a nominal type from its owning catalog".into(),
710 ));
711 }
712 let id = TypeId::of::<T>();
713 if self.types.get(&id).is_some_and(|prior| *prior != ty) {
714 return Err(MetadataError("conflicting native type binding".into()));
715 }
716 self.types.insert(id, ty);
717 Ok(())
718 }
719
720 pub fn resolve(&self, environment: &CheckingEnvironment, id: TypeId) -> Option<Ty> {
727 Arc::ptr_eq(&self.owner, &environment.owner)
728 .then(|| self.types.get(&id).cloned())
729 .flatten()
730 }
731}
732
733impl Default for CheckingBuilder {
734 fn default() -> Self {
736 Self::new()
737 }
738}
739
740impl CheckingBuilder {
741 pub fn register_type_function(
764 &mut self,
765 name: &str,
766 arguments: &[ResolvedType],
767 result: &ResolvedLeafType,
768 ) -> Result<(), MetadataError> {
769 if !crate::type_functions::valid_type_function_name(name) {
770 return Err(MetadataError("invalid type-function name".into()));
771 }
772 for argument in arguments {
773 argument
774 .complete_value_type()
775 .map_err(|error| MetadataError(error.to_string()))?;
776 }
777 result
778 .complete_value_type()
779 .map_err(|error| MetadataError(error.to_string()))?;
780 let arguments = arguments
781 .iter()
782 .map(|argument| self.shape(argument))
783 .collect::<Result<Vec<_>, _>>()?;
784 let result = CheckingType::Leaf(self.intern(result)?);
785 if arguments.is_empty()
786 && self.description.types.iter().any(|ty| {
787 ty.aliases.iter().any(|alias| alias == name) && result != CheckingType::Leaf(ty.id)
788 })
789 {
790 return Err(MetadataError(
791 "conflicting type alias and zero-operand type function".into(),
792 ));
793 }
794 if let Some(previous) = self
795 .description
796 .type_functions
797 .iter()
798 .find(|signature| signature.name == name && signature.arguments == arguments)
799 {
800 return if previous.result == result {
801 Ok(())
802 } else {
803 Err(MetadataError("conflicting type-function result".into()))
804 };
805 }
806 self.description
807 .type_functions
808 .push(TypeFunctionDescription {
809 name: name.into(),
810 arguments,
811 result,
812 });
813 Ok(())
814 }
815
816 pub fn register_type_functions(
832 &mut self,
833 functions: &crate::type_functions::TypeFunctionRegistry,
834 ) -> Result<(), MetadataError> {
835 for (name, arguments, result) in functions.descriptors() {
836 self.register_type_function(name, arguments, result)?;
837 }
838 Ok(())
839 }
840
841 pub fn new() -> Self {
846 let mut builder = Self {
847 description: CheckingDescription {
848 builtin_contract: 1,
849 types: vec![],
850 operations: vec![],
851 records: vec![],
852 functions: vec![],
853 type_functions: vec![],
854 },
855 bindings: HashMap::new(),
856 };
857 for name in crate::op_table::BUILTIN_SCALAR_NAMES {
858 let scalar = crate::op_table::builtin_scalar_type(name).expect("builtin scalar");
859 builder
860 .register_type(
861 name,
862 &ResolvedLeafType::new(*name, (scalar.value_type)()),
863 true,
864 )
865 .expect("builtin metadata");
866 }
867 let functions = crate::type_functions::builtin_type_functions();
868 builder
869 .register_type_functions(functions)
870 .expect("builtin type functions");
871 for (name, arguments, result) in functions.descriptors() {
872 builder
873 .register_type(result.type_name(), result, false)
874 .expect("builtin alias");
875 if name == "RangeInclusive"
876 && let [ResolvedType::Scalar(element)] = arguments
877 {
878 builder
879 .register_range(result, element)
880 .expect("builtin range element");
881 }
882 }
883 builder
884 .register_type(
885 "char",
886 &ResolvedLeafType::leaf::<char>("char").expect("char leaf"),
887 false,
888 )
889 .expect("char metadata");
890 let bytes = builder
891 .intern(&ResolvedLeafType::leaf::<Vec<u8>>("byte string").expect("bytes leaf"))
892 .expect("bytes metadata");
893 builder.description.types[bytes as usize]
894 .aliases
895 .push("byte string".into());
896 let cstring = builder
897 .intern(
898 &ResolvedLeafType::leaf::<std::ffi::CString>("C string").expect("C string leaf"),
899 )
900 .expect("C string metadata");
901 builder.description.types[cstring as usize]
902 .aliases
903 .push("C string".into());
904 builder
905 }
906
907 pub fn register_type(
925 &mut self,
926 name: &str,
927 leaf: &ResolvedLeafType,
928 default_available: bool,
929 ) -> Result<(), MetadataError> {
930 if !valid_metadata_name(name) {
931 return Err(MetadataError("invalid type alias".into()));
932 }
933 let id = self.intern(leaf)?;
934 if self.description.type_functions.iter().any(|signature| {
935 signature.name == name
936 && signature.arguments.is_empty()
937 && signature.result != CheckingType::Leaf(id)
938 }) {
939 return Err(MetadataError(
940 "conflicting type alias and zero-operand type function".into(),
941 ));
942 }
943 if self
944 .description
945 .types
946 .iter()
947 .any(|ty| ty.id != id && ty.aliases.iter().any(|alias| alias == name))
948 {
949 return Err(MetadataError(format!("duplicate type alias `{name}`")));
950 }
951 let ty = &mut self.description.types[id as usize];
952 if !ty.aliases.iter().any(|alias| alias == name) {
953 ty.aliases.push(name.into());
954 }
955 ty.capabilities.default_available |= default_available;
956 Ok(())
957 }
958
959 pub fn set_default_available(
976 &mut self,
977 leaf: &ResolvedLeafType,
978 available: bool,
979 ) -> Result<(), MetadataError> {
980 let id = self.bindings.get(&leaf.type_id()).ok_or_else(|| {
981 MetadataError("default availability requires a registered leaf".into())
982 })?;
983 self.description.types[*id as usize]
984 .capabilities
985 .default_available = available;
986 Ok(())
987 }
988
989 pub fn register_range(
1001 &mut self,
1002 range: &ResolvedLeafType,
1003 element: &ResolvedLeafType,
1004 ) -> Result<(), MetadataError> {
1005 self.register_type(range.type_name(), range, false)?;
1006 self.register_type(element.type_name(), element, false)?;
1007 let range = self.intern(range)?;
1008 let element = self.intern(element)?;
1009 let slot = &mut self.description.types[range as usize].range_element;
1010 if slot.is_some_and(|previous| previous != element) {
1011 return Err(MetadataError("conflicting range element".into()));
1012 }
1013 *slot = Some(element);
1014 Ok(())
1015 }
1016
1017 pub fn register_lookup(&mut self, lookup: &OpLookup) -> Result<(), MetadataError> {
1032 if let Some(category) = lookup.unsupported_checking_metadata() {
1033 return Err(MetadataError(format!(
1034 "{category} lacks complete checking metadata"
1035 )));
1036 }
1037 self.project_lookup(lookup)
1038 }
1039
1040 pub(crate) fn project_lookup(&mut self, lookup: &OpLookup) -> Result<(), MetadataError> {
1046 for operation in &lookup.registered.operations {
1047 let operands = operation
1048 .operands
1049 .iter()
1050 .map(|ty| self.shape(ty))
1051 .collect::<Result<_, _>>()?;
1052 let result = self.shape(&operation.result)?;
1053 if self
1054 .description
1055 .operations
1056 .iter()
1057 .any(|previous| previous.name == operation.name && previous.operands == operands)
1058 {
1059 return Err(MetadataError(format!(
1060 "duplicate operation signature `{}`",
1061 operation.name
1062 )));
1063 }
1064 self.description.operations.push(OperationDescription {
1065 name: operation.name.into(),
1066 operands,
1067 result,
1068 });
1069 }
1070 for record in &lookup.registered.records {
1071 if self
1072 .description
1073 .records
1074 .iter()
1075 .any(|previous| previous.name == record.ty.type_name())
1076 {
1077 return Err(MetadataError(format!(
1078 "duplicate record constructor `{}`",
1079 record.ty.type_name()
1080 )));
1081 }
1082 let ty = self.intern(&record.ty)?;
1083 let fields = record
1084 .fields
1085 .iter()
1086 .map(|field| Ok((field.name.into(), self.shape(&field.ty)?)))
1087 .collect::<Result<_, MetadataError>>()?;
1088 let name = record.ty.type_name();
1089 if !self.description.types[ty as usize]
1090 .aliases
1091 .iter()
1092 .any(|alias| alias == name)
1093 {
1094 self.description.types[ty as usize]
1095 .aliases
1096 .push(name.into());
1097 }
1098 self.description.records.push(RecordDescription {
1099 name: name.into(),
1100 ty,
1101 fields,
1102 });
1103 }
1104 for function in &lookup.registered.functions {
1105 if self
1106 .description
1107 .functions
1108 .iter()
1109 .any(|previous| previous.name == function.name)
1110 {
1111 return Err(MetadataError(format!(
1112 "duplicate function name `{}`",
1113 function.name
1114 )));
1115 }
1116 let marker = self.intern(&function.marker)?;
1117 self.description.functions.push(FunctionDescription {
1118 name: function.name.into(),
1119 marker,
1120 });
1121 }
1122 Ok(())
1123 }
1124
1125 pub fn finish(self) -> Result<CheckingEnvironment, MetadataError> {
1143 self.finish_with_bindings()
1144 .map(|(environment, _)| environment)
1145 }
1146
1147 pub fn finish_with_host_binding(
1161 self,
1162 ) -> Result<(CheckingEnvironment, HostTypeBinding), MetadataError> {
1163 let (environment, ids) = self.finish_with_bindings()?;
1164 let mut binding = HostTypeBinding::new(&environment);
1165 binding.types.extend(
1166 ids.into_iter()
1167 .map(|(host, local)| (host, environment.types[&local].clone())),
1168 );
1169 Ok((environment, binding))
1170 }
1171
1172 pub(crate) fn finish_with_bindings(
1176 mut self,
1177 ) -> Result<(CheckingEnvironment, HashMap<TypeId, u32>), MetadataError> {
1178 validate(&self.description)?;
1179 self.canonicalize();
1180 let environment = CheckingEnvironment::from_validated_description(self.description)?;
1181 Ok((environment, self.bindings))
1182 }
1183
1184 fn canonicalize(&mut self) {
1188 let mut host_ids = vec![None; self.description.types.len()];
1189 for (&host, &local) in &self.bindings {
1190 host_ids[local as usize] = Some(host);
1191 }
1192 debug_assert!(host_ids.iter().all(Option::is_some));
1193 for ty in &mut self.description.types {
1194 ty.aliases.sort();
1195 }
1196 self.description.types.sort_by(|left, right| {
1197 (&left.name, &left.aliases)
1198 .cmp(&(&right.name, &right.aliases))
1199 .then_with(|| host_ids[left.id as usize].cmp(&host_ids[right.id as usize]))
1200 });
1201 let identities: HashMap<_, _> = self
1202 .description
1203 .types
1204 .iter()
1205 .enumerate()
1206 .map(|(index, ty)| (ty.id, u32::try_from(index).expect("validated catalog size")))
1207 .collect();
1208 for ty in &mut self.description.types {
1209 ty.id = identities[&ty.id];
1210 ty.range_element = ty.range_element.map(|id| identities[&id]);
1211 }
1212 for id in self.bindings.values_mut() {
1213 *id = identities[id];
1214 }
1215 for operation in &mut self.description.operations {
1216 for operand in &mut operation.operands {
1217 remap_shape(operand, &identities);
1218 }
1219 remap_shape(&mut operation.result, &identities);
1220 }
1221 for signature in &mut self.description.type_functions {
1222 for argument in &mut signature.arguments {
1223 remap_shape(argument, &identities);
1224 }
1225 remap_shape(&mut signature.result, &identities);
1226 }
1227 self.description.type_functions.sort_by(|left, right| {
1228 (&left.name, &left.arguments).cmp(&(&right.name, &right.arguments))
1229 });
1230 self.description.operations.sort_by(|left, right| {
1231 (&left.name, &left.operands).cmp(&(&right.name, &right.operands))
1232 });
1233 for record in &mut self.description.records {
1234 record.ty = identities[&record.ty];
1235 for (_, field) in &mut record.fields {
1236 remap_shape(field, &identities);
1237 }
1238 }
1239 self.description
1240 .records
1241 .sort_by(|left, right| left.name.cmp(&right.name));
1242 for function in &mut self.description.functions {
1243 function.marker = identities[&function.marker];
1244 }
1245 self.description
1246 .functions
1247 .sort_by(|left, right| left.name.cmp(&right.name));
1248 }
1249
1250 fn intern(&mut self, leaf: &ResolvedLeafType) -> Result<u32, MetadataError> {
1256 if !valid_metadata_name(leaf.type_name()) {
1257 return Err(MetadataError("invalid nominal diagnostic name".into()));
1258 }
1259 let capabilities = Capabilities::from_host(leaf);
1260 if let Some(&id) = self.bindings.get(&leaf.type_id()) {
1261 let ty = &mut self.description.types[id as usize];
1262 if leaf.type_name() < ty.name.as_str() {
1263 ty.name = leaf.type_name().into();
1264 }
1265 ty.capabilities.cloneable |= capabilities.cloneable;
1267 ty.capabilities.comparable |= capabilities.comparable;
1268 ty.capabilities.debuggable |= capabilities.debuggable;
1269 return Ok(id);
1270 }
1271 let id = u32::try_from(self.description.types.len())
1272 .map_err(|_| MetadataError("too many nominal types".into()))?;
1273 let primitive = Ty::from_type_id(leaf.type_id());
1274 self.description.types.push(TypeDescription {
1275 id,
1276 name: leaf.type_name().into(),
1277 aliases: vec![],
1278 primitive: (primitive != Ty::Any).then(|| primitive.name().into_owned()),
1279 capabilities,
1280 range_element: None,
1281 });
1282 self.bindings.insert(leaf.type_id(), id);
1283 Ok(id)
1284 }
1285
1286 fn shape(&mut self, ty: &ResolvedType) -> Result<CheckingType, MetadataError> {
1290 Ok(match ty {
1291 ResolvedType::Scalar(leaf) => CheckingType::Leaf(self.intern(leaf)?),
1292 ResolvedType::Array { element } => CheckingType::Array(Box::new(self.shape(element)?)),
1293 ResolvedType::Tuple { elements } => CheckingType::Tuple(
1294 elements
1295 .iter()
1296 .map(|ty| self.shape(ty))
1297 .collect::<Result<_, _>>()?,
1298 ),
1299 ResolvedType::Callable { parameters, result } => CheckingType::Callable(
1300 parameters
1301 .iter()
1302 .map(|ty| self.shape(ty))
1303 .collect::<Result<_, _>>()?,
1304 Box::new(self.shape(result)?),
1305 ),
1306 })
1307 }
1308}
1309
1310fn remap_shape(shape: &mut CheckingType, identities: &HashMap<u32, u32>) {
1314 match shape {
1315 CheckingType::Leaf(id) => *id = identities[id],
1316 CheckingType::Array(element) => remap_shape(element, identities),
1317 CheckingType::Tuple(elements) => {
1318 for element in elements {
1319 remap_shape(element, identities);
1320 }
1321 }
1322 CheckingType::Callable(parameters, result) => {
1323 for parameter in parameters {
1324 remap_shape(parameter, identities);
1325 }
1326 remap_shape(result, identities);
1327 }
1328 }
1329}
1330
1331fn lower(shape: &CheckingType, types: &HashMap<u32, Ty>) -> Ty {
1335 match shape {
1336 CheckingType::Leaf(id) => types[id].clone(),
1337 CheckingType::Array(element) => Ty::Array(Box::new(lower(element, types))),
1338 CheckingType::Tuple(elements) => {
1339 Ty::Tuple(elements.iter().map(|ty| lower(ty, types)).collect())
1340 }
1341 CheckingType::Callable(parameters, result) => Ty::Callable(
1342 parameters.iter().map(|ty| lower(ty, types)).collect(),
1343 Box::new(lower(result, types)),
1344 ),
1345 }
1346}
1347
1348fn validate(description: &CheckingDescription) -> Result<(), MetadataError> {
1352 let fail = |message: &str| MetadataError(message.into());
1353 if description.builtin_contract != 1 {
1354 return Err(fail("unsupported builtin checking contract"));
1355 }
1356 let mut ids = HashSet::new();
1357 let mut names = HashMap::new();
1358 let mut primitives = HashSet::new();
1359 let mut alias_parser = crate::CELParser::new(OpLookup::new());
1360 for leaf in &description.types {
1361 if !ids.insert(leaf.id) {
1362 return Err(fail("duplicate nominal identity"));
1363 }
1364 if !valid_metadata_name(&leaf.name) {
1365 return Err(fail("invalid canonical type name"));
1366 }
1367 for alias in &leaf.aliases {
1368 if !valid_metadata_name(alias) || names.insert(alias.as_str(), leaf).is_some() {
1369 return Err(fail("duplicate or invalid type alias"));
1370 }
1371 if !matches!(alias.as_str(), "byte string" | "C string") {
1372 let syntax = alias_parser.parse_type_expr_str(alias).map_err(|error| {
1373 MetadataError(format!("invalid type alias `{alias}`: {error}"))
1374 })?;
1375 if !matches!(syntax, TypeExpr::Named { name, .. } if name != "Fn") {
1376 return Err(fail("type alias must name a nominal type"));
1377 }
1378 }
1379 }
1380 if let Some(primitive) = &leaf.primitive
1381 && (Ty::from_name(primitive).is_none()
1382 || !primitives.insert(primitive)
1383 || !leaf.aliases.contains(primitive))
1384 {
1385 return Err(fail("invalid or duplicate primitive identity"));
1386 }
1387 }
1388 validate_builtins(&names)?;
1389 for leaf in &description.types {
1390 if leaf.range_element.is_some_and(|id| !ids.contains(&id)) {
1391 return Err(fail("unresolved range element"));
1392 }
1393 }
1394 let mut shapes = Vec::new();
1395 for signature in &description.type_functions {
1396 if !crate::type_functions::valid_type_function_name(&signature.name)
1397 || !matches!(signature.result, CheckingType::Leaf(_))
1398 {
1399 return Err(fail("invalid or duplicate type-function signature"));
1400 }
1401 shapes.extend(signature.arguments.iter().map(|ty| (ty, 0usize)));
1402 shapes.push((&signature.result, 0));
1403 }
1404 for operation in &description.operations {
1405 if !valid_metadata_name(&operation.name) {
1406 return Err(fail("invalid operation name"));
1407 }
1408 shapes.extend(operation.operands.iter().map(|ty| (ty, 0usize)));
1409 shapes.push((&operation.result, 0));
1410 }
1411 let mut records = HashSet::new();
1412 for record in &description.records {
1413 if !ids.contains(&record.ty)
1414 || !records.insert(&record.name)
1415 || names
1416 .get(record.name.as_str())
1417 .is_none_or(|ty| ty.id != record.ty)
1418 {
1419 return Err(fail(
1420 "unresolved record identity or duplicate constructor name",
1421 ));
1422 }
1423 let mut fields = HashSet::new();
1424 for (name, ty) in &record.fields {
1425 if !valid_metadata_name(name) || !fields.insert(name) {
1426 return Err(fail("duplicate or invalid field name"));
1427 }
1428 shapes.push((ty, 0));
1429 }
1430 }
1431 let mut functions = HashSet::new();
1432 let mut markers = HashSet::new();
1433 for function in &description.functions {
1434 if !valid_metadata_name(&function.name)
1435 || !functions.insert(&function.name)
1436 || !markers.insert(function.marker)
1437 || !ids.contains(&function.marker)
1438 {
1439 return Err(fail("invalid function identity or name"));
1440 }
1441 }
1442 while let Some((shape, depth)) = shapes.pop() {
1443 if depth > 128 {
1444 return Err(fail("checking shape exceeds maximum depth 128"));
1445 }
1446 match shape {
1447 CheckingType::Leaf(id) if !ids.contains(id) => {
1448 return Err(fail("unresolved shape leaf"));
1449 }
1450 CheckingType::Leaf(_) => {}
1451 CheckingType::Array(element) => shapes.push((element, depth + 1)),
1452 CheckingType::Tuple(elements) => {
1453 shapes.extend(elements.iter().map(|ty| (ty, depth + 1)))
1454 }
1455 CheckingType::Callable(parameters, result) => {
1456 shapes.extend(parameters.iter().map(|ty| (ty, depth + 1)));
1457 shapes.push((result, depth + 1));
1458 }
1459 }
1460 }
1461 let mut signatures = HashSet::new();
1462 let mut type_functions = HashSet::new();
1463 for signature in &description.type_functions {
1464 if !type_functions.insert((signature.name.as_str(), signature.arguments.as_slice())) {
1465 return Err(fail("duplicate type-function signature"));
1466 }
1467 if signature.arguments.is_empty()
1468 && names
1469 .get(signature.name.as_str())
1470 .is_some_and(|alias| signature.result != CheckingType::Leaf(alias.id))
1471 {
1472 return Err(fail(
1473 "conflicting type alias and zero-operand type function",
1474 ));
1475 }
1476 }
1477 for operation in &description.operations {
1478 if !signatures.insert((operation.name.as_str(), operation.operands.as_slice())) {
1479 return Err(fail("duplicate operation signature"));
1480 }
1481 }
1482 validate_builtin_type_functions(description, &names)?;
1483 Ok(())
1484}
1485
1486fn validate_builtin_type_functions(
1490 description: &CheckingDescription,
1491 names: &HashMap<&str, &TypeDescription>,
1492) -> Result<(), MetadataError> {
1493 let fail = || MetadataError("missing or inconsistent builtin type-function signature".into());
1494 for (name, arguments, result) in crate::type_functions::builtin_type_functions().descriptors() {
1495 let argument = match arguments {
1496 [] => None,
1497 [ResolvedType::Scalar(argument)] => Some(CheckingType::Leaf(
1498 names.get(argument.type_name()).ok_or_else(fail)?.id,
1499 )),
1500 _ => return Err(fail()),
1501 };
1502 let result = CheckingType::Leaf(names.get(result.type_name()).ok_or_else(fail)?.id);
1503 if !description.type_functions.iter().any(|signature| {
1504 signature.name == name
1505 && signature.arguments == argument.as_slice()
1506 && signature.result == result
1507 }) {
1508 return Err(fail());
1509 }
1510 }
1511 Ok(())
1512}
1513
1514fn validate_builtins(names: &HashMap<&str, &TypeDescription>) -> Result<(), MetadataError> {
1518 let fail = |message: &str| MetadataError(message.into());
1519 let mut identities = HashSet::new();
1520 let mut role = |name: &str| {
1521 let leaf = names
1522 .get(name)
1523 .copied()
1524 .ok_or_else(|| fail("missing builtin identity"))?;
1525 if !identities.insert(leaf.id) {
1526 return Err(fail("distinct builtin roles share one nominal identity"));
1527 }
1528 Ok(leaf)
1529 };
1530 for name in crate::op_table::BUILTIN_SCALAR_NAMES {
1531 let leaf = role(name)?;
1532 if leaf.primitive.as_deref() != Some(*name)
1533 || !leaf.capabilities.cloneable
1534 || !leaf.capabilities.comparable
1535 || !leaf.capabilities.debuggable
1536 || leaf.range_element.is_some()
1537 {
1538 return Err(fail(
1539 "inconsistent builtin primitive capabilities or identity",
1540 ));
1541 }
1542 }
1543 for name in ["char", "byte string", "C string", "RangeFull"] {
1544 if role(name)?.primitive.is_some() {
1545 return Err(fail("missing or inconsistent builtin nominal identity"));
1546 }
1547 }
1548 for range in [
1549 "Range",
1550 "RangeInclusive",
1551 "RangeFrom",
1552 "RangeTo",
1553 "RangeToInclusive",
1554 ] {
1555 for element in crate::op_table::BUILTIN_SCALAR_NAMES
1556 .iter()
1557 .filter(|name| !matches!(**name, "bool" | "String"))
1558 {
1559 let name = format!("{range}({element})");
1560 let leaf = role(&name)?;
1561 let expected = (range == "RangeInclusive").then_some(names[element].id);
1562 if leaf.primitive.is_some() || leaf.range_element != expected {
1563 return Err(fail("inconsistent builtin range capability"));
1564 }
1565 }
1566 }
1567 Ok(())
1568}
1569
1570fn valid_metadata_name(name: &str) -> bool {
1574 if name.trim().is_empty() || name.len() > 4096 {
1575 return false;
1576 }
1577 let mut depth = 0usize;
1578 for byte in name.bytes() {
1579 if matches!(byte, b'(' | b'[') {
1580 depth += 1;
1581 if depth > 64 {
1582 return false;
1583 }
1584 } else if matches!(byte, b')' | b']') {
1585 depth = depth.saturating_sub(1);
1586 }
1587 }
1588 true
1589}
1590
1591#[derive(Debug)]
1593struct MissingMetadata {
1594 legacy_ignored: bool,
1595}
1596impl fmt::Display for MissingMetadata {
1597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1599 f.write_str("missing checking metadata")
1600 }
1601}
1602impl std::error::Error for MissingMetadata {}
1603
1604pub(crate) fn missing(message: String, span: ExprSpan) -> ParseError {
1606 ParseError::new_range(message, span.start, span.end).with_cause(MissingMetadata {
1607 legacy_ignored: false,
1608 })
1609}
1610
1611pub(crate) fn optional_missing(message: String, span: ExprSpan) -> ParseError {
1613 ParseError::new_range(message, span.start, span.end).with_cause(MissingMetadata {
1614 legacy_ignored: true,
1615 })
1616}
1617
1618pub fn check_expr_with_environment(
1647 expr: &Expr,
1648 resolve_ident: &dyn Fn(&str) -> Option<Ty>,
1649 environment: &CheckingEnvironment,
1650 availability: MetadataAvailability,
1651) -> CheckingReport<Ty> {
1652 let (value, errors) = crate::ty::check_semantic_expr(
1653 expr,
1654 resolve_ident,
1655 &|ty| resolve_partial_annotation(ty, &|ty| environment.resolve_annotation(ty)),
1656 environment,
1657 );
1658 let (incomplete, diagnostics) = errors
1659 .into_iter()
1660 .partition(|error| availability == MetadataAvailability::Unavailable && is_missing(error));
1661 CheckingReport {
1662 value,
1663 diagnostics,
1664 incomplete,
1665 }
1666}
1667
1668pub(crate) fn resolve_partial_annotation(
1677 expr: &TypeExpr,
1678 resolve: &dyn Fn(&TypeExpr) -> crate::Result<Ty>,
1679) -> (Ty, Vec<ParseError>) {
1680 let mut errors = Vec::new();
1681 let value = partial_annotation_type(expr, resolve, &mut errors);
1682 (value, errors)
1683}
1684
1685fn partial_annotation_type(
1689 expr: &TypeExpr,
1690 resolve: &dyn Fn(&TypeExpr) -> crate::Result<Ty>,
1691 errors: &mut Vec<ParseError>,
1692) -> Ty {
1693 let mut child = |expr: &TypeExpr| partial_annotation_type(expr, resolve, errors);
1694 match expr {
1695 TypeExpr::Array { element, .. } => Ty::Array(Box::new(child(element))),
1696 TypeExpr::Tuple { elements, .. } => Ty::Tuple(elements.iter().map(&mut child).collect()),
1697 TypeExpr::Named { name, args, span } if name == "Fn" => {
1698 if let [parameters, result] = args.as_slice() {
1699 let parameters = child(parameters);
1700 let result = child(result);
1701 if let Ty::Tuple(parameters) = parameters {
1702 return Ty::Callable(parameters, Box::new(result));
1703 }
1704 } else {
1705 args.iter().for_each(|arg| {
1706 child(arg);
1707 });
1708 }
1709 errors.push(ParseError::new_range(
1710 "Fn requires a parameter tuple and result type",
1711 span.start,
1712 span.end,
1713 ));
1714 Ty::Any
1715 }
1716 TypeExpr::Named { args, .. } => {
1717 let mut complete = true;
1718 for arg in args {
1720 complete &= !child(arg).contains_any();
1721 }
1722 if !complete {
1723 Ty::Any
1724 } else {
1725 match resolve(expr) {
1726 Ok(ty) => ty,
1727 Err(error) => {
1728 errors.push(error);
1729 Ty::Any
1730 }
1731 }
1732 }
1733 }
1734 }
1735}
1736
1737pub(crate) fn is_missing(error: &ParseError) -> bool {
1739 use std::error::Error;
1740 error
1741 .source()
1742 .is_some_and(|cause| cause.is::<MissingMetadata>())
1743}
1744
1745pub(crate) fn legacy_ignored(error: &ParseError) -> bool {
1747 use std::error::Error;
1748 error
1749 .source()
1750 .and_then(|cause| cause.downcast_ref::<MissingMetadata>())
1751 .is_some_and(|missing| missing.legacy_ignored)
1752}
1753
1754pub(crate) fn unbind(
1758 ty: Ty,
1759 bindings: &HashMap<u32, TypeId>,
1760 environment: &CheckingEnvironment,
1761) -> Ty {
1762 let local_id = environment.nominal_id(&ty);
1763 match ty {
1764 Ty::Registered(mut leaf) => {
1765 if let Some(id) = local_id
1766 && let Some(host) = bindings.get(&id)
1767 {
1768 leaf.identity = Identity::Host(*host);
1769 }
1770 Ty::Registered(leaf)
1771 }
1772 Ty::Array(element) => Ty::Array(Box::new(unbind(*element, bindings, environment))),
1773 Ty::Tuple(elements) => Ty::Tuple(
1774 elements
1775 .into_iter()
1776 .map(|ty| unbind(ty, bindings, environment))
1777 .collect(),
1778 ),
1779 Ty::Callable(parameters, result) => Ty::Callable(
1780 parameters
1781 .into_iter()
1782 .map(|ty| unbind(ty, bindings, environment))
1783 .collect(),
1784 Box::new(unbind(*result, bindings, environment)),
1785 ),
1786 ty => ty,
1787 }
1788}
1789
1790pub(crate) fn bind(
1794 ty: Ty,
1795 bindings: &HashMap<TypeId, u32>,
1796 environment: &CheckingEnvironment,
1797) -> Ty {
1798 match ty {
1799 Ty::Registered(ref leaf) => {
1800 if let Some(id) = leaf.type_id().and_then(|id| bindings.get(&id)) {
1801 environment.types[id].clone()
1802 } else {
1803 ty
1804 }
1805 }
1806 Ty::Array(element) => Ty::Array(Box::new(bind(*element, bindings, environment))),
1807 Ty::Tuple(elements) => Ty::Tuple(
1808 elements
1809 .into_iter()
1810 .map(|ty| bind(ty, bindings, environment))
1811 .collect(),
1812 ),
1813 Ty::Callable(parameters, result) => Ty::Callable(
1814 parameters
1815 .into_iter()
1816 .map(|ty| bind(ty, bindings, environment))
1817 .collect(),
1818 Box::new(bind(*result, bindings, environment)),
1819 ),
1820 ty => ty,
1821 }
1822}
1823
1824#[cfg(test)]
1825mod host_binding_tests {
1826 use super::*;
1827
1828 #[test]
1830 fn default_selection_replaces_seeded_facts() {
1831 let mut builder = CheckingBuilder::new();
1832 let unregistered = ResolvedLeafType::leaf::<std::path::PathBuf>("Path").unwrap();
1833 assert!(builder.set_default_available(&unregistered, true).is_err());
1834 builder
1835 .set_default_available(&ResolvedLeafType::leaf::<i32>("i32").unwrap(), false)
1836 .unwrap();
1837 let environment = builder.finish().unwrap();
1838 let imported =
1839 CheckingEnvironment::from_description(environment.description().clone()).unwrap();
1840 assert!(!imported.capabilities(&Ty::I32).unwrap().default_available);
1841 }
1842
1843 #[test]
1845 fn binding_checks_ownership_shape_and_conflicts() {
1846 let environment = CheckingBuilder::new().finish().unwrap();
1847 let imported =
1848 CheckingEnvironment::from_description(environment.description().clone()).unwrap();
1849 let mut binding = HostTypeBinding::new(&environment);
1850 assert!(binding.bind::<i32>(&imported, Ty::I32).is_err());
1851 assert!(binding.bind::<i32>(&environment, Ty::Any).is_err());
1852 assert!(
1853 binding
1854 .bind::<i32>(&environment, Ty::Array(Box::new(Ty::I32)))
1855 .is_err()
1856 );
1857 let foreign = imported.resolve_type("char").unwrap();
1858 assert!(binding.bind::<char>(&environment, foreign).is_err());
1859 binding.bind::<i32>(&environment, Ty::I32).unwrap();
1860 binding.bind::<i32>(&environment, Ty::I32).unwrap();
1861 assert!(binding.bind::<i32>(&environment, Ty::F64).is_err());
1862 assert_eq!(
1863 binding.resolve(&environment, TypeId::of::<i32>()),
1864 Some(Ty::I32)
1865 );
1866 assert_eq!(binding.resolve(&imported, TypeId::of::<i32>()), None);
1867 assert_eq!(binding.resolve(&environment, TypeId::of::<bool>()), None);
1868 }
1869}