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