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