1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2use std::borrow::Borrow;
3use std::hash::{Hash, Hasher};
4use std::mem;
5use std::sync::Arc;
6
7use ecow::EcoString;
8
9use crate::ast::Generic;
10use crate::program::{Definition, DefinitionBody};
11use fmt::Formatter;
12use std::fmt;
13use std::fmt::Display;
14use std::ops::Deref;
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct Symbol(EcoString);
25
26impl Symbol {
27 pub fn from_parts(package: &str, local: &str) -> Self {
31 let mut s = EcoString::with_capacity(package.len() + 1 + local.len());
35 s.push_str(package);
36 s.push('.');
37 s.push_str(local);
38 Self(s)
39 }
40
41 pub fn with_segment(&self, segment: &str) -> Self {
46 let mut s = EcoString::with_capacity(self.0.len() + 1 + segment.len());
47 s.push_str(&self.0);
48 s.push('.');
49 s.push_str(segment);
50 Self(s)
51 }
52
53 pub fn from_raw(qualified: impl Into<EcoString>) -> Self {
56 Self(qualified.into())
57 }
58
59 pub fn as_str(&self) -> &str {
60 &self.0
61 }
62
63 pub fn as_eco(&self) -> &EcoString {
64 &self.0
65 }
66
67 pub fn last_segment(&self) -> &str {
69 self.0.rsplit('.').next().unwrap_or(&self.0)
70 }
71
72 pub fn without_last_segment(&self) -> Option<&str> {
75 self.0.rsplit_once('.').map(|(rest, _)| rest)
76 }
77}
78
79impl Borrow<str> for Symbol {
80 fn borrow(&self) -> &str {
81 &self.0
82 }
83}
84
85impl AsRef<str> for Symbol {
86 fn as_ref(&self) -> &str {
87 &self.0
88 }
89}
90
91impl Deref for Symbol {
92 type Target = str;
93
94 fn deref(&self) -> &str {
95 &self.0
96 }
97}
98
99impl From<&Symbol> for EcoString {
100 fn from(s: &Symbol) -> Self {
101 s.0.clone()
102 }
103}
104
105impl Display for Symbol {
106 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
107 self.0.fmt(f)
108 }
109}
110
111impl From<EcoString> for Symbol {
112 fn from(s: EcoString) -> Self {
113 Self(s)
114 }
115}
116
117impl From<Symbol> for EcoString {
118 fn from(s: Symbol) -> Self {
119 s.0
120 }
121}
122
123impl From<&str> for Symbol {
124 fn from(s: &str) -> Self {
125 Self(EcoString::from(s))
126 }
127}
128
129impl From<String> for Symbol {
130 fn from(s: String) -> Self {
131 Self(EcoString::from(s))
132 }
133}
134
135impl PartialEq<str> for Symbol {
136 fn eq(&self, other: &str) -> bool {
137 self.0.as_str() == other
138 }
139}
140
141impl PartialEq<&str> for Symbol {
142 fn eq(&self, other: &&str) -> bool {
143 self.0.as_str() == *other
144 }
145}
146
147pub fn unqualified_name(id: &str) -> &str {
151 id.rsplit('.').next().unwrap_or(id)
152}
153
154pub const GO_IMPORT_PREFIX: &str = "go:";
155
156pub 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) -> 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!(f.return_type.as_ref(), Type::Simple(SimpleKind::String))
1202 )
1203 }
1204
1205 pub fn is_equals_signature(&self) -> 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!(f.return_type.as_ref(), Type::Simple(SimpleKind::Bool))
1215 && f.params[0].ty == f.params[1].ty
1216 && !f.params[0].ty.is_ref()
1217 )
1218 }
1219
1220 pub fn is_equals_bound_signature(&self, param_name: &str) -> bool {
1221 let func = match self {
1222 Type::Forall { body, .. } => body.as_ref(),
1223 other => other,
1224 };
1225 matches!(
1226 func,
1227 Type::Function(f)
1228 if f.params.len() == 1
1229 && f.return_type.is_boolean()
1230 && matches!(&f.params[0].ty, Type::Parameter(name) if name.as_str() == param_name)
1231 )
1232 }
1233
1234 pub fn equals_receiver_vars(&self, owner_id: &str, arity: usize) -> Option<Vec<EcoString>> {
1235 if !self.is_equals_signature() {
1236 return None;
1237 }
1238 let (quantified, func): (&[EcoString], &Type) = match self {
1239 Type::Forall { vars, body } => (vars, body.as_ref()),
1240 other => (&[], other),
1241 };
1242 if quantified.len() != arity {
1243 return None;
1244 }
1245 let Type::Function(f) = func else {
1246 return None;
1247 };
1248 let Type::Nominal { id, params, .. } = &f.params[0].ty else {
1249 return None;
1250 };
1251 if id.as_str() != owner_id || params.len() != arity {
1252 return None;
1253 }
1254 let mut vars = Vec::with_capacity(arity);
1255 for param in params {
1256 let Type::Parameter(name) = param else {
1257 return None;
1258 };
1259 if vars.contains(name) {
1260 return None;
1261 }
1262 vars.push(name.clone());
1263 }
1264 if !quantified.iter().all(|v| vars.contains(v)) {
1265 return None;
1266 }
1267 Some(vars)
1268 }
1269
1270 pub fn has_name(&self, name: &str) -> bool {
1271 match self {
1272 Type::Nominal { id, .. } => id.last_segment() == name,
1273 Type::Simple(kind) => kind.leaf_name() == name,
1274 Type::Compound { kind, .. } => kind.leaf_name() == name,
1275 _ => false,
1276 }
1277 }
1278
1279 pub fn get_qualified_id(&self) -> Option<&str> {
1280 match self {
1281 Type::Nominal { id, .. } => Some(id.as_str()),
1282 _ => None,
1283 }
1284 }
1285
1286 pub fn is_result(&self) -> bool {
1287 self.has_qualified_id("prelude.Result")
1288 }
1289
1290 pub fn is_option(&self) -> bool {
1291 self.has_qualified_id("prelude.Option")
1292 }
1293
1294 pub fn is_partial(&self) -> bool {
1295 self.has_qualified_id("prelude.Partial")
1296 }
1297
1298 fn has_qualified_id(&self, qualified_id: &str) -> bool {
1299 matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
1300 }
1301
1302 pub fn is_unit(&self) -> bool {
1303 self.is_simple(SimpleKind::Unit)
1304 }
1305
1306 pub fn tuple_arity(&self) -> Option<usize> {
1307 match self {
1308 Type::Tuple(elements) => Some(elements.len()),
1309 _ => None,
1310 }
1311 }
1312
1313 pub fn is_tuple(&self) -> bool {
1314 matches!(self, Type::Tuple(_))
1315 }
1316
1317 pub fn array_len(&self) -> Option<u64> {
1318 match self {
1319 Type::Array { length, .. } => Some(*length),
1320 _ => None,
1321 }
1322 }
1323
1324 pub fn as_import_namespace(&self) -> Option<&str> {
1325 match self {
1326 Type::ImportNamespace(package_id) => Some(package_id),
1327 _ => None,
1328 }
1329 }
1330
1331 pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
1332 match self {
1333 Type::Compound { kind, args, .. } => Some((*kind, args.as_slice())),
1334 _ => None,
1335 }
1336 }
1337
1338 pub fn is_native(&self, kind: CompoundKind) -> bool {
1339 self.as_compound().is_some_and(|(k, _)| k == kind)
1340 }
1341
1342 pub fn is_ref(&self) -> bool {
1343 self.is_native(CompoundKind::Ref)
1344 }
1345
1346 pub fn is_slice(&self) -> bool {
1347 self.is_native(CompoundKind::Slice)
1348 }
1349
1350 pub fn is_map(&self) -> bool {
1351 self.is_native(CompoundKind::Map)
1352 }
1353
1354 pub fn is_channel(&self) -> bool {
1355 self.is_native(CompoundKind::Channel)
1356 }
1357
1358 pub fn is_receiver_placeholder(&self) -> bool {
1359 matches!(self, Type::ReceiverPlaceholder)
1360 }
1361
1362 pub fn is_unknown(&self) -> bool {
1363 self.has_qualified_id("prelude.Unknown")
1364 }
1365
1366 pub fn is_receiver(&self) -> bool {
1367 self.is_native(CompoundKind::Receiver)
1368 }
1369
1370 pub fn is_ignored(&self) -> bool {
1371 matches!(self, Type::Ignored)
1372 }
1373
1374 pub fn is_placeholder(&self) -> bool {
1375 matches!(self, Type::Uninferred | Type::Ignored)
1376 }
1377
1378 pub fn is_variadic(&self) -> Option<Type> {
1379 let last = self.get_function_params()?.last()?;
1380 match last.ty.as_compound()? {
1381 (CompoundKind::VarArgs, _) => last.ty.inner(),
1382 _ => None,
1383 }
1384 }
1385
1386 pub fn is_string(&self) -> bool {
1387 self.is_simple(SimpleKind::String)
1388 }
1389
1390 fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
1391 match self.as_compound() {
1392 Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
1393 _ => false,
1394 }
1395 }
1396
1397 pub fn is_byte_slice(&self) -> bool {
1398 self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
1399 }
1400
1401 fn is_rune_slice(&self) -> bool {
1402 self.is_slice_of_simple(SimpleKind::Rune)
1403 }
1404
1405 fn is_byte_or_rune_slice(&self) -> bool {
1406 self.is_byte_slice() || self.is_rune_slice()
1407 }
1408
1409 pub fn as_simple(&self) -> Option<SimpleKind> {
1410 match self {
1411 Type::Simple(kind) => Some(*kind),
1412 _ => None,
1413 }
1414 }
1415
1416 pub fn is_simple(&self, kind: SimpleKind) -> bool {
1417 self.as_simple() == Some(kind)
1418 }
1419
1420 pub fn is_boolean(&self) -> bool {
1421 self.is_simple(SimpleKind::Bool)
1422 }
1423
1424 pub fn is_rune(&self) -> bool {
1425 self.is_simple(SimpleKind::Rune)
1426 }
1427
1428 pub fn is_float(&self) -> bool {
1429 self.as_simple().is_some_and(SimpleKind::is_float)
1430 }
1431
1432 pub fn is_variable(&self) -> bool {
1433 matches!(self, Type::Var { .. })
1434 }
1435
1436 pub fn is_structural_alias_body(&self) -> bool {
1439 matches!(
1440 self,
1441 Type::Simple(_) | Type::Compound { .. } | Type::Array { .. } | Type::Tuple(_)
1442 )
1443 }
1444
1445 pub fn is_numeric(&self) -> bool {
1446 self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1447 }
1448
1449 pub fn is_complex(&self) -> bool {
1450 self.as_simple().is_some_and(SimpleKind::is_complex)
1451 }
1452
1453 pub fn is_unsigned_int(&self) -> bool {
1454 self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1455 }
1456
1457 pub fn is_never(&self) -> bool {
1458 matches!(self, Type::Never)
1459 }
1460
1461 pub fn is_error(&self) -> bool {
1462 matches!(self, Type::Error)
1463 }
1464
1465 pub fn contains_error(&self) -> bool {
1466 self.is_error() || self.children().into_iter().any(Type::contains_error)
1467 }
1468
1469 pub fn has_unbound_variables(&self) -> bool {
1470 match self {
1471 Type::Var { hint, .. } => hint.is_some(),
1472 _ => self.children().into_iter().any(Type::has_unbound_variables),
1473 }
1474 }
1475
1476 pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
1477 if let Type::Var { id, hint: Some(_) } = self {
1478 out.push(*id);
1479 }
1480 for child in self.children() {
1481 child.collect_unbound_variables(out);
1482 }
1483 }
1484
1485 pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1486 if names.is_empty() {
1487 return;
1488 }
1489
1490 match self {
1491 Type::Nominal { id, params, .. } => {
1492 names.remove(id.last_segment());
1493 for param in params {
1494 param.remove_found_type_names(names);
1495 }
1496 }
1497 Type::Function(f) => {
1498 for param in &f.params {
1499 param.ty.remove_found_type_names(names);
1500 }
1501 f.return_type.remove_found_type_names(names);
1502 for bound in &f.bounds {
1503 bound.generic.remove_found_type_names(names);
1504 bound.ty.remove_found_type_names(names);
1505 }
1506 }
1507 Type::Forall { body, .. } => {
1508 body.remove_found_type_names(names);
1509 }
1510 Type::Var { .. } => {}
1511 Type::Parameter(name) => {
1512 names.remove(name);
1513 }
1514 Type::Tuple(elements) => {
1515 for element in elements {
1516 element.remove_found_type_names(names);
1517 }
1518 }
1519 Type::Compound { kind, args, .. } => {
1520 names.remove(kind.leaf_name());
1521 for arg in args {
1522 arg.remove_found_type_names(names);
1523 }
1524 }
1525 Type::Array { element, .. } => {
1526 names.remove("Array");
1527 element.remove_found_type_names(names);
1528 }
1529 Type::Simple(kind) => {
1530 names.remove(kind.leaf_name());
1531 }
1532 Type::Never
1533 | Type::Uninferred
1534 | Type::Ignored
1535 | Type::Error
1536 | Type::ImportNamespace(_)
1537 | Type::ReceiverPlaceholder => {}
1538 }
1539 }
1540}
1541
1542impl Type {
1543 pub fn get_name(&self) -> Option<&str> {
1544 match self {
1545 Type::Simple(kind) => Some(kind.leaf_name()),
1546 Type::Compound { kind, args, .. } => match kind {
1547 CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1548 _ => Some(kind.leaf_name()),
1549 },
1550 Type::Nominal { id, .. } => Some(id.last_segment()),
1551 Type::ImportNamespace(package_id) => {
1552 let path = package_id.strip_prefix("go:").unwrap_or(package_id);
1553 path.rsplit('/').next()
1554 }
1555 Type::Array { .. } => Some("Array"),
1556 _ => None,
1557 }
1558 }
1559
1560 pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1561 self.get_name().is_some_and(|n| n == name)
1562 && self
1563 .get_type_params()
1564 .and_then(|p| p.first())
1565 .is_some_and(|first| *first == *inner)
1566 }
1567
1568 pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
1569 match self {
1570 Type::Function(f) => Some(&f.params),
1571 _ => None,
1572 }
1573 }
1574
1575 pub fn param_count(&self) -> usize {
1576 match self {
1577 Type::Function(f) => f.params.len(),
1578 _ => 0,
1579 }
1580 }
1581
1582 pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1583 match self {
1584 Type::Function(f) => {
1585 if f.params.is_empty() {
1586 return self.clone();
1587 }
1588 let mut new_params = f.params.clone();
1589 new_params[0] = new_params[0].with_type(new_first.clone());
1590 f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1591 }
1592 Type::Forall { vars, body } => Type::Forall {
1593 vars: vars.clone(),
1594 body: Box::new(body.with_replaced_first_param(new_first)),
1595 },
1596 _ => self.clone(),
1597 }
1598 }
1599
1600 pub fn get_bounds(&self) -> &[Bound] {
1601 match self {
1602 Type::Function(f) => &f.bounds,
1603 Type::Forall { body, .. } => body.get_bounds(),
1604 _ => &[],
1605 }
1606 }
1607
1608 pub fn get_qualified_name(&self) -> Option<Symbol> {
1609 let mut current = self;
1610 while current.is_ref() {
1611 current = current.get_type_params()?.first()?;
1612 }
1613 match current {
1614 Type::Nominal { id, .. } => Some(id.clone()),
1615 Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1616 Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1617 _ => None,
1618 }
1619 }
1620
1621 pub fn inner(&self) -> Option<Type> {
1622 self.get_type_params()
1623 .and_then(|args| args.first().cloned())
1624 }
1625
1626 pub fn ok_type(&self) -> Type {
1627 debug_assert!(
1628 self.is_result() || self.is_option() || self.is_partial(),
1629 "ok_type called on non-Result/Option/Partial type"
1630 );
1631 self.inner()
1632 .expect("Result/Option/Partial should have inner type")
1633 }
1634
1635 pub fn err_type(&self) -> Type {
1636 debug_assert!(
1637 self.is_result() || self.is_partial(),
1638 "err_type called on non-Result/Partial type"
1639 );
1640 self.get_type_params()
1641 .and_then(|args| args.get(1).cloned())
1642 .expect("Result/Partial should have error type")
1643 }
1644}
1645
1646pub fn peel_alias<'d, F>(ty: &Type, lookup: F) -> Type
1649where
1650 F: Fn(&str) -> Option<&'d Definition>,
1651{
1652 let mut current = ty.unwrap_forall().clone();
1653 let mut seen: HashSet<Symbol> = HashSet::default();
1654 while let Type::Nominal {
1655 id,
1656 params,
1657 writable,
1658 } = ¤t
1659 {
1660 let writable = *writable;
1661 if !seen.insert(id.clone()) {
1662 break;
1663 }
1664 let Some(target) = lookup(id.as_str())
1665 .and_then(|definition| definition.instantiate_alias_target(params, writable))
1666 else {
1667 break;
1668 };
1669 current = target.unwrap_forall().clone();
1670 }
1671 current
1672}
1673
1674pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1677where
1678 F: Fn(&str) -> Option<&'d Definition>,
1679{
1680 let Type::Nominal {
1681 id,
1682 params,
1683 writable,
1684 } = ty.unwrap_forall()
1685 else {
1686 return None;
1687 };
1688 lookup(id.as_str())?.instantiate_underlying(params, *writable, &lookup)
1689}
1690
1691pub fn peel_underlying<'d, F>(ty: &Type, lookup: F) -> Type
1695where
1696 F: Fn(&str) -> Option<&'d Definition>,
1697{
1698 let mut current = ty.unwrap_forall().clone();
1699 let mut seen: HashSet<Symbol> = HashSet::default();
1700 while let Type::Nominal {
1701 id,
1702 params,
1703 writable,
1704 } = ¤t
1705 {
1706 let writable = *writable;
1707 if !seen.insert(id.clone()) {
1708 break;
1709 }
1710 let Some(underlying) = lookup(id.as_str())
1711 .and_then(|definition| definition.instantiate_underlying(params, writable, &lookup))
1712 else {
1713 break;
1714 };
1715 current = underlying.unwrap_forall().clone();
1716 }
1717 current
1718}
1719
1720pub fn resolves_to_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1721where
1722 F: Fn(&str) -> Option<&'d Definition>,
1723{
1724 peel_alias(ty, lookup).is_unknown()
1725}
1726
1727pub fn contains_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1728where
1729 F: Fn(&str) -> Option<&'d Definition>,
1730{
1731 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1732 where
1733 F: Fn(&str) -> Option<&'d Definition>,
1734 {
1735 let peeled = peel_alias(ty, lookup);
1736 peeled.is_unknown()
1737 || peeled
1738 .children()
1739 .into_iter()
1740 .any(|child| contains(child, lookup))
1741 }
1742
1743 contains(ty, &lookup)
1744}
1745
1746pub fn contains_write_permission<'d, F>(ty: &Type, lookup: F) -> bool
1747where
1748 F: Fn(&str) -> Option<&'d Definition>,
1749{
1750 fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1751 where
1752 F: Fn(&str) -> Option<&'d Definition>,
1753 {
1754 let peeled = peel_alias(ty, lookup);
1755 peeled.is_writable()
1756 || peeled
1757 .children()
1758 .into_iter()
1759 .any(|child| contains(child, lookup))
1760 }
1761
1762 contains(ty, &lookup)
1763}
1764
1765pub fn parameter_grants_write<'d, F>(ty: &Type, lookup: F) -> bool
1768where
1769 F: Fn(&str) -> Option<&'d Definition>,
1770{
1771 fn grants<'d, F>(ty: &Type, lookup: &F) -> bool
1772 where
1773 F: Fn(&str) -> Option<&'d Definition>,
1774 {
1775 match peel_alias(ty, lookup) {
1776 Type::Compound { args, writable, .. } => {
1777 writable || args.iter().any(|arg| grants(arg, lookup))
1778 }
1779 Type::Nominal {
1780 params, writable, ..
1781 } => writable || params.iter().any(|param| grants(param, lookup)),
1782 Type::Tuple(elements) => elements.iter().any(|element| grants(element, lookup)),
1783 Type::Array { element, .. } => grants(&element, lookup),
1784 _ => false,
1785 }
1786 }
1787
1788 grants(ty, &lookup)
1789}
1790
1791pub fn demoted<'d, F>(ty: &Type, lookup: &F) -> Type
1794where
1795 F: Fn(&str) -> Option<&'d Definition>,
1796{
1797 match ty {
1798 Type::Nominal {
1799 id,
1800 params,
1801 writable: _,
1802 } => {
1803 let cleared = Type::Nominal {
1804 id: id.clone(),
1805 params: params.iter().map(|param| demoted(param, lookup)).collect(),
1806 writable: false,
1807 };
1808 let peeled = peel_alias(&cleared, lookup);
1809 if peeled != cleared && demotion_changes(&peeled, lookup) {
1810 demoted(&peeled, lookup)
1811 } else {
1812 cleared
1813 }
1814 }
1815 Type::Compound {
1816 kind,
1817 args,
1818 writable: _,
1819 } => Type::Compound {
1820 kind: *kind,
1821 args: args.iter().map(|arg| demoted(arg, lookup)).collect(),
1822 writable: false,
1823 },
1824 Type::Tuple(elements) => Type::Tuple(
1825 elements
1826 .iter()
1827 .map(|element| demoted(element, lookup))
1828 .collect(),
1829 ),
1830 Type::Array { length, element } => Type::Array {
1831 length: *length,
1832 element: Box::new(demoted(element, lookup)),
1833 },
1834 Type::Function(f) => f.rebuild(
1835 f.params.clone(),
1836 f.bounds.clone(),
1837 Box::new(demoted(&f.return_type, lookup)),
1838 ),
1839 Type::Forall { vars, body } => Type::Forall {
1840 vars: vars.clone(),
1841 body: Box::new(demoted(body, lookup)),
1842 },
1843 _ => ty.clone(),
1844 }
1845}
1846
1847pub fn demotion_changes<'d, F>(ty: &Type, lookup: &F) -> bool
1849where
1850 F: Fn(&str) -> Option<&'d Definition>,
1851{
1852 match ty {
1853 Type::Nominal {
1854 params, writable, ..
1855 } => {
1856 if *writable {
1857 return true;
1858 }
1859 let peeled = peel_alias(ty, lookup);
1860 if peeled != *ty {
1861 return demotion_changes(&peeled, lookup);
1862 }
1863 params.iter().any(|param| demotion_changes(param, lookup))
1864 }
1865 Type::Compound { args, writable, .. } => {
1866 *writable || args.iter().any(|arg| demotion_changes(arg, lookup))
1867 }
1868 Type::Tuple(elements) => elements
1869 .iter()
1870 .any(|element| demotion_changes(element, lookup)),
1871 Type::Array { element, .. } => demotion_changes(element, lookup),
1872 Type::Function(f) => demotion_changes(&f.return_type, lookup),
1873 Type::Forall { body, .. } => demotion_changes(body, lookup),
1874 _ => false,
1875 }
1876}
1877
1878pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
1879where
1880 F: Fn(&str) -> Option<&'d Definition>,
1881{
1882 peel_underlying(ty, lookup).as_simple()
1883}
1884
1885pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1886where
1887 F: Fn(&str) -> Option<&'d Definition>,
1888{
1889 let underlying = peel_underlying(ty, lookup);
1890 underlying.is_numeric().then_some(underlying)
1891}
1892
1893pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1894where
1895 F: Fn(&str) -> Option<&'d Definition>,
1896{
1897 underlying_numeric_type(ty, &lookup).or_else(|| {
1898 (matches!(ty.unwrap_forall(), Type::Nominal { .. })
1899 && underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
1900 .then_some(Type::Simple(SimpleKind::Uintptr))
1901 })
1902}
1903
1904pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
1905where
1906 F: Fn(&str) -> Option<&'d Definition>,
1907{
1908 match (
1909 underlying_numeric_type(left, &lookup),
1910 underlying_numeric_type(right, &lookup),
1911 ) {
1912 (Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
1913 _ => false,
1914 }
1915}
1916
1917pub fn is_aliased_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
1918where
1919 F: Fn(&str) -> Option<&'d Definition>,
1920{
1921 matches!(ty.unwrap_forall(), Type::Nominal { .. })
1922 && underlying_type(ty, &lookup).is_some()
1923 && !ty.is_numeric()
1924 && underlying_numeric_type(ty, lookup).is_some()
1925}
1926
1927pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
1928where
1929 F: Fn(&str) -> Option<&'d Definition>,
1930{
1931 peel_underlying(ty, lookup).is_byte_or_rune_slice()
1932}
1933
1934pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
1935where
1936 F: Fn(&str) -> Option<&'d Definition>,
1937{
1938 matches!(
1939 underlying_simple_kind(ty, lookup),
1940 Some(kind) if kind.is_ordered() || kind == SimpleKind::String
1941 ) || ty.is_boolean()
1942}
1943
1944pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
1947where
1948 F: Fn(&str) -> Option<&'d Definition>,
1949{
1950 let Some(kind) = underlying_simple_kind(ty, lookup) else {
1951 return matches!(ty.unwrap_forall(), Type::Parameter(_));
1952 };
1953 matches!(
1954 kind,
1955 SimpleKind::Int
1956 | SimpleKind::Int8
1957 | SimpleKind::Int16
1958 | SimpleKind::Int32
1959 | SimpleKind::Int64
1960 | SimpleKind::Uint
1961 | SimpleKind::Uint8
1962 | SimpleKind::Uint16
1963 | SimpleKind::Uint32
1964 | SimpleKind::Uint64
1965 | SimpleKind::Uintptr
1966 | SimpleKind::Byte
1967 | SimpleKind::Rune
1968 | SimpleKind::Float32
1969 | SimpleKind::Float64
1970 | SimpleKind::String
1971 )
1972}
1973
1974pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
1977 let core = peel_underlying(ty, &lookup);
1978 if let Type::Nominal { id, .. } = &core {
1979 return matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
1980 }
1981 core.is_ref()
1982 || matches!(core, Type::Function(_))
1983 || core.is_map()
1984 || core.is_channel()
1985 || core.is_native(CompoundKind::Sender)
1986 || core.is_receiver()
1987}
1988
1989pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
1991where
1992 F: Fn(&str) -> Option<String>,
1993{
1994 let mut current = id.to_string();
1995 let mut seen: Vec<String> = Vec::new();
1996 loop {
1997 if seen.iter().any(|s| s == ¤t) {
1998 return current;
1999 }
2000 let Some(next) = next_alias(¤t) else {
2001 return current;
2002 };
2003 seen.push(current);
2004 current = next;
2005 }
2006}
2007
2008impl Type {
2009 pub fn unwrap_forall(&self) -> &Type {
2010 match self {
2011 Type::Forall { body, .. } => body.as_ref(),
2012 other => other,
2013 }
2014 }
2015
2016 pub fn as_function_type(&self) -> Option<&FunctionType> {
2017 match self.unwrap_forall() {
2018 Type::Function(f) => Some(f),
2019 _ => None,
2020 }
2021 }
2022
2023 pub fn strip_refs(&self) -> Type {
2024 if self.is_ref() {
2025 return self.inner().expect("ref type must have inner").strip_refs();
2026 }
2027
2028 self.clone()
2029 }
2030
2031 pub fn with_receiver_placeholder(self) -> Type {
2032 match self {
2033 Type::Function(f) => {
2034 let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
2035 let mut new_params = vec![FunctionParameter::new(Type::ReceiverPlaceholder)];
2036 new_params.extend(f.params);
2037
2038 Type::function(new_params, f.bounds, f.return_type)
2039 }
2040 _ => unreachable!(
2041 "with_receiver_placeholder called on non-function type: {:?}",
2042 self
2043 ),
2044 }
2045 }
2046
2047 pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
2048 let mut vars = HashMap::default();
2049 let types = types
2050 .iter()
2051 .map(|v| Self::remove_vars_impl(v, &mut vars))
2052 .collect();
2053
2054 (types, vars.into_values().collect())
2055 }
2056
2057 fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
2058 match ty {
2059 Type::Nominal {
2060 id: name,
2061 params: args,
2062 writable,
2063 } => Type::Nominal {
2064 id: name.clone(),
2065 params: args
2066 .iter()
2067 .map(|a| Self::remove_vars_impl(a, vars))
2068 .collect(),
2069 writable: *writable,
2070 },
2071
2072 Type::Function(f) => Type::function(
2073 f.params
2074 .iter()
2075 .map(|param| param.with_type(Self::remove_vars_impl(¶m.ty, vars)))
2076 .collect(),
2077 f.bounds
2078 .iter()
2079 .map(|b| Bound {
2080 param_name: b.param_name.clone(),
2081 generic: Self::remove_vars_impl(&b.generic, vars),
2082 ty: Self::remove_vars_impl(&b.ty, vars),
2083 })
2084 .collect(),
2085 Self::remove_vars_impl(&f.return_type, vars).into(),
2086 ),
2087
2088 Type::Var { id, hint } => match vars.get(&id.index()) {
2089 Some(g) => Type::Parameter(g.clone()),
2090 None => {
2091 let name: EcoString = hint
2092 .clone()
2093 .unwrap_or_else(|| alpha_index(vars.len()).into());
2094
2095 vars.insert(id.index(), name.clone());
2096 Type::Parameter(name)
2097 }
2098 },
2099
2100 Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
2101 Type::Tuple(elements) => Type::Tuple(
2102 elements
2103 .iter()
2104 .map(|e| Self::remove_vars_impl(e, vars))
2105 .collect(),
2106 ),
2107 Type::Compound {
2108 kind,
2109 args,
2110 writable,
2111 } => Type::Compound {
2112 kind: *kind,
2113 writable: *writable,
2114 args: args
2115 .iter()
2116 .map(|a| Self::remove_vars_impl(a, vars))
2117 .collect(),
2118 },
2119 Type::Array { length, element } => Type::Array {
2120 length: *length,
2121 element: Box::new(Self::remove_vars_impl(element, vars)),
2122 },
2123 Type::Simple(_) | Type::Parameter(_) => ty.clone(),
2124 Type::Never
2125 | Type::Uninferred
2126 | Type::Ignored
2127 | Type::Error
2128 | Type::ImportNamespace(_)
2129 | Type::ReceiverPlaceholder => ty.clone(),
2130 }
2131 }
2132
2133 pub fn contains_type(&self, target: &Type) -> bool {
2134 self == target
2135 || self
2136 .children()
2137 .into_iter()
2138 .any(|child| child.contains_type(target))
2139 }
2140}
2141
2142impl Type {
2143 pub fn numeric_family(&self) -> Option<NumericFamily> {
2144 self.as_simple()?.numeric_family()
2145 }
2146}
2147
2148fn alpha_index(idx: usize) -> String {
2150 let mut s = String::new();
2151 let mut n = idx + 1;
2152 while n > 0 {
2153 n -= 1;
2154 s.insert(0, (b'A' + (n % 26) as u8) as char);
2155 n /= 26;
2156 }
2157 s
2158}
2159
2160#[cfg(test)]
2161mod tests {
2162 use super::*;
2163 use std::collections::hash_map::DefaultHasher;
2164 use std::hash::{Hash, Hasher};
2165 use std::iter;
2166
2167 fn hash(ty: &Type) -> u64 {
2168 let mut state = DefaultHasher::new();
2169 ty.hash(&mut state);
2170 state.finish()
2171 }
2172
2173 #[test]
2174 fn error_type_equals_itself() {
2175 let nominal_over_error = || Type::Nominal {
2176 id: Symbol::from_parts("prelude", "Option"),
2177 params: vec![Type::Error],
2178 writable: false,
2179 };
2180
2181 assert_eq!(Type::Error, Type::Error);
2182 assert_eq!(nominal_over_error(), nominal_over_error());
2183 }
2184
2185 #[test]
2186 fn function_equality_ignores_param_names() {
2187 let named = Type::function(
2188 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2189 vec![],
2190 Box::new(Type::bool()),
2191 );
2192 let differently_named = Type::function(
2193 vec![FunctionParameter::named(Type::int(), Some("height".into()))],
2194 vec![],
2195 Box::new(Type::bool()),
2196 );
2197 let unnamed = Type::function(
2198 vec![FunctionParameter::new(Type::int())],
2199 vec![],
2200 Box::new(Type::bool()),
2201 );
2202
2203 assert_eq!(named, differently_named);
2204 assert_eq!(named, unnamed);
2205 }
2206
2207 #[test]
2208 fn equal_function_types_have_equal_hashes() {
2209 let named = Type::function(
2210 vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2211 vec![],
2212 Box::new(Type::bool()),
2213 );
2214 let unnamed = Type::function(
2215 vec![FunctionParameter::new(Type::int())],
2216 vec![],
2217 Box::new(Type::bool()),
2218 );
2219
2220 assert_eq!(hash(&named), hash(&unnamed));
2221 }
2222
2223 #[test]
2224 fn equal_type_variables_have_equal_hashes() {
2225 let named = Type::Var {
2226 id: TypeVarId::new(1),
2227 hint: Some("value".into()),
2228 };
2229 let unnamed = Type::Var {
2230 id: TypeVarId::new(1),
2231 hint: None,
2232 };
2233
2234 assert_eq!(hash(&named), hash(&unnamed));
2235 }
2236
2237 #[test]
2238 fn signature_queries_ignore_function_bound_types() {
2239 let variable = Type::Var {
2240 id: TypeVarId::new(1),
2241 hint: Some("value".into()),
2242 };
2243 let signature = Type::function(
2244 vec![FunctionParameter::new(Type::int())],
2245 vec![Bound {
2246 param_name: "T".into(),
2247 generic: variable.clone(),
2248 ty: Type::Tuple(vec![variable.clone(), Type::Error]),
2249 }],
2250 Box::new(Type::bool()),
2251 );
2252 let mut variables = Vec::new();
2253 signature.collect_unbound_variables(&mut variables);
2254
2255 assert!(!signature.contains_error());
2256 assert!(!signature.has_unbound_variables());
2257 assert!(!signature.contains_type(&variable));
2258 assert!(!signature.contains_type(&Type::Error));
2259 assert!(variables.is_empty());
2260 }
2261
2262 #[test]
2263 fn unbound_variables_preserve_occurrence_order_through_quantified_signatures() {
2264 let first = Type::Var {
2265 id: TypeVarId::new(1),
2266 hint: Some("first".into()),
2267 };
2268 let second = Type::Var {
2269 id: TypeVarId::new(2),
2270 hint: Some("second".into()),
2271 };
2272 let signature = Type::Forall {
2273 vars: vec!["T".into()],
2274 body: Box::new(Type::function(
2275 vec![
2276 FunctionParameter::new(Type::Tuple(vec![first.clone(), second.clone()])),
2277 FunctionParameter::new(unhinted_var(3)),
2278 ],
2279 vec![],
2280 Box::new(first),
2281 )),
2282 };
2283 let mut variables = Vec::new();
2284 signature.collect_unbound_variables(&mut variables);
2285
2286 assert_eq!(
2287 variables,
2288 vec![TypeVarId::new(1), TypeVarId::new(2), TypeVarId::new(1)],
2289 );
2290 assert!(signature.has_unbound_variables());
2291 assert!(signature.contains_type(&second));
2292 assert!(signature.contains_type(&signature));
2293 }
2294
2295 #[test]
2296 fn signature_queries_find_errors_in_nested_return_types() {
2297 let signature = Type::function(
2298 vec![FunctionParameter::new(Type::int())],
2299 vec![],
2300 Box::new(Type::Array {
2301 length: 1,
2302 element: Box::new(Type::Error),
2303 }),
2304 );
2305
2306 assert!(signature.contains_error());
2307 assert!(signature.contains_type(&Type::Error));
2308 }
2309
2310 #[test]
2311 fn alpha_index_single() {
2312 assert_eq!(alpha_index(0), "A");
2313 assert_eq!(alpha_index(5), "F");
2314 assert_eq!(alpha_index(25), "Z");
2315 }
2316
2317 #[test]
2318 fn alpha_index_double() {
2319 assert_eq!(alpha_index(26), "AA");
2320 assert_eq!(alpha_index(27), "AB");
2321 assert_eq!(alpha_index(51), "AZ");
2322 assert_eq!(alpha_index(52), "BA");
2323 assert_eq!(alpha_index(701), "ZZ");
2324 }
2325
2326 #[test]
2327 fn alpha_index_triple() {
2328 assert_eq!(alpha_index(702), "AAA");
2329 }
2330
2331 fn unhinted_var(id: u32) -> Type {
2332 Type::Var {
2333 id: TypeVarId::new(id),
2334 hint: None,
2335 }
2336 }
2337
2338 #[test]
2339 fn remove_vars_handles_more_than_six_unhinted_vars() {
2340 let func = Type::function(
2341 (0..6)
2342 .map(unhinted_var)
2343 .map(FunctionParameter::new)
2344 .collect(),
2345 vec![],
2346 Box::new(unhinted_var(6)),
2347 );
2348
2349 let (resolved, generics) = Type::remove_vars(&[&func]);
2350
2351 assert_eq!(generics.len(), 7);
2352 let Type::Function(f) = &resolved[0] else {
2353 panic!("expected function type");
2354 };
2355 let names: Vec<_> = f
2356 .params
2357 .iter()
2358 .map(|param| ¶m.ty)
2359 .chain(iter::once(f.return_type.as_ref()))
2360 .map(|p| match p {
2361 Type::Parameter(name) => name.to_string(),
2362 other => panic!("expected parameter, got {:?}", other),
2363 })
2364 .collect();
2365 assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
2366 }
2367
2368 #[test]
2369 fn remove_vars_handles_dozens_of_unhinted_vars() {
2370 let params: Vec<Type> = (0..30).map(unhinted_var).collect();
2371 let func = Type::function(
2372 params.iter().cloned().map(FunctionParameter::new).collect(),
2373 vec![],
2374 Box::new(Type::Simple(SimpleKind::Unit)),
2375 );
2376 let (_, generics) = Type::remove_vars(&[&func]);
2377 assert_eq!(generics.len(), 30);
2378 }
2379}