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