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
687#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
688#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
689pub enum SimpleKind {
690    Int,
691    Int8,
692    Int16,
693    Int32,
694    Int64,
695    Uint,
696    Uint8,
697    Uint16,
698    Uint32,
699    Uint64,
700    Uintptr,
701    Byte,
702    Float32,
703    Float64,
704    Complex64,
705    Complex128,
706    Rune,
707    Bool,
708    String,
709    Unit,
710}
711
712impl SimpleKind {
713    pub fn leaf_name(self) -> &'static str {
714        match self {
715            SimpleKind::Int => "int",
716            SimpleKind::Int8 => "int8",
717            SimpleKind::Int16 => "int16",
718            SimpleKind::Int32 => "int32",
719            SimpleKind::Int64 => "int64",
720            SimpleKind::Uint => "uint",
721            SimpleKind::Uint8 => "uint8",
722            SimpleKind::Uint16 => "uint16",
723            SimpleKind::Uint32 => "uint32",
724            SimpleKind::Uint64 => "uint64",
725            SimpleKind::Uintptr => "uintptr",
726            SimpleKind::Byte => "byte",
727            SimpleKind::Float32 => "float32",
728            SimpleKind::Float64 => "float64",
729            SimpleKind::Complex64 => "complex64",
730            SimpleKind::Complex128 => "complex128",
731            SimpleKind::Rune => "rune",
732            SimpleKind::Bool => "bool",
733            SimpleKind::String => "string",
734            SimpleKind::Unit => "Unit",
735        }
736    }
737
738    pub fn from_name(name: &str) -> Option<SimpleKind> {
739        Some(match name {
740            "int" => SimpleKind::Int,
741            "int8" => SimpleKind::Int8,
742            "int16" => SimpleKind::Int16,
743            "int32" => SimpleKind::Int32,
744            "int64" => SimpleKind::Int64,
745            "uint" => SimpleKind::Uint,
746            "uint8" => SimpleKind::Uint8,
747            "uint16" => SimpleKind::Uint16,
748            "uint32" => SimpleKind::Uint32,
749            "uint64" => SimpleKind::Uint64,
750            "uintptr" => SimpleKind::Uintptr,
751            "byte" => SimpleKind::Byte,
752            "float32" => SimpleKind::Float32,
753            "float64" => SimpleKind::Float64,
754            "complex64" => SimpleKind::Complex64,
755            "complex128" => SimpleKind::Complex128,
756            "rune" => SimpleKind::Rune,
757            "bool" => SimpleKind::Bool,
758            "string" => SimpleKind::String,
759            "Unit" => SimpleKind::Unit,
760            _ => return None,
761        })
762    }
763
764    pub fn is_arithmetic(self) -> bool {
765        !matches!(
766            self,
767            SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit | SimpleKind::Uintptr
768        )
769    }
770
771    pub fn is_ordered(self) -> bool {
772        self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
773    }
774
775    pub fn integer_range(self) -> Option<(i128, i128)> {
776        use SimpleKind::*;
777        Some(match self {
778            Int8 => (i8::MIN as i128, i8::MAX as i128),
779            Int16 => (i16::MIN as i128, i16::MAX as i128),
780            Int32 | Rune => (i32::MIN as i128, i32::MAX as i128),
781            Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
782            Uint8 | Byte => (0, u8::MAX as i128),
783            Uint16 => (0, u16::MAX as i128),
784            Uint32 => (0, u32::MAX as i128),
785            Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
786            _ => return None,
787        })
788    }
789
790    pub fn is_unsigned_int(self) -> bool {
791        matches!(
792            self,
793            SimpleKind::Byte
794                | SimpleKind::Uint
795                | SimpleKind::Uint8
796                | SimpleKind::Uint16
797                | SimpleKind::Uint32
798                | SimpleKind::Uint64
799        )
800    }
801
802    pub fn is_signed_int(self) -> bool {
803        matches!(
804            self,
805            SimpleKind::Int
806                | SimpleKind::Int8
807                | SimpleKind::Int16
808                | SimpleKind::Int32
809                | SimpleKind::Int64
810                | SimpleKind::Rune
811        )
812    }
813
814    pub fn is_float(self) -> bool {
815        matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
816    }
817
818    fn is_complex(self) -> bool {
819        matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
820    }
821
822    fn numeric_family(self) -> Option<NumericFamily> {
823        if self.is_signed_int() {
824            Some(NumericFamily::SignedInt)
825        } else if self.is_unsigned_int() {
826            Some(NumericFamily::UnsignedInt)
827        } else if self.is_float() {
828            Some(NumericFamily::Float)
829        } else {
830            None
831        }
832    }
833}
834
835impl Type {
836    pub fn get_function_ret(&self) -> Option<&Type> {
837        match self {
838            Type::Function(f) => Some(&f.return_type),
839            _ => None,
840        }
841    }
842
843    pub fn is_stringer_signature(&self) -> bool {
844        let func = match self {
845            Type::Forall { body, .. } => body.as_ref(),
846            other => other,
847        };
848        matches!(
849            func,
850            Type::Function(f)
851                if f.params.len() == 1
852                    && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::String))
853        )
854    }
855
856    pub fn is_equals_signature(&self) -> bool {
857        let func = match self {
858            Type::Forall { body, .. } => body.as_ref(),
859            other => other,
860        };
861        matches!(
862            func,
863            Type::Function(f)
864                if f.params.len() == 2
865                    && matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::Bool))
866                    && f.params[0].ty == f.params[1].ty
867                    && !f.params[0].ty.is_ref()
868        )
869    }
870
871    pub fn is_equals_bound_signature(&self, param_name: &str) -> bool {
872        let func = match self {
873            Type::Forall { body, .. } => body.as_ref(),
874            other => other,
875        };
876        matches!(
877            func,
878            Type::Function(f)
879                if f.params.len() == 1
880                    && f.return_type.is_boolean()
881                    && matches!(&f.params[0].ty, Type::Parameter(name) if name.as_str() == param_name)
882        )
883    }
884
885    pub fn equals_receiver_vars(&self, owner_id: &str, arity: usize) -> Option<Vec<EcoString>> {
886        if !self.is_equals_signature() {
887            return None;
888        }
889        let (quantified, func): (&[EcoString], &Type) = match self {
890            Type::Forall { vars, body } => (vars, body.as_ref()),
891            other => (&[], other),
892        };
893        if quantified.len() != arity {
894            return None;
895        }
896        let Type::Function(f) = func else {
897            return None;
898        };
899        let Type::Nominal { id, params, .. } = &f.params[0].ty else {
900            return None;
901        };
902        if id.as_str() != owner_id || params.len() != arity {
903            return None;
904        }
905        let mut vars = Vec::with_capacity(arity);
906        for param in params {
907            let Type::Parameter(name) = param else {
908                return None;
909            };
910            if vars.contains(name) {
911                return None;
912            }
913            vars.push(name.clone());
914        }
915        if !quantified.iter().all(|v| vars.contains(v)) {
916            return None;
917        }
918        Some(vars)
919    }
920
921    pub fn has_name(&self, name: &str) -> bool {
922        match self {
923            Type::Nominal { id, .. } => id.last_segment() == name,
924            Type::Simple(kind) => kind.leaf_name() == name,
925            Type::Compound { kind, .. } => kind.leaf_name() == name,
926            _ => false,
927        }
928    }
929
930    pub fn get_qualified_id(&self) -> Option<&str> {
931        match self {
932            Type::Nominal { id, .. } => Some(id.as_str()),
933            _ => None,
934        }
935    }
936
937    pub fn is_result(&self) -> bool {
938        self.has_qualified_id("prelude.Result")
939    }
940
941    pub fn is_option(&self) -> bool {
942        self.has_qualified_id("prelude.Option")
943    }
944
945    pub fn is_partial(&self) -> bool {
946        self.has_qualified_id("prelude.Partial")
947    }
948
949    fn has_qualified_id(&self, qualified_id: &str) -> bool {
950        matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
951    }
952
953    pub fn is_unit(&self) -> bool {
954        self.is_simple(SimpleKind::Unit)
955    }
956
957    pub fn tuple_arity(&self) -> Option<usize> {
958        match self {
959            Type::Tuple(elements) => Some(elements.len()),
960            _ => None,
961        }
962    }
963
964    pub fn is_tuple(&self) -> bool {
965        matches!(self, Type::Tuple(_))
966    }
967
968    pub fn array_len(&self) -> Option<u64> {
969        match self {
970            Type::Array { length, .. } => Some(*length),
971            _ => None,
972        }
973    }
974
975    pub fn as_import_namespace(&self) -> Option<&str> {
976        match self {
977            Type::ImportNamespace(module_id) => Some(module_id),
978            _ => None,
979        }
980    }
981
982    pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
983        match self {
984            Type::Compound { kind, args } => Some((*kind, args.as_slice())),
985            _ => None,
986        }
987    }
988
989    pub fn is_native(&self, kind: CompoundKind) -> bool {
990        self.as_compound().is_some_and(|(k, _)| k == kind)
991    }
992
993    pub fn is_ref(&self) -> bool {
994        self.is_native(CompoundKind::Ref)
995    }
996
997    pub fn is_slice(&self) -> bool {
998        self.is_native(CompoundKind::Slice)
999    }
1000
1001    pub fn is_map(&self) -> bool {
1002        self.is_native(CompoundKind::Map)
1003    }
1004
1005    pub fn is_channel(&self) -> bool {
1006        self.is_native(CompoundKind::Channel)
1007    }
1008
1009    pub fn is_receiver_placeholder(&self) -> bool {
1010        matches!(self, Type::ReceiverPlaceholder)
1011    }
1012
1013    pub fn is_unknown(&self) -> bool {
1014        self.has_name("Unknown")
1015    }
1016
1017    pub fn is_receiver(&self) -> bool {
1018        self.is_native(CompoundKind::Receiver)
1019    }
1020
1021    pub fn is_ignored(&self) -> bool {
1022        matches!(self, Type::Ignored)
1023    }
1024
1025    pub fn is_placeholder(&self) -> bool {
1026        matches!(self, Type::Uninferred | Type::Ignored)
1027    }
1028
1029    pub fn is_variadic(&self) -> Option<Type> {
1030        let last = self.get_function_params()?.last()?;
1031        match last.ty.as_compound()? {
1032            (CompoundKind::VarArgs, _) => last.ty.inner(),
1033            _ => None,
1034        }
1035    }
1036
1037    pub fn is_string(&self) -> bool {
1038        self.is_simple(SimpleKind::String)
1039    }
1040
1041    fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
1042        match self.as_compound() {
1043            Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
1044            _ => false,
1045        }
1046    }
1047
1048    pub fn is_byte_slice(&self) -> bool {
1049        self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
1050    }
1051
1052    fn is_rune_slice(&self) -> bool {
1053        self.is_slice_of_simple(SimpleKind::Rune)
1054    }
1055
1056    fn is_byte_or_rune_slice(&self) -> bool {
1057        self.is_byte_slice() || self.is_rune_slice()
1058    }
1059
1060    pub fn as_simple(&self) -> Option<SimpleKind> {
1061        match self {
1062            Type::Simple(kind) => Some(*kind),
1063            _ => None,
1064        }
1065    }
1066
1067    pub fn is_simple(&self, kind: SimpleKind) -> bool {
1068        self.as_simple() == Some(kind)
1069    }
1070
1071    pub fn is_boolean(&self) -> bool {
1072        self.is_simple(SimpleKind::Bool)
1073    }
1074
1075    pub fn is_rune(&self) -> bool {
1076        self.is_simple(SimpleKind::Rune)
1077    }
1078
1079    pub fn is_float(&self) -> bool {
1080        self.as_simple().is_some_and(SimpleKind::is_float)
1081    }
1082
1083    pub fn is_variable(&self) -> bool {
1084        matches!(self, Type::Var { .. })
1085    }
1086
1087    /// A transparent alias over this keeps its name, wrapped in a `Nominal`
1088    /// that unification peels back to it.
1089    pub fn is_structural_alias_body(&self) -> bool {
1090        matches!(
1091            self,
1092            Type::Simple(_) | Type::Compound { .. } | Type::Array { .. } | Type::Tuple(_)
1093        )
1094    }
1095
1096    pub fn is_numeric(&self) -> bool {
1097        self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1098    }
1099
1100    pub fn is_complex(&self) -> bool {
1101        self.as_simple().is_some_and(SimpleKind::is_complex)
1102    }
1103
1104    pub fn is_unsigned_int(&self) -> bool {
1105        self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1106    }
1107
1108    pub fn is_never(&self) -> bool {
1109        matches!(self, Type::Never)
1110    }
1111
1112    pub fn is_error(&self) -> bool {
1113        matches!(self, Type::Error)
1114    }
1115
1116    pub fn contains_error(&self) -> bool {
1117        match self {
1118            Type::Error => true,
1119            Type::Nominal { params, .. } => params.iter().any(Type::contains_error),
1120            Type::Compound { args, .. } => args.iter().any(Type::contains_error),
1121            Type::Function(f) => {
1122                f.params.iter().any(|param| param.ty.contains_error())
1123                    || f.return_type.contains_error()
1124            }
1125            Type::Tuple(elements) => elements.iter().any(Type::contains_error),
1126            Type::Array { element, .. } => element.contains_error(),
1127            Type::Forall { body, .. } => body.contains_error(),
1128            _ => false,
1129        }
1130    }
1131
1132    pub fn has_unbound_variables(&self) -> bool {
1133        match self {
1134            Type::Var { hint, .. } => hint.is_some(),
1135            Type::Nominal { params, .. } => params.iter().any(|p| p.has_unbound_variables()),
1136            Type::Function(f) => {
1137                f.params.iter().any(|p| p.ty.has_unbound_variables())
1138                    || f.return_type.has_unbound_variables()
1139            }
1140            Type::Forall { body, .. } => body.has_unbound_variables(),
1141            Type::Tuple(elements) => elements.iter().any(|e| e.has_unbound_variables()),
1142            Type::Array { element, .. } => element.has_unbound_variables(),
1143            Type::Compound { args, .. } => args.iter().any(|a| a.has_unbound_variables()),
1144            Type::Simple(_)
1145            | Type::Parameter(_)
1146            | Type::Never
1147            | Type::Uninferred
1148            | Type::Ignored
1149            | Type::Error
1150            | Type::ImportNamespace(_)
1151            | Type::ReceiverPlaceholder => false,
1152        }
1153    }
1154
1155    pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
1156        match self {
1157            Type::Var { id, hint } => {
1158                if hint.is_some() {
1159                    out.push(*id);
1160                }
1161            }
1162            Type::Nominal { params, .. } => {
1163                for p in params {
1164                    p.collect_unbound_variables(out);
1165                }
1166            }
1167            Type::Function(f) => {
1168                for p in &f.params {
1169                    p.ty.collect_unbound_variables(out);
1170                }
1171                f.return_type.collect_unbound_variables(out);
1172            }
1173            Type::Forall { body, .. } => body.collect_unbound_variables(out),
1174            Type::Tuple(elements) => {
1175                for e in elements {
1176                    e.collect_unbound_variables(out);
1177                }
1178            }
1179            Type::Array { element, .. } => element.collect_unbound_variables(out),
1180            Type::Compound { args, .. } => {
1181                for a in args {
1182                    a.collect_unbound_variables(out);
1183                }
1184            }
1185            Type::Simple(_)
1186            | Type::Parameter(_)
1187            | Type::Never
1188            | Type::Uninferred
1189            | Type::Ignored
1190            | Type::Error
1191            | Type::ImportNamespace(_)
1192            | Type::ReceiverPlaceholder => {}
1193        }
1194    }
1195
1196    pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
1197        if names.is_empty() {
1198            return;
1199        }
1200
1201        match self {
1202            Type::Nominal { id, params, .. } => {
1203                names.remove(id.last_segment());
1204                for param in params {
1205                    param.remove_found_type_names(names);
1206                }
1207            }
1208            Type::Function(f) => {
1209                for param in &f.params {
1210                    param.ty.remove_found_type_names(names);
1211                }
1212                f.return_type.remove_found_type_names(names);
1213                for bound in &f.bounds {
1214                    bound.generic.remove_found_type_names(names);
1215                    bound.ty.remove_found_type_names(names);
1216                }
1217            }
1218            Type::Forall { body, .. } => {
1219                body.remove_found_type_names(names);
1220            }
1221            Type::Var { .. } => {}
1222            Type::Parameter(name) => {
1223                names.remove(name);
1224            }
1225            Type::Tuple(elements) => {
1226                for element in elements {
1227                    element.remove_found_type_names(names);
1228                }
1229            }
1230            Type::Compound { kind, args } => {
1231                names.remove(kind.leaf_name());
1232                for arg in args {
1233                    arg.remove_found_type_names(names);
1234                }
1235            }
1236            Type::Array { element, .. } => {
1237                names.remove("Array");
1238                element.remove_found_type_names(names);
1239            }
1240            Type::Simple(kind) => {
1241                names.remove(kind.leaf_name());
1242            }
1243            Type::Never
1244            | Type::Uninferred
1245            | Type::Ignored
1246            | Type::Error
1247            | Type::ImportNamespace(_)
1248            | Type::ReceiverPlaceholder => {}
1249        }
1250    }
1251}
1252
1253impl Type {
1254    pub fn get_name(&self) -> Option<&str> {
1255        match self {
1256            Type::Simple(kind) => Some(kind.leaf_name()),
1257            Type::Compound { kind, args } => match kind {
1258                CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
1259                _ => Some(kind.leaf_name()),
1260            },
1261            Type::Nominal { id, .. } => Some(id.last_segment()),
1262            Type::ImportNamespace(module_id) => {
1263                let path = module_id.strip_prefix("go:").unwrap_or(module_id);
1264                path.rsplit('/').next()
1265            }
1266            Type::Array { .. } => Some("Array"),
1267            _ => None,
1268        }
1269    }
1270
1271    pub fn wraps(&self, name: &str, inner: &Type) -> bool {
1272        self.get_name().is_some_and(|n| n == name)
1273            && self
1274                .get_type_params()
1275                .and_then(|p| p.first())
1276                .is_some_and(|first| *first == *inner)
1277    }
1278
1279    pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
1280        match self {
1281            Type::Function(f) => Some(&f.params),
1282            _ => None,
1283        }
1284    }
1285
1286    pub fn param_count(&self) -> usize {
1287        match self {
1288            Type::Function(f) => f.params.len(),
1289            _ => 0,
1290        }
1291    }
1292
1293    pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
1294        match self {
1295            Type::Function(f) => {
1296                if f.params.is_empty() {
1297                    return self.clone();
1298                }
1299                let mut new_params = f.params.clone();
1300                new_params[0] = new_params[0].with_type(new_first.clone());
1301                f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
1302            }
1303            Type::Forall { vars, body } => Type::Forall {
1304                vars: vars.clone(),
1305                body: Box::new(body.with_replaced_first_param(new_first)),
1306            },
1307            _ => self.clone(),
1308        }
1309    }
1310
1311    pub fn get_bounds(&self) -> &[Bound] {
1312        match self {
1313            Type::Function(f) => &f.bounds,
1314            Type::Forall { body, .. } => body.get_bounds(),
1315            _ => &[],
1316        }
1317    }
1318
1319    pub fn get_qualified_name(&self) -> Option<Symbol> {
1320        let mut current = self;
1321        while current.is_ref() {
1322            current = current.get_type_params()?.first()?;
1323        }
1324        match current {
1325            Type::Nominal { id, .. } => Some(id.clone()),
1326            Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1327            Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
1328            _ => None,
1329        }
1330    }
1331
1332    pub fn inner(&self) -> Option<Type> {
1333        self.get_type_params()
1334            .and_then(|args| args.first().cloned())
1335    }
1336
1337    pub fn ok_type(&self) -> Type {
1338        debug_assert!(
1339            self.is_result() || self.is_option() || self.is_partial(),
1340            "ok_type called on non-Result/Option/Partial type"
1341        );
1342        self.inner()
1343            .expect("Result/Option/Partial should have inner type")
1344    }
1345
1346    pub fn err_type(&self) -> Type {
1347        debug_assert!(
1348            self.is_result() || self.is_partial(),
1349            "err_type called on non-Result/Partial type"
1350        );
1351        self.get_type_params()
1352            .and_then(|args| args.get(1).cloned())
1353            .expect("Result/Partial should have error type")
1354    }
1355}
1356
1357/// Resolve transparent aliases from their canonical definition targets. The
1358/// cycle guard defends against invalid external definitions and recovery types.
1359pub fn peel_alias<'d, F>(ty: &Type, lookup: F) -> Type
1360where
1361    F: Fn(&str) -> Option<&'d Definition>,
1362{
1363    let mut current = ty.unwrap_forall().clone();
1364    let mut seen: HashSet<Symbol> = HashSet::default();
1365    while let Type::Nominal { id, params } = &current {
1366        if !seen.insert(id.clone()) {
1367            break;
1368        }
1369        let Some(target) =
1370            lookup(id.as_str()).and_then(|definition| definition.instantiate_alias_target(params))
1371        else {
1372            break;
1373        };
1374        current = target.unwrap_forall().clone();
1375    }
1376    current
1377}
1378
1379/// Return the immediate underlying type of a nominal occurrence, instantiated
1380/// with that occurrence's type arguments.
1381pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1382where
1383    F: Fn(&str) -> Option<&'d Definition>,
1384{
1385    let Type::Nominal { id, params } = ty.unwrap_forall() else {
1386        return None;
1387    };
1388    lookup(id.as_str())?.instantiate_underlying(params)
1389}
1390
1391/// Follow transparent aliases and newtype fields to their canonical
1392/// representation. The cycle guard also makes this safe for recovery types
1393/// built from invalid recursive declarations.
1394pub fn peel_underlying<'d, F>(ty: &Type, lookup: F) -> Type
1395where
1396    F: Fn(&str) -> Option<&'d Definition>,
1397{
1398    let mut current = ty.unwrap_forall().clone();
1399    let mut seen: HashSet<Symbol> = HashSet::default();
1400    while let Type::Nominal { id, params } = &current {
1401        if !seen.insert(id.clone()) {
1402            break;
1403        }
1404        let Some(underlying) =
1405            lookup(id.as_str()).and_then(|definition| definition.instantiate_underlying(params))
1406        else {
1407            break;
1408        };
1409        current = underlying.unwrap_forall().clone();
1410    }
1411    current
1412}
1413
1414pub fn resolves_to_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1415where
1416    F: Fn(&str) -> Option<&'d Definition>,
1417{
1418    peel_alias(ty, lookup).is_unknown()
1419}
1420
1421pub fn contains_unknown<'d, F>(ty: &Type, lookup: F) -> bool
1422where
1423    F: Fn(&str) -> Option<&'d Definition>,
1424{
1425    fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
1426    where
1427        F: Fn(&str) -> Option<&'d Definition>,
1428    {
1429        let peeled = peel_alias(ty, lookup);
1430        peeled.is_unknown()
1431            || peeled
1432                .children()
1433                .into_iter()
1434                .any(|child| contains(child, lookup))
1435    }
1436
1437    contains(ty, &lookup)
1438}
1439
1440pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
1441where
1442    F: Fn(&str) -> Option<&'d Definition>,
1443{
1444    peel_underlying(ty, lookup).as_simple()
1445}
1446
1447pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1448where
1449    F: Fn(&str) -> Option<&'d Definition>,
1450{
1451    let underlying = peel_underlying(ty, lookup);
1452    underlying.is_numeric().then_some(underlying)
1453}
1454
1455pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
1456where
1457    F: Fn(&str) -> Option<&'d Definition>,
1458{
1459    underlying_numeric_type(ty, &lookup).or_else(|| {
1460        (matches!(ty.unwrap_forall(), Type::Nominal { .. })
1461            && underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
1462        .then_some(Type::Simple(SimpleKind::Uintptr))
1463    })
1464}
1465
1466pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
1467where
1468    F: Fn(&str) -> Option<&'d Definition>,
1469{
1470    match (
1471        underlying_numeric_type(left, &lookup),
1472        underlying_numeric_type(right, &lookup),
1473    ) {
1474        (Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
1475        _ => false,
1476    }
1477}
1478
1479pub fn is_aliased_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
1480where
1481    F: Fn(&str) -> Option<&'d Definition>,
1482{
1483    matches!(ty.unwrap_forall(), Type::Nominal { .. })
1484        && underlying_type(ty, &lookup).is_some()
1485        && !ty.is_numeric()
1486        && underlying_numeric_type(ty, lookup).is_some()
1487}
1488
1489pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
1490where
1491    F: Fn(&str) -> Option<&'d Definition>,
1492{
1493    peel_underlying(ty, lookup).is_byte_or_rune_slice()
1494}
1495
1496pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
1497where
1498    F: Fn(&str) -> Option<&'d Definition>,
1499{
1500    matches!(
1501        underlying_simple_kind(ty, lookup),
1502        Some(kind) if kind.is_ordered() || kind == SimpleKind::String
1503    ) || ty.is_boolean()
1504}
1505
1506/// True for Go's `cmp.Ordered` set: ints, floats, strings, parameters, and
1507/// named aliases over those types.
1508pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
1509where
1510    F: Fn(&str) -> Option<&'d Definition>,
1511{
1512    let Some(kind) = underlying_simple_kind(ty, lookup) else {
1513        return matches!(ty.unwrap_forall(), Type::Parameter(_));
1514    };
1515    matches!(
1516        kind,
1517        SimpleKind::Int
1518            | SimpleKind::Int8
1519            | SimpleKind::Int16
1520            | SimpleKind::Int32
1521            | SimpleKind::Int64
1522            | SimpleKind::Uint
1523            | SimpleKind::Uint8
1524            | SimpleKind::Uint16
1525            | SimpleKind::Uint32
1526            | SimpleKind::Uint64
1527            | SimpleKind::Uintptr
1528            | SimpleKind::Byte
1529            | SimpleKind::Rune
1530            | SimpleKind::Float32
1531            | SimpleKind::Float64
1532            | SimpleKind::String
1533    )
1534}
1535
1536/// True when the Go representation carries `nil`, so an `Option` over it
1537/// encodes `None` as `nil` instead of a tag.
1538pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
1539    let core = peel_underlying(ty, &lookup);
1540    if let Type::Nominal { id, .. } = &core {
1541        return matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
1542    }
1543    core.is_ref()
1544        || matches!(core, Type::Function(_))
1545        || core.is_map()
1546        || core.is_channel()
1547        || core.is_native(CompoundKind::Sender)
1548        || core.is_receiver()
1549}
1550
1551/// Walk an alias chain by id alone (for example during Go-name resolution).
1552pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
1553where
1554    F: Fn(&str) -> Option<String>,
1555{
1556    let mut current = id.to_string();
1557    let mut seen: Vec<String> = Vec::new();
1558    loop {
1559        if seen.iter().any(|s| s == &current) {
1560            return current;
1561        }
1562        let Some(next) = next_alias(&current) else {
1563            return current;
1564        };
1565        seen.push(current);
1566        current = next;
1567    }
1568}
1569
1570impl Type {
1571    pub fn unwrap_forall(&self) -> &Type {
1572        match self {
1573            Type::Forall { body, .. } => body.as_ref(),
1574            other => other,
1575        }
1576    }
1577
1578    pub fn as_function_type(&self) -> Option<&FunctionType> {
1579        match self.unwrap_forall() {
1580            Type::Function(f) => Some(f),
1581            _ => None,
1582        }
1583    }
1584
1585    pub fn strip_refs(&self) -> Type {
1586        if self.is_ref() {
1587            return self.inner().expect("ref type must have inner").strip_refs();
1588        }
1589
1590        self.clone()
1591    }
1592
1593    pub fn with_receiver_placeholder(self) -> Type {
1594        match self {
1595            Type::Function(f) => {
1596                let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
1597                let mut new_params = vec![FunctionParameter::new(Type::ReceiverPlaceholder, false)];
1598                new_params.extend(f.params);
1599
1600                Type::function(new_params, f.bounds, f.return_type)
1601            }
1602            _ => unreachable!(
1603                "with_receiver_placeholder called on non-function type: {:?}",
1604                self
1605            ),
1606        }
1607    }
1608
1609    pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
1610        let mut vars = HashMap::default();
1611        let types = types
1612            .iter()
1613            .map(|v| Self::remove_vars_impl(v, &mut vars))
1614            .collect();
1615
1616        (types, vars.into_values().collect())
1617    }
1618
1619    fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
1620        match ty {
1621            Type::Nominal {
1622                id: name,
1623                params: args,
1624            } => Type::Nominal {
1625                id: name.clone(),
1626                params: args
1627                    .iter()
1628                    .map(|a| Self::remove_vars_impl(a, vars))
1629                    .collect(),
1630            },
1631
1632            Type::Function(f) => Type::function(
1633                f.params
1634                    .iter()
1635                    .map(|param| param.with_type(Self::remove_vars_impl(&param.ty, vars)))
1636                    .collect(),
1637                f.bounds
1638                    .iter()
1639                    .map(|b| Bound {
1640                        param_name: b.param_name.clone(),
1641                        generic: Self::remove_vars_impl(&b.generic, vars),
1642                        ty: Self::remove_vars_impl(&b.ty, vars),
1643                    })
1644                    .collect(),
1645                Self::remove_vars_impl(&f.return_type, vars).into(),
1646            ),
1647
1648            Type::Var { id, hint } => match vars.get(&id.index()) {
1649                Some(g) => Type::Parameter(g.clone()),
1650                None => {
1651                    let name: EcoString = hint
1652                        .clone()
1653                        .unwrap_or_else(|| alpha_index(vars.len()).into());
1654
1655                    vars.insert(id.index(), name.clone());
1656                    Type::Parameter(name)
1657                }
1658            },
1659
1660            Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
1661            Type::Tuple(elements) => Type::Tuple(
1662                elements
1663                    .iter()
1664                    .map(|e| Self::remove_vars_impl(e, vars))
1665                    .collect(),
1666            ),
1667            Type::Compound { kind, args } => Type::Compound {
1668                kind: *kind,
1669                args: args
1670                    .iter()
1671                    .map(|a| Self::remove_vars_impl(a, vars))
1672                    .collect(),
1673            },
1674            Type::Array { length, element } => Type::Array {
1675                length: *length,
1676                element: Box::new(Self::remove_vars_impl(element, vars)),
1677            },
1678            Type::Simple(_) | Type::Parameter(_) => ty.clone(),
1679            Type::Never
1680            | Type::Uninferred
1681            | Type::Ignored
1682            | Type::Error
1683            | Type::ImportNamespace(_)
1684            | Type::ReceiverPlaceholder => ty.clone(),
1685        }
1686    }
1687
1688    pub fn contains_type(&self, target: &Type) -> bool {
1689        if *self == *target {
1690            return true;
1691        }
1692        match self {
1693            Type::Nominal { params, .. } => params.iter().any(|p| p.contains_type(target)),
1694            Type::Function(f) => {
1695                f.params.iter().any(|p| p.ty.contains_type(target))
1696                    || f.return_type.contains_type(target)
1697            }
1698            Type::Var { .. } => false,
1699            Type::Forall { body, .. } => body.contains_type(target),
1700            Type::Tuple(elements) => elements.iter().any(|e| e.contains_type(target)),
1701            Type::Array { element, .. } => element.contains_type(target),
1702            Type::Compound { args, .. } => args.iter().any(|a| a.contains_type(target)),
1703            Type::Simple(_)
1704            | Type::Parameter(_)
1705            | Type::Never
1706            | Type::Uninferred
1707            | Type::Ignored
1708            | Type::Error
1709            | Type::ImportNamespace(_)
1710            | Type::ReceiverPlaceholder => false,
1711        }
1712    }
1713}
1714
1715impl Type {
1716    pub fn numeric_family(&self) -> Option<NumericFamily> {
1717        self.as_simple()?.numeric_family()
1718    }
1719}
1720
1721/// 0 → "A", 25 → "Z", 26 → "AA", 27 → "AB", ... (bijective base-26 over A-Z).
1722fn alpha_index(idx: usize) -> String {
1723    let mut s = String::new();
1724    let mut n = idx + 1;
1725    while n > 0 {
1726        n -= 1;
1727        s.insert(0, (b'A' + (n % 26) as u8) as char);
1728        n /= 26;
1729    }
1730    s
1731}
1732
1733#[cfg(test)]
1734mod tests {
1735    use super::*;
1736
1737    #[test]
1738    fn function_equality_ignores_param_names() {
1739        let named = Type::function(
1740            vec![FunctionParameter::named(
1741                Type::int(),
1742                Some("width".into()),
1743                false,
1744            )],
1745            vec![],
1746            Box::new(Type::bool()),
1747        );
1748        let differently_named = Type::function(
1749            vec![FunctionParameter::named(
1750                Type::int(),
1751                Some("height".into()),
1752                false,
1753            )],
1754            vec![],
1755            Box::new(Type::bool()),
1756        );
1757        let unnamed = Type::function(
1758            vec![FunctionParameter::new(Type::int(), false)],
1759            vec![],
1760            Box::new(Type::bool()),
1761        );
1762
1763        assert_eq!(named, differently_named);
1764        assert_eq!(named, unnamed);
1765    }
1766
1767    #[test]
1768    fn alpha_index_single() {
1769        assert_eq!(alpha_index(0), "A");
1770        assert_eq!(alpha_index(5), "F");
1771        assert_eq!(alpha_index(25), "Z");
1772    }
1773
1774    #[test]
1775    fn alpha_index_double() {
1776        assert_eq!(alpha_index(26), "AA");
1777        assert_eq!(alpha_index(27), "AB");
1778        assert_eq!(alpha_index(51), "AZ");
1779        assert_eq!(alpha_index(52), "BA");
1780        assert_eq!(alpha_index(701), "ZZ");
1781    }
1782
1783    #[test]
1784    fn alpha_index_triple() {
1785        assert_eq!(alpha_index(702), "AAA");
1786    }
1787
1788    fn unhinted_var(id: u32) -> Type {
1789        Type::Var {
1790            id: TypeVarId::new(id),
1791            hint: None,
1792        }
1793    }
1794
1795    #[test]
1796    fn remove_vars_handles_more_than_six_unhinted_vars() {
1797        let func = Type::function(
1798            (0..6)
1799                .map(unhinted_var)
1800                .map(|ty| FunctionParameter::new(ty, false))
1801                .collect(),
1802            vec![],
1803            Box::new(unhinted_var(6)),
1804        );
1805
1806        let (resolved, generics) = Type::remove_vars(&[&func]);
1807
1808        assert_eq!(generics.len(), 7);
1809        let Type::Function(f) = &resolved[0] else {
1810            panic!("expected function type");
1811        };
1812        let names: Vec<_> = f
1813            .params
1814            .iter()
1815            .map(|param| &param.ty)
1816            .chain(std::iter::once(f.return_type.as_ref()))
1817            .map(|p| match p {
1818                Type::Parameter(name) => name.to_string(),
1819                other => panic!("expected parameter, got {:?}", other),
1820            })
1821            .collect();
1822        assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
1823    }
1824
1825    #[test]
1826    fn remove_vars_handles_dozens_of_unhinted_vars() {
1827        let params: Vec<Type> = (0..30).map(unhinted_var).collect();
1828        let func = Type::function(
1829            params
1830                .iter()
1831                .cloned()
1832                .map(|ty| FunctionParameter::new(ty, false))
1833                .collect(),
1834            vec![],
1835            Box::new(Type::Simple(SimpleKind::Unit)),
1836        );
1837        let (_, generics) = Type::remove_vars(&[&func]);
1838        assert_eq!(generics.len(), 30);
1839    }
1840}