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