Skip to main content

lisette_syntax/
types.rs

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