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