1use std::collections::HashMap;
19
20use crate::analysis::{FieldType, LogosType, TypeDef, TypeRegistry};
21use crate::intern::{Interner, Symbol};
22
23#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct TyVar(pub u32);
30
31#[derive(Clone, PartialEq, Debug)]
38pub enum InferType {
39 Int,
41 Float,
42 Bool,
43 Char,
44 Byte,
45 String,
46 Unit,
47 Nat,
48 Rational,
49 Duration,
50 Date,
51 Moment,
52 Time,
53 Span,
54 Element,
57 Event,
59 View,
61 Seq(Box<InferType>),
62 Map(Box<InferType>, Box<InferType>),
63 Set(Box<InferType>),
64 Option(Box<InferType>),
65 UserDefined(Symbol, Vec<InferType>),
70 Var(TyVar),
72 Function(Vec<InferType>, Box<InferType>),
73 Unknown,
74}
75
76#[derive(Debug, Clone)]
78pub enum TypeError {
79 Mismatch {
80 expected: InferType,
81 found: InferType,
82 },
83 InfiniteType {
84 var: TyVar,
85 ty: InferType,
86 },
87 ArityMismatch {
88 expected: usize,
89 found: usize,
90 },
91 FieldNotFound {
92 type_name: Symbol,
93 field_name: Symbol,
94 },
95 NotAFunction {
96 found: InferType,
97 },
98 UnknownFunction {
106 name: Symbol,
107 },
108 DimensionMismatch {
111 message: std::string::String,
112 },
113}
114
115impl TypeError {
116 pub fn expected_str(&self) -> std::string::String {
117 match self {
118 TypeError::Mismatch { expected, .. } => expected.to_logos_name(),
119 TypeError::ArityMismatch { expected, .. } => format!("{} arguments", expected),
120 TypeError::FieldNotFound { .. } => "a known field".to_string(),
121 TypeError::NotAFunction { .. } => "a function".to_string(),
122 TypeError::UnknownFunction { .. } => "a defined function".to_string(),
123 TypeError::InfiniteType { .. } => "a finite type".to_string(),
124 TypeError::DimensionMismatch { .. } => "a matching dimension".to_string(),
125 }
126 }
127
128 pub fn found_str(&self) -> std::string::String {
129 match self {
130 TypeError::Mismatch { found, .. } => found.to_logos_name(),
131 TypeError::ArityMismatch { found, .. } => format!("{} arguments", found),
132 TypeError::FieldNotFound { field_name, .. } => format!("{:?}", field_name),
133 TypeError::NotAFunction { found } => found.to_logos_name(),
134 TypeError::UnknownFunction { name } => format!("{:?}", name),
135 TypeError::InfiniteType { ty, .. } => ty.to_logos_name(),
136 TypeError::DimensionMismatch { message } => message.clone(),
137 }
138 }
139
140 pub fn to_parse_error_kind(
144 &self,
145 interner: &crate::intern::Interner,
146 ) -> crate::error::ParseErrorKind {
147 use crate::error::ParseErrorKind;
148 match self {
149 TypeError::Mismatch { expected, found } => ParseErrorKind::TypeMismatchDetailed {
150 expected: expected.describe(interner),
151 found: found.describe(interner),
152 context: String::new(),
153 },
154 TypeError::InfiniteType { var, ty } => ParseErrorKind::InfiniteType {
155 var_description: format!("type variable α{}", var.0),
156 type_description: ty.describe(interner),
157 },
158 TypeError::ArityMismatch { expected, found } => ParseErrorKind::ArityMismatch {
159 function: String::from("function"),
160 expected: *expected,
161 found: *found,
162 },
163 TypeError::FieldNotFound {
164 type_name,
165 field_name,
166 } => ParseErrorKind::FieldNotFound {
167 type_name: interner.resolve(*type_name).to_string(),
168 field_name: interner.resolve(*field_name).to_string(),
169 available: vec![],
170 },
171 TypeError::NotAFunction { found } => ParseErrorKind::NotAFunction {
172 found_type: found.describe(interner),
173 },
174 TypeError::UnknownFunction { name } => {
175 let name = interner.resolve(*name);
176 ParseErrorKind::Custom(match crate::semantics::builtins::retired_builtin(name) {
177 Some(refusal) => refusal.to_string(),
178 None => format!("Unknown function: {}", name),
179 })
180 }
181 TypeError::DimensionMismatch { message } => ParseErrorKind::Custom(message.clone()),
182 }
183 }
184}
185
186#[derive(Clone, Debug)]
195pub struct TypeScheme {
196 pub vars: Vec<TyVar>,
198 pub body: InferType,
200}
201
202pub struct TypeScope<'s> {
206 pub interner: &'s Interner,
207 pub registry: Option<&'s TypeRegistry>,
208 pub params: &'s HashMap<Symbol, InferType>,
209 pub twins: Option<&'s HashMap<Symbol, Symbol>>,
212}
213
214impl TypeScope<'_> {
215 pub fn canonical(&self, name: Symbol) -> Symbol {
218 self.twins
219 .and_then(|t| t.get(&name))
220 .copied()
221 .unwrap_or(name)
222 }
223}
224
225pub struct UnificationTable {
231 bindings: Vec<Option<InferType>>,
232 next_id: u32,
233}
234
235impl UnificationTable {
236 pub fn new() -> Self {
237 Self {
238 bindings: Vec::new(),
239 next_id: 0,
240 }
241 }
242
243 pub fn fresh(&mut self) -> InferType {
245 let id = self.next_id;
246 self.next_id += 1;
247 self.bindings.push(None);
248 InferType::Var(TyVar(id))
249 }
250
251 pub fn fresh_var(&mut self) -> TyVar {
253 let id = self.next_id;
254 self.next_id += 1;
255 self.bindings.push(None);
256 TyVar(id)
257 }
258
259 pub fn instantiate(&mut self, scheme: &TypeScheme) -> InferType {
264 self.instantiate_with(scheme, &[]).0
265 }
266
267 pub fn instantiate_with(
270 &mut self,
271 scheme: &TypeScheme,
272 also: &[InferType],
273 ) -> (InferType, Vec<InferType>) {
274 if scheme.vars.is_empty() {
275 return (scheme.body.clone(), also.to_vec());
276 }
277 let subst: HashMap<TyVar, TyVar> = scheme
278 .vars
279 .iter()
280 .map(|&old_tv| (old_tv, self.fresh_var()))
281 .collect();
282 let body = self.substitute_vars(&scheme.body, &subst);
283 let also = also
284 .iter()
285 .map(|t| self.substitute_vars(t, &subst))
286 .collect();
287 (body, also)
288 }
289
290 fn substitute_vars(&self, ty: &InferType, subst: &HashMap<TyVar, TyVar>) -> InferType {
292 match ty {
293 InferType::Var(tv) => {
294 let resolved = self.find(*tv);
295 match &resolved {
296 InferType::Var(rtv) => {
297 if let Some(&new_tv) = subst.get(rtv) {
298 InferType::Var(new_tv)
299 } else {
300 InferType::Var(*rtv)
301 }
302 }
303 other => self.substitute_vars(&other.clone(), subst),
304 }
305 }
306 InferType::Seq(inner) => InferType::Seq(Box::new(self.substitute_vars(inner, subst))),
307 InferType::Map(k, v) => InferType::Map(
308 Box::new(self.substitute_vars(k, subst)),
309 Box::new(self.substitute_vars(v, subst)),
310 ),
311 InferType::Set(inner) => InferType::Set(Box::new(self.substitute_vars(inner, subst))),
312 InferType::Option(inner) => {
313 InferType::Option(Box::new(self.substitute_vars(inner, subst)))
314 }
315 InferType::UserDefined(sym, args) => InferType::UserDefined(
316 *sym,
317 args.iter()
318 .map(|a| self.substitute_vars(a, subst))
319 .collect(),
320 ),
321 InferType::Function(params, ret) => InferType::Function(
322 params
323 .iter()
324 .map(|p| self.substitute_vars(p, subst))
325 .collect(),
326 Box::new(self.substitute_vars(ret, subst)),
327 ),
328 other => other.clone(),
329 }
330 }
331
332 pub fn find(&self, tv: TyVar) -> InferType {
334 let mut current = tv;
335 loop {
336 match &self.bindings[current.0 as usize] {
337 None => return InferType::Var(current),
338 Some(InferType::Var(tv2)) => current = *tv2,
339 Some(ty) => return ty.clone(),
340 }
341 }
342 }
343
344 fn walk(&self, ty: &InferType) -> InferType {
346 match ty {
347 InferType::Var(tv) => self.find(*tv),
348 other => other.clone(),
349 }
350 }
351
352 pub fn resolve(&self, ty: &InferType) -> InferType {
358 match ty {
359 InferType::Var(tv) => {
360 let resolved = self.find(*tv);
361 match &resolved {
362 InferType::Var(_) => resolved, other => self.resolve(&other.clone()),
364 }
365 }
366 InferType::Seq(inner) => InferType::Seq(Box::new(self.resolve(inner))),
367 InferType::Map(k, v) => {
368 InferType::Map(Box::new(self.resolve(k)), Box::new(self.resolve(v)))
369 }
370 InferType::Set(inner) => InferType::Set(Box::new(self.resolve(inner))),
371 InferType::Option(inner) => InferType::Option(Box::new(self.resolve(inner))),
372 InferType::UserDefined(sym, args) => {
373 InferType::UserDefined(*sym, args.iter().map(|a| self.resolve(a)).collect())
374 }
375 InferType::Function(params, ret) => {
376 let params = params.iter().map(|p| self.resolve(p)).collect();
377 InferType::Function(params, Box::new(self.resolve(ret)))
378 }
379 other => other.clone(),
380 }
381 }
382
383 pub fn zonk(&self, ty: &InferType) -> InferType {
388 match ty {
389 InferType::Var(tv) => {
390 let resolved = self.find(*tv);
391 match &resolved {
392 InferType::Var(_) => InferType::Unknown,
393 other => self.zonk(other),
394 }
395 }
396 InferType::Seq(inner) => InferType::Seq(Box::new(self.zonk(inner))),
397 InferType::Map(k, v) => InferType::Map(Box::new(self.zonk(k)), Box::new(self.zonk(v))),
398 InferType::Set(inner) => InferType::Set(Box::new(self.zonk(inner))),
399 InferType::Option(inner) => InferType::Option(Box::new(self.zonk(inner))),
400 InferType::UserDefined(sym, args) => {
401 InferType::UserDefined(*sym, args.iter().map(|a| self.zonk(a)).collect())
402 }
403 InferType::Function(params, ret) => {
404 let params = params.iter().map(|p| self.zonk(p)).collect();
405 InferType::Function(params, Box::new(self.zonk(ret)))
406 }
407 other => other.clone(),
408 }
409 }
410
411 pub fn to_logos_type(&self, ty: &InferType) -> LogosType {
413 let zonked = self.zonk(ty);
414 infer_to_logos(&zonked)
415 }
416
417 pub fn unify(&mut self, found: &InferType, expected: &InferType) -> Result<(), TypeError> {
425 let found = self.walk(found);
426 let expected = self.walk(expected);
427 self.unify_walked(&found, &expected)
428 }
429
430 fn unify_walked(&mut self, a: &InferType, b: &InferType) -> Result<(), TypeError> {
431 match (a, b) {
432 (InferType::Unknown, _) | (_, InferType::Unknown) => Ok(()),
436
437 (InferType::Var(va), InferType::Var(vb)) if va == vb => Ok(()),
439
440 (InferType::Var(tv), ty) => {
442 let tv = *tv;
443 let ty = ty.clone();
444 self.occurs_check(tv, &ty)?;
445 self.bindings[tv.0 as usize] = Some(ty);
446 Ok(())
447 }
448 (ty, InferType::Var(tv)) => {
449 let tv = *tv;
450 let ty = ty.clone();
451 self.occurs_check(tv, &ty)?;
452 self.bindings[tv.0 as usize] = Some(ty);
453 Ok(())
454 }
455
456 (InferType::Int, InferType::Int) => Ok(()),
458 (InferType::Float, InferType::Float) => Ok(()),
459 (InferType::Bool, InferType::Bool) => Ok(()),
460 (InferType::Char, InferType::Char) => Ok(()),
461 (InferType::Byte, InferType::Byte) => Ok(()),
462 (InferType::String, InferType::String) => Ok(()),
463 (InferType::Unit, InferType::Unit) => Ok(()),
464 (InferType::Nat, InferType::Nat) => Ok(()),
465 (InferType::Duration, InferType::Duration) => Ok(()),
466 (InferType::Date, InferType::Date) => Ok(()),
467 (InferType::Moment, InferType::Moment) => Ok(()),
468 (InferType::Time, InferType::Time) => Ok(()),
469 (InferType::Span, InferType::Span) => Ok(()),
470 (InferType::Element, InferType::Element) => Ok(()),
473 (InferType::Event, InferType::Event) => Ok(()),
474 (InferType::View, InferType::View) => Ok(()),
475
476 (InferType::Nat, InferType::Int) | (InferType::Int, InferType::Nat) => Ok(()),
478
479 (InferType::Byte, InferType::Int) | (InferType::Int, InferType::Byte) => Ok(()),
481
482 (InferType::Rational, InferType::Rational) => Ok(()),
486 (InferType::Rational, InferType::Int | InferType::Nat)
487 | (InferType::Int | InferType::Nat, InferType::Rational) => Ok(()),
488
489 (InferType::UserDefined(a, a_args), InferType::UserDefined(b, b_args)) if a == b => {
492 if a_args.is_empty() || b_args.is_empty() {
493 return Ok(());
494 }
495 if a_args.len() != b_args.len() {
496 return Err(TypeError::ArityMismatch {
497 expected: a_args.len(),
498 found: b_args.len(),
499 });
500 }
501 let (a_args, b_args) = (a_args.clone(), b_args.clone());
502 for (x, y) in a_args.iter().zip(b_args.iter()) {
503 self.unify(x, y)?;
504 }
505 Ok(())
506 }
507
508 (InferType::Seq(a_inner), InferType::Seq(b_inner)) => {
510 let a_inner = (**a_inner).clone();
511 let b_inner = (**b_inner).clone();
512 self.unify(&a_inner, &b_inner)
513 }
514 (InferType::Set(a_inner), InferType::Set(b_inner)) => {
515 let a_inner = (**a_inner).clone();
516 let b_inner = (**b_inner).clone();
517 self.unify(&a_inner, &b_inner)
518 }
519 (InferType::Option(a_inner), InferType::Option(b_inner)) => {
520 let a_inner = (**a_inner).clone();
521 let b_inner = (**b_inner).clone();
522 self.unify(&a_inner, &b_inner)
523 }
524 (InferType::Map(ak, av), InferType::Map(bk, bv)) => {
525 let ak = (**ak).clone();
526 let bk = (**bk).clone();
527 let av = (**av).clone();
528 let bv = (**bv).clone();
529 self.unify(&ak, &bk)?;
530 self.unify(&av, &bv)
531 }
532 (InferType::Function(a_params, a_ret), InferType::Function(b_params, b_ret)) => {
533 if a_params.len() != b_params.len() {
534 return Err(TypeError::ArityMismatch {
535 expected: a_params.len(),
536 found: b_params.len(),
537 });
538 }
539 let a_params = a_params.clone();
540 let b_params = b_params.clone();
541 let a_ret = (**a_ret).clone();
542 let b_ret = (**b_ret).clone();
543 for (ap, bp) in a_params.iter().zip(b_params.iter()) {
544 self.unify(ap, bp)?;
545 }
546 self.unify(&a_ret, &b_ret)
547 }
548
549 (a, b) => Err(TypeError::Mismatch {
551 expected: b.clone(),
552 found: a.clone(),
553 }),
554 }
555 }
556
557 fn occurs_check(&self, tv: TyVar, ty: &InferType) -> Result<(), TypeError> {
561 match ty {
562 InferType::Var(tv2) => {
563 let resolved = self.find(*tv2);
564 match &resolved {
565 InferType::Var(rtv) => {
566 if *rtv == tv {
567 Err(TypeError::InfiniteType {
568 var: tv,
569 ty: ty.clone(),
570 })
571 } else {
572 Ok(())
573 }
574 }
575 other => self.occurs_check(tv, &other.clone()),
576 }
577 }
578 InferType::Seq(inner) | InferType::Set(inner) | InferType::Option(inner) => {
579 self.occurs_check(tv, inner)
580 }
581 InferType::Map(k, v) => {
582 self.occurs_check(tv, k)?;
583 self.occurs_check(tv, v)
584 }
585 InferType::UserDefined(_, args) => {
586 for a in args {
587 self.occurs_check(tv, a)?;
588 }
589 Ok(())
590 }
591 InferType::Function(params, ret) => {
592 for p in params {
593 self.occurs_check(tv, p)?;
594 }
595 self.occurs_check(tv, ret)
596 }
597 _ => Ok(()),
598 }
599 }
600}
601
602impl InferType {
607 pub fn from_type_expr(ty: &crate::ast::stmt::TypeExpr, interner: &Interner) -> InferType {
613 Self::from_type_expr_with_params(ty, interner, &HashMap::new())
614 }
615
616 pub fn from_type_expr_with_params(
623 ty: &crate::ast::stmt::TypeExpr,
624 interner: &Interner,
625 type_params: &HashMap<Symbol, TyVar>,
626 ) -> InferType {
627 let params = type_params
628 .iter()
629 .map(|(s, tv)| (*s, InferType::Var(*tv)))
630 .collect();
631 Self::from_type_expr_in(
632 ty,
633 &TypeScope {
634 interner,
635 registry: None,
636 params: ¶ms,
637 twins: None,
638 },
639 )
640 }
641
642 pub fn from_type_expr_in(ty: &crate::ast::stmt::TypeExpr, scope: &TypeScope) -> InferType {
645 use crate::ast::stmt::TypeExpr;
646 match ty {
647 TypeExpr::Mutable { inner } => Self::from_type_expr_in(inner, scope),
649 TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
650 Self::from_applied_name(*sym, None, scope)
651 }
652 TypeExpr::Generic { base, params } => {
653 let args = params
654 .iter()
655 .map(|p| Self::from_type_expr_in(p, scope))
656 .collect();
657 Self::from_applied_name(*base, Some(args), scope)
658 }
659 TypeExpr::Tuple(_) => InferType::Unknown,
662 TypeExpr::Record { .. } => InferType::Unknown,
663 TypeExpr::Refinement { base, .. } => Self::from_type_expr_in(base, scope),
664 TypeExpr::Persistent { inner } => Self::from_type_expr_in(inner, scope),
665 TypeExpr::Function { inputs, output } => {
666 let param_types: Vec<InferType> = inputs
667 .iter()
668 .map(|p| Self::from_type_expr_in(p, scope))
669 .collect();
670 let ret_type = Self::from_type_expr_in(output, scope);
671 InferType::Function(param_types, Box::new(ret_type))
672 }
673 }
674 }
675
676 fn from_applied_name(
683 base: Symbol,
684 applied: Option<Vec<InferType>>,
685 scope: &TypeScope,
686 ) -> InferType {
687 if applied.as_ref().map_or(true, |args| args.is_empty()) {
688 if let Some(param) = scope.params.get(&base) {
689 return param.clone();
690 }
691 }
692 let name = scope.interner.resolve(base);
693 let user = scope.registry.and_then(|r| r.get(base));
694 let declared_by_user = matches!(user, Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }));
695 let is_option = name == "Option" || (name == "Maybe" && !declared_by_user);
696 let Some(args) = applied else {
697 if is_option {
698 return InferType::Option(Box::new(InferType::Unknown));
699 }
700 let primitive = Self::from_type_name(name);
701 if primitive != InferType::Unknown {
702 return primitive;
703 }
704 return match user {
705 Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }) => {
706 InferType::UserDefined(scope.canonical(base), Vec::new())
707 }
708 Some(TypeDef::Alias { target }) if *target != base => {
709 Self::from_applied_name(*target, None, scope)
710 }
711 _ => InferType::Unknown,
712 };
713 };
714 let mut args = args.into_iter();
715 if is_option {
716 return InferType::Option(Box::new(args.next().unwrap_or(InferType::Unit)));
717 }
718 match name {
719 "Seq" | "List" | "Vec" => {
720 return InferType::Seq(Box::new(args.next().unwrap_or(InferType::Unit)))
721 }
722 "Set" | "HashSet" => {
723 return InferType::Set(Box::new(args.next().unwrap_or(InferType::Unit)))
724 }
725 "Map" | "HashMap" => {
726 let k = args.next().unwrap_or(InferType::String);
727 let v = args.next().unwrap_or(InferType::String);
728 return InferType::Map(Box::new(k), Box::new(v));
729 }
730 _ => {}
731 }
732 let args: Vec<InferType> = args.collect();
733 if args.is_empty() {
734 let primitive = Self::from_type_name(name);
735 if primitive != InferType::Unknown {
736 return primitive;
737 }
738 }
739 match user {
740 Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }) => {
741 InferType::UserDefined(scope.canonical(base), args)
742 }
743 Some(TypeDef::Alias { target }) if *target != base => {
744 Self::from_applied_name(*target, Some(args), scope)
745 }
746 _ => InferType::Unknown,
747 }
748 }
749
750 pub fn from_field_type(
755 ty: &FieldType,
756 interner: &Interner,
757 type_params: &HashMap<Symbol, TyVar>,
758 ) -> InferType {
759 let params = type_params
760 .iter()
761 .map(|(s, tv)| (*s, InferType::Var(*tv)))
762 .collect();
763 Self::from_field_type_in(
764 ty,
765 &TypeScope {
766 interner,
767 registry: None,
768 params: ¶ms,
769 twins: None,
770 },
771 )
772 }
773
774 pub fn from_field_type_in(ty: &FieldType, scope: &TypeScope) -> InferType {
777 match ty {
778 FieldType::Primitive(sym) => InferType::from_type_name(scope.interner.resolve(*sym)),
779 FieldType::Named(sym) => {
780 if let Some(param) = scope.params.get(sym) {
781 return param.clone();
782 }
783 if crate::analysis::tower::TOWER_TYPES.contains(&scope.interner.resolve(*sym)) {
785 return InferType::Unknown;
786 }
787 match Self::from_applied_name(*sym, None, scope) {
788 InferType::Unknown => InferType::UserDefined(scope.canonical(*sym), Vec::new()),
789 known => known,
790 }
791 }
792 FieldType::Generic { base, params } => {
793 let args = params
794 .iter()
795 .map(|p| Self::from_field_type_in(p, scope))
796 .collect();
797 Self::from_applied_name(*base, Some(args), scope)
798 }
799 FieldType::TypeParam(sym) => {
800 scope.params.get(sym).cloned().unwrap_or(InferType::Unknown)
801 }
802 FieldType::Tuple(_) | FieldType::Record(_) => InferType::Unknown,
804 }
805 }
806
807 pub fn from_literal(lit: &crate::ast::stmt::Literal) -> InferType {
809 use crate::ast::stmt::Literal;
810 match lit {
811 Literal::Number(_) => InferType::Int,
812 Literal::Float(_) => InferType::Float,
813 Literal::Text(_) => InferType::String,
814 Literal::Boolean(_) => InferType::Bool,
815 Literal::Char(_) => InferType::Char,
816 Literal::Nothing => InferType::Unit,
817 Literal::Duration(_) => InferType::Duration,
818 Literal::Date(_) => InferType::Date,
819 Literal::Moment(_) => InferType::Moment,
820 Literal::Span { .. } => InferType::Span,
821 Literal::Time(_) => InferType::Time,
822 }
823 }
824
825 pub fn from_type_name(name: &str) -> InferType {
827 match name {
828 "Int" => InferType::Int,
829 "Nat" => InferType::Nat,
830 "Rational" => InferType::Rational,
831 "Real" | "Float" => InferType::Float,
832 "Bool" | "Boolean" => InferType::Bool,
833 "Text" | "String" => InferType::String,
834 "Char" => InferType::Char,
835 "Byte" => InferType::Byte,
836 "Unit" | "()" => InferType::Unit,
837 "Duration" => InferType::Duration,
838 "Date" => InferType::Date,
839 "Moment" => InferType::Moment,
840 "Time" => InferType::Time,
841 "Span" => InferType::Span,
842 "Element" => InferType::Element,
843 "Event" => InferType::Event,
844 "View" => InferType::View,
845 _ => InferType::Unknown,
846 }
847 }
848
849 pub fn describe(&self, interner: &crate::intern::Interner) -> std::string::String {
852 self.render(Some(interner))
853 }
854
855 pub fn to_logos_name(&self) -> std::string::String {
858 self.render(None)
859 }
860
861 pub fn primitive_name(&self) -> Option<&'static str> {
864 Some(match self {
865 InferType::Int => "Int",
866 InferType::Float => "Real",
867 InferType::Bool => "Bool",
868 InferType::Char => "Char",
869 InferType::Byte => "Byte",
870 InferType::String => "Text",
871 InferType::Unit => "Unit",
872 InferType::Nat => "Nat",
873 InferType::Rational => "Rational",
874 InferType::Duration => "Duration",
875 InferType::Date => "Date",
876 InferType::Moment => "Moment",
877 InferType::Time => "Time",
878 InferType::Span => "Span",
879 InferType::Element => "Element",
880 InferType::Event => "Event",
881 InferType::View => "View",
882 _ => return None,
883 })
884 }
885
886 fn render(&self, interner: Option<&crate::intern::Interner>) -> std::string::String {
887 match self {
888 InferType::Int => "Int".into(),
889 InferType::Float => "Real".into(),
890 InferType::Bool => "Bool".into(),
891 InferType::Char => "Char".into(),
892 InferType::Byte => "Byte".into(),
893 InferType::String => "Text".into(),
894 InferType::Unit => "Unit".into(),
895 InferType::Nat => "Nat".into(),
896 InferType::Rational => "Rational".into(),
897 InferType::Duration => "Duration".into(),
898 InferType::Date => "Date".into(),
899 InferType::Moment => "Moment".into(),
900 InferType::Time => "Time".into(),
901 InferType::Span => "Span".into(),
902 InferType::Element => "Element".into(),
903 InferType::Event => "Event".into(),
904 InferType::View => "View".into(),
905 InferType::Seq(inner) => format!("Seq of {}", inner.render(interner)),
906 InferType::Map(k, v) => {
907 format!("Map of {} and {}", k.render(interner), v.render(interner))
908 }
909 InferType::Set(inner) => format!("Set of {}", inner.render(interner)),
910 InferType::Option(inner) => format!("Option of {}", inner.render(interner)),
911 InferType::UserDefined(name, args) => match interner {
912 Some(interner) if args.is_empty() => interner.resolve(*name).to_string(),
913 Some(interner) => {
914 let args: Vec<std::string::String> =
915 args.iter().map(|a| a.render(Some(interner))).collect();
916 format!("{} of {}", interner.resolve(*name), args.join(" and "))
917 }
918 None => "a user-defined type".into(),
919 },
920 InferType::Var(_) => "an unknown type".into(),
921 InferType::Function(params, ret) => {
922 let params_str = params
923 .iter()
924 .map(|p| p.render(interner))
925 .collect::<Vec<_>>()
926 .join(", ");
927 format!("fn({}) -> {}", params_str, ret.render(interner))
928 }
929 InferType::Unknown => "unknown".into(),
930 }
931 }
932
933 pub fn to_logos_type_ground(&self) -> LogosType {
939 match self {
940 InferType::Int => LogosType::Int,
941 InferType::Float => LogosType::Float,
942 InferType::Bool => LogosType::Bool,
943 InferType::Char => LogosType::Char,
944 InferType::Byte => LogosType::Byte,
945 InferType::String => LogosType::String,
946 InferType::Unit => LogosType::Unit,
947 InferType::Nat => LogosType::Nat,
948 InferType::Rational => LogosType::Rational,
949 InferType::Duration => LogosType::Duration,
950 InferType::Date => LogosType::Date,
951 InferType::Moment => LogosType::Moment,
952 InferType::Time => LogosType::Time,
953 InferType::Span => LogosType::Span,
954 InferType::Element => LogosType::Element,
955 InferType::Event => LogosType::Event,
956 InferType::View => LogosType::View,
957 InferType::Seq(inner) => LogosType::Seq(Box::new(inner.to_logos_type_ground())),
958 InferType::Map(k, v) => LogosType::Map(
959 Box::new(k.to_logos_type_ground()),
960 Box::new(v.to_logos_type_ground()),
961 ),
962 InferType::Set(inner) => LogosType::Set(Box::new(inner.to_logos_type_ground())),
963 InferType::Option(inner) => LogosType::Option(Box::new(inner.to_logos_type_ground())),
964 InferType::UserDefined(sym, _) => LogosType::UserDefined(*sym),
965 InferType::Function(params, ret) => LogosType::Function(
966 params.iter().map(|p| p.to_logos_type_ground()).collect(),
967 Box::new(ret.to_logos_type_ground()),
968 ),
969 InferType::Unknown => LogosType::Unknown,
970 InferType::Var(_) => panic!("to_logos_type_ground called on unresolved Var"),
971 }
972 }
973}
974
975pub fn unify_numeric(a: &InferType, b: &InferType) -> Result<InferType, TypeError> {
982 match (a, b) {
983 (InferType::Float, _) | (_, InferType::Float) => Ok(InferType::Float),
984 (InferType::Rational, InferType::Rational | InferType::Int | InferType::Nat)
986 | (InferType::Int | InferType::Nat, InferType::Rational) => Ok(InferType::Rational),
987 (InferType::Int, InferType::Int) => Ok(InferType::Int),
988 (InferType::Nat, InferType::Int) | (InferType::Int, InferType::Nat) => Ok(InferType::Int),
989 (InferType::Nat, InferType::Nat) => Ok(InferType::Nat),
990 (InferType::Byte, InferType::Byte) => Ok(InferType::Byte),
991 (InferType::Byte, InferType::Int) | (InferType::Int, InferType::Byte) => {
992 Ok(InferType::Byte)
993 }
994 _ => Err(TypeError::Mismatch {
995 expected: InferType::Int,
996 found: a.clone(),
997 }),
998 }
999}
1000
1001pub fn infer_to_logos(ty: &InferType) -> LogosType {
1003 match ty {
1004 InferType::Int => LogosType::Int,
1005 InferType::Float => LogosType::Float,
1006 InferType::Bool => LogosType::Bool,
1007 InferType::Char => LogosType::Char,
1008 InferType::Byte => LogosType::Byte,
1009 InferType::String => LogosType::String,
1010 InferType::Unit => LogosType::Unit,
1011 InferType::Nat => LogosType::Nat,
1012 InferType::Rational => LogosType::Rational,
1013 InferType::Duration => LogosType::Duration,
1014 InferType::Date => LogosType::Date,
1015 InferType::Moment => LogosType::Moment,
1016 InferType::Time => LogosType::Time,
1017 InferType::Span => LogosType::Span,
1018 InferType::Element => LogosType::Element,
1019 InferType::Event => LogosType::Event,
1020 InferType::View => LogosType::View,
1021 InferType::Seq(inner) => LogosType::Seq(Box::new(infer_to_logos(inner))),
1022 InferType::Map(k, v) => {
1023 LogosType::Map(Box::new(infer_to_logos(k)), Box::new(infer_to_logos(v)))
1024 }
1025 InferType::Set(inner) => LogosType::Set(Box::new(infer_to_logos(inner))),
1026 InferType::Option(inner) => LogosType::Option(Box::new(infer_to_logos(inner))),
1027 InferType::UserDefined(sym, _) => LogosType::UserDefined(*sym),
1028 InferType::Function(params, ret) => LogosType::Function(
1029 params.iter().map(infer_to_logos).collect(),
1030 Box::new(infer_to_logos(ret)),
1031 ),
1032 InferType::Unknown | InferType::Var(_) => LogosType::Unknown,
1033 }
1034}
1035
1036#[cfg(test)]
1041#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/unify/tests.rs"]
1042mod tests;