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}
977
978#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
979#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
980pub enum CompoundKind {
981 Ref,
982 Slice,
983 EnumeratedSlice,
984 Map,
985 Channel,
986 Sender,
987 Receiver,
988 VarArgs,
989}
990
991impl CompoundKind {
992 pub fn carries_write_permission(self) -> bool {
993 matches!(
994 self,
995 CompoundKind::Slice
996 | CompoundKind::EnumeratedSlice
997 | CompoundKind::Map
998 | CompoundKind::Ref
999 )
1000 }
1001
1002 pub fn accepts_write_qualifier(self) -> bool {
1005 self.carries_write_permission() || matches!(self, CompoundKind::VarArgs)
1006 }
1007
1008 pub fn leaf_name(self) -> &'static str {
1009 match self {
1010 CompoundKind::Ref => "Ref",
1011 CompoundKind::Slice => "Slice",
1012 CompoundKind::EnumeratedSlice => "EnumeratedSlice",
1013 CompoundKind::Map => "Map",
1014 CompoundKind::Channel => "Channel",
1015 CompoundKind::Sender => "Sender",
1016 CompoundKind::Receiver => "Receiver",
1017 CompoundKind::VarArgs => "VarArgs",
1018 }
1019 }
1020
1021 pub fn from_name(name: &str) -> Option<CompoundKind> {
1022 Some(match name {
1023 "Ref" => CompoundKind::Ref,
1024 "Slice" => CompoundKind::Slice,
1025 "EnumeratedSlice" => CompoundKind::EnumeratedSlice,
1026 "Map" => CompoundKind::Map,
1027 "Channel" => CompoundKind::Channel,
1028 "Sender" => CompoundKind::Sender,
1029 "Receiver" => CompoundKind::Receiver,
1030 "VarArgs" => CompoundKind::VarArgs,
1031 _ => return None,
1032 })
1033 }
1034}
1035
1036#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1037#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1038pub enum SimpleKind {
1039 Int,
1040 Int8,
1041 Int16,
1042 Int32,
1043 Int64,
1044 Uint,
1045 Uint8,
1046 Uint16,
1047 Uint32,
1048 Uint64,
1049 Uintptr,
1050 Byte,
1051 Float32,
1052 Float64,
1053 Complex64,
1054 Complex128,
1055 Rune,
1056 Bool,
1057 String,
1058 Unit,
1059}
1060
1061impl SimpleKind {
1062 pub fn leaf_name(self) -> &'static str {
1063 match self {
1064 SimpleKind::Int => "int",
1065 SimpleKind::Int8 => "int8",
1066 SimpleKind::Int16 => "int16",
1067 SimpleKind::Int32 => "int32",
1068 SimpleKind::Int64 => "int64",
1069 SimpleKind::Uint => "uint",
1070 SimpleKind::Uint8 => "uint8",
1071 SimpleKind::Uint16 => "uint16",
1072 SimpleKind::Uint32 => "uint32",
1073 SimpleKind::Uint64 => "uint64",
1074 SimpleKind::Uintptr => "uintptr",
1075 SimpleKind::Byte => "byte",
1076 SimpleKind::Float32 => "float32",
1077 SimpleKind::Float64 => "float64",
1078 SimpleKind::Complex64 => "complex64",
1079 SimpleKind::Complex128 => "complex128",
1080 SimpleKind::Rune => "rune",
1081 SimpleKind::Bool => "bool",
1082 SimpleKind::String => "string",
1083 SimpleKind::Unit => "Unit",
1084 }
1085 }
1086
1087 pub fn from_name(name: &str) -> Option<SimpleKind> {
1088 Some(match name {
1089 "int" => SimpleKind::Int,
1090 "int8" => SimpleKind::Int8,
1091 "int16" => SimpleKind::Int16,
1092 "int32" => SimpleKind::Int32,
1093 "int64" => SimpleKind::Int64,
1094 "uint" => SimpleKind::Uint,
1095 "uint8" => SimpleKind::Uint8,
1096 "uint16" => SimpleKind::Uint16,
1097 "uint32" => SimpleKind::Uint32,
1098 "uint64" => SimpleKind::Uint64,
1099 "uintptr" => SimpleKind::Uintptr,
1100 "byte" => SimpleKind::Byte,
1101 "float32" => SimpleKind::Float32,
1102 "float64" => SimpleKind::Float64,
1103 "complex64" => SimpleKind::Complex64,
1104 "complex128" => SimpleKind::Complex128,
1105 "rune" => SimpleKind::Rune,
1106 "bool" => SimpleKind::Bool,
1107 "string" => SimpleKind::String,
1108 "Unit" => SimpleKind::Unit,
1109 _ => return None,
1110 })
1111 }
1112
1113 pub fn is_arithmetic(self) -> bool {
1114 !matches!(
1115 self,
1116 SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit | SimpleKind::Uintptr
1117 )
1118 }
1119
1120 pub fn is_ordered(self) -> bool {
1121 self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1122 }
1123
1124 pub fn integer_range(self) -> Option<(i128, i128)> {
1125 use SimpleKind::*;
1126 Some(match self {
1127 Int8 => (i8::MIN as i128, i8::MAX as i128),
1128 Int16 => (i16::MIN as i128, i16::MAX as i128),
1129 Int32 | Rune => (i32::MIN as i128, i32::MAX as i128),
1130 Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
1131 Uint8 | Byte => (0, u8::MAX as i128),
1132 Uint16 => (0, u16::MAX as i128),
1133 Uint32 => (0, u32::MAX as i128),
1134 Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
1135 _ => return None,
1136 })
1137 }
1138
1139 pub fn is_unsigned_int(self) -> bool {
1140 matches!(
1141 self,
1142 SimpleKind::Byte
1143 | SimpleKind::Uint
1144 | SimpleKind::Uint8
1145 | SimpleKind::Uint16
1146 | SimpleKind::Uint32
1147 | SimpleKind::Uint64
1148 )
1149 }
1150
1151 pub fn is_signed_int(self) -> bool {
1152 matches!(
1153 self,
1154 SimpleKind::Int
1155 | SimpleKind::Int8
1156 | SimpleKind::Int16
1157 | SimpleKind::Int32
1158 | SimpleKind::Int64
1159 | SimpleKind::Rune
1160 )
1161 }
1162
1163 pub fn is_float(self) -> bool {
1164 matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
1165 }
1166
1167 fn is_complex(self) -> bool {
1168 matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1169 }
1170
1171 fn numeric_family(self) -> Option<NumericFamily> {
1172 if self.is_signed_int() {
1173 Some(NumericFamily::SignedInt)
1174 } else if self.is_unsigned_int() {
1175 Some(NumericFamily::UnsignedInt)
1176 } else if self.is_float() {
1177 Some(NumericFamily::Float)
1178 } else {
1179 None
1180 }
1181 }
1182}
1183
1184impl Type {
1185 pub fn get_function_ret(&self) -> Option<&Type> {
1186 match self {
1187 Type::Function(f) => Some(&f.return_type),
1188 _ => None,
1189 }
1190 }
1191
1192 pub fn is_stringer_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
1193 let func = match self {
1194 Type::Forall { body, .. } => body.as_ref(),
1195 other => other,
1196 };
1197 matches!(
1198 func,
1199 Type::Function(f)
1200 if f.params.len() == 1
1201 && matches!(peel(&f.return_type), Type::Simple(SimpleKind::String))
1202 )
1203 }
1204
1205 pub fn is_equals_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
1206 let func = match self {
1207 Type::Forall { body, .. } => body.as_ref(),
1208 other => other,
1209 };
1210 matches!(
1211 func,
1212 Type::Function(f)
1213 if f.params.len() == 2
1214 && matches!(peel(&f.return_type), Type::Simple(SimpleKind::Bool))
1215 && peel(&f.params[0].ty) == peel(&f.params[1].ty)
1216 && !peel(&f.params[0].ty).is_ref()
1217 )
1218 }
1219
1220 pub fn is_equals_bound_signature(
1221 &self,
1222 param_name: &str,
1223 peel: impl Fn(&Type) -> Type,
1224 ) -> bool {
1225 let func = match self {
1226 Type::Forall { body, .. } => body.as_ref(),
1227 other => other,
1228 };
1229 matches!(
1230 func,
1231 Type::Function(f)
1232 if f.params.len() == 1
1233 && peel(&f.return_type).is_boolean()
1234 && matches!(&f.params[0].ty, Type::Parameter(name) if name.as_str() == param_name)
1235 )
1236 }
1237
1238 pub fn equals_receiver_vars(
1239 &self,
1240 owner_id: &str,
1241 arity: usize,
1242 peel: impl Fn(&Type) -> Type,
1243 ) -> Option<Vec<EcoString>> {
1244 if !self.is_equals_signature(&peel) {
1245 return None;
1246 }
1247 let (quantified, func): (&[EcoString], &Type) = match self {
1248 Type::Forall { vars, body } => (vars, body.as_ref()),
1249 other => (&[], other),
1250 };
1251 if quantified.len() != arity {
1252 return None;
1253 }
1254 let Type::Function(f) = func else {
1255 return None;
1256 };
1257 let Type::Nominal { id, params, .. } = peel(&f.params[0].ty) else {
1258 return None;
1259 };
1260 if id.as_str() != owner_id || params.len() != arity {
1261 return None;
1262 }
1263 let mut vars = Vec::with_capacity(arity);
1264 for param in params {
1265 let Type::Parameter(name) = param else {
1266 return None;
1267 };
1268 if vars.contains(&name) {
1269 return None;
1270 }
1271 vars.push(name);
1272 }
1273 if !quantified.iter().all(|v| vars.contains(v)) {
1274 return None;
1275 }
1276 Some(vars)
1277 }
1278
1279 pub fn has_name(&self, name: &str) -> bool {
1280 match self {
1281 Type::Nominal { id, .. } => id.last_segment() == name,
1282 Type::Simple(kind) => kind.leaf_name() == name,
1283 Type::Compound { kind, .. } => kind.leaf_name() == name,
1284 _ => false,
1285 }
1286 }
1287
1288 pub fn get_qualified_id(&self) -> Option<&str> {
1289 match self {
1290 Type::Nominal { id, .. } => Some(id.as_str()),
1291 _ => None,
1292 }
1293 }
1294
1295 pub fn is_result(&self) -> bool {
1296 self.has_qualified_id("prelude.Result")
1297 }
1298
1299 pub fn is_option(&self) -> bool {
1300 self.has_qualified_id("prelude.Option")
1301 }
1302
1303 pub fn is_partial(&self) -> bool {
1304 self.has_qualified_id("prelude.Partial")
1305 }
1306
1307 fn has_qualified_id(&self, qualified_id: &str) -> bool {
1308 matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
1309 }
1310
1311 pub fn is_unit(&self) -> bool {
1312 self.is_simple(SimpleKind::Unit)
1313 }
1314
1315 pub fn tuple_arity(&self) -> Option<usize> {
1316 match self {
1317 Type::Tuple(elements) => Some(elements.len()),
1318 _ => None,
1319 }
1320 }
1321
1322 pub fn is_tuple(&self) -> bool {
1323 matches!(self, Type::Tuple(_))
1324 }
1325
1326 pub fn array_len(&self) -> Option<u64> {
1327 match self {
1328 Type::Array { length, .. } => Some(*length),
1329 _ => None,
1330 }
1331 }
1332
1333 pub fn as_import_namespace(&self) -> Option<&str> {
1334 match self {
1335 Type::ImportNamespace(package_id) => Some(package_id),
1336 _ => None,
1337 }
1338 }
1339
1340 pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
1341 match self {
1342 Type::Compound { kind, args, .. } => Some((*kind, args.as_slice())),
1343 _ => None,
1344 }
1345 }
1346
1347 pub fn is_native(&self, kind: CompoundKind) -> bool {
1348 self.as_compound().is_some_and(|(k, _)| k == kind)
1349 }
1350
1351 pub fn is_ref(&self) -> bool {
1352 self.is_native(CompoundKind::Ref)
1353 }
1354
1355 pub fn is_slice(&self) -> bool {
1356 self.is_native(CompoundKind::Slice)
1357 }
1358
1359 pub fn is_map(&self) -> bool {
1360 self.is_native(CompoundKind::Map)
1361 }
1362
1363 pub fn is_channel(&self) -> bool {
1364 self.is_native(CompoundKind::Channel)
1365 }
1366
1367 pub fn is_receiver_placeholder(&self) -> bool {
1368 matches!(self, Type::ReceiverPlaceholder)
1369 }
1370
1371 pub fn is_unknown(&self) -> bool {
1372 self.has_qualified_id("prelude.Unknown")
1373 }
1374
1375 pub fn is_receiver(&self) -> bool {
1376 self.is_native(CompoundKind::Receiver)
1377 }
1378
1379 pub fn is_ignored(&self) -> bool {
1380 matches!(self, Type::Ignored)
1381 }
1382
1383 pub fn is_placeholder(&self) -> bool {
1384 matches!(self, Type::Uninferred | Type::Ignored)
1385 }
1386
1387 pub fn is_variadic(&self) -> Option<Type> {
1388 let last = self.get_function_params()?.last()?;
1389 match last.ty.as_compound()? {
1390 (CompoundKind::VarArgs, _) => last.ty.inner(),
1391 _ => None,
1392 }
1393 }
1394
1395 pub fn is_string(&self) -> bool {
1396 self.is_simple(SimpleKind::String)
1397 }
1398
1399 fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
1400 match self.as_compound() {
1401 Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
1402 _ => false,
1403 }
1404 }
1405
1406 pub fn is_byte_slice(&self) -> bool {
1407 self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
1408 }
1409
1410 fn is_rune_slice(&self) -> bool {
1411 self.is_slice_of_simple(SimpleKind::Rune)
1412 }
1413
1414 fn is_byte_or_rune_slice(&self) -> bool {
1415 self.is_byte_slice() || self.is_rune_slice()
1416 }
1417
1418 pub fn as_simple(&self) -> Option<SimpleKind> {
1419 match self {
1420 Type::Simple(kind) => Some(*kind),
1421 _ => None,
1422 }
1423 }
1424
1425 pub fn is_simple(&self, kind: SimpleKind) -> bool {
1426 self.as_simple() == Some(kind)
1427 }
1428
1429 pub fn is_boolean(&self) -> bool {
1430 self.is_simple(SimpleKind::Bool)
1431 }
1432
1433 pub fn is_rune(&self) -> bool {
1434 self.is_simple(SimpleKind::Rune)
1435 }
1436
1437 pub fn is_float(&self) -> bool {
1438 self.as_simple().is_some_and(SimpleKind::is_float)
1439 }
1440
1441 pub fn is_variable(&self) -> bool {
1442 matches!(self, Type::Var { .. })
1443 }
1444
1445 pub fn is_structural_alias_body(&self) -> bool {
1448 matches!(
1449 self,
1450 Type::Simple(_) | Type::Compound { .. } | Type::Array { .. } | Type::Tuple(_)
1451 )
1452 }
1453
1454 pub fn is_numeric(&self) -> bool {
1455 self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1456 }
1457
1458 pub fn is_complex(&self) -> bool {
1459 self.as_simple().is_some_and(SimpleKind::is_complex)
1460 }
1461
1462 pub fn is_unsigned_int(&self) -> bool {
1463 self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1464 }
1465
1466 pub fn is_never(&self) -> bool {
1467 matches!(self, Type::Never)
1468 }
1469
1470 pub fn is_error(&self) -> bool {
1471 matches!(self, Type::Error)
1472 }
1473
1474 pub fn contains_error(&self) -> bool {
1475 self.is_error() || self.children().into_iter().any(Type::contains_error)
1476 }
1477
1478 pub fn has_unbound_variables(&self) -> bool {
1479 match self {
1480 Type::Var { hint, .. } => hint.is_some(),
1481 _ => self.children().into_iter().any(Type::has_unbound_variables),
1482 }
1483 }
1484
1485 pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
1486 if let Type::Var { id, hint: Some(_) } = self {
1487 out.push(*id);
1488 }
1489 for child in self.children() {
1490 child.collect_unbound_variables(out);
1491 }
1492 }
1493
1494 pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1495 if names.is_empty() {
1496 return;
1497 }
1498
1499 match self {
1500 Type::Nominal { id, params, .. } => {
1501 names.remove(id.last_segment());
1502 for param in params {
1503 param.remove_found_type_names(names);
1504 }
1505 }
1506 Type::Function(f) => {
1507 for param in &f.params {
1508 param.ty.remove_found_type_names(names);
1509 }
1510 f.return_type.remove_found_type_names(names);
1511 for bound in &f.bounds {
1512 bound.generic.remove_found_type_names(names);
1513 bound.ty.remove_found_type_names(names);
1514 }
1515 }
1516 Type::Forall { body, .. } => {
1517 body.remove_found_type_names(names);
1518 }
1519 Type::Var { .. } => {}
1520 Type::Parameter(name) => {
1521 names.remove(name);
1522 }
1523 Type::Tuple(elements) => {
1524 for element in elements {
1525 element.remove_found_type_names(names);
1526 }
1527 }
1528 Type::Compound { kind, args, .. } => {
1529 names.remove(kind.leaf_name());
1530 for arg in args {
1531 arg.remove_found_type_names(names);
1532 }
1533 }
1534 Type::Array { element, .. } => {
1535 names.remove("Array");
1536 element.remove_found_type_names(names);
1537 }
1538 Type::Simple(kind) => {
1539 names.remove(kind.leaf_name());
1540 }
1541 Type::Never
1542 | Type::Uninferred
1543 | Type::Ignored
1544 | Type::Error
1545 | Type::ImportNamespace(_)
1546 | Type::ReceiverPlaceholder => {}
1547 }
1548 }
1549}
1550
1551impl Type {
1552 pub fn get_name(&self) -> Option<&str> {
1553 match self {
1554 Type::Simple(kind) => Some(kind.leaf_name()),
1555 Type::Compound { kind, args, .. } => match kind {
1556 CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1557 _ => Some(kind.leaf_name()),
1558 },
1559 Type::Nominal { id, .. } => Some(id.last_segment()),
1560 Type::ImportNamespace(package_id) => {
1561 let path = package_id.strip_prefix("go:").unwrap_or(package_id);
1562 path.rsplit('/').next()
1563 }
1564 Type::Array { .. } => Some("Array"),
1565 _ => None,
1566 }
1567 }
1568
1569 pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1570 self.get_name().is_some_and(|n| n == name)
1571 && self
1572 .get_type_params()
1573 .and_then(|p| p.first())
1574 .is_some_and(|first| *first == *inner)
1575 }
1576
1577 pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
1578 match self {
1579 Type::Function(f) => Some(&f.params),
1580 _ => None,
1581 }
1582 }
1583
1584 pub fn param_count(&self) -> usize {
1585 match self {
1586 Type::Function(f) => f.params.len(),
1587 _ => 0,
1588 }
1589 }
1590
1591 pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1592 match self {
1593 Type::Function(f) => {
1594 if f.params.is_empty() {
1595 return self.clone();
1596 }
1597 let mut new_params = f.params.clone();
1598 new_params[0] = new_params[0].with_type(new_first.clone());
1599 f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1600 }
1601 Type::Forall { vars, body } => Type::Forall {
1602 vars: vars.clone(),
1603 body: Box::new(body.with_replaced_first_param(new_first)),
1604 },
1605 _ => self.clone(),
1606 }
1607 }
1608
1609 pub fn get_bounds(&self) -> &[Bound] {
1610 match self {
1611 Type::Function(f) => &f.bounds,
1612 Type::Forall { body, .. } => body.get_bounds(),
1613 _ => &[],
1614 }
1615 }
1616
1617 pub fn get_qualified_name(&self) -> Option<Symbol> {
1618 let mut current = self;
1619 while current.is_ref() {
1620 current = current.get_type_params()?.first()?;
1621 }
1622 match current {
1623 Type::Nominal { id, .. } => Some(id.clone()),
1624 Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1625 Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1626 _ => None,
1627 }
1628 }
1629
1630 pub fn inner(&self) -> Option<Type> {
1631 self.get_type_params()
1632 .and_then(|args| args.first().cloned())
1633 }
1634
1635 pub fn ok_type(&self) -> Type {
1636 debug_assert!(
1637 self.is_result() || self.is_option() || self.is_partial(),
1638 "ok_type called on non-Result/Option/Partial type"
1639 );
1640 self.inner()
1641 .expect("Result/Option/Partial should have inner type")
1642 }
1643
1644 pub fn err_type(&self) -> Type {
1645 debug_assert!(
1646 self.is_result() || self.is_partial(),
1647 "err_type called on non-Result/Partial type"
1648 );
1649 self.get_type_params()
1650 .and_then(|args| args.get(1).cloned())
1651 .expect("Result/Partial should have error type")
1652 }
1653}
1654
1655pub fn peel_alias<'d, F>(ty: &Type, lookup: F) -> Type
1658where
1659 F: Fn(&str) -> Option<&'d Definition>,
1660{
1661 let mut current = ty.unwrap_forall().clone();
1662 let mut seen: HashSet<Symbol> = HashSet::default();
1663 while let Type::Nominal {
1664 id,
1665 params,
1666 writable,
1667 } = ¤t
1668 {
1669 let writable = *writable;
1670 if !seen.insert(id.clone()) {
1671 break;
1672 }
1673 let Some(target) = lookup(id.as_str())
1674 .and_then(|definition| definition.instantiate_alias_target(params, writable))
1675 else {
1676 break;
1677 };
1678 current = target.unwrap_forall().clone();
1679 }
1680 current
1681}
1682
1683pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1686where
1687 F: Fn(&str) -> Option<&'d Definition>,
1688{
1689 let Type::Nominal {
1690 id,
1691 params,
1692 writable,
1693 } = ty.unwrap_forall()
1694 else {
1695 return None;
1696 };
1697 lookup(id.as_str())?.instantiate_underlying(params, *writable, &lookup)
1698}
1699
1700pub fn peel_underlying<'d, F>(ty: &Type, lookup: F) -> Type
1704where
1705 F: Fn(&str) -> Option<&'d Definition>,
1706{
1707 let mut current = ty.unwrap_forall().clone();
1708 let mut seen: HashSet<Symbol> = HashSet::default();
1709 while let Type::Nominal {
1710 id,
1711 params,
1712 writable,
1713 } = ¤t
1714 {
1715 let writable = *writable;
1716 if !seen.insert(id.clone()) {
1717 break;
1718 }
1719 let Some(underlying) = lookup(id.as_str())
1720 .and_then(|definition| definition.instantiate_underlying(params, writable, &lookup))
1721 else {
1722 break;
1723 };
1724 current = underlying.unwrap_forall().clone();
1725 }
1726 current
1727}
1728
1729pub fn resolves_to_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1730where
1731 F: Fn(&str) -> Option<&'d Definition>,
1732{
1733 peel_alias(ty, lookup).is_unknown()
1734}
1735
1736pub fn resolves_to_unit<'d, F>(ty: &Type, lookup: F) -> bool
1737where
1738 F: Fn(&str) -> Option<&'d Definition>,
1739{
1740 peel_alias(ty, lookup).is_unit()
1741}
1742
1743pub fn contains_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1744where
1745 F: Fn(&str) -> Option<&'d Definition>,
1746{
1747 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1748 where
1749 F: Fn(&str) -> Option<&'d Definition>,
1750 {
1751 let peeled = peel_alias(ty, lookup);
1752 peeled.is_unknown()
1753 || peeled
1754 .children()
1755 .into_iter()
1756 .any(|child| contains(child, lookup))
1757 }
1758
1759 contains(ty, &lookup)
1760}
1761
1762pub fn contains_write_permission<'d, F>(ty: &Type, lookup: F) -> bool
1763where
1764 F: Fn(&str) -> Option<&'d Definition>,
1765{
1766 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1767 where
1768 F: Fn(&str) -> Option<&'d Definition>,
1769 {
1770 let peeled = peel_alias(ty, lookup);
1771 peeled.is_writable()
1772 || peeled
1773 .children()
1774 .into_iter()
1775 .any(|child| contains(child, lookup))
1776 }
1777
1778 contains(ty, &lookup)
1779}
1780
1781pub fn parameter_grants_write<'d, F>(ty: &Type, lookup: F) -> bool
1784where
1785 F: Fn(&str) -> Option<&'d Definition>,
1786{
1787 fn grants<'d, F>(ty: &Type, lookup: &F) -> bool
1788 where
1789 F: Fn(&str) -> Option<&'d Definition>,
1790 {
1791 match peel_alias(ty, lookup) {
1792 Type::Compound { args, writable, .. } => {
1793 writable || args.iter().any(|arg| grants(arg, lookup))
1794 }
1795 Type::Nominal {
1796 params, writable, ..
1797 } => writable || params.iter().any(|param| grants(param, lookup)),
1798 Type::Tuple(elements) => elements.iter().any(|element| grants(element, lookup)),
1799 Type::Array { element, .. } => grants(&element, lookup),
1800 _ => false,
1801 }
1802 }
1803
1804 grants(ty, &lookup)
1805}
1806
1807pub fn demoted<'d, F>(ty: &Type, lookup: &F) -> Type
1810where
1811 F: Fn(&str) -> Option<&'d Definition>,
1812{
1813 match ty {
1814 Type::Nominal {
1815 id,
1816 params,
1817 writable: _,
1818 } => {
1819 let cleared = Type::Nominal {
1820 id: id.clone(),
1821 params: params.iter().map(|param| demoted(param, lookup)).collect(),
1822 writable: false,
1823 };
1824 let peeled = peel_alias(&cleared, lookup);
1825 if peeled != cleared && demotion_changes(&peeled, lookup) {
1826 demoted(&peeled, lookup)
1827 } else {
1828 cleared
1829 }
1830 }
1831 Type::Compound {
1832 kind,
1833 args,
1834 writable: _,
1835 } => Type::Compound {
1836 kind: *kind,
1837 args: args.iter().map(|arg| demoted(arg, lookup)).collect(),
1838 writable: false,
1839 },
1840 Type::Tuple(elements) => Type::Tuple(
1841 elements
1842 .iter()
1843 .map(|element| demoted(element, lookup))
1844 .collect(),
1845 ),
1846 Type::Array { length, element } => Type::Array {
1847 length: *length,
1848 element: Box::new(demoted(element, lookup)),
1849 },
1850 Type::Function(f) => f.rebuild(
1851 f.params.clone(),
1852 f.bounds.clone(),
1853 Box::new(demoted(&f.return_type, lookup)),
1854 ),
1855 Type::Forall { vars, body } => Type::Forall {
1856 vars: vars.clone(),
1857 body: Box::new(demoted(body, lookup)),
1858 },
1859 _ => ty.clone(),
1860 }
1861}
1862
1863pub fn demotion_changes<'d, F>(ty: &Type, lookup: &F) -> bool
1865where
1866 F: Fn(&str) -> Option<&'d Definition>,
1867{
1868 match ty {
1869 Type::Nominal {
1870 params, writable, ..
1871 } => {
1872 if *writable {
1873 return true;
1874 }
1875 let peeled = peel_alias(ty, lookup);
1876 if peeled != *ty {
1877 return demotion_changes(&peeled, lookup);
1878 }
1879 params.iter().any(|param| demotion_changes(param, lookup))
1880 }
1881 Type::Compound { args, writable, .. } => {
1882 *writable || args.iter().any(|arg| demotion_changes(arg, lookup))
1883 }
1884 Type::Tuple(elements) => elements
1885 .iter()
1886 .any(|element| demotion_changes(element, lookup)),
1887 Type::Array { element, .. } => demotion_changes(element, lookup),
1888 Type::Function(f) => demotion_changes(&f.return_type, lookup),
1889 Type::Forall { body, .. } => demotion_changes(body, lookup),
1890 _ => false,
1891 }
1892}
1893
1894pub fn declares_writable_components<'d, F>(id: &str, lookup: &F) -> bool
1896where
1897 F: Fn(&str) -> Option<&'d Definition>,
1898{
1899 match lookup(id).map(|definition| &definition.body) {
1900 Some(DefinitionBody::Struct { fields, .. }) => fields
1901 .as_slice()
1902 .iter()
1903 .any(|field| demotion_changes(&field.ty, lookup)),
1904 Some(DefinitionBody::Enum { variants, .. }) => variants
1905 .iter()
1906 .flat_map(|variant| match &variant.fields {
1907 VariantFields::Unit => [].as_slice(),
1908 VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
1909 })
1910 .any(|field| demotion_changes(&field.ty, lookup)),
1911 _ => false,
1912 }
1913}
1914
1915pub fn writable_ref_pointee<'d, F>(pointee: &Type, lookup: &F) -> Type
1917where
1918 F: Fn(&str) -> Option<&'d Definition>,
1919{
1920 match peel_alias(pointee, lookup) {
1921 Type::Nominal {
1922 id,
1923 writable: false,
1924 ..
1925 } if declares_writable_components(id.as_str(), lookup) => pointee.clone().make_writable(),
1926 _ => pointee.clone(),
1927 }
1928}
1929
1930pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
1931where
1932 F: Fn(&str) -> Option<&'d Definition>,
1933{
1934 peel_underlying(ty, lookup).as_simple()
1935}
1936
1937pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1938where
1939 F: Fn(&str) -> Option<&'d Definition>,
1940{
1941 let underlying = peel_underlying(ty, lookup);
1942 underlying.is_numeric().then_some(underlying)
1943}
1944
1945pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1946where
1947 F: Fn(&str) -> Option<&'d Definition>,
1948{
1949 underlying_numeric_type(ty, &lookup).or_else(|| {
1950 (matches!(ty.unwrap_forall(), Type::Nominal { .. })
1951 && underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
1952 .then_some(Type::Simple(SimpleKind::Uintptr))
1953 })
1954}
1955
1956pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
1957where
1958 F: Fn(&str) -> Option<&'d Definition>,
1959{
1960 match (
1961 underlying_numeric_type(left, &lookup),
1962 underlying_numeric_type(right, &lookup),
1963 ) {
1964 (Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
1965 _ => false,
1966 }
1967}
1968
1969pub fn is_aliased_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
1970where
1971 F: Fn(&str) -> Option<&'d Definition>,
1972{
1973 matches!(ty.unwrap_forall(), Type::Nominal { .. })
1974 && underlying_type(ty, &lookup).is_some()
1975 && !ty.is_numeric()
1976 && underlying_numeric_type(ty, lookup).is_some()
1977}
1978
1979pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
1980where
1981 F: Fn(&str) -> Option<&'d Definition>,
1982{
1983 peel_underlying(ty, lookup).is_byte_or_rune_slice()
1984}
1985
1986pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
1987where
1988 F: Fn(&str) -> Option<&'d Definition>,
1989{
1990 matches!(
1991 underlying_simple_kind(ty, lookup),
1992 Some(kind) if kind.is_ordered() || kind == SimpleKind::String
1993 ) || ty.is_boolean()
1994}
1995
1996pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
1999where
2000 F: Fn(&str) -> Option<&'d Definition>,
2001{
2002 let Some(kind) = underlying_simple_kind(ty, lookup) else {
2003 return matches!(ty.unwrap_forall(), Type::Parameter(_));
2004 };
2005 matches!(
2006 kind,
2007 SimpleKind::Int
2008 | SimpleKind::Int8
2009 | SimpleKind::Int16
2010 | SimpleKind::Int32
2011 | SimpleKind::Int64
2012 | SimpleKind::Uint
2013 | SimpleKind::Uint8
2014 | SimpleKind::Uint16
2015 | SimpleKind::Uint32
2016 | SimpleKind::Uint64
2017 | SimpleKind::Uintptr
2018 | SimpleKind::Byte
2019 | SimpleKind::Rune
2020 | SimpleKind::Float32
2021 | SimpleKind::Float64
2022 | SimpleKind::String
2023 )
2024}
2025
2026pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
2029 let core = peel_underlying(ty, &lookup);
2030 if let Type::Nominal { id, .. } = &core {
2031 return matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
2032 }
2033 core.is_ref()
2034 || matches!(core, Type::Function(_))
2035 || core.is_map()
2036 || core.is_channel()
2037 || core.is_native(CompoundKind::Sender)
2038 || core.is_receiver()
2039}
2040
2041pub fn partial_ok_is_nilable<'a>(
2043 ty: &Type,
2044 lookup: impl Fn(&str) -> Option<&'a Definition>,
2045) -> bool {
2046 is_nilable_go_type(ty, &lookup) || peel_alias(ty, &lookup).is_slice()
2047}
2048
2049pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
2051where
2052 F: Fn(&str) -> Option<String>,
2053{
2054 let mut current = id.to_string();
2055 let mut seen: Vec<String> = Vec::new();
2056 loop {
2057 if seen.iter().any(|s| s == ¤t) {
2058 return current;
2059 }
2060 let Some(next) = next_alias(¤t) else {
2061 return current;
2062 };
2063 seen.push(current);
2064 current = next;
2065 }
2066}
2067
2068impl Type {
2069 pub fn unwrap_forall(&self) -> &Type {
2070 match self {
2071 Type::Forall { body, .. } => body.as_ref(),
2072 other => other,
2073 }
2074 }
2075
2076 pub fn as_function_type(&self) -> Option<&FunctionType> {
2077 match self.unwrap_forall() {
2078 Type::Function(f) => Some(f),
2079 _ => None,
2080 }
2081 }
2082
2083 pub fn strip_refs(&self) -> Type {
2084 if self.is_ref() {
2085 return self.inner().expect("ref type must have inner").strip_refs();
2086 }
2087
2088 self.clone()
2089 }
2090
2091 pub fn with_receiver_placeholder(self) -> Type {
2092 match self {
2093 Type::Function(f) => {
2094 let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
2095 let mut new_params = vec![FunctionParameter::new(Type::ReceiverPlaceholder)];
2096 new_params.extend(f.params);
2097
2098 Type::function(new_params, f.bounds, f.return_type)
2099 }
2100 _ => unreachable!(
2101 "with_receiver_placeholder called on non-function type: {:?}",
2102 self
2103 ),
2104 }
2105 }
2106
2107 pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
2108 let mut vars = HashMap::default();
2109 let types = types
2110 .iter()
2111 .map(|v| Self::remove_vars_impl(v, &mut vars))
2112 .collect();
2113
2114 (types, vars.into_values().collect())
2115 }
2116
2117 fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
2118 match ty {
2119 Type::Nominal {
2120 id: name,
2121 params: args,
2122 writable,
2123 } => Type::Nominal {
2124 id: name.clone(),
2125 params: args
2126 .iter()
2127 .map(|a| Self::remove_vars_impl(a, vars))
2128 .collect(),
2129 writable: *writable,
2130 },
2131
2132 Type::Function(f) => Type::function(
2133 f.params
2134 .iter()
2135 .map(|param| param.with_type(Self::remove_vars_impl(¶m.ty, vars)))
2136 .collect(),
2137 f.bounds
2138 .iter()
2139 .map(|b| Bound {
2140 param_name: b.param_name.clone(),
2141 generic: Self::remove_vars_impl(&b.generic, vars),
2142 ty: Self::remove_vars_impl(&b.ty, vars),
2143 })
2144 .collect(),
2145 Self::remove_vars_impl(&f.return_type, vars).into(),
2146 ),
2147
2148 Type::Var { id, hint } => match vars.get(&id.index()) {
2149 Some(g) => Type::Parameter(g.clone()),
2150 None => {
2151 let name: EcoString = hint
2152 .clone()
2153 .unwrap_or_else(|| alpha_index(vars.len()).into());
2154
2155 vars.insert(id.index(), name.clone());
2156 Type::Parameter(name)
2157 }
2158 },
2159
2160 Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
2161 Type::Tuple(elements) => Type::Tuple(
2162 elements
2163 .iter()
2164 .map(|e| Self::remove_vars_impl(e, vars))
2165 .collect(),
2166 ),
2167 Type::Compound {
2168 kind,
2169 args,
2170 writable,
2171 } => Type::Compound {
2172 kind: *kind,
2173 writable: *writable,
2174 args: args
2175 .iter()
2176 .map(|a| Self::remove_vars_impl(a, vars))
2177 .collect(),
2178 },
2179 Type::Array { length, element } => Type::Array {
2180 length: *length,
2181 element: Box::new(Self::remove_vars_impl(element, vars)),
2182 },
2183 Type::Simple(_) | Type::Parameter(_) => ty.clone(),
2184 Type::Never
2185 | Type::Uninferred
2186 | Type::Ignored
2187 | Type::Error
2188 | Type::ImportNamespace(_)
2189 | Type::ReceiverPlaceholder => ty.clone(),
2190 }
2191 }
2192
2193 pub fn contains_type(&self, target: &Type) -> bool {
2194 self == target
2195 || self
2196 .children()
2197 .into_iter()
2198 .any(|child| child.contains_type(target))
2199 }
2200}
2201
2202impl Type {
2203 pub fn numeric_family(&self) -> Option<NumericFamily> {
2204 self.as_simple()?.numeric_family()
2205 }
2206}
2207
2208fn alpha_index(idx: usize) -> String {
2210 let mut s = String::new();
2211 let mut n = idx + 1;
2212 while n > 0 {
2213 n -= 1;
2214 s.insert(0, (b'A' + (n % 26) as u8) as char);
2215 n /= 26;
2216 }
2217 s
2218}
2219
2220#[cfg(test)]
2221mod tests {
2222 use super::*;
2223 use std::collections::hash_map::DefaultHasher;
2224 use std::hash::{Hash, Hasher};
2225 use std::iter;
2226
2227 fn hash(ty: &Type) -> u64 {
2228 let mut state = DefaultHasher::new();
2229 ty.hash(&mut state);
2230 state.finish()
2231 }
2232
2233 #[test]
2234 fn error_type_equals_itself() {
2235 let nominal_over_error = || Type::Nominal {
2236 id: Symbol::from_parts("prelude", "Option"),
2237 params: vec![Type::Error],
2238 writable: false,
2239 };
2240
2241 assert_eq!(Type::Error, Type::Error);
2242 assert_eq!(nominal_over_error(), nominal_over_error());
2243 }
2244
2245 #[test]
2246 fn function_equality_ignores_param_names() {
2247 let named = Type::function(
2248 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2249 vec![],
2250 Box::new(Type::bool()),
2251 );
2252 let differently_named = Type::function(
2253 vec![FunctionParameter::named(Type::int(), Some("height".into()))],
2254 vec![],
2255 Box::new(Type::bool()),
2256 );
2257 let unnamed = Type::function(
2258 vec![FunctionParameter::new(Type::int())],
2259 vec![],
2260 Box::new(Type::bool()),
2261 );
2262
2263 assert_eq!(named, differently_named);
2264 assert_eq!(named, unnamed);
2265 }
2266
2267 #[test]
2268 fn equal_function_types_have_equal_hashes() {
2269 let named = Type::function(
2270 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2271 vec![],
2272 Box::new(Type::bool()),
2273 );
2274 let unnamed = Type::function(
2275 vec![FunctionParameter::new(Type::int())],
2276 vec![],
2277 Box::new(Type::bool()),
2278 );
2279
2280 assert_eq!(hash(&named), hash(&unnamed));
2281 }
2282
2283 #[test]
2284 fn equal_type_variables_have_equal_hashes() {
2285 let named = Type::Var {
2286 id: TypeVarId::new(1),
2287 hint: Some("value".into()),
2288 };
2289 let unnamed = Type::Var {
2290 id: TypeVarId::new(1),
2291 hint: None,
2292 };
2293
2294 assert_eq!(hash(&named), hash(&unnamed));
2295 }
2296
2297 #[test]
2298 fn signature_queries_ignore_function_bound_types() {
2299 let variable = Type::Var {
2300 id: TypeVarId::new(1),
2301 hint: Some("value".into()),
2302 };
2303 let signature = Type::function(
2304 vec![FunctionParameter::new(Type::int())],
2305 vec![Bound {
2306 param_name: "T".into(),
2307 generic: variable.clone(),
2308 ty: Type::Tuple(vec![variable.clone(), Type::Error]),
2309 }],
2310 Box::new(Type::bool()),
2311 );
2312 let mut variables = Vec::new();
2313 signature.collect_unbound_variables(&mut variables);
2314
2315 assert!(!signature.contains_error());
2316 assert!(!signature.has_unbound_variables());
2317 assert!(!signature.contains_type(&variable));
2318 assert!(!signature.contains_type(&Type::Error));
2319 assert!(variables.is_empty());
2320 }
2321
2322 #[test]
2323 fn unbound_variables_preserve_occurrence_order_through_quantified_signatures() {
2324 let first = Type::Var {
2325 id: TypeVarId::new(1),
2326 hint: Some("first".into()),
2327 };
2328 let second = Type::Var {
2329 id: TypeVarId::new(2),
2330 hint: Some("second".into()),
2331 };
2332 let signature = Type::Forall {
2333 vars: vec!["T".into()],
2334 body: Box::new(Type::function(
2335 vec![
2336 FunctionParameter::new(Type::Tuple(vec![first.clone(), second.clone()])),
2337 FunctionParameter::new(unhinted_var(3)),
2338 ],
2339 vec![],
2340 Box::new(first),
2341 )),
2342 };
2343 let mut variables = Vec::new();
2344 signature.collect_unbound_variables(&mut variables);
2345
2346 assert_eq!(
2347 variables,
2348 vec![TypeVarId::new(1), TypeVarId::new(2), TypeVarId::new(1)],
2349 );
2350 assert!(signature.has_unbound_variables());
2351 assert!(signature.contains_type(&second));
2352 assert!(signature.contains_type(&signature));
2353 }
2354
2355 #[test]
2356 fn signature_queries_find_errors_in_nested_return_types() {
2357 let signature = Type::function(
2358 vec![FunctionParameter::new(Type::int())],
2359 vec![],
2360 Box::new(Type::Array {
2361 length: 1,
2362 element: Box::new(Type::Error),
2363 }),
2364 );
2365
2366 assert!(signature.contains_error());
2367 assert!(signature.contains_type(&Type::Error));
2368 }
2369
2370 #[test]
2371 fn alpha_index_single() {
2372 assert_eq!(alpha_index(0), "A");
2373 assert_eq!(alpha_index(5), "F");
2374 assert_eq!(alpha_index(25), "Z");
2375 }
2376
2377 #[test]
2378 fn alpha_index_double() {
2379 assert_eq!(alpha_index(26), "AA");
2380 assert_eq!(alpha_index(27), "AB");
2381 assert_eq!(alpha_index(51), "AZ");
2382 assert_eq!(alpha_index(52), "BA");
2383 assert_eq!(alpha_index(701), "ZZ");
2384 }
2385
2386 #[test]
2387 fn alpha_index_triple() {
2388 assert_eq!(alpha_index(702), "AAA");
2389 }
2390
2391 fn unhinted_var(id: u32) -> Type {
2392 Type::Var {
2393 id: TypeVarId::new(id),
2394 hint: None,
2395 }
2396 }
2397
2398 #[test]
2399 fn remove_vars_handles_more_than_six_unhinted_vars() {
2400 let func = Type::function(
2401 (0..6)
2402 .map(unhinted_var)
2403 .map(FunctionParameter::new)
2404 .collect(),
2405 vec![],
2406 Box::new(unhinted_var(6)),
2407 );
2408
2409 let (resolved, generics) = Type::remove_vars(&[&func]);
2410
2411 assert_eq!(generics.len(), 7);
2412 let Type::Function(f) = &resolved[0] else {
2413 panic!("expected function type");
2414 };
2415 let names: Vec<_> = f
2416 .params
2417 .iter()
2418 .map(|param| ¶m.ty)
2419 .chain(iter::once(f.return_type.as_ref()))
2420 .map(|p| match p {
2421 Type::Parameter(name) => name.to_string(),
2422 other => panic!("expected parameter, got {:?}", other),
2423 })
2424 .collect();
2425 assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
2426 }
2427
2428 #[test]
2429 fn remove_vars_handles_dozens_of_unhinted_vars() {
2430 let params: Vec<Type> = (0..30).map(unhinted_var).collect();
2431 let func = Type::function(
2432 params.iter().cloned().map(FunctionParameter::new).collect(),
2433 vec![],
2434 Box::new(Type::Simple(SimpleKind::Unit)),
2435 );
2436 let (_, generics) = Type::remove_vars(&[&func]);
2437 assert_eq!(generics.len(), 30);
2438 }
2439}