Skip to main content

lisette_syntax/
types.rs

1use rustc_hash::{FxHashMap, FxHashSet};
2use std::borrow::Borrow;
3use std::hash::{Hash, Hasher};
4use std::mem;
5use std::slice;
6use std::sync::Arc;
7
8use ecow::EcoString;
9
10use crate::ast::{Generic, VariantFields};
11use crate::program::{
12    Definition, DefinitionBody, PRELUDE_PACKAGE_ID, is_go_import, strip_go_prefix,
13};
14use fmt::Formatter;
15use std::fmt;
16use std::fmt::Display;
17use std::ops::Deref;
18
19/// Dot-qualified identifier for a named type, method, value, or variant.
20///
21/// Wraps the qualified name (`"main.Point.sum"`, `"prelude.Option"`,
22/// `"go:net/http.Handler"`) as a single `EcoString` and exposes structured
23/// accessors. Centralizes the join/split logic that used to live in ad-hoc
24/// `format!("{}.{}", ..)` and `split_once('.')` call sites.
25#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct Symbol(EcoString);
28
29impl Symbol {
30    /// Joins a package id and a local (possibly multi-segment) name.
31    ///
32    /// `Symbol::from_parts("main", "Point.sum")` → `"main.Point.sum"`.
33    pub fn from_parts(package: &str, local: &str) -> Self {
34        // Build straight into the EcoString: results up to its 15-byte inline
35        // limit never touch the heap, and longer ones allocate once instead of
36        // twice (a temporary `String` plus the `EcoString` copy).
37        let mut s = EcoString::with_capacity(package.len() + 1 + local.len());
38        s.push_str(package);
39        s.push('.');
40        s.push_str(local);
41        Self(s)
42    }
43
44    /// Appends an additional dot-segment to an already-qualified symbol.
45    ///
46    /// `Symbol::from_raw("main.Shape").with_segment("Circle")` →
47    /// `"main.Shape.Circle"`.
48    pub fn with_segment(&self, segment: &str) -> Self {
49        let mut s = EcoString::with_capacity(self.0.len() + 1 + segment.len());
50        s.push_str(&self.0);
51        s.push('.');
52        s.push_str(segment);
53        Self(s)
54    }
55
56    /// Wraps an already-constructed qualified string. Prefer `from_parts`
57    /// when the package id and local name are available separately.
58    pub fn from_raw(qualified: impl Into<EcoString>) -> Self {
59        Self(qualified.into())
60    }
61
62    pub fn as_str(&self) -> &str {
63        &self.0
64    }
65
66    pub fn as_eco(&self) -> &EcoString {
67        &self.0
68    }
69
70    /// Last dot-separated segment. `"main.Point.sum"` → `"sum"`.
71    pub fn last_segment(&self) -> &str {
72        self.0.rsplit('.').next().unwrap_or(&self.0)
73    }
74
75    /// Strips the last dot-separated segment. `"main.Point.sum"` → `"main.Point"`.
76    /// Returns `None` if the symbol has no dot.
77    pub fn without_last_segment(&self) -> Option<&str> {
78        self.0.rsplit_once('.').map(|(rest, _)| rest)
79    }
80}
81
82impl Borrow<str> for Symbol {
83    fn borrow(&self) -> &str {
84        &self.0
85    }
86}
87
88impl AsRef<str> for Symbol {
89    fn as_ref(&self) -> &str {
90        &self.0
91    }
92}
93
94impl Deref for Symbol {
95    type Target = str;
96
97    fn deref(&self) -> &str {
98        &self.0
99    }
100}
101
102impl From<&Symbol> for EcoString {
103    fn from(s: &Symbol) -> Self {
104        s.0.clone()
105    }
106}
107
108impl Display for Symbol {
109    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
110        self.0.fmt(f)
111    }
112}
113
114impl From<Symbol> for EcoString {
115    fn from(s: Symbol) -> Self {
116        s.0
117    }
118}
119
120impl PartialEq<str> for Symbol {
121    fn eq(&self, other: &str) -> bool {
122        self.0.as_str() == other
123    }
124}
125
126impl PartialEq<&str> for Symbol {
127    fn eq(&self, other: &&str) -> bool {
128        self.0.as_str() == *other
129    }
130}
131
132/// Extract the unqualified name from a dot-qualified identifier.
133///
134/// `"prelude.Option"` → `"Option"`, `"**nominal.int"` → `"int"`, `"foo"` → `"foo"`
135pub fn unqualified_name(id: &str) -> &str {
136    id.rsplit('.').next().unwrap_or(id)
137}
138
139pub const SELF_TYPE_NAME: &str = "Self";
140
141/// Resolve the package of a qualified ID. For `go:` IDs containing `/`,
142/// does a longest-prefix match against known packages to disambiguate paths
143/// whose package segment contains dots (e.g. `gopkg.in/yaml.v3`). Otherwise
144/// splits on the first dot. Returns `None` when the id has no dot and is
145/// not a registered `go:` package.
146pub fn package_for_qualified_name(
147    id: &str,
148    mut contains_package: impl FnMut(&str) -> bool,
149) -> Option<&str> {
150    if !is_go_import(id) || !id.contains('/') {
151        return id.split_once('.').map(|(m, _)| m);
152    }
153
154    let mut end = id.len();
155    while let Some(separator) = id[..end].rfind('.') {
156        let candidate = &id[..separator];
157        if contains_package(candidate) {
158            return Some(candidate);
159        }
160        end = separator;
161    }
162    None
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum RangeKind {
167    Range,
168    RangeInclusive,
169    RangeFrom,
170    RangeTo,
171    RangeToInclusive,
172}
173
174impl RangeKind {
175    pub fn of(ty: &Type) -> Option<Self> {
176        match ty.get_qualified_id()? {
177            "prelude.Range" => Some(Self::Range),
178            "prelude.RangeInclusive" => Some(Self::RangeInclusive),
179            "prelude.RangeFrom" => Some(Self::RangeFrom),
180            "prelude.RangeTo" => Some(Self::RangeTo),
181            "prelude.RangeToInclusive" => Some(Self::RangeToInclusive),
182            _ => None,
183        }
184    }
185
186    pub fn has_start(self) -> bool {
187        matches!(self, Self::Range | Self::RangeInclusive | Self::RangeFrom)
188    }
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub enum IterableKind {
193    String,
194    Slice,
195    EnumeratedSlice,
196    Channel,
197    Array,
198    Map,
199    Seq,
200    Seq2,
201    Range(RangeKind),
202    NotIterable,
203}
204
205impl IterableKind {
206    pub fn of(ty: &Type) -> Option<Self> {
207        if let Some(range) = RangeKind::of(ty) {
208            return Some(Self::Range(range));
209        }
210        Some(match ty.kind() {
211            TypeKind::Simple(SimpleKind::String) => Self::String,
212            TypeKind::Array { .. } => Self::Array,
213            TypeKind::Compound { kind, .. } => match kind {
214                CompoundKind::Slice => Self::Slice,
215                CompoundKind::EnumeratedSlice => Self::EnumeratedSlice,
216                CompoundKind::Channel | CompoundKind::Receiver => Self::Channel,
217                CompoundKind::Map => Self::Map,
218                _ => Self::NotIterable,
219            },
220            TypeKind::Simple(_) | TypeKind::Nominal { .. } | TypeKind::ImportNamespace(_) => {
221                Self::NotIterable
222            }
223            _ => return None,
224        })
225    }
226
227    pub fn yields_key_value(self) -> bool {
228        matches!(self, Self::Map | Self::EnumeratedSlice | Self::Seq2)
229    }
230}
231
232/// Gives out no `&str`, so no code can decide a type property by its spelling.
233#[derive(Debug, Clone, Copy)]
234pub struct DisplayName<'a>(&'a str);
235
236impl Display for DisplayName<'_> {
237    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
238        f.write_str(self.0)
239    }
240}
241
242/// Type parameter name -> concrete type.
243#[derive(Debug, Clone, Default, PartialEq, Eq)]
244pub struct SubstitutionMap(Vec<(EcoString, Type)>);
245
246impl SubstitutionMap {
247    pub fn is_empty(&self) -> bool {
248        self.0.is_empty()
249    }
250
251    pub fn get(&self, name: &str) -> Option<&Type> {
252        self.0
253            .iter()
254            .find_map(|(candidate, ty)| (candidate == name).then_some(ty))
255    }
256
257    pub fn insert(&mut self, name: EcoString, ty: Type) -> Option<Type> {
258        if let Some((_, existing)) = self.0.iter_mut().find(|(candidate, _)| candidate == &name) {
259            return Some(mem::replace(existing, ty));
260        }
261        self.0.push((name, ty));
262        None
263    }
264
265    pub fn iter(&self) -> impl Iterator<Item = (&EcoString, &Type)> {
266        self.0.iter().map(|(name, ty)| (name, ty))
267    }
268
269    pub fn types(&self) -> impl ExactSizeIterator<Item = &Type> + Clone {
270        self.0.iter().map(|(_, ty)| ty)
271    }
272
273    pub fn types_mut(&mut self) -> impl Iterator<Item = &mut Type> {
274        self.0.iter_mut().map(|(_, ty)| ty)
275    }
276}
277
278impl FromIterator<(EcoString, Type)> for SubstitutionMap {
279    fn from_iter<T: IntoIterator<Item = (EcoString, Type)>>(iter: T) -> Self {
280        let mut map = Self::default();
281        for (name, ty) in iter {
282            map.insert(name, ty);
283        }
284        map
285    }
286}
287
288/// Build a substitution map from a list of generics and their type arguments,
289/// pairing each generic's name with the type at the same position.
290pub fn build_substitution_map(generics: &[Generic], type_args: &[Type]) -> SubstitutionMap {
291    generics
292        .iter()
293        .zip(type_args.iter())
294        .map(|(g, t)| (g.name.clone(), t.clone()))
295        .collect()
296}
297
298pub fn build_named_substitution_map<'a>(
299    names: &[EcoString],
300    type_args: impl IntoIterator<Item = &'a Type>,
301) -> SubstitutionMap {
302    names
303        .iter()
304        .zip(type_args)
305        .map(|(name, ty)| (name.clone(), ty.clone()))
306        .collect()
307}
308
309pub fn type_args_match_params<'a>(
310    args: &[Type],
311    params: impl ExactSizeIterator<Item = &'a EcoString>,
312) -> bool {
313    args.len() == params.len()
314        && args
315            .iter()
316            .zip(params)
317            .all(|(arg, param)| matches!(arg.kind(), TypeKind::Parameter(name) if name == param))
318}
319
320pub fn substitute(ty: &Type, map: &SubstitutionMap) -> Type {
321    if map.is_empty() {
322        return ty.clone();
323    }
324    if let TypeKind::Parameter(name) = ty.kind() {
325        return map.get(name).cloned().unwrap_or_else(|| ty.clone());
326    }
327    ty.carry_spelling(substitute_structure(ty, map), |argument| {
328        substitute(argument, map)
329    })
330}
331
332fn substitute_structure(ty: &Type, map: &SubstitutionMap) -> Type {
333    match ty.kind() {
334        TypeKind::Parameter(_) => ty.clone(),
335        TypeKind::Nominal {
336            id,
337            params,
338            writable,
339        } => TypeKind::Nominal {
340            id: id.clone(),
341            params: params.iter().map(|p| substitute(p, map)).collect(),
342            writable: *writable,
343        }
344        .into(),
345        TypeKind::Function(f) => f.rebuild(
346            f.params
347                .iter()
348                .map(|param| param.with_type(substitute(&param.ty, map)))
349                .collect(),
350            f.bounds
351                .iter()
352                .map(|b| Bound {
353                    param_name: b.param_name.clone(),
354                    generic: substitute(&b.generic, map),
355                    ty: substitute(&b.ty, map),
356                })
357                .collect(),
358            Box::new(substitute(&f.return_type, map)),
359        ),
360        TypeKind::Var { .. } | TypeKind::Uninferred | TypeKind::Error(_) => ty.clone(),
361        TypeKind::Tuple(elements) => {
362            Type::tuple(elements.iter().map(|e| substitute(e, map)).collect())
363        }
364        TypeKind::Array { length, element } => TypeKind::Array {
365            length: *length,
366            element: Box::new(substitute(element, map)),
367        }
368        .into(),
369        TypeKind::Compound {
370            kind,
371            args,
372            writable,
373        } => Type::qualified_compound(
374            *kind,
375            args.iter().map(|a| substitute(a, map)).collect(),
376            *writable,
377        ),
378        TypeKind::Simple(_)
379        | TypeKind::Never
380        | TypeKind::ImportNamespace(_)
381        | TypeKind::ReceiverPlaceholder => ty.clone(),
382    }
383}
384
385#[derive(Debug, Clone, PartialEq)]
386#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
387pub struct Bound {
388    pub param_name: EcoString,
389    pub generic: Type,
390    pub ty: Type,
391}
392
393#[derive(Debug, Clone, PartialEq)]
394#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
395pub struct FunctionParameter {
396    pub ty: Type,
397    pub name: Option<EcoString>,
398}
399
400impl FunctionParameter {
401    pub fn new(ty: Type) -> Self {
402        Self { ty, name: None }
403    }
404
405    pub fn named(ty: Type, name: Option<EcoString>) -> Self {
406        Self { ty, name }
407    }
408
409    pub fn with_type(&self, ty: Type) -> Self {
410        Self {
411            ty,
412            name: self.name.clone(),
413        }
414    }
415}
416
417#[derive(Clone)]
418#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
419pub struct FunctionType {
420    pub params: Vec<FunctionParameter>,
421    pub bounds: Vec<Bound>,
422    pub return_type: Box<Type>,
423}
424
425impl PartialEq for FunctionType {
426    fn eq(&self, other: &Self) -> bool {
427        self.params.len() == other.params.len()
428            && self
429                .params
430                .iter()
431                .zip(&other.params)
432                .all(|(left, right)| left.ty == right.ty)
433            && self.bounds == other.bounds
434            && self.return_type == other.return_type
435    }
436}
437
438impl FunctionType {
439    pub fn remove_receiver(&mut self) -> Type {
440        self.params.remove(0).ty
441    }
442
443    pub fn without_receiver(&self) -> Type {
444        let mut stripped = self.clone();
445        if !stripped.params.is_empty() {
446            stripped.remove_receiver();
447        }
448        TypeKind::Function(Arc::new(stripped)).into()
449    }
450
451    pub fn rebuild(
452        &self,
453        params: Vec<FunctionParameter>,
454        bounds: Vec<Bound>,
455        return_type: Box<Type>,
456    ) -> Type {
457        Type::function(params, bounds, return_type)
458    }
459}
460
461/// A unique handle identifying an inference variable in a checker's type environment.
462#[derive(Clone, Copy, PartialEq, Eq, Hash)]
463#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
464pub struct TypeVarId(u32);
465
466impl TypeVarId {
467    pub const fn new(index: u32) -> Self {
468        Self(index)
469    }
470
471    pub const fn index(self) -> u32 {
472        self.0
473    }
474}
475
476impl fmt::Debug for TypeVarId {
477    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
478        write!(f, "#{}", self.0)
479    }
480}
481
482#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
483#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
484pub struct ErrorReported(());
485
486impl ErrorReported {
487    #[doc(hidden)]
488    pub fn unchecked() -> Self {
489        Self(())
490    }
491}
492
493#[derive(Clone)]
494#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
495pub struct Type {
496    kind: TypeKind,
497    spelling: Option<Arc<Spelling>>,
498}
499
500const RUNE_ALIAS: &str = "prelude.rune";
501
502#[derive(Debug, Clone)]
503#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
504pub struct Spelling {
505    pub alias: Symbol,
506    pub args: TypeList,
507}
508
509impl Type {
510    pub fn kind(&self) -> &TypeKind {
511        &self.kind
512    }
513
514    pub fn into_kind(self) -> TypeKind {
515        self.kind
516    }
517
518    pub fn kind_mut(&mut self) -> &mut TypeKind {
519        self.spelling = None;
520        &mut self.kind
521    }
522
523    pub fn spelling(&self) -> Option<&Spelling> {
524        self.spelling.as_deref()
525    }
526
527    pub fn spelled(kind: TypeKind, spelling: Spelling) -> Self {
528        Self {
529            kind,
530            spelling: Some(Arc::new(spelling)),
531        }
532    }
533
534    pub fn same_spelling_as(&self, other: &Type) -> bool {
535        self == other && self.spellings_match(other)
536    }
537
538    fn spellings_match(&self, other: &Type) -> bool {
539        match (self.spelling(), other.spelling()) {
540            (Some(left), Some(right)) => {
541                left.alias == right.alias
542                    && left.args.len() == right.args.len()
543                    && left
544                        .args
545                        .iter()
546                        .zip(right.args.iter())
547                        .all(|(left, right)| left.same_spelling_as(right))
548            }
549            (None, None) => self
550                .children()
551                .zip(other.children())
552                .all(|(left, right)| left.spellings_match(right)),
553            (Some(_), None) | (None, Some(_)) => false,
554        }
555    }
556
557    pub fn written_alias(&self) -> Option<Type> {
558        let spelling = self.spelling()?;
559        Some(
560            TypeKind::Nominal {
561                id: spelling.alias.clone(),
562                params: spelling.args.clone(),
563                writable: self.is_writable(),
564            }
565            .into(),
566        )
567    }
568
569    pub fn without_spelling(&self) -> Type {
570        self.kind.clone().into()
571    }
572
573    pub fn carry_spelling(&self, target: Type, map: impl FnMut(&Type) -> Type) -> Type {
574        match &self.spelling {
575            None => target,
576            Some(_) => self.rebuilt(target.kind, map),
577        }
578    }
579
580    pub fn edit_kind_keeping_spelling(mut self, edit: impl FnOnce(&mut TypeKind)) -> Type {
581        edit(&mut self.kind);
582        self
583    }
584
585    fn rebuilt(&self, kind: TypeKind, mut map: impl FnMut(&Type) -> Type) -> Type {
586        let spelling = self.spelling.as_ref().map(|spelling| {
587            Arc::new(Spelling {
588                alias: spelling.alias.clone(),
589                args: spelling.args.iter().map(&mut map).collect(),
590            })
591        });
592        Type { kind, spelling }
593    }
594}
595
596#[derive(Clone, Debug, PartialEq)]
597#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
598pub struct TypeScheme {
599    pub vars: Vec<EcoString>,
600    pub body: Type,
601}
602
603impl TypeScheme {
604    pub fn mono(body: Type) -> Self {
605        Self {
606            vars: Vec::new(),
607            body,
608        }
609    }
610
611    pub fn is_generic(&self) -> bool {
612        !self.vars.is_empty()
613    }
614
615    pub fn equals_receiver_vars(
616        &self,
617        owner_id: &str,
618        arity: usize,
619        peel: impl Fn(&Type) -> Type,
620    ) -> Option<Vec<EcoString>> {
621        if !self.body.is_equals_signature(&peel) || self.vars.len() != arity {
622            return None;
623        }
624        let TypeKind::Function(f) = self.body.kind() else {
625            return None;
626        };
627        let TypeKind::Nominal { id, params, .. } = peel(&f.params[0].ty).into_kind() else {
628            return None;
629        };
630        if id.as_str() != owner_id || params.len() != arity {
631            return None;
632        }
633        let mut vars = Vec::with_capacity(arity);
634        for param in params.iter().cloned() {
635            let TypeKind::Parameter(name) = param.into_kind() else {
636                return None;
637            };
638            if vars.contains(&name) {
639                return None;
640            }
641            vars.push(name);
642        }
643        if !self.vars.iter().all(|v| vars.contains(v)) {
644            return None;
645        }
646        Some(vars)
647    }
648}
649
650impl From<TypeKind> for Type {
651    fn from(kind: TypeKind) -> Self {
652        Self {
653            kind,
654            spelling: None,
655        }
656    }
657}
658
659impl PartialEq for Type {
660    fn eq(&self, other: &Self) -> bool {
661        self.kind == other.kind
662    }
663}
664
665impl Eq for Type {}
666
667impl Hash for Type {
668    fn hash<H: Hasher>(&self, state: &mut H) {
669        self.kind.hash(state);
670    }
671}
672
673impl fmt::Debug for Type {
674    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
675        self.kind.fmt(f)
676    }
677}
678
679#[derive(Clone)]
680#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
681pub enum TypeKind {
682    Simple(SimpleKind),
683
684    Compound {
685        kind: CompoundKind,
686        args: TypeList,
687        /// Write permission through this reference. Only `Slice`, `Map`,
688        /// and `Ref` can carry it.
689        writable: bool,
690    },
691
692    Nominal {
693        id: Symbol,
694        params: TypeList,
695        writable: bool,
696    },
697
698    /// Package namespace handle. Produced by imports (e.g. `import http "net/http"`
699    /// produces an `ImportNamespace("go:net/http")` on the local identifier).
700    /// Dot-access on this type resolves to the package's exports.
701    ImportNamespace(EcoString),
702
703    Function(Arc<FunctionType>),
704
705    /// Type variable handle. Binding state lives in a `TypeEnv` owned by the
706    /// checker; the inline `hint` is display metadata set at allocation time
707    /// so `Display`/`Debug` work without env access.
708    Var {
709        id: TypeVarId,
710        hint: Option<EcoString>,
711    },
712
713    /// Placeholder on syntax that has not entered type inference yet.
714    Uninferred,
715
716    Parameter(EcoString),
717
718    Never,
719
720    Tuple(Vec<Type>),
721
722    /// Fixed-size array `Array<T, N>`, lowered to Go `[N]T`. The length is part
723    /// of the type, so different-length arrays never unify.
724    Array {
725        length: u64,
726        element: Box<Type>,
727    },
728
729    /// Poison type returned after an error has been reported.
730    /// Unifies with everything silently, preventing cascading diagnostics.
731    Error(ErrorReported),
732
733    /// Sentinel occupying the receiver slot of an interface method type.
734    /// Unifies silently so an implementing type's receiver does not conflict
735    /// with the abstract method shape. Previously encoded as
736    /// `Constructor { id: "**nominal.__receiver__" }`.
737    ReceiverPlaceholder,
738}
739
740#[derive(Clone, Default, PartialEq, Eq, Hash)]
741pub struct TypeList(Option<Arc<Box<[Type]>>>);
742
743impl TypeList {
744    pub const fn new() -> Self {
745        Self(None)
746    }
747
748    pub fn as_slice(&self) -> &[Type] {
749        self.0.as_deref().map_or(&[], |items| items)
750    }
751}
752
753impl Deref for TypeList {
754    type Target = [Type];
755
756    fn deref(&self) -> &[Type] {
757        self.as_slice()
758    }
759}
760
761impl fmt::Debug for TypeList {
762    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
763        self.as_slice().fmt(f)
764    }
765}
766
767impl From<Vec<Type>> for TypeList {
768    fn from(items: Vec<Type>) -> Self {
769        Self((!items.is_empty()).then(|| Arc::new(items.into_boxed_slice())))
770    }
771}
772
773impl From<&[Type]> for TypeList {
774    fn from(items: &[Type]) -> Self {
775        Self((!items.is_empty()).then(|| Arc::new(Box::from(items))))
776    }
777}
778
779impl FromIterator<Type> for TypeList {
780    fn from_iter<I: IntoIterator<Item = Type>>(iter: I) -> Self {
781        Self::from(iter.into_iter().collect::<Vec<_>>())
782    }
783}
784
785impl<'a> IntoIterator for &'a TypeList {
786    type Item = &'a Type;
787    type IntoIter = slice::Iter<'a, Type>;
788
789    fn into_iter(self) -> Self::IntoIter {
790        self.as_slice().iter()
791    }
792}
793
794#[cfg(feature = "serde")]
795impl serde::Serialize for TypeList {
796    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
797        self.as_slice().serialize(serializer)
798    }
799}
800
801#[cfg(feature = "serde")]
802impl<'de> serde::Deserialize<'de> for TypeList {
803    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
804        Vec::<Type>::deserialize(deserializer).map(Self::from)
805    }
806}
807
808struct TypePlaceholder(&'static str);
809
810impl fmt::Debug for TypePlaceholder {
811    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
812        f.write_str(self.0)
813    }
814}
815
816impl fmt::Debug for TypeKind {
817    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
818        match self {
819            TypeKind::Nominal {
820                id,
821                params,
822                writable,
823            } => {
824                let mut s = f.debug_struct("Nominal");
825                s.field("id", id).field("params", params);
826                if *writable {
827                    s.field("writable", writable);
828                }
829                s.finish()
830            }
831            TypeKind::Function(f_ty) => {
832                let mut s = f.debug_struct("Function");
833                s.field("params", &f_ty.params)
834                    .field("bounds", &f_ty.bounds)
835                    .field("return_type", &f_ty.return_type)
836                    .finish()
837            }
838            TypeKind::Var { id, hint } => {
839                let mut s = f.debug_struct("Var");
840                s.field("id", id);
841                if let Some(h) = hint {
842                    s.field("hint", h);
843                }
844                s.finish()
845            }
846            TypeKind::Uninferred => f
847                .debug_struct("Var")
848                .field("id", &TypePlaceholder("uninferred"))
849                .finish(),
850            TypeKind::Parameter(name) => f.debug_tuple("Parameter").field(name).finish(),
851            TypeKind::Never => write!(f, "Never"),
852            TypeKind::Tuple(elements) => f.debug_tuple("Tuple").field(elements).finish(),
853            TypeKind::Array { length, element } => f
854                .debug_struct("Array")
855                .field("length", length)
856                .field("element", element)
857                .finish(),
858            TypeKind::Error(_) => write!(f, "Error"),
859            TypeKind::ImportNamespace(package_id) => {
860                f.debug_tuple("ImportNamespace").field(package_id).finish()
861            }
862            TypeKind::ReceiverPlaceholder => write!(f, "ReceiverPlaceholder"),
863            TypeKind::Simple(kind) => f.debug_tuple("Simple").field(kind).finish(),
864            TypeKind::Compound {
865                kind,
866                args,
867                writable,
868            } => {
869                let mut s = f.debug_struct("Compound");
870                s.field("kind", kind).field("args", args);
871                if *writable {
872                    s.field("writable", writable);
873                }
874                s.finish()
875            }
876        }
877    }
878}
879
880impl PartialEq for TypeKind {
881    fn eq(&self, other: &Self) -> bool {
882        match (self, other) {
883            (
884                TypeKind::Nominal {
885                    id: id1,
886                    params: params1,
887                    writable: w1,
888                },
889                TypeKind::Nominal {
890                    id: id2,
891                    params: params2,
892                    writable: w2,
893                },
894            ) => id1 == id2 && params1 == params2 && w1 == w2,
895            (TypeKind::Function(f1), TypeKind::Function(f2)) => f1 == f2,
896            (TypeKind::Var { id: id1, .. }, TypeKind::Var { id: id2, .. }) => id1 == id2,
897            (TypeKind::Uninferred, TypeKind::Uninferred)
898            | (TypeKind::Error(_), TypeKind::Error(_)) => true,
899            (TypeKind::Parameter(name1), TypeKind::Parameter(name2)) => name1 == name2,
900            (TypeKind::Never, TypeKind::Never) => true,
901            (TypeKind::Tuple(elems1), TypeKind::Tuple(elems2)) => elems1 == elems2,
902            (
903                TypeKind::Array {
904                    length: length1,
905                    element: element1,
906                },
907                TypeKind::Array {
908                    length: length2,
909                    element: element2,
910                },
911            ) => length1 == length2 && element1 == element2,
912            (TypeKind::ImportNamespace(m1), TypeKind::ImportNamespace(m2)) => m1 == m2,
913            (TypeKind::ReceiverPlaceholder, TypeKind::ReceiverPlaceholder) => true,
914            (TypeKind::Simple(k1), TypeKind::Simple(k2)) => k1 == k2,
915            (
916                TypeKind::Compound {
917                    kind: k1,
918                    args: a1,
919                    writable: w1,
920                },
921                TypeKind::Compound {
922                    kind: k2,
923                    args: a2,
924                    writable: w2,
925                },
926            ) => k1 == k2 && a1 == a2 && w1 == w2,
927            _ => false,
928        }
929    }
930}
931
932impl Eq for TypeKind {}
933
934impl Hash for TypeKind {
935    fn hash<H: Hasher>(&self, state: &mut H) {
936        mem::discriminant(self).hash(state);
937        match self {
938            TypeKind::Simple(kind) => kind.hash(state),
939            TypeKind::Compound {
940                kind,
941                args,
942                writable,
943            } => {
944                kind.hash(state);
945                args.hash(state);
946                writable.hash(state);
947            }
948            TypeKind::Nominal {
949                id,
950                params,
951                writable,
952            } => {
953                id.hash(state);
954                params.hash(state);
955                writable.hash(state);
956            }
957            TypeKind::ImportNamespace(package_id) => package_id.hash(state),
958            TypeKind::Function(function) => {
959                function.params.len().hash(state);
960                for parameter in &function.params {
961                    parameter.ty.hash(state);
962                }
963                function.bounds.len().hash(state);
964                for bound in &function.bounds {
965                    bound.param_name.hash(state);
966                    bound.generic.hash(state);
967                    bound.ty.hash(state);
968                }
969                function.return_type.hash(state);
970            }
971            TypeKind::Var { id, .. } => id.hash(state),
972            TypeKind::Parameter(name) => name.hash(state),
973            TypeKind::Tuple(elements) => elements.hash(state),
974            TypeKind::Array { length, element } => {
975                length.hash(state);
976                element.hash(state);
977            }
978            TypeKind::Uninferred
979            | TypeKind::Never
980            | TypeKind::Error(_)
981            | TypeKind::ReceiverPlaceholder => {}
982        }
983    }
984}
985
986impl Type {
987    pub fn simple(kind: SimpleKind) -> Type {
988        TypeKind::Simple(kind).into()
989    }
990
991    pub fn never() -> Type {
992        TypeKind::Never.into()
993    }
994
995    pub fn error(reported: ErrorReported) -> Type {
996        TypeKind::Error(reported).into()
997    }
998
999    pub fn parameter(name: EcoString) -> Type {
1000        TypeKind::Parameter(name).into()
1001    }
1002
1003    pub fn tuple(elements: Vec<Type>) -> Type {
1004        TypeKind::Tuple(elements).into()
1005    }
1006
1007    pub fn compound(kind: CompoundKind, args: Vec<Type>) -> Type {
1008        Self::qualified_compound(kind, args, false)
1009    }
1010
1011    pub fn qualified_compound(kind: CompoundKind, args: Vec<Type>, writable: bool) -> Type {
1012        debug_assert!(
1013            !writable || kind.accepts_write_qualifier(),
1014            "writable flag is restricted to Slice, Map, Ref, and VarArgs"
1015        );
1016        let args = if kind.carries_write_permission()
1017            && !writable
1018            && args.iter().any(Type::demotion_changes)
1019        {
1020            args.iter().map(Type::demoted).collect()
1021        } else {
1022            args
1023        };
1024        TypeKind::Compound {
1025            kind,
1026            args: args.into(),
1027            writable,
1028        }
1029        .into()
1030    }
1031
1032    /// Whether a write permission appears anywhere in this type.
1033    pub fn contains_write_permission(&self) -> bool {
1034        match self.kind() {
1035            TypeKind::Compound { args, writable, .. } => {
1036                *writable || args.iter().any(Type::contains_write_permission)
1037            }
1038            TypeKind::Nominal {
1039                params, writable, ..
1040            } => *writable || params.iter().any(Type::contains_write_permission),
1041            TypeKind::Tuple(elements) => elements.iter().any(Type::contains_write_permission),
1042            TypeKind::Array { element, .. } => element.contains_write_permission(),
1043            _ => false,
1044        }
1045    }
1046
1047    /// Whether a type parameter appears anywhere in this type.
1048    pub fn contains_type_parameter(&self) -> bool {
1049        self.is_type_parameter()
1050            || self
1051                .children()
1052                .into_iter()
1053                .any(Type::contains_type_parameter)
1054    }
1055
1056    pub fn is_writable(&self) -> bool {
1057        matches!(
1058            self.kind(),
1059            TypeKind::Compound { writable: true, .. } | TypeKind::Nominal { writable: true, .. }
1060        )
1061    }
1062
1063    pub fn make_writable(self) -> Type {
1064        let spelling = self.spelling;
1065        let kind = match self.kind {
1066            TypeKind::Compound { kind, args, .. } if kind.accepts_write_qualifier() => {
1067                Type::qualified_compound(kind, args.to_vec(), true).kind
1068            }
1069            TypeKind::Nominal { id, params, .. } => TypeKind::Nominal {
1070                id,
1071                params,
1072                writable: true,
1073            },
1074            other => other,
1075        };
1076        Type { kind, spelling }
1077    }
1078
1079    /// A deep clone's type: fresh writable storage at every built-in
1080    /// container layer, nominal elements copied shallowly.
1081    pub fn writable_clone_result(&self) -> Type {
1082        match self.kind() {
1083            TypeKind::Compound { kind, args, .. }
1084                if matches!(kind, CompoundKind::Slice | CompoundKind::EnumeratedSlice) =>
1085            {
1086                let [element] = args.as_slice() else {
1087                    return self.clone();
1088                };
1089                let result =
1090                    Type::qualified_compound(*kind, vec![element.writable_clone_result()], true);
1091                self.carry_spelling(result, Type::writable_clone_result)
1092            }
1093            TypeKind::Compound {
1094                kind: CompoundKind::Map,
1095                args,
1096                ..
1097            } => {
1098                let [key, value] = args.as_slice() else {
1099                    return self.clone();
1100                };
1101                Type::qualified_compound(
1102                    CompoundKind::Map,
1103                    vec![key.clone(), value.writable_clone_result()],
1104                    true,
1105                )
1106            }
1107            TypeKind::Tuple(elements) => {
1108                Type::tuple(elements.iter().map(Type::writable_clone_result).collect())
1109            }
1110            _ => self.clone(),
1111        }
1112    }
1113
1114    /// This type with its own write permission removed, type arguments untouched.
1115    pub fn shallow_demoted(&self) -> Type {
1116        let kind = match self.kind() {
1117            TypeKind::Compound {
1118                kind,
1119                args,
1120                writable: _,
1121            } => TypeKind::Compound {
1122                kind: *kind,
1123                args: args.clone(),
1124                writable: false,
1125            },
1126            TypeKind::Nominal {
1127                id,
1128                params,
1129                writable: _,
1130            } => TypeKind::Nominal {
1131                id: id.clone(),
1132                params: params.clone(),
1133                writable: false,
1134            },
1135            _ => return self.clone(),
1136        };
1137        self.rebuilt(kind, Type::clone)
1138    }
1139
1140    /// Whether `demoted` would return a different type. Must mirror `demoted`.
1141    pub fn demotion_changes(&self) -> bool {
1142        match self.kind() {
1143            TypeKind::Compound { args, writable, .. } => {
1144                *writable || args.iter().any(Type::demotion_changes)
1145            }
1146            TypeKind::Nominal {
1147                params, writable, ..
1148            } => *writable || params.iter().any(Type::demotion_changes),
1149            TypeKind::Tuple(elements) => elements.iter().any(Type::demotion_changes),
1150            TypeKind::Array { element, .. } => element.demotion_changes(),
1151            TypeKind::Function(f) => f.return_type.demotion_changes(),
1152            _ => false,
1153        }
1154    }
1155
1156    pub fn demoted(&self) -> Type {
1157        let kind = match self.kind() {
1158            TypeKind::Compound {
1159                kind,
1160                args,
1161                writable: _,
1162            } => TypeKind::Compound {
1163                kind: *kind,
1164                args: args.iter().map(Type::demoted).collect(),
1165                writable: false,
1166            },
1167            TypeKind::Nominal {
1168                id,
1169                params,
1170                writable: _,
1171            } => TypeKind::Nominal {
1172                id: id.clone(),
1173                params: params.iter().map(Type::demoted).collect(),
1174                writable: false,
1175            },
1176            TypeKind::Tuple(elements) => {
1177                TypeKind::Tuple(elements.iter().map(Type::demoted).collect())
1178            }
1179            TypeKind::Array { length, element } => TypeKind::Array {
1180                length: *length,
1181                element: Box::new(element.demoted()),
1182            },
1183            // A read-only owner hands out a function whose result is read-only.
1184            // Parameters are contravariant, so they keep their permission.
1185            TypeKind::Function(f) => {
1186                f.rebuild(
1187                    f.params.clone(),
1188                    f.bounds.clone(),
1189                    Box::new(f.return_type.demoted()),
1190                )
1191                .kind
1192            }
1193            _ => return self.clone(),
1194        };
1195        self.rebuilt(kind, Type::demoted)
1196    }
1197
1198    pub fn function(
1199        params: Vec<FunctionParameter>,
1200        bounds: Vec<Bound>,
1201        return_type: Box<Type>,
1202    ) -> Type {
1203        TypeKind::Function(Arc::new(FunctionType {
1204            params,
1205            bounds,
1206            return_type,
1207        }))
1208        .into()
1209    }
1210
1211    pub fn int() -> Type {
1212        Self::simple(SimpleKind::Int)
1213    }
1214
1215    pub fn rune() -> Type {
1216        Self::spelled(
1217            TypeKind::Simple(SimpleKind::Int32),
1218            Spelling {
1219                alias: Symbol::from_raw(RUNE_ALIAS),
1220                args: TypeList::new(),
1221            },
1222        )
1223    }
1224
1225    pub fn string() -> Type {
1226        Self::simple(SimpleKind::String)
1227    }
1228
1229    pub fn bool() -> Type {
1230        Self::simple(SimpleKind::Bool)
1231    }
1232
1233    pub fn unit() -> Type {
1234        Self::simple(SimpleKind::Unit)
1235    }
1236
1237    pub fn test_context() -> Type {
1238        TypeKind::Nominal {
1239            id: Symbol::from_raw(TEST_CONTEXT_ID),
1240            params: TypeList::new(),
1241            writable: false,
1242        }
1243        .into()
1244    }
1245
1246    pub fn is_test_context(&self) -> bool {
1247        self.strip_refs().get_qualified_id() == Some(TEST_CONTEXT_ID)
1248    }
1249}
1250
1251pub const TEST_CONTEXT_ID: &str = "**test_prelude.TestContext";
1252
1253#[derive(Clone, Copy)]
1254pub enum ScaledImaginary {
1255    FloatLeft(f64),
1256    FloatRight(f64),
1257}
1258
1259pub fn scaled_imaginary(
1260    left_coefficient: Option<f64>,
1261    left_is_float: bool,
1262    right_coefficient: Option<f64>,
1263    right_is_float: bool,
1264) -> Option<ScaledImaginary> {
1265    if let Some(coefficient) = right_coefficient
1266        && left_is_float
1267    {
1268        Some(ScaledImaginary::FloatLeft(coefficient))
1269    } else if let Some(coefficient) = left_coefficient
1270        && right_is_float
1271    {
1272        Some(ScaledImaginary::FloatRight(coefficient))
1273    } else {
1274        None
1275    }
1276}
1277
1278impl Type {
1279    pub fn uninferred() -> Self {
1280        TypeKind::Uninferred.into()
1281    }
1282
1283    pub fn is_uninferred(&self) -> bool {
1284        matches!(self.kind(), TypeKind::Uninferred)
1285    }
1286
1287    pub fn get_type_params(&self) -> Option<&[Type]> {
1288        match self.kind() {
1289            TypeKind::Nominal { params, .. } => Some(params),
1290            TypeKind::Compound { args, .. } => Some(args),
1291            _ => None,
1292        }
1293    }
1294
1295    pub fn without_permissions(&self) -> Type {
1296        self.map_children(Type::without_permissions)
1297            .shallow_demoted()
1298    }
1299
1300    pub fn map_children(&self, mut map: impl FnMut(&Type) -> Type) -> Type {
1301        let kind = match self.kind() {
1302            TypeKind::Nominal {
1303                id,
1304                params: parameters,
1305                writable,
1306            } => TypeKind::Nominal {
1307                id: id.clone(),
1308                params: parameters.iter().map(&mut map).collect(),
1309                writable: *writable,
1310            },
1311            TypeKind::Compound {
1312                kind,
1313                args: arguments,
1314                writable,
1315            } => TypeKind::Compound {
1316                kind: *kind,
1317                args: arguments.iter().map(&mut map).collect(),
1318                writable: *writable,
1319            },
1320            TypeKind::Function(function) => {
1321                let parameters = function
1322                    .params
1323                    .iter()
1324                    .map(|parameter| parameter.with_type(map(&parameter.ty)))
1325                    .collect();
1326                let bounds = function
1327                    .bounds
1328                    .iter()
1329                    .map(|bound| Bound {
1330                        param_name: bound.param_name.clone(),
1331                        generic: map(&bound.generic),
1332                        ty: map(&bound.ty),
1333                    })
1334                    .collect();
1335                function
1336                    .rebuild(parameters, bounds, Box::new(map(&function.return_type)))
1337                    .kind
1338            }
1339            TypeKind::Tuple(elements) => TypeKind::Tuple(elements.iter().map(&mut map).collect()),
1340            TypeKind::Array { element, length } => TypeKind::Array {
1341                element: Box::new(map(element)),
1342                length: *length,
1343            },
1344            TypeKind::Simple(_)
1345            | TypeKind::ImportNamespace(_)
1346            | TypeKind::Var { .. }
1347            | TypeKind::Uninferred
1348            | TypeKind::Parameter(_)
1349            | TypeKind::Never
1350            | TypeKind::Error(_)
1351            | TypeKind::ReceiverPlaceholder => {
1352                if self.spelling.is_none() {
1353                    return self.clone();
1354                }
1355                self.kind.clone()
1356            }
1357        };
1358        self.rebuilt(kind, map)
1359    }
1360
1361    /// Direct child types, for read-only walks. Excludes `Function.bounds`.
1362    pub fn children(&self) -> TypeChildren<'_> {
1363        match self.kind() {
1364            TypeKind::Nominal { params, .. } => TypeChildren::Types(params.iter()),
1365            TypeKind::Compound { args, .. } => TypeChildren::Types(args.iter()),
1366            TypeKind::Function(f) => {
1367                TypeChildren::Function(f.params.iter(), Some(f.return_type.as_ref()))
1368            }
1369            TypeKind::Tuple(elements) => TypeChildren::Types(elements.iter()),
1370            TypeKind::Array { element, .. } => TypeChildren::One(Some(element)),
1371            _ => TypeChildren::One(None),
1372        }
1373    }
1374}
1375
1376#[derive(Clone)]
1377pub enum TypeChildren<'a> {
1378    Types(slice::Iter<'a, Type>),
1379    Function(slice::Iter<'a, FunctionParameter>, Option<&'a Type>),
1380    One(Option<&'a Type>),
1381}
1382
1383impl<'a> Iterator for TypeChildren<'a> {
1384    type Item = &'a Type;
1385
1386    fn next(&mut self) -> Option<&'a Type> {
1387        match self {
1388            TypeChildren::Types(types) => types.next(),
1389            TypeChildren::Function(params, return_type) => params
1390                .next()
1391                .map(|param| &param.ty)
1392                .or_else(|| return_type.take()),
1393            TypeChildren::One(child) => child.take(),
1394        }
1395    }
1396
1397    fn size_hint(&self) -> (usize, Option<usize>) {
1398        let len = self.len();
1399        (len, Some(len))
1400    }
1401}
1402
1403impl ExactSizeIterator for TypeChildren<'_> {
1404    fn len(&self) -> usize {
1405        match self {
1406            TypeChildren::Types(types) => types.len(),
1407            TypeChildren::Function(params, return_type) => {
1408                params.len() + usize::from(return_type.is_some())
1409            }
1410            TypeChildren::One(child) => usize::from(child.is_some()),
1411        }
1412    }
1413}
1414
1415impl DoubleEndedIterator for TypeChildren<'_> {
1416    fn next_back(&mut self) -> Option<Self::Item> {
1417        match self {
1418            TypeChildren::Types(types) => types.next_back(),
1419            TypeChildren::Function(params, return_type) => return_type
1420                .take()
1421                .or_else(|| params.next_back().map(|param| &param.ty)),
1422            TypeChildren::One(child) => child.take(),
1423        }
1424    }
1425}
1426
1427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1428pub enum NumericFamily {
1429    SignedInt,
1430    UnsignedInt,
1431    Float,
1432    Complex,
1433}
1434
1435impl NumericFamily {
1436    pub fn is_integer(self) -> bool {
1437        matches!(self, Self::SignedInt | Self::UnsignedInt)
1438    }
1439}
1440
1441#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1442#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1443pub enum CompoundKind {
1444    Ref,
1445    Slice,
1446    EnumeratedSlice,
1447    Map,
1448    Channel,
1449    Sender,
1450    Receiver,
1451    VarArgs,
1452}
1453
1454impl CompoundKind {
1455    pub fn carries_write_permission(self) -> bool {
1456        matches!(
1457            self,
1458            CompoundKind::Slice
1459                | CompoundKind::EnumeratedSlice
1460                | CompoundKind::Map
1461                | CompoundKind::Ref
1462        )
1463    }
1464
1465    /// Whether `mut` may qualify this kind. A `VarArgs` accepts it for the
1466    /// storage a spread hands over, without being a hop that gates elements.
1467    pub fn accepts_write_qualifier(self) -> bool {
1468        self.carries_write_permission() || matches!(self, CompoundKind::VarArgs)
1469    }
1470
1471    pub fn leaf_name(self) -> &'static str {
1472        match self {
1473            CompoundKind::Ref => "Ref",
1474            CompoundKind::Slice => "Slice",
1475            CompoundKind::EnumeratedSlice => "EnumeratedSlice",
1476            CompoundKind::Map => "Map",
1477            CompoundKind::Channel => "Channel",
1478            CompoundKind::Sender => "Sender",
1479            CompoundKind::Receiver => "Receiver",
1480            CompoundKind::VarArgs => "VarArgs",
1481        }
1482    }
1483
1484    pub fn from_name(name: &str) -> Option<CompoundKind> {
1485        Some(match name {
1486            "Ref" => CompoundKind::Ref,
1487            "Slice" => CompoundKind::Slice,
1488            "EnumeratedSlice" => CompoundKind::EnumeratedSlice,
1489            "Map" => CompoundKind::Map,
1490            "Channel" => CompoundKind::Channel,
1491            "Sender" => CompoundKind::Sender,
1492            "Receiver" => CompoundKind::Receiver,
1493            "VarArgs" => CompoundKind::VarArgs,
1494            _ => return None,
1495        })
1496    }
1497}
1498
1499#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1500#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1501pub enum SimpleKind {
1502    Int,
1503    Int8,
1504    Int16,
1505    Int32,
1506    Int64,
1507    Uint,
1508    Uint8,
1509    Uint16,
1510    Uint32,
1511    Uint64,
1512    Uintptr,
1513    Float32,
1514    Float64,
1515    Complex64,
1516    Complex128,
1517    Bool,
1518    String,
1519    Unit,
1520}
1521
1522impl SimpleKind {
1523    pub fn leaf_name(self) -> &'static str {
1524        match self {
1525            SimpleKind::Int => "int",
1526            SimpleKind::Int8 => "int8",
1527            SimpleKind::Int16 => "int16",
1528            SimpleKind::Int32 => "int32",
1529            SimpleKind::Int64 => "int64",
1530            SimpleKind::Uint => "uint",
1531            SimpleKind::Uint8 => "uint8",
1532            SimpleKind::Uint16 => "uint16",
1533            SimpleKind::Uint32 => "uint32",
1534            SimpleKind::Uint64 => "uint64",
1535            SimpleKind::Uintptr => "uintptr",
1536            SimpleKind::Float32 => "float32",
1537            SimpleKind::Float64 => "float64",
1538            SimpleKind::Complex64 => "complex64",
1539            SimpleKind::Complex128 => "complex128",
1540            SimpleKind::Bool => "bool",
1541            SimpleKind::String => "string",
1542            SimpleKind::Unit => "Unit",
1543        }
1544    }
1545
1546    pub fn from_name(name: &str) -> Option<SimpleKind> {
1547        Some(match name {
1548            "int" => SimpleKind::Int,
1549            "int8" => SimpleKind::Int8,
1550            "int16" => SimpleKind::Int16,
1551            "int32" => SimpleKind::Int32,
1552            "int64" => SimpleKind::Int64,
1553            "uint" => SimpleKind::Uint,
1554            "uint8" => SimpleKind::Uint8,
1555            "uint16" => SimpleKind::Uint16,
1556            "uint32" => SimpleKind::Uint32,
1557            "uint64" => SimpleKind::Uint64,
1558            "uintptr" => SimpleKind::Uintptr,
1559            "byte" => SimpleKind::Uint8,
1560            "float32" => SimpleKind::Float32,
1561            "float64" => SimpleKind::Float64,
1562            "complex64" => SimpleKind::Complex64,
1563            "complex128" => SimpleKind::Complex128,
1564            "rune" => SimpleKind::Int32,
1565            "bool" => SimpleKind::Bool,
1566            "string" => SimpleKind::String,
1567            "Unit" => SimpleKind::Unit,
1568            _ => return None,
1569        })
1570    }
1571
1572    pub fn is_arithmetic(self) -> bool {
1573        !matches!(
1574            self,
1575            SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit
1576        )
1577    }
1578
1579    pub fn is_ordered(self) -> bool {
1580        self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1581    }
1582
1583    pub fn integer_range(self) -> Option<(i128, i128)> {
1584        use SimpleKind::*;
1585        Some(match self {
1586            Int8 => (i8::MIN as i128, i8::MAX as i128),
1587            Int16 => (i16::MIN as i128, i16::MAX as i128),
1588            Int32 => (i32::MIN as i128, i32::MAX as i128),
1589            Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
1590            Uint8 => (0, u8::MAX as i128),
1591            Uint16 => (0, u16::MAX as i128),
1592            Uint32 => (0, u32::MAX as i128),
1593            Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
1594            _ => return None,
1595        })
1596    }
1597
1598    pub fn is_integer(self) -> bool {
1599        self.is_signed_int() || self.is_unsigned_int()
1600    }
1601
1602    pub fn is_unsigned_int(self) -> bool {
1603        matches!(
1604            self,
1605            SimpleKind::Uint
1606                | SimpleKind::Uint8
1607                | SimpleKind::Uint16
1608                | SimpleKind::Uint32
1609                | SimpleKind::Uint64
1610        )
1611    }
1612
1613    pub fn is_unsigned(self) -> bool {
1614        self.is_unsigned_int() || self == SimpleKind::Uintptr
1615    }
1616
1617    pub fn sized_name(self) -> &'static str {
1618        match self {
1619            SimpleKind::Int | SimpleKind::Int64 => "int64",
1620            SimpleKind::Uint | SimpleKind::Uint64 | SimpleKind::Uintptr => "uint64",
1621            kind => kind.leaf_name(),
1622        }
1623    }
1624
1625    pub fn is_signed_int(self) -> bool {
1626        matches!(
1627            self,
1628            SimpleKind::Int
1629                | SimpleKind::Int8
1630                | SimpleKind::Int16
1631                | SimpleKind::Int32
1632                | SimpleKind::Int64
1633        )
1634    }
1635
1636    pub fn is_float(self) -> bool {
1637        matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
1638    }
1639
1640    fn is_complex(self) -> bool {
1641        matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
1642    }
1643
1644    fn numeric_family(self) -> Option<NumericFamily> {
1645        if self.is_signed_int() {
1646            Some(NumericFamily::SignedInt)
1647        } else if self.is_unsigned() {
1648            Some(NumericFamily::UnsignedInt)
1649        } else if self.is_float() {
1650            Some(NumericFamily::Float)
1651        } else if self.is_complex() {
1652            Some(NumericFamily::Complex)
1653        } else {
1654            None
1655        }
1656    }
1657}
1658
1659impl Type {
1660    pub fn get_function_ret(&self) -> Option<&Type> {
1661        match self.kind() {
1662            TypeKind::Function(f) => Some(&f.return_type),
1663            _ => None,
1664        }
1665    }
1666
1667    pub fn is_stringer_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
1668        matches!(
1669            self.kind(),
1670            TypeKind::Function(f)
1671                if f.params.len() == 1
1672                    && matches!(peel(&f.return_type).kind(), TypeKind::Simple(SimpleKind::String))
1673        )
1674    }
1675
1676    pub fn is_equals_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
1677        matches!(
1678            self.kind(),
1679            TypeKind::Function(f)
1680                if f.params.len() == 2
1681                    && matches!(peel(&f.return_type).kind(), TypeKind::Simple(SimpleKind::Bool))
1682                    && peel(&f.params[0].ty) == peel(&f.params[1].ty)
1683                    && !peel(&f.params[0].ty).is_ref()
1684        )
1685    }
1686
1687    pub fn is_equals_bound_signature(
1688        &self,
1689        param_name: &str,
1690        peel: impl Fn(&Type) -> Type,
1691    ) -> bool {
1692        matches!(
1693            self.kind(),
1694            TypeKind::Function(f)
1695                if f.params.len() == 1
1696                    && peel(&f.return_type).is_boolean()
1697                    && matches!(f.params[0].ty.kind(), TypeKind::Parameter(name) if name.as_str() == param_name)
1698        )
1699    }
1700
1701    pub fn has_name(&self, name: &str) -> bool {
1702        match self.kind() {
1703            TypeKind::Nominal { id, .. } => id.last_segment() == name,
1704            TypeKind::Simple(kind) => kind.leaf_name() == name,
1705            TypeKind::Compound { kind, .. } => kind.leaf_name() == name,
1706            _ => false,
1707        }
1708    }
1709
1710    pub fn get_qualified_id(&self) -> Option<&str> {
1711        self.nominal_id().map(Symbol::as_str)
1712    }
1713
1714    pub fn nominal_id(&self) -> Option<&Symbol> {
1715        match self.kind() {
1716            TypeKind::Nominal { id, .. } => Some(id),
1717            _ => None,
1718        }
1719    }
1720
1721    pub fn is_result(&self) -> bool {
1722        self.has_qualified_id("prelude.Result")
1723    }
1724
1725    pub fn is_option(&self) -> bool {
1726        self.has_qualified_id("prelude.Option")
1727    }
1728
1729    pub fn is_partial(&self) -> bool {
1730        self.has_qualified_id("prelude.Partial")
1731    }
1732
1733    pub fn is_value_and_bool(&self) -> bool {
1734        matches!(self.kind(), TypeKind::Tuple(elements) if elements.len() == 2 && elements[1].is_boolean())
1735    }
1736
1737    pub fn option_of(inner: Type) -> Type {
1738        TypeKind::Nominal {
1739            id: Symbol::from_parts(PRELUDE_PACKAGE_ID, "Option"),
1740            params: vec![inner].into(),
1741            writable: false,
1742        }
1743        .into()
1744    }
1745
1746    fn has_qualified_id(&self, qualified_id: &str) -> bool {
1747        matches!(self.kind(), TypeKind::Nominal { id, .. } if id.as_str() == qualified_id)
1748    }
1749
1750    pub fn is_unit(&self) -> bool {
1751        self.is_simple(SimpleKind::Unit)
1752    }
1753
1754    pub fn tuple_arity(&self) -> Option<usize> {
1755        match self.kind() {
1756            TypeKind::Tuple(elements) => Some(elements.len()),
1757            _ => None,
1758        }
1759    }
1760
1761    pub fn is_tuple(&self) -> bool {
1762        matches!(self.kind(), TypeKind::Tuple(_))
1763    }
1764
1765    pub fn is_function(&self) -> bool {
1766        matches!(self.kind(), TypeKind::Function(_))
1767    }
1768
1769    pub fn is_nominal(&self) -> bool {
1770        matches!(self.kind(), TypeKind::Nominal { .. })
1771    }
1772
1773    pub fn is_type_parameter(&self) -> bool {
1774        matches!(self.kind(), TypeKind::Parameter(_))
1775    }
1776
1777    pub fn is_array(&self) -> bool {
1778        matches!(self.kind(), TypeKind::Array { .. })
1779    }
1780
1781    pub fn tuple_elements(&self) -> Option<&[Type]> {
1782        match self.kind() {
1783            TypeKind::Tuple(elements) => Some(elements),
1784            _ => None,
1785        }
1786    }
1787
1788    pub fn array_parts(&self) -> Option<(u64, &Type)> {
1789        match self.kind() {
1790            TypeKind::Array { length, element } => Some((*length, element)),
1791            _ => None,
1792        }
1793    }
1794
1795    pub fn array_len(&self) -> Option<u64> {
1796        match self.kind() {
1797            TypeKind::Array { length, .. } => Some(*length),
1798            _ => None,
1799        }
1800    }
1801
1802    pub fn as_import_namespace(&self) -> Option<&str> {
1803        match self.kind() {
1804            TypeKind::ImportNamespace(package_id) => Some(package_id),
1805            _ => None,
1806        }
1807    }
1808
1809    pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
1810        match self.kind() {
1811            TypeKind::Compound { kind, args, .. } => Some((*kind, args.as_slice())),
1812            _ => None,
1813        }
1814    }
1815
1816    pub fn is_native(&self, kind: CompoundKind) -> bool {
1817        self.as_compound().is_some_and(|(k, _)| k == kind)
1818    }
1819
1820    pub fn is_ref(&self) -> bool {
1821        self.is_native(CompoundKind::Ref)
1822    }
1823
1824    pub fn is_slice(&self) -> bool {
1825        self.is_native(CompoundKind::Slice)
1826    }
1827
1828    pub fn is_map(&self) -> bool {
1829        self.is_native(CompoundKind::Map)
1830    }
1831
1832    pub fn is_channel(&self) -> bool {
1833        self.is_native(CompoundKind::Channel)
1834    }
1835
1836    pub fn is_receiver_placeholder(&self) -> bool {
1837        matches!(self.kind(), TypeKind::ReceiverPlaceholder)
1838    }
1839
1840    pub fn is_unknown(&self) -> bool {
1841        self.has_qualified_id("prelude.Unknown")
1842    }
1843
1844    pub fn is_receiver(&self) -> bool {
1845        self.is_native(CompoundKind::Receiver)
1846    }
1847
1848    pub fn is_variadic(&self) -> Option<Type> {
1849        let last = self.get_function_params()?.last()?;
1850        match last.ty.as_compound()? {
1851            (CompoundKind::VarArgs, _) => last.ty.inner(),
1852            _ => None,
1853        }
1854    }
1855
1856    pub fn is_string(&self) -> bool {
1857        self.is_simple(SimpleKind::String)
1858    }
1859
1860    pub fn as_simple(&self) -> Option<SimpleKind> {
1861        match self.kind() {
1862            TypeKind::Simple(kind) => Some(*kind),
1863            _ => None,
1864        }
1865    }
1866
1867    pub fn is_simple(&self, kind: SimpleKind) -> bool {
1868        self.as_simple() == Some(kind)
1869    }
1870
1871    pub fn is_boolean(&self) -> bool {
1872        self.is_simple(SimpleKind::Bool)
1873    }
1874
1875    pub fn is_float(&self) -> bool {
1876        self.as_simple().is_some_and(SimpleKind::is_float)
1877    }
1878
1879    pub fn is_variable(&self) -> bool {
1880        matches!(self.kind(), TypeKind::Var { .. })
1881    }
1882
1883    /// A transparent alias over this keeps its name, wrapped in a `Nominal`
1884    /// that unification peels back to it.
1885    pub fn is_structural_alias_body(&self) -> bool {
1886        matches!(
1887            self.kind(),
1888            TypeKind::Simple(_)
1889                | TypeKind::Compound { .. }
1890                | TypeKind::Array { .. }
1891                | TypeKind::Tuple(_)
1892        )
1893    }
1894
1895    pub fn is_numeric(&self) -> bool {
1896        self.as_simple().is_some_and(SimpleKind::is_arithmetic)
1897    }
1898
1899    pub fn is_complex(&self) -> bool {
1900        self.as_simple().is_some_and(SimpleKind::is_complex)
1901    }
1902
1903    pub fn is_unsigned_int(&self) -> bool {
1904        self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
1905    }
1906
1907    pub fn is_never(&self) -> bool {
1908        matches!(self.kind(), TypeKind::Never)
1909    }
1910
1911    pub fn is_error(&self) -> bool {
1912        matches!(self.kind(), TypeKind::Error(_))
1913    }
1914
1915    pub fn contains_error(&self) -> bool {
1916        self.reported_error().is_some()
1917    }
1918
1919    pub fn reported_error(&self) -> Option<ErrorReported> {
1920        match self.kind() {
1921            TypeKind::Error(reported) => Some(*reported),
1922            _ => self.children().into_iter().find_map(Type::reported_error),
1923        }
1924    }
1925
1926    pub fn has_variables(&self) -> bool {
1927        self.is_variable() || self.children().into_iter().any(Type::has_variables)
1928    }
1929
1930    pub fn collect_variables(&self, out: &mut Vec<TypeVarId>) {
1931        if let TypeKind::Var { id, .. } = self.kind() {
1932            out.push(*id);
1933        }
1934        for child in self.children() {
1935            child.collect_variables(out);
1936        }
1937    }
1938
1939    pub fn has_unbound_variables(&self) -> bool {
1940        match self.kind() {
1941            TypeKind::Var { hint, .. } => hint.is_some(),
1942            _ => self.children().into_iter().any(Type::has_unbound_variables),
1943        }
1944    }
1945
1946    pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
1947        if let TypeKind::Var { id, hint: Some(_) } = self.kind() {
1948            out.push(*id);
1949        }
1950        for child in self.children() {
1951            child.collect_unbound_variables(out);
1952        }
1953    }
1954
1955    pub fn remove_found_type_names(&self, names: &mut FxHashSet<EcoString>) {
1956        if names.is_empty() {
1957            return;
1958        }
1959
1960        match self.kind() {
1961            TypeKind::Nominal { id, params, .. } => {
1962                names.remove(id.last_segment());
1963                for param in params {
1964                    param.remove_found_type_names(names);
1965                }
1966            }
1967            TypeKind::Function(f) => {
1968                for param in &f.params {
1969                    param.ty.remove_found_type_names(names);
1970                }
1971                f.return_type.remove_found_type_names(names);
1972                for bound in &f.bounds {
1973                    bound.generic.remove_found_type_names(names);
1974                    bound.ty.remove_found_type_names(names);
1975                }
1976            }
1977            TypeKind::Var { .. } => {}
1978            TypeKind::Parameter(name) => {
1979                names.remove(name);
1980            }
1981            TypeKind::Tuple(elements) => {
1982                for element in elements {
1983                    element.remove_found_type_names(names);
1984                }
1985            }
1986            TypeKind::Compound { kind, args, .. } => {
1987                names.remove(kind.leaf_name());
1988                for arg in args {
1989                    arg.remove_found_type_names(names);
1990                }
1991            }
1992            TypeKind::Array { element, .. } => {
1993                names.remove("Array");
1994                element.remove_found_type_names(names);
1995            }
1996            TypeKind::Simple(kind) => {
1997                names.remove(kind.leaf_name());
1998            }
1999            TypeKind::Never
2000            | TypeKind::Uninferred
2001            | TypeKind::Error(_)
2002            | TypeKind::ImportNamespace(_)
2003            | TypeKind::ReceiverPlaceholder => {}
2004        }
2005    }
2006}
2007
2008impl Type {
2009    pub fn display_name(&self) -> Option<DisplayName<'_>> {
2010        if let Some(spelling) = self.spelling() {
2011            return Some(DisplayName(spelling.alias.last_segment()));
2012        }
2013        match self.kind() {
2014            TypeKind::Simple(kind) => Some(DisplayName(kind.leaf_name())),
2015            TypeKind::Compound { kind, args, .. } => match kind {
2016                CompoundKind::Ref => args.first().and_then(|inner| inner.display_name()),
2017                _ => Some(DisplayName(kind.leaf_name())),
2018            },
2019            TypeKind::Nominal { id, .. } => Some(DisplayName(id.last_segment())),
2020            TypeKind::ImportNamespace(_) => self.namespace_name().map(DisplayName),
2021            TypeKind::Array { .. } => Some(DisplayName("Array")),
2022            _ => None,
2023        }
2024    }
2025
2026    pub fn namespace_name(&self) -> Option<&str> {
2027        let TypeKind::ImportNamespace(package_id) = self.kind() else {
2028            return None;
2029        };
2030        let path = strip_go_prefix(package_id).unwrap_or(package_id);
2031        path.rsplit('/').next()
2032    }
2033
2034    pub fn wraps(&self, is_wrapper: impl Fn(&Type) -> bool, inner: &Type) -> bool {
2035        is_wrapper(self)
2036            && self
2037                .get_type_params()
2038                .and_then(|p| p.first())
2039                .is_some_and(|first| *first == *inner)
2040    }
2041
2042    pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
2043        match self.kind() {
2044            TypeKind::Function(f) => Some(&f.params),
2045            _ => None,
2046        }
2047    }
2048
2049    pub fn param_count(&self) -> usize {
2050        match self.kind() {
2051            TypeKind::Function(f) => f.params.len(),
2052            _ => 0,
2053        }
2054    }
2055
2056    pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
2057        match self.kind() {
2058            TypeKind::Function(f) => {
2059                if f.params.is_empty() {
2060                    return self.clone();
2061                }
2062                let mut new_params = f.params.clone();
2063                new_params[0] = new_params[0].with_type(new_first.clone());
2064                f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
2065            }
2066            _ => self.clone(),
2067        }
2068    }
2069
2070    pub fn get_bounds(&self) -> &[Bound] {
2071        match self.kind() {
2072            TypeKind::Function(f) => &f.bounds,
2073            _ => &[],
2074        }
2075    }
2076
2077    pub fn get_qualified_name(&self) -> Option<Symbol> {
2078        let mut current = self;
2079        while current.is_ref() {
2080            current = current.get_type_params()?.first()?;
2081        }
2082        match current.kind() {
2083            TypeKind::Nominal { id, .. } => Some(id.clone()),
2084            TypeKind::Simple(kind) => {
2085                Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name()))
2086            }
2087            TypeKind::Compound { kind, .. } => {
2088                Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name()))
2089            }
2090            _ => None,
2091        }
2092    }
2093
2094    pub fn inner(&self) -> Option<Type> {
2095        self.get_type_params()
2096            .and_then(|args| args.first().cloned())
2097    }
2098
2099    pub fn ok_type(&self) -> Type {
2100        debug_assert!(
2101            self.is_result() || self.is_option() || self.is_partial(),
2102            "ok_type called on non-Result/Option/Partial type"
2103        );
2104        self.inner()
2105            .expect("Result/Option/Partial should have inner type")
2106    }
2107
2108    pub fn err_type(&self) -> Type {
2109        debug_assert!(
2110            self.is_result() || self.is_partial(),
2111            "err_type called on non-Result/Partial type"
2112        );
2113        self.get_type_params()
2114            .and_then(|args| args.get(1).cloned())
2115            .expect("Result/Partial should have error type")
2116    }
2117}
2118
2119#[derive(Clone, Copy, PartialEq, Eq)]
2120pub enum IterSeqKind {
2121    Seq,
2122    Seq2,
2123}
2124
2125pub fn is_rune<'d, F>(ty: &Type, lookup: F) -> bool
2126where
2127    F: Fn(&str) -> Option<&'d Definition>,
2128{
2129    let mut current = ty.clone();
2130    let mut seen: Vec<Symbol> = Vec::new();
2131    while current.is_simple(SimpleKind::Int32) {
2132        let Some(spelling) = current.spelling() else {
2133            return false;
2134        };
2135        if spelling.alias.as_str() == RUNE_ALIAS {
2136            return true;
2137        }
2138        if seen.contains(&spelling.alias) {
2139            return false;
2140        }
2141        seen.push(spelling.alias.clone());
2142        let Some(next) = lookup(spelling.alias.as_str()).and_then(|alias| {
2143            alias.instantiate_alias_target(&spelling.args, current.is_writable())
2144        }) else {
2145            return false;
2146        };
2147        current = next.clone();
2148    }
2149    false
2150}
2151
2152pub fn peel_to_iter_seq<'d, F>(ty: &Type, lookup: F) -> Option<(IterSeqKind, Type)>
2153where
2154    F: Fn(&str) -> Option<&'d Definition>,
2155{
2156    let mut current = ty.clone();
2157    let mut seen: Vec<Symbol> = Vec::new();
2158    loop {
2159        let spelling = current.spelling()?;
2160        match spelling.alias.as_str() {
2161            "go:iter.Seq" => return Some((IterSeqKind::Seq, current)),
2162            "go:iter.Seq2" => return Some((IterSeqKind::Seq2, current)),
2163            _ => {}
2164        }
2165        if seen.contains(&spelling.alias) {
2166            return None;
2167        }
2168        seen.push(spelling.alias.clone());
2169        let next = lookup(spelling.alias.as_str())?
2170            .instantiate_alias_target(&spelling.args, current.is_writable())?;
2171        current = next.strip_refs();
2172    }
2173}
2174
2175/// Return the field type of a newtype occurrence, demoted when the occurrence
2176/// is read-only.
2177pub fn newtype_underlying<'d, F>(ty: &Type, lookup: F) -> Option<Type>
2178where
2179    F: Fn(&str) -> Option<&'d Definition>,
2180{
2181    let TypeKind::Nominal { id, writable, .. } = ty.kind() else {
2182        return None;
2183    };
2184    lookup(id.as_str())?.newtype_underlying(*writable)
2185}
2186
2187/// Follow newtype fields to their canonical representation. The cycle guard
2188/// also makes this safe for recovery types built from invalid recursive
2189/// declarations.
2190pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Type
2191where
2192    F: Fn(&str) -> Option<&'d Definition>,
2193{
2194    let mut current = ty.clone();
2195    let mut seen: FxHashSet<Symbol> = FxHashSet::default();
2196    while let TypeKind::Nominal { id, writable, .. } = current.kind() {
2197        let writable = *writable;
2198        if !seen.insert(id.clone()) {
2199            break;
2200        }
2201        let Some(underlying) =
2202            lookup(id.as_str()).and_then(|definition| definition.newtype_underlying(writable))
2203        else {
2204            break;
2205        };
2206        current = underlying.clone();
2207    }
2208    current
2209}
2210
2211pub const PRELUDE_ERROR_ID: &str = "prelude.error";
2212
2213pub fn as_interface<'d, F>(ty: &Type, lookup: F) -> Option<Symbol>
2214where
2215    F: Fn(&str) -> Option<&'d Definition>,
2216{
2217    let TypeKind::Nominal { id, .. } = ty.without_spelling().into_kind() else {
2218        return None;
2219    };
2220    matches!(
2221        lookup(id.as_str()).map(|definition| &definition.body),
2222        Some(DefinitionBody::Interface { .. })
2223    )
2224    .then_some(id)
2225}
2226
2227pub fn is_lisette_enum<'d, F>(ty: &Type, lookup: F) -> bool
2228where
2229    F: Fn(&str) -> Option<&'d Definition>,
2230{
2231    matches!(ty.without_spelling().kind(), TypeKind::Nominal { id, .. }
2232    if !is_go_import(id)
2233        && matches!(
2234            lookup(id.as_str()).map(|definition| &definition.body),
2235            Some(DefinitionBody::Enum { .. })
2236        ))
2237}
2238
2239pub fn resolve_to_function_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
2240where
2241    F: Fn(&str) -> Option<&'d Definition>,
2242{
2243    let resolved = ty.without_spelling();
2244    if resolved.is_function() {
2245        return Some(resolved);
2246    }
2247    newtype_underlying(&resolved, &lookup).filter(|underlying| underlying.is_function())
2248}
2249
2250pub fn contains_unknown(ty: &Type) -> bool {
2251    ty.is_unknown() || ty.children().into_iter().any(contains_unknown)
2252}
2253
2254pub fn contains_write_permission(ty: &Type) -> bool {
2255    ty.is_writable() || ty.children().into_iter().any(contains_write_permission)
2256}
2257
2258/// Whether a parameter of this type grants the callee write permission over
2259/// the argument's storage.
2260pub fn parameter_grants_write(ty: &Type) -> bool {
2261    match ty.kind() {
2262        TypeKind::Compound { args, writable, .. } => {
2263            *writable || args.iter().any(parameter_grants_write)
2264        }
2265        TypeKind::Nominal {
2266            params, writable, ..
2267        } => *writable || params.iter().any(parameter_grants_write),
2268        TypeKind::Tuple(elements) => elements.iter().any(parameter_grants_write),
2269        TypeKind::Array { element, .. } => parameter_grants_write(element),
2270        _ => false,
2271    }
2272}
2273
2274/// Whether a struct or enum declares a component that carries write permission.
2275pub fn declares_writable_components<'d, F>(id: &str, lookup: &F) -> bool
2276where
2277    F: Fn(&str) -> Option<&'d Definition>,
2278{
2279    match lookup(id).map(|definition| &definition.body) {
2280        Some(DefinitionBody::Struct { fields, .. }) => fields
2281            .as_slice()
2282            .iter()
2283            .any(|field| field.ty.demotion_changes()),
2284        Some(DefinitionBody::Enum { variants, .. }) => variants
2285            .iter()
2286            .flat_map(|variant| match &variant.fields {
2287                VariantFields::Unit => [].as_slice(),
2288                VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
2289            })
2290            .any(|field| field.ty.demotion_changes()),
2291        _ => false,
2292    }
2293}
2294
2295/// The pointee of a `mut Ref`, which is writable when its type declares writable components.
2296pub fn writable_ref_pointee<'d, F>(pointee: &Type, lookup: &F) -> Type
2297where
2298    F: Fn(&str) -> Option<&'d Definition>,
2299{
2300    match pointee.without_spelling().kind() {
2301        TypeKind::Nominal {
2302            id,
2303            writable: false,
2304            ..
2305        } if declares_writable_components(id.as_str(), lookup) => pointee.clone().make_writable(),
2306        _ => pointee.clone(),
2307    }
2308}
2309
2310pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
2311where
2312    F: Fn(&str) -> Option<&'d Definition>,
2313{
2314    underlying_type(ty, lookup).as_simple()
2315}
2316
2317pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
2318where
2319    F: Fn(&str) -> Option<&'d Definition>,
2320{
2321    let underlying = underlying_type(ty, lookup);
2322    underlying.is_numeric().then_some(underlying)
2323}
2324
2325pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
2326where
2327    F: Fn(&str) -> Option<&'d Definition>,
2328{
2329    underlying_numeric_type(ty, &lookup).or_else(|| {
2330        (ty.is_nominal() && underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
2331            .then_some(Type::simple(SimpleKind::Uintptr))
2332    })
2333}
2334
2335pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
2336where
2337    F: Fn(&str) -> Option<&'d Definition>,
2338{
2339    match (
2340        underlying_numeric_type(left, &lookup),
2341        underlying_numeric_type(right, &lookup),
2342    ) {
2343        (Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
2344        _ => false,
2345    }
2346}
2347
2348pub fn is_named_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
2349where
2350    F: Fn(&str) -> Option<&'d Definition>,
2351{
2352    let ty = ty.without_spelling();
2353    ty.is_nominal()
2354        && newtype_underlying(&ty, &lookup).is_some()
2355        && underlying_numeric_type(&ty, lookup).is_some()
2356}
2357
2358pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
2359where
2360    F: Fn(&str) -> Option<&'d Definition>,
2361{
2362    let peeled = underlying_type(ty, &lookup);
2363    let Some((CompoundKind::Slice, [element])) = peeled.as_compound() else {
2364        return false;
2365    };
2366    matches!(
2367        element.without_spelling().as_simple(),
2368        Some(SimpleKind::Uint8 | SimpleKind::Int32)
2369    )
2370}
2371
2372pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
2373where
2374    F: Fn(&str) -> Option<&'d Definition>,
2375{
2376    matches!(
2377        underlying_simple_kind(ty, lookup),
2378        Some(kind) if kind.is_ordered() || kind == SimpleKind::String
2379    )
2380}
2381
2382/// True for Go's `cmp.Ordered` set: ints, floats, strings, parameters, and
2383/// named aliases over those types.
2384pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
2385where
2386    F: Fn(&str) -> Option<&'d Definition>,
2387{
2388    let Some(kind) = underlying_simple_kind(ty, lookup) else {
2389        return ty.is_type_parameter();
2390    };
2391    matches!(
2392        kind,
2393        SimpleKind::Int
2394            | SimpleKind::Int8
2395            | SimpleKind::Int16
2396            | SimpleKind::Int32
2397            | SimpleKind::Int64
2398            | SimpleKind::Uint
2399            | SimpleKind::Uint8
2400            | SimpleKind::Uint16
2401            | SimpleKind::Uint32
2402            | SimpleKind::Uint64
2403            | SimpleKind::Uintptr
2404            | SimpleKind::Float32
2405            | SimpleKind::Float64
2406            | SimpleKind::String
2407    )
2408}
2409
2410/// True when the Go representation carries `nil`, so an `Option` over it
2411/// encodes `None` as `nil` instead of a tag.
2412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2413pub enum GoNilForm {
2414    Never,
2415    Pointer,
2416    Interface,
2417}
2418
2419pub fn go_nil_form<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> GoNilForm {
2420    let core = underlying_type(ty, &lookup);
2421    if let TypeKind::Nominal { id, .. } = core.kind() {
2422        return if matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }))
2423        {
2424            GoNilForm::Interface
2425        } else {
2426            GoNilForm::Never
2427        };
2428    }
2429    let pointer = core.is_ref()
2430        || core.is_function()
2431        || core.is_map()
2432        || core.is_channel()
2433        || core.is_native(CompoundKind::Sender)
2434        || core.is_receiver();
2435    if pointer {
2436        GoNilForm::Pointer
2437    } else {
2438        GoNilForm::Never
2439    }
2440}
2441
2442pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
2443    go_nil_form(ty, lookup) != GoNilForm::Never
2444}
2445
2446/// Whether a Go `Partial` value can be nil, which makes the bare `Err` reachable.
2447pub fn partial_ok_is_nilable<'a>(
2448    ty: &Type,
2449    lookup: impl Fn(&str) -> Option<&'a Definition>,
2450) -> bool {
2451    is_nilable_go_type(ty, &lookup) || ty.without_spelling().is_slice()
2452}
2453
2454impl Type {
2455    pub fn as_function_type(&self) -> Option<&FunctionType> {
2456        match self.kind() {
2457            TypeKind::Function(f) => Some(f),
2458            _ => None,
2459        }
2460    }
2461
2462    pub fn ref_depth(&self) -> usize {
2463        match self.is_ref().then(|| self.inner()).flatten() {
2464            Some(inner) => 1 + inner.ref_depth(),
2465            None => 0,
2466        }
2467    }
2468
2469    pub fn strip_refs(&self) -> Type {
2470        if self.is_ref() {
2471            return self.inner().expect("ref type must have inner").strip_refs();
2472        }
2473
2474        self.clone()
2475    }
2476
2477    pub fn receiver_shape(&self) -> Type {
2478        self.strip_refs().without_spelling()
2479    }
2480
2481    pub fn points_to_ref(&self) -> bool {
2482        self.is_ref() && self.inner().is_some_and(|inner| inner.is_ref())
2483    }
2484
2485    pub fn is_option_or_result(&self) -> bool {
2486        self.is_option() || self.is_result()
2487    }
2488
2489    pub fn tuple_or_type_arguments(&self) -> Vec<Type> {
2490        match self.kind() {
2491            TypeKind::Tuple(elements) => elements.clone(),
2492            TypeKind::Nominal { params, .. } => params.to_vec(),
2493            _ => Vec::new(),
2494        }
2495    }
2496
2497    pub fn is_prelude_error(&self) -> bool {
2498        matches!(self.kind(), TypeKind::Nominal { id, .. } if id.as_str() == PRELUDE_ERROR_ID)
2499    }
2500
2501    pub fn range_type(&self) -> Option<Type> {
2502        RangeKind::of(self)
2503            .is_some()
2504            .then(|| self.without_spelling())
2505    }
2506
2507    pub fn with_receiver_placeholder(self) -> Type {
2508        match self.kind() {
2509            TypeKind::Function(f) => {
2510                let f = FunctionType::clone(f);
2511                let mut new_params =
2512                    vec![FunctionParameter::new(TypeKind::ReceiverPlaceholder.into())];
2513                new_params.extend(f.params);
2514
2515                Type::function(new_params, f.bounds, f.return_type)
2516            }
2517            _ => unreachable!(
2518                "with_receiver_placeholder called on non-function type: {:?}",
2519                self
2520            ),
2521        }
2522    }
2523
2524    pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
2525        let mut vars = FxHashMap::default();
2526        let types = types
2527            .iter()
2528            .map(|v| Self::remove_vars_impl(v, &mut vars))
2529            .collect();
2530
2531        (types, vars.into_values().collect())
2532    }
2533
2534    fn remove_vars_impl(ty: &Type, vars: &mut FxHashMap<u32, EcoString>) -> Type {
2535        let structure = Self::remove_vars_structure(ty, vars);
2536        ty.carry_spelling(structure, |argument| Self::remove_vars_impl(argument, vars))
2537    }
2538
2539    fn remove_vars_structure(ty: &Type, vars: &mut FxHashMap<u32, EcoString>) -> Type {
2540        match ty.kind() {
2541            TypeKind::Nominal {
2542                id: name,
2543                params: args,
2544                writable,
2545            } => TypeKind::Nominal {
2546                id: name.clone(),
2547                params: args
2548                    .iter()
2549                    .map(|a| Self::remove_vars_impl(a, vars))
2550                    .collect(),
2551                writable: *writable,
2552            }
2553            .into(),
2554
2555            TypeKind::Function(f) => Type::function(
2556                f.params
2557                    .iter()
2558                    .map(|param| param.with_type(Self::remove_vars_impl(&param.ty, vars)))
2559                    .collect(),
2560                f.bounds
2561                    .iter()
2562                    .map(|b| Bound {
2563                        param_name: b.param_name.clone(),
2564                        generic: Self::remove_vars_impl(&b.generic, vars),
2565                        ty: Self::remove_vars_impl(&b.ty, vars),
2566                    })
2567                    .collect(),
2568                Self::remove_vars_impl(&f.return_type, vars).into(),
2569            ),
2570
2571            TypeKind::Var { id, hint } => match vars.get(&id.index()) {
2572                Some(g) => Type::parameter(g.clone()),
2573                None => {
2574                    let name: EcoString = hint
2575                        .clone()
2576                        .unwrap_or_else(|| alpha_index(vars.len()).into());
2577
2578                    vars.insert(id.index(), name.clone());
2579                    Type::parameter(name)
2580                }
2581            },
2582
2583            TypeKind::Tuple(elements) => Type::tuple(
2584                elements
2585                    .iter()
2586                    .map(|e| Self::remove_vars_impl(e, vars))
2587                    .collect(),
2588            ),
2589            TypeKind::Compound {
2590                kind,
2591                args,
2592                writable,
2593            } => TypeKind::Compound {
2594                kind: *kind,
2595                writable: *writable,
2596                args: args
2597                    .iter()
2598                    .map(|a| Self::remove_vars_impl(a, vars))
2599                    .collect(),
2600            }
2601            .into(),
2602            TypeKind::Array { length, element } => TypeKind::Array {
2603                length: *length,
2604                element: Box::new(Self::remove_vars_impl(element, vars)),
2605            }
2606            .into(),
2607            TypeKind::Simple(_) | TypeKind::Parameter(_) => ty.clone(),
2608            TypeKind::Never
2609            | TypeKind::Uninferred
2610            | TypeKind::Error(_)
2611            | TypeKind::ImportNamespace(_)
2612            | TypeKind::ReceiverPlaceholder => ty.clone(),
2613        }
2614    }
2615
2616    pub fn contains_type(&self, target: &Type) -> bool {
2617        self == target
2618            || self
2619                .children()
2620                .into_iter()
2621                .any(|child| child.contains_type(target))
2622    }
2623}
2624
2625impl Type {
2626    pub fn numeric_family(&self) -> Option<NumericFamily> {
2627        self.as_simple()?.numeric_family()
2628    }
2629}
2630
2631/// 0 → "A", 25 → "Z", 26 → "AA", 27 → "AB", ... (bijective base-26 over A-Z).
2632fn alpha_index(idx: usize) -> String {
2633    let mut s = String::new();
2634    let mut n = idx + 1;
2635    while n > 0 {
2636        n -= 1;
2637        s.insert(0, (b'A' + (n % 26) as u8) as char);
2638        n /= 26;
2639    }
2640    s
2641}
2642
2643pub fn method_receiver_substitution(
2644    receiver_ty: &Type,
2645    concrete_ty: &Type,
2646) -> Option<SubstitutionMap> {
2647    let receiver = receiver_ty.strip_refs();
2648    let concrete = concrete_ty.strip_refs();
2649    let (
2650        TypeKind::Nominal {
2651            id: receiver_id,
2652            params: receiver_params,
2653            ..
2654        },
2655        TypeKind::Nominal {
2656            id: concrete_id,
2657            params: concrete_params,
2658            ..
2659        },
2660    ) = (receiver.kind(), concrete.kind())
2661    else {
2662        return None;
2663    };
2664    if receiver_id != concrete_id || receiver_params.len() != concrete_params.len() {
2665        return None;
2666    }
2667
2668    receiver_params
2669        .iter()
2670        .zip(concrete_params)
2671        .map(|(receiver_param, concrete_param)| {
2672            let TypeKind::Parameter(name) = receiver_param.kind() else {
2673                return None;
2674            };
2675            Some((name.clone(), concrete_param.clone()))
2676        })
2677        .collect()
2678}
2679
2680#[cfg(test)]
2681mod tests {
2682    use super::*;
2683    use std::collections::hash_map::DefaultHasher;
2684    use std::hash::{Hash, Hasher};
2685    use std::iter;
2686
2687    fn hash(ty: &Type) -> u64 {
2688        let mut state = DefaultHasher::new();
2689        ty.hash(&mut state);
2690        state.finish()
2691    }
2692
2693    #[test]
2694    fn error_type_equals_itself() {
2695        let nominal_over_error = || -> Type {
2696            TypeKind::Nominal {
2697                id: Symbol::from_parts(PRELUDE_PACKAGE_ID, "Option"),
2698                params: vec![Type::error(ErrorReported::unchecked())].into(),
2699                writable: false,
2700            }
2701            .into()
2702        };
2703
2704        assert_eq!(
2705            TypeKind::Error(ErrorReported::unchecked()),
2706            TypeKind::Error(ErrorReported::unchecked())
2707        );
2708        assert_eq!(nominal_over_error(), nominal_over_error());
2709    }
2710
2711    #[test]
2712    fn function_equality_ignores_param_names() {
2713        let named = Type::function(
2714            vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2715            vec![],
2716            Box::new(Type::bool()),
2717        );
2718        let differently_named = Type::function(
2719            vec![FunctionParameter::named(Type::int(), Some("height".into()))],
2720            vec![],
2721            Box::new(Type::bool()),
2722        );
2723        let unnamed = Type::function(
2724            vec![FunctionParameter::new(Type::int())],
2725            vec![],
2726            Box::new(Type::bool()),
2727        );
2728
2729        assert_eq!(named, differently_named);
2730        assert_eq!(named, unnamed);
2731    }
2732
2733    #[test]
2734    fn equal_function_types_have_equal_hashes() {
2735        let named = Type::function(
2736            vec![FunctionParameter::named(Type::int(), Some("width".into()))],
2737            vec![],
2738            Box::new(Type::bool()),
2739        );
2740        let unnamed = Type::function(
2741            vec![FunctionParameter::new(Type::int())],
2742            vec![],
2743            Box::new(Type::bool()),
2744        );
2745
2746        assert_eq!(hash(&named), hash(&unnamed));
2747    }
2748
2749    #[test]
2750    fn equal_type_variables_have_equal_hashes() {
2751        let named: Type = TypeKind::Var {
2752            id: TypeVarId::new(1),
2753            hint: Some("value".into()),
2754        }
2755        .into();
2756        let unnamed: Type = TypeKind::Var {
2757            id: TypeVarId::new(1),
2758            hint: None,
2759        }
2760        .into();
2761
2762        assert_eq!(hash(&named), hash(&unnamed));
2763    }
2764
2765    #[test]
2766    fn signature_queries_ignore_function_bound_types() {
2767        let variable: Type = TypeKind::Var {
2768            id: TypeVarId::new(1),
2769            hint: Some("value".into()),
2770        }
2771        .into();
2772        let signature = Type::function(
2773            vec![FunctionParameter::new(Type::int())],
2774            vec![Bound {
2775                param_name: "T".into(),
2776                generic: variable.clone(),
2777                ty: TypeKind::Tuple(vec![
2778                    variable.clone(),
2779                    Type::error(ErrorReported::unchecked()),
2780                ])
2781                .into(),
2782            }],
2783            Box::new(Type::bool()),
2784        );
2785        let mut variables = Vec::new();
2786        signature.collect_unbound_variables(&mut variables);
2787
2788        assert!(!signature.contains_error());
2789        assert!(!signature.has_unbound_variables());
2790        assert!(!signature.contains_type(&variable));
2791        assert!(!signature.contains_type(&Type::error(ErrorReported::unchecked())));
2792        assert!(variables.is_empty());
2793    }
2794
2795    #[test]
2796    fn signature_queries_find_errors_in_nested_return_types() {
2797        let signature = Type::function(
2798            vec![FunctionParameter::new(Type::int())],
2799            vec![],
2800            Box::new(
2801                TypeKind::Array {
2802                    length: 1,
2803                    element: Box::new(Type::error(ErrorReported::unchecked())),
2804                }
2805                .into(),
2806            ),
2807        );
2808
2809        assert!(signature.contains_error());
2810        assert!(signature.contains_type(&Type::error(ErrorReported::unchecked())));
2811    }
2812
2813    #[test]
2814    fn alpha_index_single() {
2815        assert_eq!(alpha_index(0), "A");
2816        assert_eq!(alpha_index(5), "F");
2817        assert_eq!(alpha_index(25), "Z");
2818    }
2819
2820    #[test]
2821    fn alpha_index_double() {
2822        assert_eq!(alpha_index(26), "AA");
2823        assert_eq!(alpha_index(27), "AB");
2824        assert_eq!(alpha_index(51), "AZ");
2825        assert_eq!(alpha_index(52), "BA");
2826        assert_eq!(alpha_index(701), "ZZ");
2827    }
2828
2829    #[test]
2830    fn alpha_index_triple() {
2831        assert_eq!(alpha_index(702), "AAA");
2832    }
2833
2834    fn unhinted_var(id: u32) -> Type {
2835        TypeKind::Var {
2836            id: TypeVarId::new(id),
2837            hint: None,
2838        }
2839        .into()
2840    }
2841
2842    #[test]
2843    fn remove_vars_handles_more_than_six_unhinted_vars() {
2844        let func = Type::function(
2845            (0..6)
2846                .map(unhinted_var)
2847                .map(FunctionParameter::new)
2848                .collect(),
2849            vec![],
2850            Box::new(unhinted_var(6)),
2851        );
2852
2853        let (resolved, generics) = Type::remove_vars(&[&func]);
2854
2855        assert_eq!(generics.len(), 7);
2856        let TypeKind::Function(f) = resolved[0].kind() else {
2857            panic!("expected function type");
2858        };
2859        let names: Vec<_> = f
2860            .params
2861            .iter()
2862            .map(|param| &param.ty)
2863            .chain(iter::once(f.return_type.as_ref()))
2864            .map(|p| match p.kind() {
2865                TypeKind::Parameter(name) => name.to_string(),
2866                other => panic!("expected parameter, got {:?}", other),
2867            })
2868            .collect();
2869        assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
2870    }
2871
2872    #[test]
2873    fn remove_vars_handles_dozens_of_unhinted_vars() {
2874        let params: Vec<Type> = (0..30).map(unhinted_var).collect();
2875        let func = Type::function(
2876            params.iter().cloned().map(FunctionParameter::new).collect(),
2877            vec![],
2878            Box::new(Type::simple(SimpleKind::Unit)),
2879        );
2880        let (_, generics) = Type::remove_vars(&[&func]);
2881        assert_eq!(generics.len(), 30);
2882    }
2883}