1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2use std::borrow::Borrow;
3use std::cell::OnceCell;
4use std::sync::Arc;
5
6use ecow::EcoString;
7
8use crate::ast::Generic;
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct Symbol(EcoString);
19
20impl Symbol {
21 pub fn from_parts(module: &str, local: &str) -> Self {
25 let mut s = EcoString::with_capacity(module.len() + 1 + local.len());
29 s.push_str(module);
30 s.push('.');
31 s.push_str(local);
32 Self(s)
33 }
34
35 pub fn with_segment(&self, segment: &str) -> Self {
40 let mut s = EcoString::with_capacity(self.0.len() + 1 + segment.len());
41 s.push_str(&self.0);
42 s.push('.');
43 s.push_str(segment);
44 Self(s)
45 }
46
47 pub fn from_raw(qualified: impl Into<EcoString>) -> Self {
50 Self(qualified.into())
51 }
52
53 pub fn as_str(&self) -> &str {
54 &self.0
55 }
56
57 pub fn as_eco(&self) -> &EcoString {
58 &self.0
59 }
60
61 pub fn last_segment(&self) -> &str {
63 self.0.rsplit('.').next().unwrap_or(&self.0)
64 }
65
66 pub fn without_last_segment(&self) -> Option<&str> {
69 self.0.rsplit_once('.').map(|(rest, _)| rest)
70 }
71}
72
73impl Borrow<str> for Symbol {
74 fn borrow(&self) -> &str {
75 &self.0
76 }
77}
78
79impl AsRef<str> for Symbol {
80 fn as_ref(&self) -> &str {
81 &self.0
82 }
83}
84
85impl std::ops::Deref for Symbol {
86 type Target = str;
87
88 fn deref(&self) -> &str {
89 &self.0
90 }
91}
92
93impl From<&Symbol> for EcoString {
94 fn from(s: &Symbol) -> Self {
95 s.0.clone()
96 }
97}
98
99impl std::fmt::Display for Symbol {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 self.0.fmt(f)
102 }
103}
104
105impl From<EcoString> for Symbol {
106 fn from(s: EcoString) -> Self {
107 Self(s)
108 }
109}
110
111impl From<Symbol> for EcoString {
112 fn from(s: Symbol) -> Self {
113 s.0
114 }
115}
116
117impl From<&str> for Symbol {
118 fn from(s: &str) -> Self {
119 Self(EcoString::from(s))
120 }
121}
122
123impl From<String> for Symbol {
124 fn from(s: String) -> Self {
125 Self(EcoString::from(s))
126 }
127}
128
129impl PartialEq<str> for Symbol {
130 fn eq(&self, other: &str) -> bool {
131 self.0.as_str() == other
132 }
133}
134
135impl PartialEq<&str> for Symbol {
136 fn eq(&self, other: &&str) -> bool {
137 self.0.as_str() == *other
138 }
139}
140
141pub fn unqualified_name(id: &str) -> &str {
145 id.rsplit('.').next().unwrap_or(id)
146}
147
148pub const GO_IMPORT_PREFIX: &str = "go:";
149
150pub fn module_for_qualified_name<'a, I>(id: &'a str, module_ids: I) -> Option<&'a str>
156where
157 I: IntoIterator<Item = &'a str>,
158{
159 if !id.starts_with(GO_IMPORT_PREFIX) || !id.contains('/') {
160 return id.split_once('.').map(|(m, _)| m);
161 }
162 let mut best: Option<&str> = None;
163 for module_id in module_ids {
164 if id.starts_with(module_id)
165 && id.as_bytes().get(module_id.len()) == Some(&b'.')
166 && best.is_none_or(|prev| module_id.len() > prev.len())
167 {
168 best = Some(module_id);
169 }
170 }
171 best
172}
173
174pub fn is_range_type_name(name: &str) -> bool {
175 matches!(
176 name,
177 "Range" | "RangeInclusive" | "RangeFrom" | "RangeTo" | "RangeToInclusive"
178 )
179}
180
181pub fn peel_to_range_type(ty: &Type) -> Option<&Type> {
182 std::iter::successors(Some(ty), |t| match t {
183 Type::Nominal {
184 underlying_ty: Some(u),
185 ..
186 } => Some(u.as_ref()),
187 _ => None,
188 })
189 .find(|t| t.get_name().is_some_and(is_range_type_name))
190}
191
192pub type SubstitutionMap = HashMap<EcoString, Type>;
194
195pub fn build_substitution_map(generics: &[Generic], type_args: &[Type]) -> SubstitutionMap {
198 generics
199 .iter()
200 .zip(type_args.iter())
201 .map(|(g, t)| (g.name.clone(), t.clone()))
202 .collect()
203}
204
205pub fn type_args_match_params<'a>(
206 args: &[Type],
207 params: impl ExactSizeIterator<Item = &'a EcoString>,
208) -> bool {
209 args.len() == params.len()
210 && args
211 .iter()
212 .zip(params)
213 .all(|(arg, param)| matches!(arg, Type::Parameter(name) if name == param))
214}
215
216pub fn substitute(ty: &Type, map: &HashMap<EcoString, Type>) -> Type {
217 if map.is_empty() {
218 return ty.clone();
219 }
220 match ty {
221 Type::Parameter(name) => map.get(name).cloned().unwrap_or_else(|| ty.clone()),
222 Type::Nominal {
223 id,
224 params,
225 underlying_ty: underlying,
226 } => Type::Nominal {
227 id: id.clone(),
228 params: params.iter().map(|p| substitute(p, map)).collect(),
229 underlying_ty: underlying.as_ref().map(|u| Box::new(substitute(u, map))),
230 },
231 Type::Function(f) => f.rebuild(
232 f.params.iter().map(|p| substitute(p, map)).collect(),
233 f.bounds
234 .iter()
235 .map(|b| Bound {
236 param_name: b.param_name.clone(),
237 generic: substitute(&b.generic, map),
238 ty: substitute(&b.ty, map),
239 })
240 .collect(),
241 Box::new(substitute(&f.return_type, map)),
242 ),
243 Type::Var { .. } | Type::Error => ty.clone(),
244 Type::Forall { vars, body } => {
245 let has_overlap = map.keys().any(|k| vars.contains(k));
246 let substituted_body = if has_overlap {
247 let filtered_map: HashMap<EcoString, Type> = map
248 .iter()
249 .filter(|(k, _)| !vars.contains(*k))
250 .map(|(k, v)| (k.clone(), v.clone()))
251 .collect();
252 substitute(body, &filtered_map)
253 } else {
254 substitute(body, map)
255 };
256 Type::Forall {
257 vars: vars.clone(),
258 body: Box::new(substituted_body),
259 }
260 }
261 Type::Tuple(elements) => Type::Tuple(elements.iter().map(|e| substitute(e, map)).collect()),
262 Type::Compound { kind, args } => Type::Compound {
263 kind: *kind,
264 args: args.iter().map(|a| substitute(a, map)).collect(),
265 },
266 Type::Simple(_) | Type::Never | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {
267 ty.clone()
268 }
269 }
270}
271
272#[derive(Debug, Clone, PartialEq)]
273#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
274pub struct Bound {
275 pub param_name: EcoString,
276 pub generic: Type,
277 pub ty: Type,
278}
279
280#[derive(Clone)]
281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
282pub struct FunctionType {
283 pub params: Vec<Type>,
284 #[cfg_attr(feature = "serde", serde(default))]
285 pub param_names: Vec<Option<EcoString>>,
286 pub param_mutability: Vec<bool>,
287 pub bounds: Vec<Bound>,
288 pub return_type: Box<Type>,
289}
290
291impl PartialEq for FunctionType {
292 fn eq(&self, other: &Self) -> bool {
293 self.params == other.params
294 && self.param_mutability == other.param_mutability
295 && self.bounds == other.bounds
296 && self.return_type == other.return_type
297 }
298}
299
300impl FunctionType {
301 pub fn remove_receiver(&mut self) -> Type {
302 let receiver = self.params.remove(0);
303 if !self.param_mutability.is_empty() {
304 self.param_mutability.remove(0);
305 }
306 if !self.param_names.is_empty() {
307 self.param_names.remove(0);
308 }
309 receiver
310 }
311
312 pub fn without_receiver(&self) -> Type {
313 let mut stripped = self.clone();
314 if !stripped.params.is_empty() {
315 stripped.remove_receiver();
316 }
317 Type::Function(Arc::new(stripped))
318 }
319
320 pub fn rebuild(&self, params: Vec<Type>, bounds: Vec<Bound>, return_type: Box<Type>) -> Type {
321 debug_assert!(
322 self.param_names.is_empty() || self.param_names.len() == params.len(),
323 "rebuild changed arity: param_names would misalign with params"
324 );
325 debug_assert!(
326 self.param_mutability.is_empty() || self.param_mutability.len() == params.len(),
327 "rebuild changed arity: param_mutability would misalign with params"
328 );
329 Type::function_with_names(
330 params,
331 self.param_names.clone(),
332 self.param_mutability.clone(),
333 bounds,
334 return_type,
335 )
336 }
337}
338
339#[derive(Clone, Copy, PartialEq, Eq, Hash)]
343#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
344pub struct TypeVarId(pub u32);
345
346impl TypeVarId {
347 pub const IGNORED: TypeVarId = TypeVarId(u32::MAX);
348 pub const UNINFERRED: TypeVarId = TypeVarId(u32::MAX - 1);
349
350 pub fn is_reserved(self) -> bool {
351 self == Self::IGNORED || self == Self::UNINFERRED
352 }
353
354 pub fn as_u32(self) -> u32 {
355 self.0
356 }
357}
358
359impl std::fmt::Debug for TypeVarId {
360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361 match *self {
362 Self::IGNORED => write!(f, "ignored"),
363 Self::UNINFERRED => write!(f, "uninferred"),
364 TypeVarId(n) => write!(f, "#{}", n),
365 }
366 }
367}
368
369#[derive(Clone)]
370#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
371pub enum Type {
372 Simple(SimpleKind),
373
374 Compound {
375 kind: CompoundKind,
376 args: Vec<Type>,
377 },
378
379 Nominal {
380 id: Symbol,
381 params: Vec<Type>,
382 underlying_ty: Option<Box<Type>>,
383 },
384
385 ImportNamespace(EcoString),
389
390 Function(Arc<FunctionType>),
391
392 Var {
396 id: TypeVarId,
397 hint: Option<EcoString>,
398 },
399
400 Forall {
401 vars: Vec<EcoString>,
402 body: Box<Type>,
403 },
404
405 Parameter(EcoString),
406
407 Never,
408
409 Tuple(Vec<Type>),
410
411 Error,
414
415 ReceiverPlaceholder,
420}
421
422impl std::fmt::Debug for Type {
423 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424 match self {
425 Type::Nominal { id, params, .. } => f
426 .debug_struct("Nominal")
427 .field("id", id)
428 .field("params", params)
429 .finish(),
430 Type::Function(f_ty) => {
431 let mut s = f.debug_struct("Function");
432 s.field("params", &f_ty.params);
433 if f_ty.param_mutability.iter().any(|m| *m) {
434 s.field("param_mutability", &f_ty.param_mutability);
435 }
436 s.field("bounds", &f_ty.bounds)
437 .field("return_type", &f_ty.return_type)
438 .finish()
439 }
440 Type::Var { id, hint } => {
441 let mut s = f.debug_struct("Var");
442 s.field("id", id);
443 if let Some(h) = hint {
444 s.field("hint", h);
445 }
446 s.finish()
447 }
448 Type::Forall { vars, body } => f
449 .debug_struct("Forall")
450 .field("vars", vars)
451 .field("body", body)
452 .finish(),
453 Type::Parameter(name) => f.debug_tuple("Parameter").field(name).finish(),
454 Type::Never => write!(f, "Never"),
455 Type::Tuple(elements) => f.debug_tuple("Tuple").field(elements).finish(),
456 Type::Error => write!(f, "Error"),
457 Type::ImportNamespace(module_id) => {
458 f.debug_tuple("ImportNamespace").field(module_id).finish()
459 }
460 Type::ReceiverPlaceholder => write!(f, "ReceiverPlaceholder"),
461 Type::Simple(kind) => f.debug_tuple("Simple").field(kind).finish(),
462 Type::Compound { kind, args } => f
463 .debug_struct("Compound")
464 .field("kind", kind)
465 .field("args", args)
466 .finish(),
467 }
468 }
469}
470
471impl PartialEq for Type {
472 fn eq(&self, other: &Self) -> bool {
473 match (self, other) {
474 (
475 Type::Nominal {
476 id: id1,
477 params: params1,
478 ..
479 },
480 Type::Nominal {
481 id: id2,
482 params: params2,
483 ..
484 },
485 ) => id1 == id2 && params1 == params2,
486 (Type::Function(f1), Type::Function(f2)) => f1 == f2,
487 (Type::Var { id: id1, .. }, Type::Var { id: id2, .. }) => id1 == id2,
488 (
489 Type::Forall {
490 vars: vars1,
491 body: body1,
492 },
493 Type::Forall {
494 vars: vars2,
495 body: body2,
496 },
497 ) => vars1 == vars2 && body1 == body2,
498 (Type::Parameter(name1), Type::Parameter(name2)) => name1 == name2,
499 (Type::Never, Type::Never) => true,
500 (Type::Tuple(elems1), Type::Tuple(elems2)) => elems1 == elems2,
501 (Type::ImportNamespace(m1), Type::ImportNamespace(m2)) => m1 == m2,
502 (Type::ReceiverPlaceholder, Type::ReceiverPlaceholder) => true,
503 (Type::Simple(k1), Type::Simple(k2)) => k1 == k2,
504 (Type::Compound { kind: k1, args: a1 }, Type::Compound { kind: k2, args: a2 }) => {
505 k1 == k2 && a1 == a2
506 }
507 _ => false,
508 }
509 }
510}
511
512thread_local! {
513 static INTERNED_INT: OnceCell<Type> = const { OnceCell::new() };
514 static INTERNED_STRING: OnceCell<Type> = const { OnceCell::new() };
515 static INTERNED_BOOL: OnceCell<Type> = const { OnceCell::new() };
516 static INTERNED_UNIT: OnceCell<Type> = const { OnceCell::new() };
517 static INTERNED_FLOAT64: OnceCell<Type> = const { OnceCell::new() };
518 static INTERNED_RUNE: OnceCell<Type> = const { OnceCell::new() };
519 static INTERNED_BYTE: OnceCell<Type> = const { OnceCell::new() };
520}
521
522impl Type {
523 pub fn simple(kind: SimpleKind) -> Type {
524 Self::Simple(kind)
525 }
526
527 pub fn compound(kind: CompoundKind, args: Vec<Type>) -> Type {
528 Self::Compound { kind, args }
529 }
530
531 pub fn function(
532 params: Vec<Type>,
533 param_mutability: Vec<bool>,
534 bounds: Vec<Bound>,
535 return_type: Box<Type>,
536 ) -> Type {
537 Self::function_with_names(params, Vec::new(), param_mutability, bounds, return_type)
538 }
539
540 pub fn function_with_names(
541 params: Vec<Type>,
542 param_names: Vec<Option<EcoString>>,
543 param_mutability: Vec<bool>,
544 bounds: Vec<Bound>,
545 return_type: Box<Type>,
546 ) -> Type {
547 Type::Function(Arc::new(FunctionType {
548 params,
549 param_names,
550 param_mutability,
551 bounds,
552 return_type,
553 }))
554 }
555
556 pub fn int() -> Type {
557 INTERNED_INT.with(|cell| cell.get_or_init(|| Self::simple(SimpleKind::Int)).clone())
558 }
559
560 pub fn string() -> Type {
561 INTERNED_STRING.with(|cell| {
562 cell.get_or_init(|| Self::simple(SimpleKind::String))
563 .clone()
564 })
565 }
566
567 pub fn bool() -> Type {
568 INTERNED_BOOL.with(|cell| cell.get_or_init(|| Self::simple(SimpleKind::Bool)).clone())
569 }
570
571 pub fn unit() -> Type {
572 INTERNED_UNIT.with(|cell| cell.get_or_init(|| Self::simple(SimpleKind::Unit)).clone())
573 }
574
575 pub fn float64() -> Type {
576 INTERNED_FLOAT64.with(|cell| {
577 cell.get_or_init(|| Self::simple(SimpleKind::Float64))
578 .clone()
579 })
580 }
581
582 pub fn rune() -> Type {
583 INTERNED_RUNE.with(|cell| cell.get_or_init(|| Self::simple(SimpleKind::Rune)).clone())
584 }
585
586 pub fn byte() -> Type {
587 INTERNED_BYTE.with(|cell| cell.get_or_init(|| Self::simple(SimpleKind::Byte)).clone())
588 }
589}
590
591impl Type {
592 pub fn uninferred() -> Self {
593 Self::Var {
594 id: TypeVarId::UNINFERRED,
595 hint: None,
596 }
597 }
598
599 pub fn is_uninferred(&self) -> bool {
600 matches!(
601 self,
602 Self::Var {
603 id: TypeVarId::UNINFERRED,
604 ..
605 }
606 )
607 }
608
609 pub fn ignored() -> Self {
610 Self::Var {
611 id: TypeVarId::IGNORED,
612 hint: None,
613 }
614 }
615
616 pub fn get_type_params(&self) -> Option<&[Type]> {
617 match self {
618 Type::Nominal { params, .. } => Some(params),
619 Type::Compound { args, .. } => Some(args),
620 _ => None,
621 }
622 }
623
624 pub fn children(&self) -> Vec<&Type> {
626 match self {
627 Type::Nominal {
628 params,
629 underlying_ty,
630 ..
631 } => {
632 let mut c: Vec<&Type> = params.iter().collect();
633 if let Some(u) = underlying_ty {
634 c.push(u);
635 }
636 c
637 }
638 Type::Compound { args, .. } => args.iter().collect(),
639 Type::Function(f) => {
640 let mut c: Vec<&Type> = f.params.iter().collect();
641 c.push(&f.return_type);
642 c
643 }
644 Type::Tuple(elements) => elements.iter().collect(),
645 Type::Forall { body, .. } => vec![body],
646 _ => vec![],
647 }
648 }
649}
650
651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
652pub enum NumericFamily {
653 SignedInt,
654 UnsignedInt,
655 Float,
656}
657
658#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
659#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
660pub enum CompoundKind {
661 Ref,
662 Slice,
663 EnumeratedSlice,
664 Map,
665 Channel,
666 Sender,
667 Receiver,
668 VarArgs,
669}
670
671impl CompoundKind {
672 pub fn leaf_name(self) -> &'static str {
673 match self {
674 CompoundKind::Ref => "Ref",
675 CompoundKind::Slice => "Slice",
676 CompoundKind::EnumeratedSlice => "EnumeratedSlice",
677 CompoundKind::Map => "Map",
678 CompoundKind::Channel => "Channel",
679 CompoundKind::Sender => "Sender",
680 CompoundKind::Receiver => "Receiver",
681 CompoundKind::VarArgs => "VarArgs",
682 }
683 }
684
685 pub fn from_name(name: &str) -> Option<CompoundKind> {
686 Some(match name {
687 "Ref" => CompoundKind::Ref,
688 "Slice" => CompoundKind::Slice,
689 "EnumeratedSlice" => CompoundKind::EnumeratedSlice,
690 "Map" => CompoundKind::Map,
691 "Channel" => CompoundKind::Channel,
692 "Sender" => CompoundKind::Sender,
693 "Receiver" => CompoundKind::Receiver,
694 "VarArgs" => CompoundKind::VarArgs,
695 _ => return None,
696 })
697 }
698
699 pub fn from_qualified_id(id: &str) -> Option<CompoundKind> {
700 Self::from_name(id.strip_prefix("prelude.")?)
701 }
702}
703
704#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
705#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
706pub enum SimpleKind {
707 Int,
708 Int8,
709 Int16,
710 Int32,
711 Int64,
712 Uint,
713 Uint8,
714 Uint16,
715 Uint32,
716 Uint64,
717 Uintptr,
718 Byte,
719 Float32,
720 Float64,
721 Complex64,
722 Complex128,
723 Rune,
724 Bool,
725 String,
726 Unit,
727}
728
729impl SimpleKind {
730 pub fn leaf_name(self) -> &'static str {
731 match self {
732 SimpleKind::Int => "int",
733 SimpleKind::Int8 => "int8",
734 SimpleKind::Int16 => "int16",
735 SimpleKind::Int32 => "int32",
736 SimpleKind::Int64 => "int64",
737 SimpleKind::Uint => "uint",
738 SimpleKind::Uint8 => "uint8",
739 SimpleKind::Uint16 => "uint16",
740 SimpleKind::Uint32 => "uint32",
741 SimpleKind::Uint64 => "uint64",
742 SimpleKind::Uintptr => "uintptr",
743 SimpleKind::Byte => "byte",
744 SimpleKind::Float32 => "float32",
745 SimpleKind::Float64 => "float64",
746 SimpleKind::Complex64 => "complex64",
747 SimpleKind::Complex128 => "complex128",
748 SimpleKind::Rune => "rune",
749 SimpleKind::Bool => "bool",
750 SimpleKind::String => "string",
751 SimpleKind::Unit => "Unit",
752 }
753 }
754
755 pub fn from_name(name: &str) -> Option<SimpleKind> {
756 Some(match name {
757 "int" => SimpleKind::Int,
758 "int8" => SimpleKind::Int8,
759 "int16" => SimpleKind::Int16,
760 "int32" => SimpleKind::Int32,
761 "int64" => SimpleKind::Int64,
762 "uint" => SimpleKind::Uint,
763 "uint8" => SimpleKind::Uint8,
764 "uint16" => SimpleKind::Uint16,
765 "uint32" => SimpleKind::Uint32,
766 "uint64" => SimpleKind::Uint64,
767 "uintptr" => SimpleKind::Uintptr,
768 "byte" => SimpleKind::Byte,
769 "float32" => SimpleKind::Float32,
770 "float64" => SimpleKind::Float64,
771 "complex64" => SimpleKind::Complex64,
772 "complex128" => SimpleKind::Complex128,
773 "rune" => SimpleKind::Rune,
774 "bool" => SimpleKind::Bool,
775 "string" => SimpleKind::String,
776 "Unit" => SimpleKind::Unit,
777 _ => return None,
778 })
779 }
780
781 pub fn is_arithmetic(self) -> bool {
782 !matches!(
783 self,
784 SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit | SimpleKind::Uintptr
785 )
786 }
787
788 pub fn is_ordered(self) -> bool {
789 self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
790 }
791
792 pub fn integer_range(self) -> Option<(i128, i128)> {
793 use SimpleKind::*;
794 Some(match self {
795 Int8 => (i8::MIN as i128, i8::MAX as i128),
796 Int16 => (i16::MIN as i128, i16::MAX as i128),
797 Int32 | Rune => (i32::MIN as i128, i32::MAX as i128),
798 Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
799 Uint8 | Byte => (0, u8::MAX as i128),
800 Uint16 => (0, u16::MAX as i128),
801 Uint32 => (0, u32::MAX as i128),
802 Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
803 _ => return None,
804 })
805 }
806
807 pub fn is_unsigned_int(self) -> bool {
808 matches!(
809 self,
810 SimpleKind::Byte
811 | SimpleKind::Uint
812 | SimpleKind::Uint8
813 | SimpleKind::Uint16
814 | SimpleKind::Uint32
815 | SimpleKind::Uint64
816 )
817 }
818
819 pub fn is_signed_int(self) -> bool {
820 matches!(
821 self,
822 SimpleKind::Int
823 | SimpleKind::Int8
824 | SimpleKind::Int16
825 | SimpleKind::Int32
826 | SimpleKind::Int64
827 | SimpleKind::Rune
828 )
829 }
830
831 pub fn is_float(self) -> bool {
832 matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
833 }
834
835 pub fn is_complex(self) -> bool {
836 matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
837 }
838
839 pub fn numeric_family(self) -> Option<NumericFamily> {
840 if self.is_signed_int() {
841 Some(NumericFamily::SignedInt)
842 } else if self.is_unsigned_int() {
843 Some(NumericFamily::UnsignedInt)
844 } else if self.is_float() {
845 Some(NumericFamily::Float)
846 } else {
847 None
848 }
849 }
850}
851
852impl Type {
853 pub fn get_function_ret(&self) -> Option<&Type> {
854 match self {
855 Type::Function(f) => Some(&f.return_type),
856 _ => None,
857 }
858 }
859
860 pub fn is_stringer_signature(&self) -> bool {
861 let func = match self {
862 Type::Forall { body, .. } => body.as_ref(),
863 other => other,
864 };
865 matches!(
866 func,
867 Type::Function(f)
868 if f.params.len() == 1
869 && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::String))
870 )
871 }
872
873 pub fn is_equals_signature(&self) -> bool {
874 let func = match self {
875 Type::Forall { body, .. } => body.as_ref(),
876 other => other,
877 };
878 matches!(
879 func,
880 Type::Function(f)
881 if f.params.len() == 2
882 && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::Bool))
883 && f.params[0] == f.params[1]
884 && !f.params[0].is_ref()
885 )
886 }
887
888 pub fn equals_receiver_vars(&self, owner_id: &str, arity: usize) -> Option<Vec<EcoString>> {
889 if !self.is_equals_signature() {
890 return None;
891 }
892 let (quantified, func): (&[EcoString], &Type) = match self {
893 Type::Forall { vars, body } => (vars, body.as_ref()),
894 other => (&[], other),
895 };
896 if quantified.len() != arity {
897 return None;
898 }
899 let Type::Function(f) = func else {
900 return None;
901 };
902 let Type::Nominal { id, params, .. } = &f.params[0] else {
903 return None;
904 };
905 if id.as_str() != owner_id || params.len() != arity {
906 return None;
907 }
908 let mut vars = Vec::with_capacity(arity);
909 for param in params {
910 let Type::Parameter(name) = param else {
911 return None;
912 };
913 if vars.contains(name) {
914 return None;
915 }
916 vars.push(name.clone());
917 }
918 if !quantified.iter().all(|v| vars.contains(v)) {
919 return None;
920 }
921 Some(vars)
922 }
923
924 pub fn has_name(&self, name: &str) -> bool {
925 match self {
926 Type::Nominal { id, .. } => id.last_segment() == name,
927 Type::Simple(kind) => kind.leaf_name() == name,
928 Type::Compound { kind, .. } => kind.leaf_name() == name,
929 _ => false,
930 }
931 }
932
933 pub fn get_qualified_id(&self) -> Option<&str> {
934 match self {
935 Type::Nominal { id, .. } => Some(id.as_str()),
936 _ => None,
937 }
938 }
939
940 pub fn get_underlying(&self) -> Option<&Type> {
941 match self {
942 Type::Nominal {
943 underlying_ty: underlying,
944 ..
945 } => underlying.as_deref(),
946 _ => None,
947 }
948 }
949
950 pub fn is_result(&self) -> bool {
951 self.has_qualified_id("prelude.Result")
952 }
953
954 pub fn is_option(&self) -> bool {
955 self.has_qualified_id("prelude.Option")
956 }
957
958 pub fn is_partial(&self) -> bool {
959 self.has_qualified_id("prelude.Partial")
960 }
961
962 fn has_qualified_id(&self, qualified_id: &str) -> bool {
963 matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
964 }
965
966 pub fn is_unit(&self) -> bool {
967 self.is_simple(SimpleKind::Unit)
968 }
969
970 pub fn tuple_arity(&self) -> Option<usize> {
971 match self {
972 Type::Tuple(elements) => Some(elements.len()),
973 _ => None,
974 }
975 }
976
977 pub fn is_tuple(&self) -> bool {
978 matches!(self, Type::Tuple(_))
979 }
980
981 pub fn as_import_namespace(&self) -> Option<&str> {
982 match self {
983 Type::ImportNamespace(module_id) => Some(module_id),
984 _ => None,
985 }
986 }
987
988 pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
989 match self {
990 Type::Compound { kind, args } => Some((*kind, args.as_slice())),
991 Type::Nominal { id, params, .. } => {
992 CompoundKind::from_qualified_id(id.as_str()).map(|k| (k, params.as_slice()))
993 }
994 _ => None,
995 }
996 }
997
998 pub fn is_native(&self, kind: CompoundKind) -> bool {
999 self.as_compound().is_some_and(|(k, _)| k == kind)
1000 }
1001
1002 pub fn is_ref(&self) -> bool {
1003 self.is_native(CompoundKind::Ref)
1004 }
1005
1006 pub fn is_slice(&self) -> bool {
1007 self.is_native(CompoundKind::Slice)
1008 }
1009
1010 pub fn is_map(&self) -> bool {
1011 self.is_native(CompoundKind::Map)
1012 }
1013
1014 pub fn is_channel(&self) -> bool {
1015 self.is_native(CompoundKind::Channel)
1016 }
1017
1018 pub fn is_receiver_placeholder(&self) -> bool {
1019 matches!(self, Type::ReceiverPlaceholder)
1020 }
1021
1022 pub fn is_unknown(&self) -> bool {
1023 self.has_name("Unknown")
1024 }
1025
1026 pub fn resolves_to_unknown(&self) -> bool {
1027 peel_alias(self, |_| true).is_unknown()
1028 }
1029
1030 pub fn contains_unknown(&self) -> bool {
1031 let peeled = peel_alias(self, |_| true);
1032 if peeled.is_unknown() {
1033 return true;
1034 }
1035 match &peeled {
1036 Type::Compound { args, .. } => args.iter().any(|a| a.contains_unknown()),
1037 Type::Function(f) => {
1038 f.params.iter().any(|p| p.contains_unknown()) || f.return_type.contains_unknown()
1039 }
1040 Type::Tuple(elements) => elements.iter().any(|e| e.contains_unknown()),
1041 Type::Nominal { params, .. } => params.iter().any(|p| p.contains_unknown()),
1042 Type::Forall { body, .. } => body.contains_unknown(),
1043 _ => false,
1044 }
1045 }
1046
1047 pub fn is_receiver(&self) -> bool {
1048 self.is_native(CompoundKind::Receiver)
1049 }
1050
1051 pub fn is_ignored(&self) -> bool {
1052 matches!(self, Type::Var { id, .. } if *id == TypeVarId::IGNORED)
1053 }
1054
1055 pub fn is_variadic(&self) -> Option<Type> {
1056 let last = self.get_function_params()?.last()?;
1057 match last.as_compound()? {
1058 (CompoundKind::VarArgs, _) => last.inner(),
1059 _ => None,
1060 }
1061 }
1062
1063 pub fn is_string(&self) -> bool {
1064 self.is_simple(SimpleKind::String)
1065 }
1066
1067 pub fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
1068 match self.as_compound() {
1069 Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
1070 _ => false,
1071 }
1072 }
1073
1074 pub fn is_slice_of(&self, element_name: &str) -> bool {
1075 match self.as_compound() {
1076 Some((CompoundKind::Slice, [elem])) => elem.has_name(element_name),
1077 _ => false,
1078 }
1079 }
1080
1081 pub fn is_byte_slice(&self) -> bool {
1082 self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
1083 }
1084
1085 pub fn is_rune_slice(&self) -> bool {
1086 self.is_slice_of_simple(SimpleKind::Rune)
1087 }
1088
1089 pub fn is_byte_or_rune_slice(&self) -> bool {
1090 self.is_byte_slice() || self.is_rune_slice()
1091 }
1092
1093 pub fn has_underlying_rune(&self) -> bool {
1094 self.underlying_numeric_type().is_some_and(|t| t.is_rune())
1095 }
1096
1097 pub fn has_underlying_byte(&self) -> bool {
1098 self.underlying_numeric_type()
1099 .is_some_and(|t| t.is_simple(SimpleKind::Byte) || t.is_simple(SimpleKind::Uint8))
1100 }
1101
1102 pub fn has_byte_or_rune_slice_underlying(&self) -> bool {
1103 if self.is_byte_or_rune_slice() {
1104 return true;
1105 }
1106 match self {
1107 Type::Nominal { underlying_ty, .. } => underlying_ty
1108 .as_deref()
1109 .is_some_and(|u| u.has_byte_or_rune_slice_underlying()),
1110 _ => false,
1111 }
1112 }
1113
1114 pub fn as_simple(&self) -> Option<SimpleKind> {
1115 match self {
1116 Type::Simple(kind) => Some(*kind),
1117 Type::Nominal { id, .. } => SimpleKind::from_name(id.last_segment()),
1118 _ => None,
1119 }
1120 }
1121
1122 pub fn is_simple(&self, kind: SimpleKind) -> bool {
1123 self.as_simple() == Some(kind)
1124 }
1125
1126 pub fn is_boolean(&self) -> bool {
1127 self.is_simple(SimpleKind::Bool)
1128 }
1129
1130 pub fn is_rune(&self) -> bool {
1131 self.is_simple(SimpleKind::Rune)
1132 }
1133
1134 pub fn is_float64(&self) -> bool {
1135 self.is_simple(SimpleKind::Float64)
1136 }
1137
1138 pub fn is_float32(&self) -> bool {
1139 self.is_simple(SimpleKind::Float32)
1140 }
1141
1142 pub fn is_float(&self) -> bool {
1143 self.as_simple().is_some_and(SimpleKind::is_float)
1144 }
1145
1146 pub fn is_variable(&self) -> bool {
1147 matches!(self, Type::Var { .. })
1148 }
1149
1150 pub fn is_type_var(&self) -> bool {
1151 matches!(self, Type::Var { .. })
1152 }
1153
1154 pub fn is_numeric(&self) -> bool {
1155 self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1156 }
1157
1158 pub fn is_ordered(&self) -> bool {
1159 self.as_simple().is_some_and(SimpleKind::is_ordered)
1160 }
1161
1162 pub fn is_orderable(&self) -> bool {
1165 matches!(
1166 self.underlying_simple_kind(),
1167 Some(kind) if kind.is_ordered() || kind == SimpleKind::String
1168 ) || self.is_boolean()
1169 }
1170
1171 pub fn satisfies_ordered_constraint(&self) -> bool {
1173 if let Some(kind) = self.as_simple() {
1174 return matches!(
1175 kind,
1176 SimpleKind::Int
1177 | SimpleKind::Int8
1178 | SimpleKind::Int16
1179 | SimpleKind::Int32
1180 | SimpleKind::Int64
1181 | SimpleKind::Uint
1182 | SimpleKind::Uint8
1183 | SimpleKind::Uint16
1184 | SimpleKind::Uint32
1185 | SimpleKind::Uint64
1186 | SimpleKind::Uintptr
1187 | SimpleKind::Byte
1188 | SimpleKind::Rune
1189 | SimpleKind::Float32
1190 | SimpleKind::Float64
1191 | SimpleKind::String
1192 );
1193 }
1194 match self {
1195 Type::Nominal { underlying_ty, .. } => underlying_ty
1196 .as_deref()
1197 .is_some_and(Type::satisfies_ordered_constraint),
1198 Type::Parameter(_) => true,
1199 _ => false,
1200 }
1201 }
1202
1203 pub fn is_complex(&self) -> bool {
1204 self.as_simple().is_some_and(SimpleKind::is_complex)
1205 }
1206
1207 pub fn is_unsigned_int(&self) -> bool {
1208 self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1209 }
1210
1211 pub fn underlying_is_unsigned_int(&self) -> bool {
1212 self.underlying_simple_kind()
1213 .is_some_and(SimpleKind::is_unsigned_int)
1214 }
1215
1216 pub fn is_never(&self) -> bool {
1217 matches!(self, Type::Never)
1218 }
1219
1220 pub fn is_error(&self) -> bool {
1221 matches!(self, Type::Error)
1222 }
1223
1224 pub fn contains_error(&self) -> bool {
1225 match self {
1226 Type::Error => true,
1227 Type::Nominal {
1228 params,
1229 underlying_ty,
1230 ..
1231 } => {
1232 params.iter().any(Type::contains_error)
1233 || underlying_ty.as_deref().is_some_and(Type::contains_error)
1234 }
1235 Type::Compound { args, .. } => args.iter().any(Type::contains_error),
1236 Type::Function(f) => {
1237 f.params.iter().any(Type::contains_error) || f.return_type.contains_error()
1238 }
1239 Type::Tuple(elements) => elements.iter().any(Type::contains_error),
1240 Type::Forall { body, .. } => body.contains_error(),
1241 _ => false,
1242 }
1243 }
1244
1245 pub fn has_unbound_variables(&self) -> bool {
1246 match self {
1247 Type::Var { hint, .. } => hint.is_some(),
1248 Type::Nominal { params, .. } => params.iter().any(|p| p.has_unbound_variables()),
1249 Type::Function(f) => {
1250 f.params.iter().any(|p| p.has_unbound_variables())
1251 || f.return_type.has_unbound_variables()
1252 }
1253 Type::Forall { body, .. } => body.has_unbound_variables(),
1254 Type::Tuple(elements) => elements.iter().any(|e| e.has_unbound_variables()),
1255 Type::Compound { args, .. } => args.iter().any(|a| a.has_unbound_variables()),
1256 Type::Simple(_)
1257 | Type::Parameter(_)
1258 | Type::Never
1259 | Type::Error
1260 | Type::ImportNamespace(_)
1261 | Type::ReceiverPlaceholder => false,
1262 }
1263 }
1264
1265 pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1266 if names.is_empty() {
1267 return;
1268 }
1269
1270 match self {
1271 Type::Nominal { id, params, .. } => {
1272 names.remove(id.last_segment());
1273 for param in params {
1274 param.remove_found_type_names(names);
1275 }
1276 }
1277 Type::Function(f) => {
1278 for param in &f.params {
1279 param.remove_found_type_names(names);
1280 }
1281 f.return_type.remove_found_type_names(names);
1282 for bound in &f.bounds {
1283 bound.generic.remove_found_type_names(names);
1284 bound.ty.remove_found_type_names(names);
1285 }
1286 }
1287 Type::Forall { body, .. } => {
1288 body.remove_found_type_names(names);
1289 }
1290 Type::Var { .. } => {}
1291 Type::Parameter(name) => {
1292 names.remove(name);
1293 }
1294 Type::Tuple(elements) => {
1295 for element in elements {
1296 element.remove_found_type_names(names);
1297 }
1298 }
1299 Type::Compound { kind, args } => {
1300 names.remove(kind.leaf_name());
1301 for arg in args {
1302 arg.remove_found_type_names(names);
1303 }
1304 }
1305 Type::Simple(kind) => {
1306 names.remove(kind.leaf_name());
1307 }
1308 Type::Never | Type::Error | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {}
1309 }
1310 }
1311}
1312
1313impl Type {
1314 pub fn get_name(&self) -> Option<&str> {
1315 match self {
1316 Type::Simple(kind) => Some(kind.leaf_name()),
1317 Type::Compound { kind, args } => match kind {
1318 CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1319 _ => Some(kind.leaf_name()),
1320 },
1321 Type::Nominal { id, params, .. } => {
1322 if CompoundKind::from_qualified_id(id.as_str()) == Some(CompoundKind::Ref) {
1323 return params.first().and_then(|inner| inner.get_name());
1324 }
1325 Some(id.last_segment())
1326 }
1327 Type::ImportNamespace(module_id) => {
1328 let path = module_id.strip_prefix("go:").unwrap_or(module_id);
1329 path.rsplit('/').next()
1330 }
1331 _ => None,
1332 }
1333 }
1334
1335 pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1336 self.get_name().is_some_and(|n| n == name)
1337 && self
1338 .get_type_params()
1339 .and_then(|p| p.first())
1340 .is_some_and(|first| *first == *inner)
1341 }
1342
1343 pub fn get_function_params(&self) -> Option<&[Type]> {
1344 match self {
1345 Type::Function(f) => Some(&f.params),
1346 Type::Nominal {
1347 underlying_ty: Some(inner),
1348 ..
1349 } => inner.get_function_params(),
1350 _ => None,
1351 }
1352 }
1353
1354 pub fn param_count(&self) -> usize {
1355 match self {
1356 Type::Function(f) => f.params.len(),
1357 _ => 0,
1358 }
1359 }
1360
1361 pub fn get_param_mutability(&self) -> &[bool] {
1362 match self {
1363 Type::Function(f) => &f.param_mutability,
1364 _ => &[],
1365 }
1366 }
1367
1368 pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1369 match self {
1370 Type::Function(f) => {
1371 if f.params.is_empty() {
1372 return self.clone();
1373 }
1374 let mut new_params = f.params.clone();
1375 new_params[0] = new_first.clone();
1376 f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1377 }
1378 Type::Forall { vars, body } => Type::Forall {
1379 vars: vars.clone(),
1380 body: Box::new(body.with_replaced_first_param(new_first)),
1381 },
1382 _ => self.clone(),
1383 }
1384 }
1385
1386 pub fn get_bounds(&self) -> &[Bound] {
1387 match self {
1388 Type::Function(f) => &f.bounds,
1389 Type::Forall { body, .. } => body.get_bounds(),
1390 _ => &[],
1391 }
1392 }
1393
1394 pub fn get_qualified_name(&self) -> Symbol {
1395 match self.strip_refs() {
1396 Type::Nominal { id, .. } => id,
1397 Type::Simple(kind) => Symbol::from_parts("prelude", kind.leaf_name()),
1398 Type::Compound { kind, .. } => Symbol::from_parts("prelude", kind.leaf_name()),
1399 _ => panic!("called get_qualified_name on {:#?}", self),
1400 }
1401 }
1402
1403 pub fn inner(&self) -> Option<Type> {
1404 self.get_type_params()
1405 .and_then(|args| args.first().cloned())
1406 }
1407
1408 pub fn ok_type(&self) -> Type {
1409 debug_assert!(
1410 self.is_result() || self.is_option() || self.is_partial(),
1411 "ok_type called on non-Result/Option/Partial type"
1412 );
1413 self.inner()
1414 .expect("Result/Option/Partial should have inner type")
1415 }
1416
1417 pub fn err_type(&self) -> Type {
1418 debug_assert!(
1419 self.is_result() || self.is_partial(),
1420 "err_type called on non-Result/Partial type"
1421 );
1422 self.get_type_params()
1423 .and_then(|args| args.get(1).cloned())
1424 .expect("Result/Partial should have error type")
1425 }
1426}
1427
1428pub fn peel_alias<F>(ty: &Type, is_alias: F) -> Type
1431where
1432 F: Fn(&str) -> bool,
1433{
1434 let mut current = ty.unwrap_forall().clone();
1435 let mut seen: Vec<String> = Vec::new();
1436 while let Type::Nominal {
1437 id,
1438 underlying_ty: Some(u),
1439 ..
1440 } = ¤t
1441 {
1442 if !is_alias(id.as_str()) {
1443 break;
1444 }
1445 if seen.iter().any(|s| s == id.as_str()) {
1446 break;
1447 }
1448 seen.push(id.to_string());
1449 current = u.unwrap_forall().clone();
1450 }
1451 current
1452}
1453
1454pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
1457where
1458 F: Fn(&str) -> Option<String>,
1459{
1460 let mut current = id.to_string();
1461 let mut seen: Vec<String> = Vec::new();
1462 loop {
1463 if seen.iter().any(|s| s == ¤t) {
1464 return current;
1465 }
1466 let Some(next) = next_alias(¤t) else {
1467 return current;
1468 };
1469 seen.push(current);
1470 current = next;
1471 }
1472}
1473
1474impl Type {
1475 pub fn unwrap_forall(&self) -> &Type {
1476 match self {
1477 Type::Forall { body, .. } => body.as_ref(),
1478 other => other,
1479 }
1480 }
1481
1482 pub fn strip_refs(&self) -> Type {
1483 if self.is_ref() {
1484 return self.inner().expect("ref type must have inner").strip_refs();
1485 }
1486
1487 self.clone()
1488 }
1489
1490 pub fn with_receiver_placeholder(self) -> Type {
1491 match self {
1492 Type::Function(f) => {
1493 let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
1494 let mut new_params = vec![Type::ReceiverPlaceholder];
1495 new_params.extend(f.params);
1496
1497 let mut new_mutability = vec![false];
1498 new_mutability.extend(f.param_mutability);
1499
1500 let new_param_names = if f.param_names.is_empty() {
1501 Vec::new()
1502 } else {
1503 let mut names = vec![None];
1504 names.extend(f.param_names);
1505 names
1506 };
1507
1508 Type::function_with_names(
1509 new_params,
1510 new_param_names,
1511 new_mutability,
1512 f.bounds,
1513 f.return_type,
1514 )
1515 }
1516 _ => unreachable!(
1517 "with_receiver_placeholder called on non-function type: {:?}",
1518 self
1519 ),
1520 }
1521 }
1522
1523 pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
1524 let mut vars = HashMap::default();
1525 let types = types
1526 .iter()
1527 .map(|v| Self::remove_vars_impl(v, &mut vars))
1528 .collect();
1529
1530 (types, vars.into_values().collect())
1531 }
1532
1533 fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
1534 match ty {
1535 Type::Nominal {
1536 id: name,
1537 params: args,
1538 underlying_ty: underlying,
1539 } => Type::Nominal {
1540 id: name.clone(),
1541 params: args
1542 .iter()
1543 .map(|a| Self::remove_vars_impl(a, vars))
1544 .collect(),
1545 underlying_ty: underlying
1546 .as_ref()
1547 .map(|u| Box::new(Self::remove_vars_impl(u, vars))),
1548 },
1549
1550 Type::Function(f) => Type::function(
1551 f.params
1552 .iter()
1553 .map(|a| Self::remove_vars_impl(a, vars))
1554 .collect(),
1555 f.param_mutability.clone(),
1556 f.bounds
1557 .iter()
1558 .map(|b| Bound {
1559 param_name: b.param_name.clone(),
1560 generic: Self::remove_vars_impl(&b.generic, vars),
1561 ty: Self::remove_vars_impl(&b.ty, vars),
1562 })
1563 .collect(),
1564 Self::remove_vars_impl(&f.return_type, vars).into(),
1565 ),
1566
1567 Type::Var { id, hint } => match vars.get(&id.0) {
1568 Some(g) => Type::Parameter(g.clone()),
1569 None => {
1570 let name: EcoString = hint
1571 .clone()
1572 .unwrap_or_else(|| alpha_index(vars.len()).into());
1573
1574 vars.insert(id.0, name.clone());
1575 Type::Parameter(name)
1576 }
1577 },
1578
1579 Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
1580 Type::Tuple(elements) => Type::Tuple(
1581 elements
1582 .iter()
1583 .map(|e| Self::remove_vars_impl(e, vars))
1584 .collect(),
1585 ),
1586 Type::Compound { kind, args } => Type::Compound {
1587 kind: *kind,
1588 args: args
1589 .iter()
1590 .map(|a| Self::remove_vars_impl(a, vars))
1591 .collect(),
1592 },
1593 Type::Simple(_) | Type::Parameter(_) => ty.clone(),
1594 Type::Never | Type::Error | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {
1595 ty.clone()
1596 }
1597 }
1598 }
1599
1600 pub fn contains_type(&self, target: &Type) -> bool {
1601 if *self == *target {
1602 return true;
1603 }
1604 match self {
1605 Type::Nominal { params, .. } => params.iter().any(|p| p.contains_type(target)),
1606 Type::Function(f) => {
1607 f.params.iter().any(|p| p.contains_type(target))
1608 || f.return_type.contains_type(target)
1609 }
1610 Type::Var { .. } => false,
1611 Type::Forall { body, .. } => body.contains_type(target),
1612 Type::Tuple(elements) => elements.iter().any(|e| e.contains_type(target)),
1613 Type::Compound { args, .. } => args.iter().any(|a| a.contains_type(target)),
1614 Type::Simple(_)
1615 | Type::Parameter(_)
1616 | Type::Never
1617 | Type::Error
1618 | Type::ImportNamespace(_)
1619 | Type::ReceiverPlaceholder => false,
1620 }
1621 }
1622}
1623
1624impl Type {
1625 pub fn underlying_numeric_type(&self) -> Option<Type> {
1626 self.underlying_numeric_type_recursive(&mut HashSet::default())
1627 }
1628
1629 pub fn has_underlying_numeric_type(&self) -> bool {
1630 self.underlying_numeric_type().is_some()
1631 }
1632
1633 pub fn literal_adaptation_target(&self) -> Option<Type> {
1634 if let Some(numeric) = self.underlying_numeric_type() {
1635 return Some(numeric);
1636 }
1637 match self {
1638 Type::Nominal { .. } if self.underlying_simple_kind() == Some(SimpleKind::Uintptr) => {
1639 Some(Type::Simple(SimpleKind::Uintptr))
1640 }
1641 _ => None,
1642 }
1643 }
1644
1645 pub fn underlying_simple_kind(&self) -> Option<SimpleKind> {
1646 self.underlying_simple_kind_recursive(&mut HashSet::default())
1647 }
1648
1649 fn underlying_simple_kind_recursive(
1650 &self,
1651 visited: &mut HashSet<Symbol>,
1652 ) -> Option<SimpleKind> {
1653 if let Some(kind) = self.as_simple() {
1654 return Some(kind);
1655 }
1656 match self {
1657 Type::Nominal {
1658 id,
1659 underlying_ty: Some(underlying),
1660 ..
1661 } => {
1662 if !visited.insert(id.clone()) {
1663 return None;
1664 }
1665 underlying.underlying_simple_kind_recursive(visited)
1666 }
1667 _ => None,
1668 }
1669 }
1670
1671 fn underlying_numeric_type_recursive(&self, visited: &mut HashSet<Symbol>) -> Option<Type> {
1672 match self {
1673 Type::Simple(_) if self.is_numeric() => Some(self.clone()),
1674 Type::Nominal {
1675 id,
1676 underlying_ty: underlying,
1677 ..
1678 } => {
1679 if self.is_numeric() {
1680 return Some(self.clone());
1681 }
1682
1683 if !visited.insert(id.clone()) {
1684 return None;
1685 }
1686
1687 underlying
1688 .as_ref()?
1689 .underlying_numeric_type_recursive(visited)
1690 }
1691 _ => None,
1692 }
1693 }
1694
1695 pub fn numeric_family(&self) -> Option<NumericFamily> {
1696 self.as_simple()?.numeric_family()
1697 }
1698
1699 pub fn is_numeric_compatible_with(&self, other: &Type) -> bool {
1700 let self_underlying_ty = self.underlying_numeric_type();
1701 let other_underlying_ty = other.underlying_numeric_type();
1702
1703 match (self_underlying_ty, other_underlying_ty) {
1704 (Some(s), Some(o)) => s.numeric_family() == o.numeric_family(),
1705 _ => false,
1706 }
1707 }
1708
1709 pub fn is_aliased_numeric_type(&self) -> bool {
1710 match self {
1711 Type::Nominal { underlying_ty, .. } => {
1712 underlying_ty.is_some() && !self.is_numeric() && self.has_underlying_numeric_type()
1713 }
1714 _ => false,
1715 }
1716 }
1717}
1718
1719fn alpha_index(idx: usize) -> String {
1721 let mut s = String::new();
1722 let mut n = idx + 1;
1723 while n > 0 {
1724 n -= 1;
1725 s.insert(0, (b'A' + (n % 26) as u8) as char);
1726 n /= 26;
1727 }
1728 s
1729}
1730
1731#[cfg(test)]
1732mod tests {
1733 use super::*;
1734
1735 #[test]
1736 fn function_equality_ignores_param_names() {
1737 let named = Type::function_with_names(
1738 vec![Type::int()],
1739 vec![Some("width".into())],
1740 vec![false],
1741 vec![],
1742 Box::new(Type::bool()),
1743 );
1744 let differently_named = Type::function_with_names(
1745 vec![Type::int()],
1746 vec![Some("height".into())],
1747 vec![false],
1748 vec![],
1749 Box::new(Type::bool()),
1750 );
1751 let unnamed = Type::function(
1752 vec![Type::int()],
1753 vec![false],
1754 vec![],
1755 Box::new(Type::bool()),
1756 );
1757
1758 assert_eq!(named, differently_named);
1759 assert_eq!(named, unnamed);
1760 }
1761
1762 #[test]
1763 fn alpha_index_single() {
1764 assert_eq!(alpha_index(0), "A");
1765 assert_eq!(alpha_index(5), "F");
1766 assert_eq!(alpha_index(25), "Z");
1767 }
1768
1769 #[test]
1770 fn alpha_index_double() {
1771 assert_eq!(alpha_index(26), "AA");
1772 assert_eq!(alpha_index(27), "AB");
1773 assert_eq!(alpha_index(51), "AZ");
1774 assert_eq!(alpha_index(52), "BA");
1775 assert_eq!(alpha_index(701), "ZZ");
1776 }
1777
1778 #[test]
1779 fn alpha_index_triple() {
1780 assert_eq!(alpha_index(702), "AAA");
1781 }
1782
1783 fn unhinted_var(id: u32) -> Type {
1784 Type::Var {
1785 id: TypeVarId(id),
1786 hint: None,
1787 }
1788 }
1789
1790 #[test]
1791 fn remove_vars_handles_more_than_six_unhinted_vars() {
1792 let func = Type::function(
1793 (0..6).map(unhinted_var).collect(),
1794 vec![false; 6],
1795 vec![],
1796 Box::new(unhinted_var(6)),
1797 );
1798
1799 let (resolved, generics) = Type::remove_vars(&[&func]);
1800
1801 assert_eq!(generics.len(), 7);
1802 let Type::Function(f) = &resolved[0] else {
1803 panic!("expected function type");
1804 };
1805 let names: Vec<_> = f
1806 .params
1807 .iter()
1808 .chain(std::iter::once(f.return_type.as_ref()))
1809 .map(|p| match p {
1810 Type::Parameter(name) => name.to_string(),
1811 other => panic!("expected parameter, got {:?}", other),
1812 })
1813 .collect();
1814 assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
1815 }
1816
1817 #[test]
1818 fn remove_vars_handles_dozens_of_unhinted_vars() {
1819 let params: Vec<Type> = (0..30).map(unhinted_var).collect();
1820 let func = Type::function(
1821 params.clone(),
1822 vec![false; params.len()],
1823 vec![],
1824 Box::new(Type::Simple(SimpleKind::Unit)),
1825 );
1826 let (_, generics) = Type::remove_vars(&[&func]);
1827 assert_eq!(generics.len(), 30);
1828 }
1829}