1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2use std::borrow::Borrow;
3use std::hash::{Hash, Hasher};
4use std::mem;
5use std::sync::Arc;
6
7use ecow::EcoString;
8
9use crate::ast::Generic;
10use crate::program::{Definition, DefinitionBody};
11use fmt::Formatter;
12use std::fmt;
13use std::fmt::Display;
14use std::ops::Deref;
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct Symbol(EcoString);
25
26impl Symbol {
27 pub fn from_parts(package: &str, local: &str) -> Self {
31 let mut s = EcoString::with_capacity(package.len() + 1 + local.len());
35 s.push_str(package);
36 s.push('.');
37 s.push_str(local);
38 Self(s)
39 }
40
41 pub fn with_segment(&self, segment: &str) -> Self {
46 let mut s = EcoString::with_capacity(self.0.len() + 1 + segment.len());
47 s.push_str(&self.0);
48 s.push('.');
49 s.push_str(segment);
50 Self(s)
51 }
52
53 pub fn from_raw(qualified: impl Into<EcoString>) -> Self {
56 Self(qualified.into())
57 }
58
59 pub fn as_str(&self) -> &str {
60 &self.0
61 }
62
63 pub fn as_eco(&self) -> &EcoString {
64 &self.0
65 }
66
67 pub fn last_segment(&self) -> &str {
69 self.0.rsplit('.').next().unwrap_or(&self.0)
70 }
71
72 pub fn without_last_segment(&self) -> Option<&str> {
75 self.0.rsplit_once('.').map(|(rest, _)| rest)
76 }
77}
78
79impl Borrow<str> for Symbol {
80 fn borrow(&self) -> &str {
81 &self.0
82 }
83}
84
85impl AsRef<str> for Symbol {
86 fn as_ref(&self) -> &str {
87 &self.0
88 }
89}
90
91impl Deref for Symbol {
92 type Target = str;
93
94 fn deref(&self) -> &str {
95 &self.0
96 }
97}
98
99impl From<&Symbol> for EcoString {
100 fn from(s: &Symbol) -> Self {
101 s.0.clone()
102 }
103}
104
105impl Display for Symbol {
106 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
107 self.0.fmt(f)
108 }
109}
110
111impl From<EcoString> for Symbol {
112 fn from(s: EcoString) -> Self {
113 Self(s)
114 }
115}
116
117impl From<Symbol> for EcoString {
118 fn from(s: Symbol) -> Self {
119 s.0
120 }
121}
122
123impl From<&str> for Symbol {
124 fn from(s: &str) -> Self {
125 Self(EcoString::from(s))
126 }
127}
128
129impl From<String> for Symbol {
130 fn from(s: String) -> Self {
131 Self(EcoString::from(s))
132 }
133}
134
135impl PartialEq<str> for Symbol {
136 fn eq(&self, other: &str) -> bool {
137 self.0.as_str() == other
138 }
139}
140
141impl PartialEq<&str> for Symbol {
142 fn eq(&self, other: &&str) -> bool {
143 self.0.as_str() == *other
144 }
145}
146
147pub fn unqualified_name(id: &str) -> &str {
151 id.rsplit('.').next().unwrap_or(id)
152}
153
154pub const GO_IMPORT_PREFIX: &str = "go:";
155
156pub fn package_for_qualified_name(
162 id: &str,
163 mut contains_package: impl FnMut(&str) -> bool,
164) -> Option<&str> {
165 if !id.starts_with(GO_IMPORT_PREFIX) || !id.contains('/') {
166 return id.split_once('.').map(|(m, _)| m);
167 }
168
169 let mut end = id.len();
170 while let Some(separator) = id[..end].rfind('.') {
171 let candidate = &id[..separator];
172 if contains_package(candidate) {
173 return Some(candidate);
174 }
175 end = separator;
176 }
177 None
178}
179
180fn is_range_type_name(name: &str) -> bool {
181 matches!(
182 name,
183 "Range" | "RangeInclusive" | "RangeFrom" | "RangeTo" | "RangeToInclusive"
184 )
185}
186
187pub fn peel_to_range_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
188where
189 F: Fn(&str) -> Option<&'d Definition>,
190{
191 let peeled = peel_alias(ty, lookup);
192 peeled
193 .get_name()
194 .is_some_and(is_range_type_name)
195 .then_some(peeled)
196}
197
198#[derive(Debug, Clone, Default)]
200pub struct SubstitutionMap(Vec<(EcoString, Type)>);
201
202impl SubstitutionMap {
203 pub fn is_empty(&self) -> bool {
204 self.0.is_empty()
205 }
206
207 pub fn get(&self, name: &EcoString) -> Option<&Type> {
208 self.0
209 .iter()
210 .find_map(|(candidate, ty)| (candidate == name).then_some(ty))
211 }
212
213 pub fn insert(&mut self, name: EcoString, ty: Type) -> Option<Type> {
214 if let Some((_, existing)) = self.0.iter_mut().find(|(candidate, _)| candidate == &name) {
215 return Some(mem::replace(existing, ty));
216 }
217 self.0.push((name, ty));
218 None
219 }
220
221 fn keys(&self) -> impl Iterator<Item = &EcoString> {
222 self.0.iter().map(|(name, _)| name)
223 }
224
225 fn iter(&self) -> impl Iterator<Item = (&EcoString, &Type)> {
226 self.0.iter().map(|(name, ty)| (name, ty))
227 }
228}
229
230impl FromIterator<(EcoString, Type)> for SubstitutionMap {
231 fn from_iter<T: IntoIterator<Item = (EcoString, Type)>>(iter: T) -> Self {
232 let mut map = Self::default();
233 for (name, ty) in iter {
234 map.insert(name, ty);
235 }
236 map
237 }
238}
239
240pub fn build_substitution_map(generics: &[Generic], type_args: &[Type]) -> SubstitutionMap {
243 generics
244 .iter()
245 .zip(type_args.iter())
246 .map(|(g, t)| (g.name.clone(), t.clone()))
247 .collect()
248}
249
250pub fn build_named_substitution_map<'a>(
251 names: &[EcoString],
252 type_args: impl IntoIterator<Item = &'a Type>,
253) -> SubstitutionMap {
254 names
255 .iter()
256 .zip(type_args)
257 .map(|(name, ty)| (name.clone(), ty.clone()))
258 .collect()
259}
260
261pub fn type_args_match_params<'a>(
262 args: &[Type],
263 params: impl ExactSizeIterator<Item = &'a EcoString>,
264) -> bool {
265 args.len() == params.len()
266 && args
267 .iter()
268 .zip(params)
269 .all(|(arg, param)| matches!(arg, Type::Parameter(name) if name == param))
270}
271
272pub fn substitute(ty: &Type, map: &SubstitutionMap) -> Type {
273 if map.is_empty() {
274 return ty.clone();
275 }
276 match ty {
277 Type::Parameter(name) => map.get(name).cloned().unwrap_or_else(|| ty.clone()),
278 Type::Nominal {
279 id,
280 params,
281 writable,
282 } => Type::Nominal {
283 id: id.clone(),
284 params: params.iter().map(|p| substitute(p, map)).collect(),
285 writable: *writable,
286 },
287 Type::Function(f) => f.rebuild(
288 f.params
289 .iter()
290 .map(|param| param.with_type(substitute(¶m.ty, map)))
291 .collect(),
292 f.bounds
293 .iter()
294 .map(|b| Bound {
295 param_name: b.param_name.clone(),
296 generic: substitute(&b.generic, map),
297 ty: substitute(&b.ty, map),
298 })
299 .collect(),
300 Box::new(substitute(&f.return_type, map)),
301 ),
302 Type::Var { .. } | Type::Uninferred | Type::Ignored | Type::Error => ty.clone(),
303 Type::Forall { vars, body } => {
304 let has_overlap = map.keys().any(|k| vars.contains(k));
305 let substituted_body = if has_overlap {
306 let filtered_map: SubstitutionMap = map
307 .iter()
308 .filter(|(k, _)| !vars.contains(*k))
309 .map(|(k, v)| (k.clone(), v.clone()))
310 .collect();
311 substitute(body, &filtered_map)
312 } else {
313 substitute(body, map)
314 };
315 Type::Forall {
316 vars: vars.clone(),
317 body: Box::new(substituted_body),
318 }
319 }
320 Type::Tuple(elements) => Type::Tuple(elements.iter().map(|e| substitute(e, map)).collect()),
321 Type::Array { length, element } => Type::Array {
322 length: *length,
323 element: Box::new(substitute(element, map)),
324 },
325 Type::Compound {
326 kind,
327 args,
328 writable,
329 } => Type::qualified_compound(
330 *kind,
331 args.iter().map(|a| substitute(a, map)).collect(),
332 *writable,
333 ),
334 Type::Simple(_) | Type::Never | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {
335 ty.clone()
336 }
337 }
338}
339
340#[derive(Debug, Clone, PartialEq)]
341#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
342pub struct Bound {
343 pub param_name: EcoString,
344 pub generic: Type,
345 pub ty: Type,
346}
347
348#[derive(Debug, Clone, PartialEq)]
349#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
350pub struct FunctionParameter {
351 pub ty: Type,
352 pub name: Option<EcoString>,
353}
354
355impl FunctionParameter {
356 pub fn new(ty: Type) -> Self {
357 Self { ty, name: None }
358 }
359
360 pub fn named(ty: Type, name: Option<EcoString>) -> Self {
361 Self { ty, name }
362 }
363
364 pub fn with_type(&self, ty: Type) -> Self {
365 Self {
366 ty,
367 name: self.name.clone(),
368 }
369 }
370}
371
372#[derive(Clone)]
373#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
374pub struct FunctionType {
375 pub params: Vec<FunctionParameter>,
376 pub bounds: Vec<Bound>,
377 pub return_type: Box<Type>,
378}
379
380impl PartialEq for FunctionType {
381 fn eq(&self, other: &Self) -> bool {
382 self.params.len() == other.params.len()
383 && self
384 .params
385 .iter()
386 .zip(&other.params)
387 .all(|(left, right)| left.ty == right.ty)
388 && self.bounds == other.bounds
389 && self.return_type == other.return_type
390 }
391}
392
393impl FunctionType {
394 pub fn remove_receiver(&mut self) -> Type {
395 self.params.remove(0).ty
396 }
397
398 pub fn without_receiver(&self) -> Type {
399 let mut stripped = self.clone();
400 if !stripped.params.is_empty() {
401 stripped.remove_receiver();
402 }
403 Type::Function(Arc::new(stripped))
404 }
405
406 pub fn rebuild(
407 &self,
408 params: Vec<FunctionParameter>,
409 bounds: Vec<Bound>,
410 return_type: Box<Type>,
411 ) -> Type {
412 Type::function(params, bounds, return_type)
413 }
414}
415
416#[derive(Clone, Copy, PartialEq, Eq, Hash)]
418#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
419pub struct TypeVarId(u32);
420
421impl TypeVarId {
422 pub const fn new(index: u32) -> Self {
423 Self(index)
424 }
425
426 pub const fn index(self) -> u32 {
427 self.0
428 }
429}
430
431impl fmt::Debug for TypeVarId {
432 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
433 write!(f, "#{}", self.0)
434 }
435}
436
437#[derive(Clone)]
438#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
439pub enum Type {
440 Simple(SimpleKind),
441
442 Compound {
443 kind: CompoundKind,
444 args: Vec<Type>,
445 writable: bool,
448 },
449
450 Nominal {
451 id: Symbol,
452 params: Vec<Type>,
453 writable: bool,
454 },
455
456 ImportNamespace(EcoString),
460
461 Function(Arc<FunctionType>),
462
463 Var {
467 id: TypeVarId,
468 hint: Option<EcoString>,
469 },
470
471 Uninferred,
473
474 Ignored,
476
477 Forall {
478 vars: Vec<EcoString>,
479 body: Box<Type>,
480 },
481
482 Parameter(EcoString),
483
484 Never,
485
486 Tuple(Vec<Type>),
487
488 Array {
491 length: u64,
492 element: Box<Type>,
493 },
494
495 Error,
498
499 ReceiverPlaceholder,
504}
505
506struct TypePlaceholder(&'static str);
507
508impl fmt::Debug for TypePlaceholder {
509 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
510 f.write_str(self.0)
511 }
512}
513
514impl fmt::Debug for Type {
515 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
516 match self {
517 Type::Nominal {
518 id,
519 params,
520 writable,
521 } => {
522 let mut s = f.debug_struct("Nominal");
523 s.field("id", id).field("params", params);
524 if *writable {
525 s.field("writable", writable);
526 }
527 s.finish()
528 }
529 Type::Function(f_ty) => {
530 let mut s = f.debug_struct("Function");
531 s.field("params", &f_ty.params)
532 .field("bounds", &f_ty.bounds)
533 .field("return_type", &f_ty.return_type)
534 .finish()
535 }
536 Type::Var { id, hint } => {
537 let mut s = f.debug_struct("Var");
538 s.field("id", id);
539 if let Some(h) = hint {
540 s.field("hint", h);
541 }
542 s.finish()
543 }
544 Type::Uninferred => f
545 .debug_struct("Var")
546 .field("id", &TypePlaceholder("uninferred"))
547 .finish(),
548 Type::Ignored => f
549 .debug_struct("Var")
550 .field("id", &TypePlaceholder("ignored"))
551 .finish(),
552 Type::Forall { vars, body } => f
553 .debug_struct("Forall")
554 .field("vars", vars)
555 .field("body", body)
556 .finish(),
557 Type::Parameter(name) => f.debug_tuple("Parameter").field(name).finish(),
558 Type::Never => write!(f, "Never"),
559 Type::Tuple(elements) => f.debug_tuple("Tuple").field(elements).finish(),
560 Type::Array { length, element } => f
561 .debug_struct("Array")
562 .field("length", length)
563 .field("element", element)
564 .finish(),
565 Type::Error => write!(f, "Error"),
566 Type::ImportNamespace(package_id) => {
567 f.debug_tuple("ImportNamespace").field(package_id).finish()
568 }
569 Type::ReceiverPlaceholder => write!(f, "ReceiverPlaceholder"),
570 Type::Simple(kind) => f.debug_tuple("Simple").field(kind).finish(),
571 Type::Compound {
572 kind,
573 args,
574 writable,
575 } => {
576 let mut s = f.debug_struct("Compound");
577 s.field("kind", kind).field("args", args);
578 if *writable {
579 s.field("writable", writable);
580 }
581 s.finish()
582 }
583 }
584 }
585}
586
587impl PartialEq for Type {
588 fn eq(&self, other: &Self) -> bool {
589 match (self, other) {
590 (
591 Type::Nominal {
592 id: id1,
593 params: params1,
594 writable: w1,
595 },
596 Type::Nominal {
597 id: id2,
598 params: params2,
599 writable: w2,
600 },
601 ) => id1 == id2 && params1 == params2 && w1 == w2,
602 (Type::Function(f1), Type::Function(f2)) => f1 == f2,
603 (Type::Var { id: id1, .. }, Type::Var { id: id2, .. }) => id1 == id2,
604 (Type::Uninferred, Type::Uninferred)
605 | (Type::Ignored, Type::Ignored)
606 | (Type::Error, Type::Error) => true,
607 (
608 Type::Forall {
609 vars: vars1,
610 body: body1,
611 },
612 Type::Forall {
613 vars: vars2,
614 body: body2,
615 },
616 ) => vars1 == vars2 && body1 == body2,
617 (Type::Parameter(name1), Type::Parameter(name2)) => name1 == name2,
618 (Type::Never, Type::Never) => true,
619 (Type::Tuple(elems1), Type::Tuple(elems2)) => elems1 == elems2,
620 (
621 Type::Array {
622 length: length1,
623 element: element1,
624 },
625 Type::Array {
626 length: length2,
627 element: element2,
628 },
629 ) => length1 == length2 && element1 == element2,
630 (Type::ImportNamespace(m1), Type::ImportNamespace(m2)) => m1 == m2,
631 (Type::ReceiverPlaceholder, Type::ReceiverPlaceholder) => true,
632 (Type::Simple(k1), Type::Simple(k2)) => k1 == k2,
633 (
634 Type::Compound {
635 kind: k1,
636 args: a1,
637 writable: w1,
638 },
639 Type::Compound {
640 kind: k2,
641 args: a2,
642 writable: w2,
643 },
644 ) => k1 == k2 && a1 == a2 && w1 == w2,
645 _ => false,
646 }
647 }
648}
649
650impl Eq for Type {}
651
652impl Hash for Type {
653 fn hash<H: Hasher>(&self, state: &mut H) {
654 mem::discriminant(self).hash(state);
655 match self {
656 Type::Simple(kind) => kind.hash(state),
657 Type::Compound {
658 kind,
659 args,
660 writable,
661 } => {
662 kind.hash(state);
663 args.hash(state);
664 writable.hash(state);
665 }
666 Type::Nominal {
667 id,
668 params,
669 writable,
670 } => {
671 id.hash(state);
672 params.hash(state);
673 writable.hash(state);
674 }
675 Type::ImportNamespace(package_id) => package_id.hash(state),
676 Type::Function(function) => {
677 function.params.len().hash(state);
678 for parameter in &function.params {
679 parameter.ty.hash(state);
680 }
681 function.bounds.len().hash(state);
682 for bound in &function.bounds {
683 bound.param_name.hash(state);
684 bound.generic.hash(state);
685 bound.ty.hash(state);
686 }
687 function.return_type.hash(state);
688 }
689 Type::Var { id, .. } => id.hash(state),
690 Type::Forall { vars, body } => {
691 vars.hash(state);
692 body.hash(state);
693 }
694 Type::Parameter(name) => name.hash(state),
695 Type::Tuple(elements) => elements.hash(state),
696 Type::Array { length, element } => {
697 length.hash(state);
698 element.hash(state);
699 }
700 Type::Uninferred
701 | Type::Ignored
702 | Type::Never
703 | Type::Error
704 | Type::ReceiverPlaceholder => {}
705 }
706 }
707}
708
709impl Type {
710 fn simple(kind: SimpleKind) -> Type {
711 Self::Simple(kind)
712 }
713
714 pub fn compound(kind: CompoundKind, args: Vec<Type>) -> Type {
715 Self::qualified_compound(kind, args, false)
716 }
717
718 pub fn qualified_compound(kind: CompoundKind, args: Vec<Type>, writable: bool) -> Type {
719 debug_assert!(
720 !writable || kind.accepts_write_qualifier(),
721 "writable flag is restricted to Slice, Map, Ref, and VarArgs"
722 );
723 let args = if kind.carries_write_permission()
724 && !writable
725 && args.iter().any(Type::demotion_changes)
726 {
727 args.iter().map(Type::demoted).collect()
728 } else {
729 args
730 };
731 Self::Compound {
732 kind,
733 args,
734 writable,
735 }
736 }
737
738 pub fn contains_write_permission(&self) -> bool {
740 match self {
741 Type::Compound { args, writable, .. } => {
742 *writable || args.iter().any(Type::contains_write_permission)
743 }
744 Type::Nominal {
745 params, writable, ..
746 } => *writable || params.iter().any(Type::contains_write_permission),
747 Type::Tuple(elements) => elements.iter().any(Type::contains_write_permission),
748 Type::Array { element, .. } => element.contains_write_permission(),
749 _ => false,
750 }
751 }
752
753 pub fn contains_type_parameter(&self) -> bool {
755 matches!(self, Type::Parameter(_))
756 || self
757 .children()
758 .into_iter()
759 .any(Type::contains_type_parameter)
760 }
761
762 pub fn is_writable(&self) -> bool {
763 matches!(
764 self,
765 Type::Compound { writable: true, .. } | Type::Nominal { writable: true, .. }
766 )
767 }
768
769 pub fn make_writable(self) -> Type {
770 match self {
771 Type::Compound { kind, args, .. } if kind.accepts_write_qualifier() => {
772 Type::qualified_compound(kind, args, true)
773 }
774 Type::Nominal { id, params, .. } => Type::Nominal {
775 id,
776 params,
777 writable: true,
778 },
779 other => other,
780 }
781 }
782
783 pub fn writable_clone_result(&self) -> Type {
786 match self {
787 Type::Compound { kind, args, .. }
788 if matches!(kind, CompoundKind::Slice | CompoundKind::EnumeratedSlice) =>
789 {
790 let element = args
791 .first()
792 .map(Type::writable_clone_result)
793 .unwrap_or(Type::Error);
794 Type::qualified_compound(*kind, vec![element], true)
795 }
796 Type::Compound {
797 kind: CompoundKind::Map,
798 args,
799 ..
800 } => {
801 let key = args.first().cloned().unwrap_or(Type::Error);
802 let value = args
803 .get(1)
804 .map(Type::writable_clone_result)
805 .unwrap_or(Type::Error);
806 Type::qualified_compound(CompoundKind::Map, vec![key, value], true)
807 }
808 Type::Tuple(elements) => {
809 Type::Tuple(elements.iter().map(Type::writable_clone_result).collect())
810 }
811 other => other.clone(),
812 }
813 }
814
815 pub fn shallow_demoted(&self) -> Type {
817 match self {
818 Type::Compound {
819 kind,
820 args,
821 writable: _,
822 } => Type::Compound {
823 kind: *kind,
824 args: args.clone(),
825 writable: false,
826 },
827 Type::Nominal {
828 id,
829 params,
830 writable: _,
831 } => Type::Nominal {
832 id: id.clone(),
833 params: params.clone(),
834 writable: false,
835 },
836 other => other.clone(),
837 }
838 }
839
840 pub fn demotion_changes(&self) -> bool {
842 match self {
843 Type::Compound { args, writable, .. } => {
844 *writable || args.iter().any(Type::demotion_changes)
845 }
846 Type::Nominal {
847 params, writable, ..
848 } => *writable || params.iter().any(Type::demotion_changes),
849 Type::Tuple(elements) => elements.iter().any(Type::demotion_changes),
850 Type::Array { element, .. } => element.demotion_changes(),
851 Type::Function(f) => f.return_type.demotion_changes(),
852 Type::Forall { body, .. } => body.demotion_changes(),
853 _ => false,
854 }
855 }
856
857 pub fn demoted(&self) -> Type {
858 match self {
859 Type::Compound {
860 kind,
861 args,
862 writable: _,
863 } => Type::Compound {
864 kind: *kind,
865 args: args.iter().map(Type::demoted).collect(),
866 writable: false,
867 },
868 Type::Nominal {
869 id,
870 params,
871 writable: _,
872 } => Type::Nominal {
873 id: id.clone(),
874 params: params.iter().map(Type::demoted).collect(),
875 writable: false,
876 },
877 Type::Tuple(elements) => Type::Tuple(elements.iter().map(Type::demoted).collect()),
878 Type::Array { length, element } => Type::Array {
879 length: *length,
880 element: Box::new(element.demoted()),
881 },
882 Type::Function(f) => f.rebuild(
885 f.params.clone(),
886 f.bounds.clone(),
887 Box::new(f.return_type.demoted()),
888 ),
889 Type::Forall { vars, body } => Type::Forall {
890 vars: vars.clone(),
891 body: Box::new(body.demoted()),
892 },
893 _ => self.clone(),
894 }
895 }
896
897 pub fn function(
898 params: Vec<FunctionParameter>,
899 bounds: Vec<Bound>,
900 return_type: Box<Type>,
901 ) -> Type {
902 Type::Function(Arc::new(FunctionType {
903 params,
904 bounds,
905 return_type,
906 }))
907 }
908
909 pub fn int() -> Type {
910 Self::simple(SimpleKind::Int)
911 }
912
913 pub fn string() -> Type {
914 Self::simple(SimpleKind::String)
915 }
916
917 pub fn bool() -> Type {
918 Self::simple(SimpleKind::Bool)
919 }
920
921 pub fn unit() -> Type {
922 Self::simple(SimpleKind::Unit)
923 }
924}
925
926impl Type {
927 pub fn uninferred() -> Self {
928 Self::Uninferred
929 }
930
931 pub fn is_uninferred(&self) -> bool {
932 matches!(self, Self::Uninferred)
933 }
934
935 pub fn ignored() -> Self {
936 Self::Ignored
937 }
938
939 pub fn get_type_params(&self) -> Option<&[Type]> {
940 match self {
941 Type::Nominal { params, .. } => Some(params),
942 Type::Compound { args, .. } => Some(args),
943 _ => None,
944 }
945 }
946
947 pub fn children(&self) -> Vec<&Type> {
949 match self {
950 Type::Nominal { params, .. } => params.iter().collect(),
951 Type::Compound { args, .. } => args.iter().collect(),
952 Type::Function(f) => {
953 let mut c: Vec<&Type> = f.params.iter().map(|param| ¶m.ty).collect();
954 c.push(&f.return_type);
955 c
956 }
957 Type::Tuple(elements) => elements.iter().collect(),
958 Type::Array { element, .. } => vec![element],
959 Type::Forall { body, .. } => vec![body],
960 _ => vec![],
961 }
962 }
963}
964
965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
966pub enum NumericFamily {
967 SignedInt,
968 UnsignedInt,
969 Float,
970}
971
972#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
973#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
974pub enum CompoundKind {
975 Ref,
976 Slice,
977 EnumeratedSlice,
978 Map,
979 Channel,
980 Sender,
981 Receiver,
982 VarArgs,
983}
984
985impl CompoundKind {
986 pub fn carries_write_permission(self) -> bool {
987 matches!(
988 self,
989 CompoundKind::Slice
990 | CompoundKind::EnumeratedSlice
991 | CompoundKind::Map
992 | CompoundKind::Ref
993 )
994 }
995
996 pub fn accepts_write_qualifier(self) -> bool {
999 self.carries_write_permission() || matches!(self, CompoundKind::VarArgs)
1000 }
1001
1002 pub fn leaf_name(self) -> &'static str {
1003 match self {
1004 CompoundKind::Ref => "Ref",
1005 CompoundKind::Slice => "Slice",
1006 CompoundKind::EnumeratedSlice => "EnumeratedSlice",
1007 CompoundKind::Map => "Map",
1008 CompoundKind::Channel => "Channel",
1009 CompoundKind::Sender => "Sender",
1010 CompoundKind::Receiver => "Receiver",
1011 CompoundKind::VarArgs => "VarArgs",
1012 }
1013 }
1014
1015 pub fn from_name(name: &str) -> Option<CompoundKind> {
1016 Some(match name {
1017 "Ref" => CompoundKind::Ref,
1018 "Slice" => CompoundKind::Slice,
1019 "EnumeratedSlice" => CompoundKind::EnumeratedSlice,
1020 "Map" => CompoundKind::Map,
1021 "Channel" => CompoundKind::Channel,
1022 "Sender" => CompoundKind::Sender,
1023 "Receiver" => CompoundKind::Receiver,
1024 "VarArgs" => CompoundKind::VarArgs,
1025 _ => return None,
1026 })
1027 }
1028}
1029
1030#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1031#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1032pub enum SimpleKind {
1033 Int,
1034 Int8,
1035 Int16,
1036 Int32,
1037 Int64,
1038 Uint,
1039 Uint8,
1040 Uint16,
1041 Uint32,
1042 Uint64,
1043 Uintptr,
1044 Byte,
1045 Float32,
1046 Float64,
1047 Complex64,
1048 Complex128,
1049 Rune,
1050 Bool,
1051 String,
1052 Unit,
1053}
1054
1055impl SimpleKind {
1056 pub fn leaf_name(self) -> &'static str {
1057 match self {
1058 SimpleKind::Int => "int",
1059 SimpleKind::Int8 => "int8",
1060 SimpleKind::Int16 => "int16",
1061 SimpleKind::Int32 => "int32",
1062 SimpleKind::Int64 => "int64",
1063 SimpleKind::Uint => "uint",
1064 SimpleKind::Uint8 => "uint8",
1065 SimpleKind::Uint16 => "uint16",
1066 SimpleKind::Uint32 => "uint32",
1067 SimpleKind::Uint64 => "uint64",
1068 SimpleKind::Uintptr => "uintptr",
1069 SimpleKind::Byte => "byte",
1070 SimpleKind::Float32 => "float32",
1071 SimpleKind::Float64 => "float64",
1072 SimpleKind::Complex64 => "complex64",
1073 SimpleKind::Complex128 => "complex128",
1074 SimpleKind::Rune => "rune",
1075 SimpleKind::Bool => "bool",
1076 SimpleKind::String => "string",
1077 SimpleKind::Unit => "Unit",
1078 }
1079 }
1080
1081 pub fn from_name(name: &str) -> Option<SimpleKind> {
1082 Some(match name {
1083 "int" => SimpleKind::Int,
1084 "int8" => SimpleKind::Int8,
1085 "int16" => SimpleKind::Int16,
1086 "int32" => SimpleKind::Int32,
1087 "int64" => SimpleKind::Int64,
1088 "uint" => SimpleKind::Uint,
1089 "uint8" => SimpleKind::Uint8,
1090 "uint16" => SimpleKind::Uint16,
1091 "uint32" => SimpleKind::Uint32,
1092 "uint64" => SimpleKind::Uint64,
1093 "uintptr" => SimpleKind::Uintptr,
1094 "byte" => SimpleKind::Byte,
1095 "float32" => SimpleKind::Float32,
1096 "float64" => SimpleKind::Float64,
1097 "complex64" => SimpleKind::Complex64,
1098 "complex128" => SimpleKind::Complex128,
1099 "rune" => SimpleKind::Rune,
1100 "bool" => SimpleKind::Bool,
1101 "string" => SimpleKind::String,
1102 "Unit" => SimpleKind::Unit,
1103 _ => return None,
1104 })
1105 }
1106
1107 pub fn is_arithmetic(self) -> bool {
1108 !matches!(
1109 self,
1110 SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit | SimpleKind::Uintptr
1111 )
1112 }
1113
1114 pub fn is_ordered(self) -> bool {
1115 self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1116 }
1117
1118 pub fn integer_range(self) -> Option<(i128, i128)> {
1119 use SimpleKind::*;
1120 Some(match self {
1121 Int8 => (i8::MIN as i128, i8::MAX as i128),
1122 Int16 => (i16::MIN as i128, i16::MAX as i128),
1123 Int32 | Rune => (i32::MIN as i128, i32::MAX as i128),
1124 Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
1125 Uint8 | Byte => (0, u8::MAX as i128),
1126 Uint16 => (0, u16::MAX as i128),
1127 Uint32 => (0, u32::MAX as i128),
1128 Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
1129 _ => return None,
1130 })
1131 }
1132
1133 pub fn is_unsigned_int(self) -> bool {
1134 matches!(
1135 self,
1136 SimpleKind::Byte
1137 | SimpleKind::Uint
1138 | SimpleKind::Uint8
1139 | SimpleKind::Uint16
1140 | SimpleKind::Uint32
1141 | SimpleKind::Uint64
1142 )
1143 }
1144
1145 pub fn is_signed_int(self) -> bool {
1146 matches!(
1147 self,
1148 SimpleKind::Int
1149 | SimpleKind::Int8
1150 | SimpleKind::Int16
1151 | SimpleKind::Int32
1152 | SimpleKind::Int64
1153 | SimpleKind::Rune
1154 )
1155 }
1156
1157 pub fn is_float(self) -> bool {
1158 matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
1159 }
1160
1161 fn is_complex(self) -> bool {
1162 matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1163 }
1164
1165 fn numeric_family(self) -> Option<NumericFamily> {
1166 if self.is_signed_int() {
1167 Some(NumericFamily::SignedInt)
1168 } else if self.is_unsigned_int() {
1169 Some(NumericFamily::UnsignedInt)
1170 } else if self.is_float() {
1171 Some(NumericFamily::Float)
1172 } else {
1173 None
1174 }
1175 }
1176}
1177
1178impl Type {
1179 pub fn get_function_ret(&self) -> Option<&Type> {
1180 match self {
1181 Type::Function(f) => Some(&f.return_type),
1182 _ => None,
1183 }
1184 }
1185
1186 pub fn is_stringer_signature(&self) -> bool {
1187 let func = match self {
1188 Type::Forall { body, .. } => body.as_ref(),
1189 other => other,
1190 };
1191 matches!(
1192 func,
1193 Type::Function(f)
1194 if f.params.len() == 1
1195 && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::String))
1196 )
1197 }
1198
1199 pub fn is_equals_signature(&self) -> bool {
1200 let func = match self {
1201 Type::Forall { body, .. } => body.as_ref(),
1202 other => other,
1203 };
1204 matches!(
1205 func,
1206 Type::Function(f)
1207 if f.params.len() == 2
1208 && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::Bool))
1209 && f.params[0].ty == f.params[1].ty
1210 && !f.params[0].ty.is_ref()
1211 )
1212 }
1213
1214 pub fn is_equals_bound_signature(&self, param_name: &str) -> bool {
1215 let func = match self {
1216 Type::Forall { body, .. } => body.as_ref(),
1217 other => other,
1218 };
1219 matches!(
1220 func,
1221 Type::Function(f)
1222 if f.params.len() == 1
1223 && f.return_type.is_boolean()
1224 && matches!(&f.params[0].ty, Type::Parameter(name) if name.as_str() == param_name)
1225 )
1226 }
1227
1228 pub fn equals_receiver_vars(&self, owner_id: &str, arity: usize) -> Option<Vec<EcoString>> {
1229 if !self.is_equals_signature() {
1230 return None;
1231 }
1232 let (quantified, func): (&[EcoString], &Type) = match self {
1233 Type::Forall { vars, body } => (vars, body.as_ref()),
1234 other => (&[], other),
1235 };
1236 if quantified.len() != arity {
1237 return None;
1238 }
1239 let Type::Function(f) = func else {
1240 return None;
1241 };
1242 let Type::Nominal { id, params, .. } = &f.params[0].ty else {
1243 return None;
1244 };
1245 if id.as_str() != owner_id || params.len() != arity {
1246 return None;
1247 }
1248 let mut vars = Vec::with_capacity(arity);
1249 for param in params {
1250 let Type::Parameter(name) = param else {
1251 return None;
1252 };
1253 if vars.contains(name) {
1254 return None;
1255 }
1256 vars.push(name.clone());
1257 }
1258 if !quantified.iter().all(|v| vars.contains(v)) {
1259 return None;
1260 }
1261 Some(vars)
1262 }
1263
1264 pub fn has_name(&self, name: &str) -> bool {
1265 match self {
1266 Type::Nominal { id, .. } => id.last_segment() == name,
1267 Type::Simple(kind) => kind.leaf_name() == name,
1268 Type::Compound { kind, .. } => kind.leaf_name() == name,
1269 _ => false,
1270 }
1271 }
1272
1273 pub fn get_qualified_id(&self) -> Option<&str> {
1274 match self {
1275 Type::Nominal { id, .. } => Some(id.as_str()),
1276 _ => None,
1277 }
1278 }
1279
1280 pub fn is_result(&self) -> bool {
1281 self.has_qualified_id("prelude.Result")
1282 }
1283
1284 pub fn is_option(&self) -> bool {
1285 self.has_qualified_id("prelude.Option")
1286 }
1287
1288 pub fn is_partial(&self) -> bool {
1289 self.has_qualified_id("prelude.Partial")
1290 }
1291
1292 fn has_qualified_id(&self, qualified_id: &str) -> bool {
1293 matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
1294 }
1295
1296 pub fn is_unit(&self) -> bool {
1297 self.is_simple(SimpleKind::Unit)
1298 }
1299
1300 pub fn tuple_arity(&self) -> Option<usize> {
1301 match self {
1302 Type::Tuple(elements) => Some(elements.len()),
1303 _ => None,
1304 }
1305 }
1306
1307 pub fn is_tuple(&self) -> bool {
1308 matches!(self, Type::Tuple(_))
1309 }
1310
1311 pub fn array_len(&self) -> Option<u64> {
1312 match self {
1313 Type::Array { length, .. } => Some(*length),
1314 _ => None,
1315 }
1316 }
1317
1318 pub fn as_import_namespace(&self) -> Option<&str> {
1319 match self {
1320 Type::ImportNamespace(package_id) => Some(package_id),
1321 _ => None,
1322 }
1323 }
1324
1325 pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
1326 match self {
1327 Type::Compound { kind, args, .. } => Some((*kind, args.as_slice())),
1328 _ => None,
1329 }
1330 }
1331
1332 pub fn is_native(&self, kind: CompoundKind) -> bool {
1333 self.as_compound().is_some_and(|(k, _)| k == kind)
1334 }
1335
1336 pub fn is_ref(&self) -> bool {
1337 self.is_native(CompoundKind::Ref)
1338 }
1339
1340 pub fn is_slice(&self) -> bool {
1341 self.is_native(CompoundKind::Slice)
1342 }
1343
1344 pub fn is_map(&self) -> bool {
1345 self.is_native(CompoundKind::Map)
1346 }
1347
1348 pub fn is_channel(&self) -> bool {
1349 self.is_native(CompoundKind::Channel)
1350 }
1351
1352 pub fn is_receiver_placeholder(&self) -> bool {
1353 matches!(self, Type::ReceiverPlaceholder)
1354 }
1355
1356 pub fn is_unknown(&self) -> bool {
1357 self.has_name("Unknown")
1358 }
1359
1360 pub fn is_receiver(&self) -> bool {
1361 self.is_native(CompoundKind::Receiver)
1362 }
1363
1364 pub fn is_ignored(&self) -> bool {
1365 matches!(self, Type::Ignored)
1366 }
1367
1368 pub fn is_placeholder(&self) -> bool {
1369 matches!(self, Type::Uninferred | Type::Ignored)
1370 }
1371
1372 pub fn is_variadic(&self) -> Option<Type> {
1373 let last = self.get_function_params()?.last()?;
1374 match last.ty.as_compound()? {
1375 (CompoundKind::VarArgs, _) => last.ty.inner(),
1376 _ => None,
1377 }
1378 }
1379
1380 pub fn is_string(&self) -> bool {
1381 self.is_simple(SimpleKind::String)
1382 }
1383
1384 fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
1385 match self.as_compound() {
1386 Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
1387 _ => false,
1388 }
1389 }
1390
1391 pub fn is_byte_slice(&self) -> bool {
1392 self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
1393 }
1394
1395 fn is_rune_slice(&self) -> bool {
1396 self.is_slice_of_simple(SimpleKind::Rune)
1397 }
1398
1399 fn is_byte_or_rune_slice(&self) -> bool {
1400 self.is_byte_slice() || self.is_rune_slice()
1401 }
1402
1403 pub fn as_simple(&self) -> Option<SimpleKind> {
1404 match self {
1405 Type::Simple(kind) => Some(*kind),
1406 _ => None,
1407 }
1408 }
1409
1410 pub fn is_simple(&self, kind: SimpleKind) -> bool {
1411 self.as_simple() == Some(kind)
1412 }
1413
1414 pub fn is_boolean(&self) -> bool {
1415 self.is_simple(SimpleKind::Bool)
1416 }
1417
1418 pub fn is_rune(&self) -> bool {
1419 self.is_simple(SimpleKind::Rune)
1420 }
1421
1422 pub fn is_float(&self) -> bool {
1423 self.as_simple().is_some_and(SimpleKind::is_float)
1424 }
1425
1426 pub fn is_variable(&self) -> bool {
1427 matches!(self, Type::Var { .. })
1428 }
1429
1430 pub fn is_structural_alias_body(&self) -> bool {
1433 matches!(
1434 self,
1435 Type::Simple(_) | Type::Compound { .. } | Type::Array { .. } | Type::Tuple(_)
1436 )
1437 }
1438
1439 pub fn is_numeric(&self) -> bool {
1440 self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1441 }
1442
1443 pub fn is_complex(&self) -> bool {
1444 self.as_simple().is_some_and(SimpleKind::is_complex)
1445 }
1446
1447 pub fn is_unsigned_int(&self) -> bool {
1448 self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1449 }
1450
1451 pub fn is_never(&self) -> bool {
1452 matches!(self, Type::Never)
1453 }
1454
1455 pub fn is_error(&self) -> bool {
1456 matches!(self, Type::Error)
1457 }
1458
1459 pub fn contains_error(&self) -> bool {
1460 self.is_error() || self.children().into_iter().any(Type::contains_error)
1461 }
1462
1463 pub fn has_unbound_variables(&self) -> bool {
1464 match self {
1465 Type::Var { hint, .. } => hint.is_some(),
1466 _ => self.children().into_iter().any(Type::has_unbound_variables),
1467 }
1468 }
1469
1470 pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
1471 if let Type::Var { id, hint: Some(_) } = self {
1472 out.push(*id);
1473 }
1474 for child in self.children() {
1475 child.collect_unbound_variables(out);
1476 }
1477 }
1478
1479 pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1480 if names.is_empty() {
1481 return;
1482 }
1483
1484 match self {
1485 Type::Nominal { id, params, .. } => {
1486 names.remove(id.last_segment());
1487 for param in params {
1488 param.remove_found_type_names(names);
1489 }
1490 }
1491 Type::Function(f) => {
1492 for param in &f.params {
1493 param.ty.remove_found_type_names(names);
1494 }
1495 f.return_type.remove_found_type_names(names);
1496 for bound in &f.bounds {
1497 bound.generic.remove_found_type_names(names);
1498 bound.ty.remove_found_type_names(names);
1499 }
1500 }
1501 Type::Forall { body, .. } => {
1502 body.remove_found_type_names(names);
1503 }
1504 Type::Var { .. } => {}
1505 Type::Parameter(name) => {
1506 names.remove(name);
1507 }
1508 Type::Tuple(elements) => {
1509 for element in elements {
1510 element.remove_found_type_names(names);
1511 }
1512 }
1513 Type::Compound { kind, args, .. } => {
1514 names.remove(kind.leaf_name());
1515 for arg in args {
1516 arg.remove_found_type_names(names);
1517 }
1518 }
1519 Type::Array { element, .. } => {
1520 names.remove("Array");
1521 element.remove_found_type_names(names);
1522 }
1523 Type::Simple(kind) => {
1524 names.remove(kind.leaf_name());
1525 }
1526 Type::Never
1527 | Type::Uninferred
1528 | Type::Ignored
1529 | Type::Error
1530 | Type::ImportNamespace(_)
1531 | Type::ReceiverPlaceholder => {}
1532 }
1533 }
1534}
1535
1536impl Type {
1537 pub fn get_name(&self) -> Option<&str> {
1538 match self {
1539 Type::Simple(kind) => Some(kind.leaf_name()),
1540 Type::Compound { kind, args, .. } => match kind {
1541 CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1542 _ => Some(kind.leaf_name()),
1543 },
1544 Type::Nominal { id, .. } => Some(id.last_segment()),
1545 Type::ImportNamespace(package_id) => {
1546 let path = package_id.strip_prefix("go:").unwrap_or(package_id);
1547 path.rsplit('/').next()
1548 }
1549 Type::Array { .. } => Some("Array"),
1550 _ => None,
1551 }
1552 }
1553
1554 pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1555 self.get_name().is_some_and(|n| n == name)
1556 && self
1557 .get_type_params()
1558 .and_then(|p| p.first())
1559 .is_some_and(|first| *first == *inner)
1560 }
1561
1562 pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
1563 match self {
1564 Type::Function(f) => Some(&f.params),
1565 _ => None,
1566 }
1567 }
1568
1569 pub fn param_count(&self) -> usize {
1570 match self {
1571 Type::Function(f) => f.params.len(),
1572 _ => 0,
1573 }
1574 }
1575
1576 pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1577 match self {
1578 Type::Function(f) => {
1579 if f.params.is_empty() {
1580 return self.clone();
1581 }
1582 let mut new_params = f.params.clone();
1583 new_params[0] = new_params[0].with_type(new_first.clone());
1584 f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1585 }
1586 Type::Forall { vars, body } => Type::Forall {
1587 vars: vars.clone(),
1588 body: Box::new(body.with_replaced_first_param(new_first)),
1589 },
1590 _ => self.clone(),
1591 }
1592 }
1593
1594 pub fn get_bounds(&self) -> &[Bound] {
1595 match self {
1596 Type::Function(f) => &f.bounds,
1597 Type::Forall { body, .. } => body.get_bounds(),
1598 _ => &[],
1599 }
1600 }
1601
1602 pub fn get_qualified_name(&self) -> Option<Symbol> {
1603 let mut current = self;
1604 while current.is_ref() {
1605 current = current.get_type_params()?.first()?;
1606 }
1607 match current {
1608 Type::Nominal { id, .. } => Some(id.clone()),
1609 Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1610 Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1611 _ => None,
1612 }
1613 }
1614
1615 pub fn inner(&self) -> Option<Type> {
1616 self.get_type_params()
1617 .and_then(|args| args.first().cloned())
1618 }
1619
1620 pub fn ok_type(&self) -> Type {
1621 debug_assert!(
1622 self.is_result() || self.is_option() || self.is_partial(),
1623 "ok_type called on non-Result/Option/Partial type"
1624 );
1625 self.inner()
1626 .expect("Result/Option/Partial should have inner type")
1627 }
1628
1629 pub fn err_type(&self) -> Type {
1630 debug_assert!(
1631 self.is_result() || self.is_partial(),
1632 "err_type called on non-Result/Partial type"
1633 );
1634 self.get_type_params()
1635 .and_then(|args| args.get(1).cloned())
1636 .expect("Result/Partial should have error type")
1637 }
1638}
1639
1640pub fn peel_alias<'d, F>(ty: &Type, lookup: F) -> Type
1643where
1644 F: Fn(&str) -> Option<&'d Definition>,
1645{
1646 let mut current = ty.unwrap_forall().clone();
1647 let mut seen: HashSet<Symbol> = HashSet::default();
1648 while let Type::Nominal {
1649 id,
1650 params,
1651 writable,
1652 } = ¤t
1653 {
1654 let writable = *writable;
1655 if !seen.insert(id.clone()) {
1656 break;
1657 }
1658 let Some(target) = lookup(id.as_str())
1659 .and_then(|definition| definition.instantiate_alias_target(params, writable))
1660 else {
1661 break;
1662 };
1663 current = target.unwrap_forall().clone();
1664 }
1665 current
1666}
1667
1668pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1671where
1672 F: Fn(&str) -> Option<&'d Definition>,
1673{
1674 let Type::Nominal {
1675 id,
1676 params,
1677 writable,
1678 } = ty.unwrap_forall()
1679 else {
1680 return None;
1681 };
1682 lookup(id.as_str())?.instantiate_underlying(params, *writable, &lookup)
1683}
1684
1685pub fn peel_underlying<'d, F>(ty: &Type, lookup: F) -> Type
1689where
1690 F: Fn(&str) -> Option<&'d Definition>,
1691{
1692 let mut current = ty.unwrap_forall().clone();
1693 let mut seen: HashSet<Symbol> = HashSet::default();
1694 while let Type::Nominal {
1695 id,
1696 params,
1697 writable,
1698 } = ¤t
1699 {
1700 let writable = *writable;
1701 if !seen.insert(id.clone()) {
1702 break;
1703 }
1704 let Some(underlying) = lookup(id.as_str())
1705 .and_then(|definition| definition.instantiate_underlying(params, writable, &lookup))
1706 else {
1707 break;
1708 };
1709 current = underlying.unwrap_forall().clone();
1710 }
1711 current
1712}
1713
1714pub fn resolves_to_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1715where
1716 F: Fn(&str) -> Option<&'d Definition>,
1717{
1718 peel_alias(ty, lookup).is_unknown()
1719}
1720
1721pub fn contains_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1722where
1723 F: Fn(&str) -> Option<&'d Definition>,
1724{
1725 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1726 where
1727 F: Fn(&str) -> Option<&'d Definition>,
1728 {
1729 let peeled = peel_alias(ty, lookup);
1730 peeled.is_unknown()
1731 || peeled
1732 .children()
1733 .into_iter()
1734 .any(|child| contains(child, lookup))
1735 }
1736
1737 contains(ty, &lookup)
1738}
1739
1740pub fn contains_write_permission<'d, F>(ty: &Type, lookup: F) -> bool
1741where
1742 F: Fn(&str) -> Option<&'d Definition>,
1743{
1744 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1745 where
1746 F: Fn(&str) -> Option<&'d Definition>,
1747 {
1748 let peeled = peel_alias(ty, lookup);
1749 peeled.is_writable()
1750 || peeled
1751 .children()
1752 .into_iter()
1753 .any(|child| contains(child, lookup))
1754 }
1755
1756 contains(ty, &lookup)
1757}
1758
1759pub fn parameter_grants_write<'d, F>(ty: &Type, lookup: F) -> bool
1762where
1763 F: Fn(&str) -> Option<&'d Definition>,
1764{
1765 fn grants<'d, F>(ty: &Type, lookup: &F) -> bool
1766 where
1767 F: Fn(&str) -> Option<&'d Definition>,
1768 {
1769 match peel_alias(ty, lookup) {
1770 Type::Compound { args, writable, .. } => {
1771 writable || args.iter().any(|arg| grants(arg, lookup))
1772 }
1773 Type::Nominal {
1774 params, writable, ..
1775 } => writable || params.iter().any(|param| grants(param, lookup)),
1776 Type::Tuple(elements) => elements.iter().any(|element| grants(element, lookup)),
1777 Type::Array { element, .. } => grants(&element, lookup),
1778 _ => false,
1779 }
1780 }
1781
1782 grants(ty, &lookup)
1783}
1784
1785pub fn demoted<'d, F>(ty: &Type, lookup: &F) -> Type
1788where
1789 F: Fn(&str) -> Option<&'d Definition>,
1790{
1791 match ty {
1792 Type::Nominal {
1793 id,
1794 params,
1795 writable: _,
1796 } => {
1797 let cleared = Type::Nominal {
1798 id: id.clone(),
1799 params: params.iter().map(|param| demoted(param, lookup)).collect(),
1800 writable: false,
1801 };
1802 let peeled = peel_alias(&cleared, lookup);
1803 if peeled != cleared && demotion_changes(&peeled, lookup) {
1804 demoted(&peeled, lookup)
1805 } else {
1806 cleared
1807 }
1808 }
1809 Type::Compound {
1810 kind,
1811 args,
1812 writable: _,
1813 } => Type::Compound {
1814 kind: *kind,
1815 args: args.iter().map(|arg| demoted(arg, lookup)).collect(),
1816 writable: false,
1817 },
1818 Type::Tuple(elements) => Type::Tuple(
1819 elements
1820 .iter()
1821 .map(|element| demoted(element, lookup))
1822 .collect(),
1823 ),
1824 Type::Array { length, element } => Type::Array {
1825 length: *length,
1826 element: Box::new(demoted(element, lookup)),
1827 },
1828 Type::Function(f) => f.rebuild(
1829 f.params.clone(),
1830 f.bounds.clone(),
1831 Box::new(demoted(&f.return_type, lookup)),
1832 ),
1833 Type::Forall { vars, body } => Type::Forall {
1834 vars: vars.clone(),
1835 body: Box::new(demoted(body, lookup)),
1836 },
1837 _ => ty.clone(),
1838 }
1839}
1840
1841pub fn demotion_changes<'d, F>(ty: &Type, lookup: &F) -> bool
1843where
1844 F: Fn(&str) -> Option<&'d Definition>,
1845{
1846 match ty {
1847 Type::Nominal {
1848 params, writable, ..
1849 } => {
1850 if *writable {
1851 return true;
1852 }
1853 let peeled = peel_alias(ty, lookup);
1854 if peeled != *ty {
1855 return demotion_changes(&peeled, lookup);
1856 }
1857 params.iter().any(|param| demotion_changes(param, lookup))
1858 }
1859 Type::Compound { args, writable, .. } => {
1860 *writable || args.iter().any(|arg| demotion_changes(arg, lookup))
1861 }
1862 Type::Tuple(elements) => elements
1863 .iter()
1864 .any(|element| demotion_changes(element, lookup)),
1865 Type::Array { element, .. } => demotion_changes(element, lookup),
1866 Type::Function(f) => demotion_changes(&f.return_type, lookup),
1867 Type::Forall { body, .. } => demotion_changes(body, lookup),
1868 _ => false,
1869 }
1870}
1871
1872pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
1873where
1874 F: Fn(&str) -> Option<&'d Definition>,
1875{
1876 peel_underlying(ty, lookup).as_simple()
1877}
1878
1879pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1880where
1881 F: Fn(&str) -> Option<&'d Definition>,
1882{
1883 let underlying = peel_underlying(ty, lookup);
1884 underlying.is_numeric().then_some(underlying)
1885}
1886
1887pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1888where
1889 F: Fn(&str) -> Option<&'d Definition>,
1890{
1891 underlying_numeric_type(ty, &lookup).or_else(|| {
1892 (matches!(ty.unwrap_forall(), Type::Nominal { .. })
1893 && underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
1894 .then_some(Type::Simple(SimpleKind::Uintptr))
1895 })
1896}
1897
1898pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
1899where
1900 F: Fn(&str) -> Option<&'d Definition>,
1901{
1902 match (
1903 underlying_numeric_type(left, &lookup),
1904 underlying_numeric_type(right, &lookup),
1905 ) {
1906 (Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
1907 _ => false,
1908 }
1909}
1910
1911pub fn is_aliased_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
1912where
1913 F: Fn(&str) -> Option<&'d Definition>,
1914{
1915 matches!(ty.unwrap_forall(), Type::Nominal { .. })
1916 && underlying_type(ty, &lookup).is_some()
1917 && !ty.is_numeric()
1918 && underlying_numeric_type(ty, lookup).is_some()
1919}
1920
1921pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
1922where
1923 F: Fn(&str) -> Option<&'d Definition>,
1924{
1925 peel_underlying(ty, lookup).is_byte_or_rune_slice()
1926}
1927
1928pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
1929where
1930 F: Fn(&str) -> Option<&'d Definition>,
1931{
1932 matches!(
1933 underlying_simple_kind(ty, lookup),
1934 Some(kind) if kind.is_ordered() || kind == SimpleKind::String
1935 ) || ty.is_boolean()
1936}
1937
1938pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
1941where
1942 F: Fn(&str) -> Option<&'d Definition>,
1943{
1944 let Some(kind) = underlying_simple_kind(ty, lookup) else {
1945 return matches!(ty.unwrap_forall(), Type::Parameter(_));
1946 };
1947 matches!(
1948 kind,
1949 SimpleKind::Int
1950 | SimpleKind::Int8
1951 | SimpleKind::Int16
1952 | SimpleKind::Int32
1953 | SimpleKind::Int64
1954 | SimpleKind::Uint
1955 | SimpleKind::Uint8
1956 | SimpleKind::Uint16
1957 | SimpleKind::Uint32
1958 | SimpleKind::Uint64
1959 | SimpleKind::Uintptr
1960 | SimpleKind::Byte
1961 | SimpleKind::Rune
1962 | SimpleKind::Float32
1963 | SimpleKind::Float64
1964 | SimpleKind::String
1965 )
1966}
1967
1968pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
1971 let core = peel_underlying(ty, &lookup);
1972 if let Type::Nominal { id, .. } = &core {
1973 return matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
1974 }
1975 core.is_ref()
1976 || matches!(core, Type::Function(_))
1977 || core.is_map()
1978 || core.is_channel()
1979 || core.is_native(CompoundKind::Sender)
1980 || core.is_receiver()
1981}
1982
1983pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
1985where
1986 F: Fn(&str) -> Option<String>,
1987{
1988 let mut current = id.to_string();
1989 let mut seen: Vec<String> = Vec::new();
1990 loop {
1991 if seen.iter().any(|s| s == ¤t) {
1992 return current;
1993 }
1994 let Some(next) = next_alias(¤t) else {
1995 return current;
1996 };
1997 seen.push(current);
1998 current = next;
1999 }
2000}
2001
2002impl Type {
2003 pub fn unwrap_forall(&self) -> &Type {
2004 match self {
2005 Type::Forall { body, .. } => body.as_ref(),
2006 other => other,
2007 }
2008 }
2009
2010 pub fn as_function_type(&self) -> Option<&FunctionType> {
2011 match self.unwrap_forall() {
2012 Type::Function(f) => Some(f),
2013 _ => None,
2014 }
2015 }
2016
2017 pub fn strip_refs(&self) -> Type {
2018 if self.is_ref() {
2019 return self.inner().expect("ref type must have inner").strip_refs();
2020 }
2021
2022 self.clone()
2023 }
2024
2025 pub fn with_receiver_placeholder(self) -> Type {
2026 match self {
2027 Type::Function(f) => {
2028 let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
2029 let mut new_params = vec![FunctionParameter::new(Type::ReceiverPlaceholder)];
2030 new_params.extend(f.params);
2031
2032 Type::function(new_params, f.bounds, f.return_type)
2033 }
2034 _ => unreachable!(
2035 "with_receiver_placeholder called on non-function type: {:?}",
2036 self
2037 ),
2038 }
2039 }
2040
2041 pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
2042 let mut vars = HashMap::default();
2043 let types = types
2044 .iter()
2045 .map(|v| Self::remove_vars_impl(v, &mut vars))
2046 .collect();
2047
2048 (types, vars.into_values().collect())
2049 }
2050
2051 fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
2052 match ty {
2053 Type::Nominal {
2054 id: name,
2055 params: args,
2056 writable,
2057 } => Type::Nominal {
2058 id: name.clone(),
2059 params: args
2060 .iter()
2061 .map(|a| Self::remove_vars_impl(a, vars))
2062 .collect(),
2063 writable: *writable,
2064 },
2065
2066 Type::Function(f) => Type::function(
2067 f.params
2068 .iter()
2069 .map(|param| param.with_type(Self::remove_vars_impl(¶m.ty, vars)))
2070 .collect(),
2071 f.bounds
2072 .iter()
2073 .map(|b| Bound {
2074 param_name: b.param_name.clone(),
2075 generic: Self::remove_vars_impl(&b.generic, vars),
2076 ty: Self::remove_vars_impl(&b.ty, vars),
2077 })
2078 .collect(),
2079 Self::remove_vars_impl(&f.return_type, vars).into(),
2080 ),
2081
2082 Type::Var { id, hint } => match vars.get(&id.index()) {
2083 Some(g) => Type::Parameter(g.clone()),
2084 None => {
2085 let name: EcoString = hint
2086 .clone()
2087 .unwrap_or_else(|| alpha_index(vars.len()).into());
2088
2089 vars.insert(id.index(), name.clone());
2090 Type::Parameter(name)
2091 }
2092 },
2093
2094 Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
2095 Type::Tuple(elements) => Type::Tuple(
2096 elements
2097 .iter()
2098 .map(|e| Self::remove_vars_impl(e, vars))
2099 .collect(),
2100 ),
2101 Type::Compound {
2102 kind,
2103 args,
2104 writable,
2105 } => Type::Compound {
2106 kind: *kind,
2107 writable: *writable,
2108 args: args
2109 .iter()
2110 .map(|a| Self::remove_vars_impl(a, vars))
2111 .collect(),
2112 },
2113 Type::Array { length, element } => Type::Array {
2114 length: *length,
2115 element: Box::new(Self::remove_vars_impl(element, vars)),
2116 },
2117 Type::Simple(_) | Type::Parameter(_) => ty.clone(),
2118 Type::Never
2119 | Type::Uninferred
2120 | Type::Ignored
2121 | Type::Error
2122 | Type::ImportNamespace(_)
2123 | Type::ReceiverPlaceholder => ty.clone(),
2124 }
2125 }
2126
2127 pub fn contains_type(&self, target: &Type) -> bool {
2128 self == target
2129 || self
2130 .children()
2131 .into_iter()
2132 .any(|child| child.contains_type(target))
2133 }
2134}
2135
2136impl Type {
2137 pub fn numeric_family(&self) -> Option<NumericFamily> {
2138 self.as_simple()?.numeric_family()
2139 }
2140}
2141
2142fn alpha_index(idx: usize) -> String {
2144 let mut s = String::new();
2145 let mut n = idx + 1;
2146 while n > 0 {
2147 n -= 1;
2148 s.insert(0, (b'A' + (n % 26) as u8) as char);
2149 n /= 26;
2150 }
2151 s
2152}
2153
2154#[cfg(test)]
2155mod tests {
2156 use super::*;
2157 use std::collections::hash_map::DefaultHasher;
2158 use std::hash::{Hash, Hasher};
2159 use std::iter;
2160
2161 fn hash(ty: &Type) -> u64 {
2162 let mut state = DefaultHasher::new();
2163 ty.hash(&mut state);
2164 state.finish()
2165 }
2166
2167 #[test]
2168 fn error_type_equals_itself() {
2169 let nominal_over_error = || Type::Nominal {
2170 id: Symbol::from_parts("prelude", "Option"),
2171 params: vec![Type::Error],
2172 writable: false,
2173 };
2174
2175 assert_eq!(Type::Error, Type::Error);
2176 assert_eq!(nominal_over_error(), nominal_over_error());
2177 }
2178
2179 #[test]
2180 fn function_equality_ignores_param_names() {
2181 let named = Type::function(
2182 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2183 vec![],
2184 Box::new(Type::bool()),
2185 );
2186 let differently_named = Type::function(
2187 vec![FunctionParameter::named(Type::int(), Some("height".into()))],
2188 vec![],
2189 Box::new(Type::bool()),
2190 );
2191 let unnamed = Type::function(
2192 vec![FunctionParameter::new(Type::int())],
2193 vec![],
2194 Box::new(Type::bool()),
2195 );
2196
2197 assert_eq!(named, differently_named);
2198 assert_eq!(named, unnamed);
2199 }
2200
2201 #[test]
2202 fn equal_function_types_have_equal_hashes() {
2203 let named = Type::function(
2204 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2205 vec![],
2206 Box::new(Type::bool()),
2207 );
2208 let unnamed = Type::function(
2209 vec![FunctionParameter::new(Type::int())],
2210 vec![],
2211 Box::new(Type::bool()),
2212 );
2213
2214 assert_eq!(hash(&named), hash(&unnamed));
2215 }
2216
2217 #[test]
2218 fn equal_type_variables_have_equal_hashes() {
2219 let named = Type::Var {
2220 id: TypeVarId::new(1),
2221 hint: Some("value".into()),
2222 };
2223 let unnamed = Type::Var {
2224 id: TypeVarId::new(1),
2225 hint: None,
2226 };
2227
2228 assert_eq!(hash(&named), hash(&unnamed));
2229 }
2230
2231 #[test]
2232 fn signature_queries_ignore_function_bound_types() {
2233 let variable = Type::Var {
2234 id: TypeVarId::new(1),
2235 hint: Some("value".into()),
2236 };
2237 let signature = Type::function(
2238 vec![FunctionParameter::new(Type::int())],
2239 vec![Bound {
2240 param_name: "T".into(),
2241 generic: variable.clone(),
2242 ty: Type::Tuple(vec![variable.clone(), Type::Error]),
2243 }],
2244 Box::new(Type::bool()),
2245 );
2246 let mut variables = Vec::new();
2247 signature.collect_unbound_variables(&mut variables);
2248
2249 assert!(!signature.contains_error());
2250 assert!(!signature.has_unbound_variables());
2251 assert!(!signature.contains_type(&variable));
2252 assert!(!signature.contains_type(&Type::Error));
2253 assert!(variables.is_empty());
2254 }
2255
2256 #[test]
2257 fn unbound_variables_preserve_occurrence_order_through_quantified_signatures() {
2258 let first = Type::Var {
2259 id: TypeVarId::new(1),
2260 hint: Some("first".into()),
2261 };
2262 let second = Type::Var {
2263 id: TypeVarId::new(2),
2264 hint: Some("second".into()),
2265 };
2266 let signature = Type::Forall {
2267 vars: vec!["T".into()],
2268 body: Box::new(Type::function(
2269 vec![
2270 FunctionParameter::new(Type::Tuple(vec![first.clone(), second.clone()])),
2271 FunctionParameter::new(unhinted_var(3)),
2272 ],
2273 vec![],
2274 Box::new(first),
2275 )),
2276 };
2277 let mut variables = Vec::new();
2278 signature.collect_unbound_variables(&mut variables);
2279
2280 assert_eq!(
2281 variables,
2282 vec![TypeVarId::new(1), TypeVarId::new(2), TypeVarId::new(1)],
2283 );
2284 assert!(signature.has_unbound_variables());
2285 assert!(signature.contains_type(&second));
2286 assert!(signature.contains_type(&signature));
2287 }
2288
2289 #[test]
2290 fn signature_queries_find_errors_in_nested_return_types() {
2291 let signature = Type::function(
2292 vec![FunctionParameter::new(Type::int())],
2293 vec![],
2294 Box::new(Type::Array {
2295 length: 1,
2296 element: Box::new(Type::Error),
2297 }),
2298 );
2299
2300 assert!(signature.contains_error());
2301 assert!(signature.contains_type(&Type::Error));
2302 }
2303
2304 #[test]
2305 fn alpha_index_single() {
2306 assert_eq!(alpha_index(0), "A");
2307 assert_eq!(alpha_index(5), "F");
2308 assert_eq!(alpha_index(25), "Z");
2309 }
2310
2311 #[test]
2312 fn alpha_index_double() {
2313 assert_eq!(alpha_index(26), "AA");
2314 assert_eq!(alpha_index(27), "AB");
2315 assert_eq!(alpha_index(51), "AZ");
2316 assert_eq!(alpha_index(52), "BA");
2317 assert_eq!(alpha_index(701), "ZZ");
2318 }
2319
2320 #[test]
2321 fn alpha_index_triple() {
2322 assert_eq!(alpha_index(702), "AAA");
2323 }
2324
2325 fn unhinted_var(id: u32) -> Type {
2326 Type::Var {
2327 id: TypeVarId::new(id),
2328 hint: None,
2329 }
2330 }
2331
2332 #[test]
2333 fn remove_vars_handles_more_than_six_unhinted_vars() {
2334 let func = Type::function(
2335 (0..6)
2336 .map(unhinted_var)
2337 .map(FunctionParameter::new)
2338 .collect(),
2339 vec![],
2340 Box::new(unhinted_var(6)),
2341 );
2342
2343 let (resolved, generics) = Type::remove_vars(&[&func]);
2344
2345 assert_eq!(generics.len(), 7);
2346 let Type::Function(f) = &resolved[0] else {
2347 panic!("expected function type");
2348 };
2349 let names: Vec<_> = f
2350 .params
2351 .iter()
2352 .map(|param| ¶m.ty)
2353 .chain(iter::once(f.return_type.as_ref()))
2354 .map(|p| match p {
2355 Type::Parameter(name) => name.to_string(),
2356 other => panic!("expected parameter, got {:?}", other),
2357 })
2358 .collect();
2359 assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
2360 }
2361
2362 #[test]
2363 fn remove_vars_handles_dozens_of_unhinted_vars() {
2364 let params: Vec<Type> = (0..30).map(unhinted_var).collect();
2365 let func = Type::function(
2366 params.iter().cloned().map(FunctionParameter::new).collect(),
2367 vec![],
2368 Box::new(Type::Simple(SimpleKind::Unit)),
2369 );
2370 let (_, generics) = Type::remove_vars(&[&func]);
2371 assert_eq!(generics.len(), 30);
2372 }
2373}