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 remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1308 if names.is_empty() {
1309 return;
1310 }
1311
1312 match self {
1313 Type::Nominal { id, params, .. } => {
1314 names.remove(id.last_segment());
1315 for param in params {
1316 param.remove_found_type_names(names);
1317 }
1318 }
1319 Type::Function(f) => {
1320 for param in &f.params {
1321 param.remove_found_type_names(names);
1322 }
1323 f.return_type.remove_found_type_names(names);
1324 for bound in &f.bounds {
1325 bound.generic.remove_found_type_names(names);
1326 bound.ty.remove_found_type_names(names);
1327 }
1328 }
1329 Type::Forall { body, .. } => {
1330 body.remove_found_type_names(names);
1331 }
1332 Type::Var { .. } => {}
1333 Type::Parameter(name) => {
1334 names.remove(name);
1335 }
1336 Type::Tuple(elements) => {
1337 for element in elements {
1338 element.remove_found_type_names(names);
1339 }
1340 }
1341 Type::Compound { kind, args } => {
1342 names.remove(kind.leaf_name());
1343 for arg in args {
1344 arg.remove_found_type_names(names);
1345 }
1346 }
1347 Type::Array { element, .. } => {
1348 names.remove("Array");
1349 element.remove_found_type_names(names);
1350 }
1351 Type::Simple(kind) => {
1352 names.remove(kind.leaf_name());
1353 }
1354 Type::Never | Type::Error | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {}
1355 }
1356 }
1357}
1358
1359impl Type {
1360 pub fn get_name(&self) -> Option<&str> {
1361 match self {
1362 Type::Simple(kind) => Some(kind.leaf_name()),
1363 Type::Compound { kind, args } => match kind {
1364 CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1365 _ => Some(kind.leaf_name()),
1366 },
1367 Type::Nominal { id, params, .. } => {
1368 if CompoundKind::from_qualified_id(id.as_str()) == Some(CompoundKind::Ref) {
1369 return params.first().and_then(|inner| inner.get_name());
1370 }
1371 Some(id.last_segment())
1372 }
1373 Type::ImportNamespace(module_id) => {
1374 let path = module_id.strip_prefix("go:").unwrap_or(module_id);
1375 path.rsplit('/').next()
1376 }
1377 Type::Array { .. } => Some("Array"),
1378 _ => None,
1379 }
1380 }
1381
1382 pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1383 self.get_name().is_some_and(|n| n == name)
1384 && self
1385 .get_type_params()
1386 .and_then(|p| p.first())
1387 .is_some_and(|first| *first == *inner)
1388 }
1389
1390 pub fn get_function_params(&self) -> Option<&[Type]> {
1391 match self {
1392 Type::Function(f) => Some(&f.params),
1393 Type::Nominal {
1394 underlying_ty: Some(inner),
1395 ..
1396 } => inner.get_function_params(),
1397 _ => None,
1398 }
1399 }
1400
1401 pub fn param_count(&self) -> usize {
1402 match self {
1403 Type::Function(f) => f.params.len(),
1404 _ => 0,
1405 }
1406 }
1407
1408 pub fn get_param_mutability(&self) -> &[bool] {
1409 match self {
1410 Type::Function(f) => &f.param_mutability,
1411 _ => &[],
1412 }
1413 }
1414
1415 pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1416 match self {
1417 Type::Function(f) => {
1418 if f.params.is_empty() {
1419 return self.clone();
1420 }
1421 let mut new_params = f.params.clone();
1422 new_params[0] = new_first.clone();
1423 f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1424 }
1425 Type::Forall { vars, body } => Type::Forall {
1426 vars: vars.clone(),
1427 body: Box::new(body.with_replaced_first_param(new_first)),
1428 },
1429 _ => self.clone(),
1430 }
1431 }
1432
1433 pub fn get_bounds(&self) -> &[Bound] {
1434 match self {
1435 Type::Function(f) => &f.bounds,
1436 Type::Forall { body, .. } => body.get_bounds(),
1437 _ => &[],
1438 }
1439 }
1440
1441 pub fn get_qualified_name(&self) -> Symbol {
1442 match self.strip_refs() {
1443 Type::Nominal { id, .. } => id,
1444 Type::Simple(kind) => Symbol::from_parts("prelude", kind.leaf_name()),
1445 Type::Compound { kind, .. } => Symbol::from_parts("prelude", kind.leaf_name()),
1446 _ => panic!("called get_qualified_name on {:#?}", self),
1447 }
1448 }
1449
1450 pub fn inner(&self) -> Option<Type> {
1451 self.get_type_params()
1452 .and_then(|args| args.first().cloned())
1453 }
1454
1455 pub fn ok_type(&self) -> Type {
1456 debug_assert!(
1457 self.is_result() || self.is_option() || self.is_partial(),
1458 "ok_type called on non-Result/Option/Partial type"
1459 );
1460 self.inner()
1461 .expect("Result/Option/Partial should have inner type")
1462 }
1463
1464 pub fn err_type(&self) -> Type {
1465 debug_assert!(
1466 self.is_result() || self.is_partial(),
1467 "err_type called on non-Result/Partial type"
1468 );
1469 self.get_type_params()
1470 .and_then(|args| args.get(1).cloned())
1471 .expect("Result/Partial should have error type")
1472 }
1473}
1474
1475pub fn peel_alias<F>(ty: &Type, is_alias: F) -> Type
1478where
1479 F: Fn(&str) -> bool,
1480{
1481 let mut current = ty.unwrap_forall().clone();
1482 let mut seen: Vec<String> = Vec::new();
1483 while let Type::Nominal {
1484 id,
1485 underlying_ty: Some(u),
1486 ..
1487 } = ¤t
1488 {
1489 if !is_alias(id.as_str()) {
1490 break;
1491 }
1492 if seen.iter().any(|s| s == id.as_str()) {
1493 break;
1494 }
1495 seen.push(id.to_string());
1496 current = u.unwrap_forall().clone();
1497 }
1498 current
1499}
1500
1501pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
1502 let is_alias = |id: &str| lookup(id).is_some_and(Definition::is_type_alias);
1503 let is_interface = |id: &str| matches!(lookup(id), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
1504 resolves_to_pointer(ty, is_alias)
1505 || resolves_to_interface(ty, is_alias, is_interface)
1506 || resolves_to_function(ty, is_alias)
1507}
1508
1509fn resolves_to_pointer<FA: Fn(&str) -> bool>(ty: &Type, is_alias: FA) -> bool {
1510 fn as_pointer(ty: &Type) -> bool {
1511 ty.is_ref() || ty.get_underlying().is_some_and(Type::is_ref)
1512 }
1513 as_pointer(ty) || as_pointer(&peel_alias(ty, is_alias))
1514}
1515
1516fn resolves_to_interface<FA, FI>(ty: &Type, is_alias: FA, is_interface: FI) -> bool
1517where
1518 FA: Fn(&str) -> bool,
1519 FI: Fn(&str) -> bool,
1520{
1521 matches!(peel_alias(ty, is_alias), Type::Nominal { id, .. } if is_interface(id.as_str()))
1522}
1523
1524fn resolves_to_function<FA: Fn(&str) -> bool>(ty: &Type, is_alias: FA) -> bool {
1525 fn as_function(ty: &Type) -> bool {
1526 matches!(ty, Type::Function(_)) || matches!(ty.get_underlying(), Some(Type::Function(_)))
1527 }
1528 as_function(ty) || as_function(&peel_alias(ty, is_alias))
1529}
1530
1531pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
1534where
1535 F: Fn(&str) -> Option<String>,
1536{
1537 let mut current = id.to_string();
1538 let mut seen: Vec<String> = Vec::new();
1539 loop {
1540 if seen.iter().any(|s| s == ¤t) {
1541 return current;
1542 }
1543 let Some(next) = next_alias(¤t) else {
1544 return current;
1545 };
1546 seen.push(current);
1547 current = next;
1548 }
1549}
1550
1551impl Type {
1552 pub fn unwrap_forall(&self) -> &Type {
1553 match self {
1554 Type::Forall { body, .. } => body.as_ref(),
1555 other => other,
1556 }
1557 }
1558
1559 pub fn as_function_type(&self) -> Option<&FunctionType> {
1560 match self.unwrap_forall() {
1561 Type::Function(f) => Some(f),
1562 _ => None,
1563 }
1564 }
1565
1566 pub fn strip_refs(&self) -> Type {
1567 if self.is_ref() {
1568 return self.inner().expect("ref type must have inner").strip_refs();
1569 }
1570
1571 self.clone()
1572 }
1573
1574 pub fn with_receiver_placeholder(self) -> Type {
1575 match self {
1576 Type::Function(f) => {
1577 let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
1578 let mut new_params = vec![Type::ReceiverPlaceholder];
1579 new_params.extend(f.params);
1580
1581 let mut new_mutability = vec![false];
1582 new_mutability.extend(f.param_mutability);
1583
1584 let new_param_names = if f.param_names.is_empty() {
1585 Vec::new()
1586 } else {
1587 let mut names = vec![None];
1588 names.extend(f.param_names);
1589 names
1590 };
1591
1592 Type::function_with_names(
1593 new_params,
1594 new_param_names,
1595 new_mutability,
1596 f.bounds,
1597 f.return_type,
1598 )
1599 }
1600 _ => unreachable!(
1601 "with_receiver_placeholder called on non-function type: {:?}",
1602 self
1603 ),
1604 }
1605 }
1606
1607 pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
1608 let mut vars = HashMap::default();
1609 let types = types
1610 .iter()
1611 .map(|v| Self::remove_vars_impl(v, &mut vars))
1612 .collect();
1613
1614 (types, vars.into_values().collect())
1615 }
1616
1617 fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
1618 match ty {
1619 Type::Nominal {
1620 id: name,
1621 params: args,
1622 underlying_ty: underlying,
1623 } => Type::Nominal {
1624 id: name.clone(),
1625 params: args
1626 .iter()
1627 .map(|a| Self::remove_vars_impl(a, vars))
1628 .collect(),
1629 underlying_ty: underlying
1630 .as_ref()
1631 .map(|u| Box::new(Self::remove_vars_impl(u, vars))),
1632 },
1633
1634 Type::Function(f) => Type::function(
1635 f.params
1636 .iter()
1637 .map(|a| Self::remove_vars_impl(a, vars))
1638 .collect(),
1639 f.param_mutability.clone(),
1640 f.bounds
1641 .iter()
1642 .map(|b| Bound {
1643 param_name: b.param_name.clone(),
1644 generic: Self::remove_vars_impl(&b.generic, vars),
1645 ty: Self::remove_vars_impl(&b.ty, vars),
1646 })
1647 .collect(),
1648 Self::remove_vars_impl(&f.return_type, vars).into(),
1649 ),
1650
1651 Type::Var { id, hint } => match vars.get(&id.0) {
1652 Some(g) => Type::Parameter(g.clone()),
1653 None => {
1654 let name: EcoString = hint
1655 .clone()
1656 .unwrap_or_else(|| alpha_index(vars.len()).into());
1657
1658 vars.insert(id.0, name.clone());
1659 Type::Parameter(name)
1660 }
1661 },
1662
1663 Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
1664 Type::Tuple(elements) => Type::Tuple(
1665 elements
1666 .iter()
1667 .map(|e| Self::remove_vars_impl(e, vars))
1668 .collect(),
1669 ),
1670 Type::Compound { kind, args } => Type::Compound {
1671 kind: *kind,
1672 args: args
1673 .iter()
1674 .map(|a| Self::remove_vars_impl(a, vars))
1675 .collect(),
1676 },
1677 Type::Array { length, element } => Type::Array {
1678 length: *length,
1679 element: Box::new(Self::remove_vars_impl(element, vars)),
1680 },
1681 Type::Simple(_) | Type::Parameter(_) => ty.clone(),
1682 Type::Never | Type::Error | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {
1683 ty.clone()
1684 }
1685 }
1686 }
1687
1688 pub fn contains_type(&self, target: &Type) -> bool {
1689 if *self == *target {
1690 return true;
1691 }
1692 match self {
1693 Type::Nominal { params, .. } => params.iter().any(|p| p.contains_type(target)),
1694 Type::Function(f) => {
1695 f.params.iter().any(|p| p.contains_type(target))
1696 || f.return_type.contains_type(target)
1697 }
1698 Type::Var { .. } => false,
1699 Type::Forall { body, .. } => body.contains_type(target),
1700 Type::Tuple(elements) => elements.iter().any(|e| e.contains_type(target)),
1701 Type::Array { element, .. } => element.contains_type(target),
1702 Type::Compound { args, .. } => args.iter().any(|a| a.contains_type(target)),
1703 Type::Simple(_)
1704 | Type::Parameter(_)
1705 | Type::Never
1706 | Type::Error
1707 | Type::ImportNamespace(_)
1708 | Type::ReceiverPlaceholder => false,
1709 }
1710 }
1711}
1712
1713impl Type {
1714 pub fn underlying_numeric_type(&self) -> Option<Type> {
1715 self.underlying_numeric_type_recursive(&mut HashSet::default())
1716 }
1717
1718 pub fn has_underlying_numeric_type(&self) -> bool {
1719 self.underlying_numeric_type().is_some()
1720 }
1721
1722 pub fn literal_adaptation_target(&self) -> Option<Type> {
1723 if let Some(numeric) = self.underlying_numeric_type() {
1724 return Some(numeric);
1725 }
1726 match self {
1727 Type::Nominal { .. } if self.underlying_simple_kind() == Some(SimpleKind::Uintptr) => {
1728 Some(Type::Simple(SimpleKind::Uintptr))
1729 }
1730 _ => None,
1731 }
1732 }
1733
1734 pub fn underlying_simple_kind(&self) -> Option<SimpleKind> {
1735 self.underlying_simple_kind_recursive(&mut HashSet::default())
1736 }
1737
1738 fn underlying_simple_kind_recursive(
1739 &self,
1740 visited: &mut HashSet<Symbol>,
1741 ) -> Option<SimpleKind> {
1742 if let Some(kind) = self.as_simple() {
1743 return Some(kind);
1744 }
1745 match self {
1746 Type::Nominal {
1747 id,
1748 underlying_ty: Some(underlying),
1749 ..
1750 } => {
1751 if !visited.insert(id.clone()) {
1752 return None;
1753 }
1754 underlying.underlying_simple_kind_recursive(visited)
1755 }
1756 _ => None,
1757 }
1758 }
1759
1760 fn underlying_numeric_type_recursive(&self, visited: &mut HashSet<Symbol>) -> Option<Type> {
1761 match self {
1762 Type::Simple(_) if self.is_numeric() => Some(self.clone()),
1763 Type::Nominal {
1764 id,
1765 underlying_ty: underlying,
1766 ..
1767 } => {
1768 if self.is_numeric() {
1769 return Some(self.clone());
1770 }
1771
1772 if !visited.insert(id.clone()) {
1773 return None;
1774 }
1775
1776 underlying
1777 .as_ref()?
1778 .underlying_numeric_type_recursive(visited)
1779 }
1780 _ => None,
1781 }
1782 }
1783
1784 pub fn numeric_family(&self) -> Option<NumericFamily> {
1785 self.as_simple()?.numeric_family()
1786 }
1787
1788 pub fn is_numeric_compatible_with(&self, other: &Type) -> bool {
1789 let self_underlying_ty = self.underlying_numeric_type();
1790 let other_underlying_ty = other.underlying_numeric_type();
1791
1792 match (self_underlying_ty, other_underlying_ty) {
1793 (Some(s), Some(o)) => s.numeric_family() == o.numeric_family(),
1794 _ => false,
1795 }
1796 }
1797
1798 pub fn is_aliased_numeric_type(&self) -> bool {
1799 match self {
1800 Type::Nominal { underlying_ty, .. } => {
1801 underlying_ty.is_some() && !self.is_numeric() && self.has_underlying_numeric_type()
1802 }
1803 _ => false,
1804 }
1805 }
1806}
1807
1808fn alpha_index(idx: usize) -> String {
1810 let mut s = String::new();
1811 let mut n = idx + 1;
1812 while n > 0 {
1813 n -= 1;
1814 s.insert(0, (b'A' + (n % 26) as u8) as char);
1815 n /= 26;
1816 }
1817 s
1818}
1819
1820#[cfg(test)]
1821mod tests {
1822 use super::*;
1823
1824 #[test]
1825 fn function_equality_ignores_param_names() {
1826 let named = Type::function_with_names(
1827 vec![Type::int()],
1828 vec![Some("width".into())],
1829 vec![false],
1830 vec![],
1831 Box::new(Type::bool()),
1832 );
1833 let differently_named = Type::function_with_names(
1834 vec![Type::int()],
1835 vec![Some("height".into())],
1836 vec![false],
1837 vec![],
1838 Box::new(Type::bool()),
1839 );
1840 let unnamed = Type::function(
1841 vec![Type::int()],
1842 vec![false],
1843 vec![],
1844 Box::new(Type::bool()),
1845 );
1846
1847 assert_eq!(named, differently_named);
1848 assert_eq!(named, unnamed);
1849 }
1850
1851 #[test]
1852 fn alpha_index_single() {
1853 assert_eq!(alpha_index(0), "A");
1854 assert_eq!(alpha_index(5), "F");
1855 assert_eq!(alpha_index(25), "Z");
1856 }
1857
1858 #[test]
1859 fn alpha_index_double() {
1860 assert_eq!(alpha_index(26), "AA");
1861 assert_eq!(alpha_index(27), "AB");
1862 assert_eq!(alpha_index(51), "AZ");
1863 assert_eq!(alpha_index(52), "BA");
1864 assert_eq!(alpha_index(701), "ZZ");
1865 }
1866
1867 #[test]
1868 fn alpha_index_triple() {
1869 assert_eq!(alpha_index(702), "AAA");
1870 }
1871
1872 fn unhinted_var(id: u32) -> Type {
1873 Type::Var {
1874 id: TypeVarId(id),
1875 hint: None,
1876 }
1877 }
1878
1879 #[test]
1880 fn remove_vars_handles_more_than_six_unhinted_vars() {
1881 let func = Type::function(
1882 (0..6).map(unhinted_var).collect(),
1883 vec![false; 6],
1884 vec![],
1885 Box::new(unhinted_var(6)),
1886 );
1887
1888 let (resolved, generics) = Type::remove_vars(&[&func]);
1889
1890 assert_eq!(generics.len(), 7);
1891 let Type::Function(f) = &resolved[0] else {
1892 panic!("expected function type");
1893 };
1894 let names: Vec<_> = f
1895 .params
1896 .iter()
1897 .chain(std::iter::once(f.return_type.as_ref()))
1898 .map(|p| match p {
1899 Type::Parameter(name) => name.to_string(),
1900 other => panic!("expected parameter, got {:?}", other),
1901 })
1902 .collect();
1903 assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
1904 }
1905
1906 #[test]
1907 fn remove_vars_handles_dozens_of_unhinted_vars() {
1908 let params: Vec<Type> = (0..30).map(unhinted_var).collect();
1909 let func = Type::function(
1910 params.clone(),
1911 vec![false; params.len()],
1912 vec![],
1913 Box::new(Type::Simple(SimpleKind::Unit)),
1914 );
1915 let (_, generics) = Type::remove_vars(&[&func]);
1916 assert_eq!(generics.len(), 30);
1917 }
1918}