Skip to main content

lisette_syntax/
types.rs

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