Skip to main content

submilli_engine/
types.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3
4use crate::mangle::MangledName;
5use serde::{Deserialize, Serialize};
6
7/// One member of an enum, as the member literal type `E.A` names it.
8#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
9pub struct EnumMember<V> {
10    pub name: String,
11    pub value: V,
12    /// How many members the enum has, so a union naming them all folds into
13    /// the enum, as TypeScript reduces `E.A | E.B` to `E`.
14    pub member_count: usize,
15}
16
17impl<V> EnumMember<V> {
18    pub fn new(name: &str, value: V, member_count: usize) -> Self {
19        EnumMember {
20            name: name.to_string(),
21            value,
22            member_count,
23        }
24    }
25}
26
27/// The value an enum member holds.
28#[derive(Clone, Debug, PartialEq)]
29pub enum EnumValue {
30    Number(LiteralF64),
31    String(String),
32}
33
34impl EnumValue {
35    /// The plain literal type of this value: `1` or `"a"`.
36    pub fn literal_type(&self) -> Type {
37        match self {
38            EnumValue::Number(value) => Type::NumberLiteral(*value),
39            EnumValue::String(value) => Type::StringLiteral(value.clone()),
40        }
41    }
42}
43
44/// `f64` wrapper for total ordering and bit-pattern equality — bare `f64` lacks `Eq`/`Ord`,
45/// which would break the derived impls on [`Type`]. Construction must canonicalize `-0.0 → 0.0`;
46/// NaN can't appear from source literals so bit-pattern equality is safe.
47#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
48pub struct LiteralF64(#[serde(with = "crate::artifact_f64")] pub f64);
49
50impl PartialEq for LiteralF64 {
51    fn eq(&self, other: &Self) -> bool {
52        self.0.to_bits() == other.0.to_bits()
53    }
54}
55
56impl Eq for LiteralF64 {}
57
58impl PartialOrd for LiteralF64 {
59    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
60        Some(self.cmp(other))
61    }
62}
63
64impl Ord for LiteralF64 {
65    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
66        self.0.total_cmp(&other.0)
67    }
68}
69
70impl std::hash::Hash for LiteralF64 {
71    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
72        self.0.to_bits().hash(state);
73    }
74}
75
76/// Owning package of a by-name [`Type`] reference (`InterfaceRef`, `AliasRef`, `Alias`,
77/// `NumberEnum`, `StringEnum`). Carried so *structural* resolution of an already-typed
78/// value can find the symbol by FQN in a global registry, independent of what the current
79/// module imported.
80///
81/// **Excluded from identity:** `Eq`/`Ord`/`Hash` treat every `Package` as equal, so the
82/// owning package never drives a by-name type's identity. Identity is the sibling
83/// `mangled` field (the declaring symbol's mangled name, which already encodes the
84/// package and module); `package` only keeps *structural* registry lookup robust to
85/// which construction site stamped it.
86#[derive(Clone, Debug, Serialize, Deserialize)]
87pub struct Package(pub String);
88
89impl Package {
90    pub fn prelude() -> Self {
91        Self(crate::mangle::PRELUDE_PACKAGE.to_string())
92    }
93
94    pub fn user() -> Self {
95        Self(crate::mangle::USER_PACKAGE.to_string())
96    }
97
98    pub fn as_str(&self) -> &str {
99        &self.0
100    }
101}
102
103impl PartialEq for Package {
104    fn eq(&self, _: &Self) -> bool {
105        true
106    }
107}
108
109impl Eq for Package {}
110
111impl PartialOrd for Package {
112    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
113        Some(self.cmp(other))
114    }
115}
116
117impl Ord for Package {
118    fn cmp(&self, _: &Self) -> std::cmp::Ordering {
119        std::cmp::Ordering::Equal
120    }
121}
122
123impl std::hash::Hash for Package {
124    fn hash<H: std::hash::Hasher>(&self, _: &mut H) {}
125}
126
127/// `optional: true` means reads widen to `ty | undefined` and construction may omit the field.
128/// Distinct from a value-nullable field (`ty: T | null, optional: false`): must be present
129/// but can be null.
130#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
131pub struct ObjectField {
132    pub ty: Type,
133    pub optional: bool,
134    /// `readonly` forbids writes through the field; assignability treats a writable
135    /// target field invariantly (see `assignable.rs`). Inferred object literals and
136    /// freshly-synthesized shapes are writable (`false`); only an explicit `readonly`
137    /// modifier on an object-type/interface property sets this.
138    pub readonly: bool,
139    /// A method rather than a function-typed property. `tsc` compares a method's
140    /// parameters bivariantly and a property's contravariantly.
141    #[serde(default)]
142    pub method: bool,
143}
144
145impl ObjectField {
146    pub fn required(ty: Type) -> Self {
147        Self {
148            ty,
149            optional: false,
150            readonly: false,
151            method: false,
152        }
153    }
154    pub fn optional(ty: Type) -> Self {
155        Self {
156            ty,
157            optional: true,
158            readonly: false,
159            method: false,
160        }
161    }
162
163    /// The type a *read* of this field yields: an optional field widens to
164    /// `T | undefined`, since an absent property reads as undefined. Every field
165    /// read — object type, interface property, class field, union member, and
166    /// codegen's mirror of all four — goes through this, so the widening rule
167    /// has one definition.
168    pub fn read_ty(&self) -> Type {
169        Self::widen_optional(self.optional, self.ty.clone())
170    }
171
172    /// [`read_ty`](Self::read_ty) for callers holding the two facts separately
173    /// (an interface `PropertySig`, a class `FieldSig`).
174    pub fn widen_optional(optional: bool, ty: Type) -> Type {
175        if optional {
176            Type::union(vec![ty, Type::Undefined])
177        } else {
178            ty
179        }
180    }
181}
182
183/// Values available under arbitrary string property names.
184#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
185pub struct IndexSignature {
186    pub value: Box<Type>,
187    pub readonly: bool,
188}
189
190impl IndexSignature {
191    pub fn map_value(&self, transform: impl FnOnce(&Type) -> Type) -> Self {
192        Self {
193            value: Box::new(transform(&self.value)),
194            readonly: self.readonly,
195        }
196    }
197
198    /// [`map_value`](Self::map_value) with a transform that can fail.
199    pub fn try_map_value<E>(
200        &self,
201        transform: impl FnOnce(&Type) -> Result<Type, E>,
202    ) -> Result<Self, E> {
203        Ok(Self {
204            value: Box::new(transform(&self.value)?),
205            readonly: self.readonly,
206        })
207    }
208
209    pub fn read_ty(&self) -> Type {
210        Type::union(vec![(*self.value).clone(), Type::Undefined])
211    }
212}
213
214#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
215pub struct TypePredicate {
216    pub parameter_index: u32,
217    pub asserted_type: Type,
218}
219
220/// Tuple positions and the number of trailing positions that may be omitted.
221/// Optional positions include `Undefined` in their element type.
222#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
223pub struct TupleType {
224    pub elements: Vec<Type>,
225    pub optional: usize,
226}
227
228impl TupleType {
229    pub fn required_len(&self) -> usize {
230        self.elements.len().saturating_sub(self.optional)
231    }
232
233    pub fn map(&self, transform: impl FnMut(&Type) -> Type) -> Self {
234        Self {
235            elements: self.elements.iter().map(transform).collect(),
236            optional: self.optional,
237        }
238    }
239
240    pub fn try_map<E>(&self, transform: impl FnMut(&Type) -> Result<Type, E>) -> Result<Self, E> {
241        Ok(Self {
242            elements: self
243                .elements
244                .iter()
245                .map(transform)
246                .collect::<Result<_, _>>()?,
247            optional: self.optional,
248        })
249    }
250}
251
252impl From<Vec<Type>> for TupleType {
253    fn from(elements: Vec<Type>) -> Self {
254        Self {
255            elements,
256            optional: 0,
257        }
258    }
259}
260
261impl std::ops::Deref for TupleType {
262    type Target = [Type];
263    fn deref(&self) -> &Self::Target {
264        &self.elements
265    }
266}
267
268impl IntoIterator for TupleType {
269    type Item = Type;
270    type IntoIter = std::vec::IntoIter<Type>;
271    fn into_iter(self) -> Self::IntoIter {
272        self.elements.into_iter()
273    }
274}
275
276impl<'a> IntoIterator for &'a TupleType {
277    type Item = &'a Type;
278    type IntoIter = std::slice::Iter<'a, Type>;
279    fn into_iter(self) -> Self::IntoIter {
280        self.elements.iter()
281    }
282}
283
284#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
285pub enum Type {
286    Number,
287    /// No distinct runtime representation — codegen widens to `f64` at every emission site.
288    NumberLiteral(LiteralF64),
289    BigInt,
290    /// A bigint literal type: `123n`, `-1n`. Holds the value in decimal, with a
291    /// leading `-` when negative, so each value has one spelling. Like the other
292    /// literal types it lowers exactly as its base, `bigint`.
293    BigIntLiteral(String),
294    String,
295    StringLiteral(String),
296    Uint8Array,
297    Boolean,
298    /// `true` or `false`. Like the other literal types it has no runtime
299    /// representation of its own: it lowers exactly as `boolean`. `Type::union`
300    /// folds `true | false` into `boolean`, which is what `boolean` means.
301    BooleanLiteral(bool),
302    Null,
303    /// The single undefined value, distinct from language null and Wasm null.
304    Undefined,
305    Void,
306    /// Unlike TypeScript's `any`, requires explicit narrowing before use.
307    /// `Unknown | T` collapses to `Unknown`.
308    Unknown,
309    Function {
310        params: Vec<Type>,
311        /// Number of trailing fixed parameters callers may omit.
312        optional: usize,
313        ret: Box<Type>,
314        /// Boxed to break the `Type → Function → TypePredicate → Type` cycle. Guards are
315        /// assignable to plain functions but not vice versa.
316        predicate: Option<Box<TypePredicate>>,
317        /// When true, the last `params` entry holds the rest array type.
318        has_rest: bool,
319    },
320    /// `BTreeMap` gives structural `==`, deterministic iteration, and canonical field order for codegen.
321    Object {
322        fields: BTreeMap<String, ObjectField>,
323        index: Option<IndexSignature>,
324    },
325    Array(Box<Type>),
326    /// Parser rejects empty tuples. Index access requires an integer literal; out-of-range and
327    /// non-literal indices are rejected at typecheck time. Lowers to `(ref $Array)` at runtime.
328    Tuple(TupleType),
329    /// `readonly T[]` (also spelled `ReadonlyArray<T>`) or `readonly [A, B]`. The inner
330    /// type is always a [`Type::Array`] or [`Type::Tuple`]: the wrapper only forbids
331    /// writes, so [`Type::peel`] strips it and every read path sees the plain array.
332    /// Write paths (index assignment, mutating methods) must ask
333    /// [`Type::is_readonly_array`] before peeling. `Eq`/`Ord` keep it distinct from the
334    /// mutable type because a readonly array is not assignable to a mutable one.
335    Readonly(Box<Type>),
336    /// Diagnostic already reported; downstream code must not emit cascading errors.
337    Error,
338    /// No Wasm representation — never values never reach codegen.
339    Never,
340    /// Signature-form generic parameter. Never appears in function bodies — body inference
341    /// replaces each TypeVar with a fresh [`GenericParam`](Type::GenericParam) at body entry.
342    TypeVar(String),
343    /// Body-internal generic placeholder. Identity by `id` — two GPs with different ids are
344    /// distinct even when they share a name, preventing collisions across nested generic scopes.
345    GenericParam {
346        id: u32,
347        name: String,
348    },
349    /// A generic value with a proven runtime shape. Member access and lowering
350    /// use `ty`; assignability also preserves the original generic identity.
351    Refined {
352        original: Box<Type>,
353        ty: Box<Type>,
354    },
355    /// `args` carries already-substituted type arguments; empty for non-generic interfaces.
356    /// `mangled` is the declaring symbol's mangled name — the **nominal identity** (two
357    /// modules' same-named interfaces have distinct mangled names). `package`/`name` are
358    /// kept for diagnostics and import-independent *structural* resolution (see [`Package`]);
359    /// they do not drive identity. `mangled` is listed first so derived `Ord` keys on it.
360    InterfaceRef {
361        mangled: MangledName,
362        package: Package,
363        name: String,
364        args: Vec<Type>,
365    },
366    /// Nominal reference to a `class` declaration. Identity is `mangled` (two modules'
367    /// same-named classes are distinct); `package`/`name` are for diagnostics and
368    /// import-independent structural resolution, mirroring [`Type::InterfaceRef`].
369    /// `args` instantiates the class's type parameters; empty for a
370    /// non-generic class.
371    ClassRef {
372        mangled: MangledName,
373        package: Package,
374        name: String,
375        args: Vec<Type>,
376    },
377    /// Distinct from `StringEnum` so codegen knows the `i32` representation without consulting the type namespace.
378    ///
379    /// `member` narrows the enum to one member's literal type, `E.A`, which is
380    /// what a member read has, as in TypeScript. It shares the enum's runtime
381    /// representation; [`Type::widen_literal`] drops it back to the enum.
382    NumberEnum {
383        mangled: MangledName,
384        package: Package,
385        name: String,
386        member: Option<EnumMember<LiteralF64>>,
387    },
388    StringEnum {
389        mangled: MangledName,
390        package: Package,
391        name: String,
392        member: Option<EnumMember<String>>,
393    },
394    /// Canonical union: sorted, deduplicated, no nested unions, no `Error` members, always ≥2
395    /// members. Build *only* via [`Type::union`].
396    Union(Vec<Type>),
397    /// Every pattern-match site must call [`Type::peel`] first; sole exception is
398    /// [`Display`](fmt::Display). `Eq`/`Ord`/`Hash` are nominal: `Alias { "ID", Number }` ≠
399    /// `Number` at the raw level. `args` carries already-substituted type arguments.
400    Alias {
401        mangled: MangledName,
402        package: Package,
403        name: String,
404        args: Vec<Type>,
405        ty: Box<Type>,
406    },
407    /// Lazy by-name reference to a type alias, used **only at a
408    /// recursion back-edge** — the inner `Json` in
409    /// `type Json = number | string | Json[]`, or the `Node` in
410    /// `type Node = { next: Node | null }`. Unlike [`Type::Alias`] it
411    /// carries no inline body; the body lives in the type namespace and
412    /// is resolved by name on demand (mirroring [`Type::InterfaceRef`]).
413    /// This keeps a recursive alias a *finite* `Type` value — a cyclic
414    /// inline body would infinitely recurse the derived `Eq`/`Ord` and
415    /// [`Type::peel`]. `peel` does **not** expand it (it stops here, the
416    /// same as `InterfaceRef`); the few sites that need the alias's
417    /// structure resolve it by name with cycle-safety.
418    AliasRef {
419        mangled: MangledName,
420        package: Package,
421        name: String,
422        args: Vec<Type>,
423    },
424    /// `object`: any value that isn't a primitive, `null` or `undefined`, as in
425    /// TypeScript. Every object, array, function and class instance is one. It
426    /// has `{}`'s members and, like `{}`, lowers as `unknown`.
427    NonPrimitive,
428}
429
430impl Type {
431    pub fn tuple(elements: Vec<Type>) -> Self {
432        Self::Tuple(elements.into())
433    }
434
435    /// A receiver whose computed string keys use the object property carrier.
436    pub fn is_structural_object(&self) -> bool {
437        match self.peel() {
438            Self::Object { .. } | Self::InterfaceRef { .. } => true,
439            Self::Union(members) => members.iter().all(Self::is_structural_object),
440            _ => false,
441        }
442    }
443
444    /// Build an [`Type::InterfaceRef`]. `mangled` is the declaring symbol's mangled
445    /// name (its nominal identity) — pass the symbol's own `mangled_name`, never a
446    /// value recomputed from `package`/`name`, so two construction sites for the same
447    /// type always agree.
448    pub fn interface_ref(
449        package: Package,
450        name: impl Into<String>,
451        mangled: MangledName,
452        args: Vec<Type>,
453    ) -> Type {
454        Type::InterfaceRef {
455            mangled,
456            package,
457            name: name.into(),
458            args,
459        }
460    }
461
462    /// Build a [`Type::ClassRef`]. `mangled` is the class symbol's nominal identity;
463    /// pass the symbol's own `mangled_name`, never one recomputed from `package`/`name`.
464    pub fn class_ref(
465        package: Package,
466        name: impl Into<String>,
467        mangled: MangledName,
468        args: Vec<Type>,
469    ) -> Type {
470        Type::ClassRef {
471            mangled,
472            package,
473            name: name.into(),
474            args,
475        }
476    }
477
478    pub fn number_enum(package: Package, name: impl Into<String>, mangled: MangledName) -> Type {
479        Type::NumberEnum {
480            mangled,
481            package,
482            name: name.into(),
483            member: None,
484        }
485    }
486
487    pub fn string_enum(package: Package, name: impl Into<String>, mangled: MangledName) -> Type {
488        Type::StringEnum {
489            mangled,
490            package,
491            name: name.into(),
492            member: None,
493        }
494    }
495
496    /// The member literal type `E.A` of the enum type `self`, which has
497    /// `member_count` members. `self` must be a `NumberEnum` holding a number
498    /// or a `StringEnum` holding a string. As in TypeScript, the one member of
499    /// an enum has the enum's own type.
500    pub fn with_enum_member(
501        &self,
502        member_name: &str,
503        value: EnumValue,
504        member_count: usize,
505    ) -> Type {
506        if member_count < 2 {
507            return self.without_enum_member();
508        }
509        match (self.clone(), value) {
510            (
511                Type::NumberEnum {
512                    mangled,
513                    package,
514                    name,
515                    ..
516                },
517                EnumValue::Number(value),
518            ) => Type::NumberEnum {
519                mangled,
520                package,
521                name,
522                member: Some(EnumMember::new(member_name, value, member_count)),
523            },
524            (
525                Type::StringEnum {
526                    mangled,
527                    package,
528                    name,
529                    ..
530                },
531                EnumValue::String(value),
532            ) => Type::StringEnum {
533                mangled,
534                package,
535                name,
536                member: Some(EnumMember::new(member_name, value, member_count)),
537            },
538            (ty, _) => ty,
539        }
540    }
541
542    /// The enum a member literal type `E.A` belongs to; any other type unchanged.
543    pub fn without_enum_member(&self) -> Type {
544        match self {
545            Type::NumberEnum {
546                mangled,
547                package,
548                name,
549                member: Some(_),
550            } => Type::number_enum(package.clone(), name.clone(), mangled.clone()),
551            Type::StringEnum {
552                mangled,
553                package,
554                name,
555                member: Some(_),
556            } => Type::string_enum(package.clone(), name.clone(), mangled.clone()),
557            _ => self.clone(),
558        }
559    }
560
561    /// Whether this is one literal type, what TypeScript calls a unit type:
562    /// `1`, `"a"`, `true`, `1n` or an enum member `E.A`.
563    pub fn is_literal_type(&self) -> bool {
564        matches!(
565            self,
566            Type::NumberLiteral(_)
567                | Type::StringLiteral(_)
568                | Type::BooleanLiteral(_)
569                | Type::BigIntLiteral(_)
570        ) || self.is_enum_member()
571    }
572
573    /// Whether this is an enum member literal type `E.A`.
574    pub fn is_enum_member(&self) -> bool {
575        self.enum_member_name().is_some()
576    }
577
578    /// The enum, member name and member count of an enum member literal type `E.A`.
579    pub fn enum_member_name(&self) -> Option<(&MangledName, &str, usize)> {
580        match self {
581            Type::NumberEnum {
582                mangled,
583                member: Some(member),
584                ..
585            } => Some((mangled, &member.name, member.member_count)),
586            Type::StringEnum {
587                mangled,
588                member: Some(member),
589                ..
590            } => Some((mangled, &member.name, member.member_count)),
591            _ => None,
592        }
593    }
594
595    /// The value an enum member literal type `E.A` holds.
596    pub fn enum_member_value(&self) -> Option<EnumValue> {
597        match self.peel() {
598            Type::NumberEnum {
599                member: Some(member),
600                ..
601            } => Some(EnumValue::Number(member.value)),
602            Type::StringEnum {
603                member: Some(member),
604                ..
605            } => Some(EnumValue::String(member.value.clone())),
606            _ => None,
607        }
608    }
609
610    pub fn alias_ref(
611        package: Package,
612        name: impl Into<String>,
613        mangled: MangledName,
614        args: Vec<Type>,
615    ) -> Type {
616        Type::AliasRef {
617            mangled,
618            package,
619            name: name.into(),
620            args,
621        }
622    }
623
624    pub fn alias_ty(
625        package: Package,
626        name: impl Into<String>,
627        mangled: MangledName,
628        args: Vec<Type>,
629        ty: Box<Type>,
630    ) -> Type {
631        Type::Alias {
632            mangled,
633            package,
634            name: name.into(),
635            args,
636            ty,
637        }
638    }
639
640    /// Convenience for a non-namespaced prelude interface (`Error`, `Response`, …):
641    /// the prelude registers these with `mangled_name = prelude(name)`, so this is
642    /// the matching identity. Namespaced prelude types (`Temporal.*`) must instead
643    /// use [`Type::interface_ref`] with `extend(prelude("Temporal"), local)`.
644    pub fn prelude_interface(name: impl Into<String>, args: Vec<Type>) -> Type {
645        let name = name.into();
646        let mangled = crate::mangle::prelude(&name);
647        Type::interface_ref(Package::prelude(), name, mangled, args)
648    }
649
650    /// The built-in `Error` class reference — the type of `throw`/`catch` values
651    /// and the root of user error subclasses.
652    pub fn prelude_error_class() -> Type {
653        Type::class_ref(
654            Package::prelude(),
655            "Error",
656            crate::mangle::prelude("Error"),
657            Vec::new(),
658        )
659    }
660
661    /// The built-in `RangeError` class reference — the host-implemented
662    /// `Error` subclass for out-of-range failures.
663    pub fn prelude_range_error_class() -> Type {
664        Type::class_ref(
665            Package::prelude(),
666            "RangeError",
667            crate::mangle::prelude("RangeError"),
668            Vec::new(),
669        )
670    }
671
672    /// Remove display aliases while retaining generic guard identity.
673    pub fn without_aliases(&self) -> &Type {
674        match self {
675            Type::Alias { ty, .. } => ty.without_aliases(),
676            _ => self,
677        }
678    }
679
680    /// Whether this holds every value: `unknown`, or a union of `{}`, `null`
681    /// and `undefined` (and possibly more). Through aliases only: a refinement
682    /// like `T & unknown` holds only `T`'s values.
683    pub fn holds_every_value(&self) -> bool {
684        let members: &[Type] = match self.without_aliases() {
685            Type::Unknown => return true,
686            Type::Union(members) => members,
687            _ => return false,
688        };
689        // Through aliases only: `T & undefined` holds `undefined` only when `T`
690        // does.
691        members.iter().any(Type::is_empty_object)
692            && members
693                .iter()
694                .any(|m| matches!(m.without_aliases(), Type::Null))
695            && members
696                .iter()
697                .any(|m| matches!(m.without_aliases(), Type::Undefined))
698    }
699
700    /// The pieces of a refinement whose shape is a union: `T & ({} | null)`
701    /// is `T & {}` and `null`. `None` for any other type.
702    pub fn refinement_pieces(&self) -> Option<Vec<Type>> {
703        let Type::Refined { original, ty } = self.without_aliases() else {
704            return None;
705        };
706        let Type::Union(parts) = ty.peel() else {
707            return None;
708        };
709        Some(
710            parts
711                .iter()
712                .map(|part| match part.peel() {
713                    Type::Null | Type::Undefined | Type::Void => part.clone(),
714                    _ => Type::Refined {
715                        original: original.clone(),
716                        ty: Box::new(part.clone()),
717                    },
718                })
719                .collect(),
720        )
721    }
722
723    /// Whether this is a narrowed type parameter, like `T & {}`.
724    pub fn refines_type_parameter(&self) -> bool {
725        matches!(self.without_aliases(), Type::Refined { original, .. }
726            if matches!(original.peel(), Type::GenericParam { .. }))
727    }
728
729    pub fn peel(&self) -> &Type {
730        let mut t = self;
731        while let Type::Alias { ty, .. } | Type::Refined { ty, .. } | Type::Readonly(ty) = t {
732            t = ty;
733        }
734        t
735    }
736
737    /// `{ [key: string]: unknown }`: any object, interface or class instance,
738    /// for host declarations that read a value as an object. Not `{}`, which
739    /// also holds primitives that have no object representation.
740    pub fn any_object() -> Type {
741        Type::Object {
742            index: Some(IndexSignature {
743                value: Box::new(Type::Unknown),
744                readonly: false,
745            }),
746            fields: BTreeMap::new(),
747        }
748    }
749
750    /// `{}`, the object type with no fields.
751    pub fn empty_object() -> Type {
752        Type::Object {
753            fields: BTreeMap::new(),
754            index: None,
755        }
756    }
757
758    /// Whether this is `{}`: the object type with no fields and no index
759    /// signature. As in TypeScript, it holds every value but `null` and
760    /// `undefined`, primitives included, so codegen lowers it as `unknown`.
761    /// A refinement such as `T & {}` is not `{}`: it holds only `T`'s values.
762    pub fn is_empty_object(&self) -> bool {
763        let mut t = self;
764        while let Type::Alias { ty, .. } | Type::Readonly(ty) = t {
765            t = ty;
766        }
767        matches!(t, Type::Object { fields, index: None } if fields.is_empty())
768    }
769
770    /// [`peel`](Self::peel), with `{}` and `object` read as `unknown`: the type whose
771    /// representation and run-time operations a value of this type uses.
772    /// Codegen matches on this rather than on `peel`, so a `{}` holding a
773    /// number is never treated as an object struct. `peel` reads a refinement
774    /// as its shape, so `T & {}` lowers as `unknown`, like `T` itself.
775    pub fn lowered(&self) -> &Type {
776        let peeled = self.peel();
777        if peeled.is_empty_object() || matches!(peeled, Type::NonPrimitive) {
778            return &Type::Unknown;
779        }
780        peeled
781    }
782
783    /// [`peel`](Self::peel), but stopping at a [`Type::Readonly`] wrapper, for
784    /// sites that carry a type onward and must not drop its readonly-ness.
785    pub fn peel_preserving_readonly(&self) -> &Type {
786        let mut t = self;
787        while let Type::Alias { ty, .. } | Type::Refined { ty, .. } = t {
788            t = ty;
789        }
790        t
791    }
792
793    /// Whether writes through a value of this type are forbidden because it is a
794    /// `readonly` array or tuple, looking through aliases and refinements.
795    pub fn is_readonly_array(&self) -> bool {
796        matches!(self.peel_preserving_readonly(), Type::Readonly(_))
797    }
798
799    /// The element type of a rest parameter's array: `T` for `T[]` or
800    /// `readonly T[]`. Not peeled through aliases, since rest lowering matches the
801    /// parameter type as written.
802    pub fn rest_element(&self) -> Option<&Type> {
803        match self {
804            Type::Array(element) => Some(element),
805            Type::Readonly(inner) => match inner.as_ref() {
806                Type::Array(element) => Some(element),
807                _ => None,
808            },
809            _ => None,
810        }
811    }
812
813    /// A rest parameter's type with any `readonly` removed. Each call packs a
814    /// fresh array for the rest, so whether the callee may write to it is the
815    /// callee's own concern: two function types relate on their rest elements,
816    /// as in tsc.
817    pub fn rest_array_ignoring_readonly(&self) -> &Type {
818        match self {
819            Type::Readonly(inner) if matches!(inner.as_ref(), Type::Array(_)) => inner,
820            _ => self,
821        }
822    }
823
824    /// Whether this is a union of only arrays and tuples, which share the `$Array`
825    /// representation.
826    pub fn is_array_like_union(&self) -> bool {
827        match self.peel() {
828            Type::Union(members) => members
829                .iter()
830                .all(|member| matches!(member.peel(), Type::Array(_) | Type::Tuple(_))),
831            _ => false,
832        }
833    }
834
835    /// The element of a union of arrays and tuples read as one array: any
836    /// member's element. `None` for any other type. Only reads may go through
837    /// it; writing a member's element through the joined type could store
838    /// another member's element type.
839    pub fn array_like_union_element(&self) -> Option<Type> {
840        let Type::Union(members) = self.peel() else {
841            return None;
842        };
843        let elements = members
844            .iter()
845            .map(|member| match member.peel() {
846                Type::Array(element) => Some((**element).clone()),
847                Type::Tuple(positions) => Some(Type::union(positions.elements.clone())),
848                _ => None,
849            })
850            .collect::<Option<Vec<_>>>()?;
851        Some(Type::union(elements))
852    }
853
854    /// The arrays and tuples of a union of strings with arrays or tuples, and
855    /// nothing else, as their own union. Such a union has no shared
856    /// representation, so each use tests `typeof` and takes the string's or the
857    /// array's path.
858    pub fn string_or_array_union_arrays(&self) -> Option<Type> {
859        let Type::Union(members) = self.peel() else {
860            return None;
861        };
862        let (strings, arrays): (Vec<Type>, Vec<Type>) = members
863            .iter()
864            .cloned()
865            .partition(|member| member.peel().is_string_shaped());
866        let all_arrays = arrays
867            .iter()
868            .all(|member| matches!(member.peel(), Type::Array(_) | Type::Tuple(_)));
869        (!strings.is_empty() && !arrays.is_empty() && all_arrays).then(|| Type::union(arrays))
870    }
871
872    /// The array a union of arrays and tuples reads as: see
873    /// [`Self::array_like_union_element`].
874    pub fn array_like_union_view(&self) -> Option<Type> {
875        self.array_like_union_element()
876            .map(|element| Type::Array(Box::new(element)))
877    }
878
879    /// Whether this type is `void`, through any depth of alias.
880    ///
881    /// `void` is the one type with no value slot at all, so a gate that tests
882    /// for it decides between "one Wasm result" and "none". Every such gate —
883    /// in the typechecker *and* in codegen — must answer the same way for
884    /// `type V = void` as for `void`: a bare `matches!(ty, Type::Void)` hands an
885    /// aliased `void` a value slot that
886    /// [`SymbolTable::value_type`](crate::codegen::symbol_table::SymbolTable::value_type)
887    /// then refuses to lower. A typecheck gate must not start peeling ahead of
888    /// its codegen counterpart, which turns a clean diagnostic into a panic.
889    pub fn is_void(&self) -> bool {
890        matches!(self.peel(), Type::Void)
891    }
892
893    /// Whether a function taking `actual` parameters can stand where one taking
894    /// `expected` is called. As in TypeScript, it may declare fewer and ignore
895    /// the rest of the arguments; a closure adapter drops them at runtime. Rest
896    /// functions keep an exact arity, since their packed array has a slot of its
897    /// own.
898    pub fn function_arity_fits(actual: usize, expected: usize, has_rest: bool) -> bool {
899        actual == expected || (!has_rest && actual < expected)
900    }
901
902    /// Whether a value of this type would need a `void` slot at runtime:
903    /// `void` itself, or a union that lists it.
904    ///
905    /// Deliberately one level deep — it does **not** descend into a function's
906    /// return type, where `void` is legitimate (`() => void`). Every gate that
907    /// refuses `void` in a value or comparison position wants this, not the
908    /// bare [`is_void`](Self::is_void). `cond ? f() : 1` and `a ?? f()` are
909    /// plain `void`, so no expression builds the union form; a gate that asks
910    /// this still refuses one that did, rather than letting it reach codegen.
911    pub fn carries_void(&self) -> bool {
912        match self.peel() {
913            Type::Void => true,
914            Type::Union(members) => members.iter().any(|m| matches!(m.peel(), Type::Void)),
915            _ => false,
916        }
917    }
918
919    /// Primitive operations shared by enums and homogeneous literal unions,
920    /// without widening their type identity or changing assignability.
921    pub fn primitive_behavior(&self) -> &Type {
922        match self.peel() {
923            Type::NumberEnum { .. } => &Type::Number,
924            Type::StringEnum { .. } => &Type::String,
925            Type::BooleanLiteral(_) => &Type::Boolean,
926            Type::BigIntLiteral(_) => &Type::BigInt,
927            Type::Union(members)
928                if !members.is_empty()
929                    && members.iter().all(|member| {
930                        matches!(
931                            member.primitive_behavior(),
932                            Type::Number | Type::NumberLiteral(_)
933                        )
934                    }) =>
935            {
936                &Type::Number
937            }
938            Type::Union(members)
939                if !members.is_empty()
940                    && members
941                        .iter()
942                        .all(|member| matches!(member.primitive_behavior(), Type::BigInt)) =>
943            {
944                &Type::BigInt
945            }
946            Type::Union(members)
947                if !members.is_empty() && members.iter().all(Type::is_string_shaped) =>
948            {
949                &Type::String
950            }
951            ty => ty,
952        }
953    }
954
955    /// Whether every value of this type is a bigint: `bigint`, a bigint literal
956    /// type, or a union or alias of those.
957    pub fn is_bigint(&self) -> bool {
958        matches!(self.primitive_behavior(), Type::BigInt)
959    }
960
961    /// This type with literal types replaced by the primitive they are a literal of.
962    ///
963    /// A literal type is only sound where the value cannot change, so inference keeps
964    /// it at a `const` binding and widens here at every position that is mutable or
965    /// whose type is inferred from its contents — a `let` binding, an array element,
966    /// an object-literal property, a generic argument. `const a = 1` is `1`, but
967    /// `let b = a` is `number`, matching TypeScript.
968    ///
969    /// An enum member literal type `E.A` widens to its enum `E`, not to the
970    /// enum's primitive: the enum is a nominal type whose identity its members
971    /// are checked against. Use [`primitive_behavior`](Self::primitive_behavior)
972    /// for the primitive.
973    pub fn widen_literal(&self) -> Type {
974        match self {
975            Type::NumberLiteral(_) => Type::Number,
976            Type::StringLiteral(_) => Type::String,
977            Type::BooleanLiteral(_) => Type::Boolean,
978            Type::BigIntLiteral(_) => Type::BigInt,
979            _ if self.is_enum_member() => self.without_enum_member(),
980            // A union widens memberwise, which also collapses it when the members
981            // share a base: `1 | 2` is `number`, not `number | number`, because
982            // `Type::union` deduplicates.
983            Type::Union(members) => Type::union(without_members_of_empty_object(
984                members.iter().map(Type::widen_literal).collect(),
985            )),
986            _ => self.clone(),
987        }
988    }
989
990    /// The primitive this literal type, or union of literals of one
991    /// primitive, is a literal of: `number` for `1 | 2`, `None` for
992    /// `1 | "a"` or a type that is no literal.
993    pub fn literal_base(&self) -> Option<Type> {
994        let widened = self.widen_literal();
995        (widened != *self && matches!(widened, Type::Number | Type::String | Type::Boolean))
996            .then_some(widened)
997    }
998
999    /// Whether every part of this type is a string — a `string`, a
1000    /// string-literal type, or a union of those.
1001    ///
1002    /// The typechecker, the import collector, and codegen must agree on this
1003    /// exactly: a shape accepted by one and not the others emits a `$string`
1004    /// into an `f64` slot, which fails Wasm validation rather than type
1005    /// checking. Contrast [`contains_string`](Self::contains_string), which
1006    /// asks the `any` question.
1007    pub fn is_string_shaped(&self) -> bool {
1008        match self.peel() {
1009            Type::String | Type::StringLiteral(_) | Type::StringEnum { .. } => true,
1010            Type::Union(members) => members.iter().all(Type::is_string_shaped),
1011            _ => false,
1012        }
1013    }
1014
1015    /// Whether *some* part of this type is a string. Diagnostics-only: it is
1016    /// what decides whether a rejected operand still deserves the "convert
1017    /// first" help, so `string | null` gets it.
1018    pub fn contains_string(&self) -> bool {
1019        match self.peel() {
1020            Type::String | Type::StringLiteral(_) | Type::StringEnum { .. } => true,
1021            Type::Union(members) => members.iter().any(Type::contains_string),
1022            _ => false,
1023        }
1024    }
1025
1026    /// Whether any member, through unions, satisfies `leaf`, which sees peeled
1027    /// types. Syntactic: an alias reference is a leaf, not expanded; the
1028    /// typechecker's `any_resolved_member` follows alias bodies through its
1029    /// resolver.
1030    pub fn any_member(&self, leaf: &dyn Fn(&Type) -> bool) -> bool {
1031        match self.peel() {
1032            Type::Union(members) => members.iter().any(|member| member.any_member(leaf)),
1033            member => leaf(member),
1034        }
1035    }
1036
1037    /// Whether every member, through unions, satisfies `leaf`. Syntactic,
1038    /// like [`Type::any_member`].
1039    pub fn all_members(&self, leaf: &dyn Fn(&Type) -> bool) -> bool {
1040        !self.any_member(&|member| !leaf(member))
1041    }
1042
1043    /// Whether `null` is spelled among the members. Syntactic, unlike the
1044    /// typechecker's `type_admits_null`: `unknown` doesn't count.
1045    pub fn spells_null(&self) -> bool {
1046        self.any_member(&|member| matches!(member, Type::Null))
1047    }
1048
1049    /// Whether `undefined`, or an erased `void` result, is spelled among the
1050    /// members. `unknown` and type parameters don't count.
1051    pub fn spells_undefined(&self) -> bool {
1052        self.any_member(&|member| matches!(member, Type::Undefined | Type::Void))
1053    }
1054
1055    /// Whether a value of the member type `leaf` has no JSON text at the
1056    /// document root, so `JSON.stringify` returns `undefined` for it.
1057    /// Objects and arrays holding such values still produce a document.
1058    pub fn stringifies_to_undefined(leaf: &Type) -> bool {
1059        // `{}` may hold a function, as `unknown` may.
1060        matches!(
1061            leaf.lowered(),
1062            Type::Undefined
1063                | Type::Void
1064                | Type::Unknown
1065                | Type::GenericParam { .. }
1066                | Type::TypeVar(_)
1067                | Type::Function { .. }
1068        )
1069    }
1070
1071    /// Normalizes to a flat member list that is unique *by peeled type*.
1072    ///
1073    /// Both halves peel because a nominal key is unsound here: an alias whose
1074    /// body is a union is a nested union in disguise, and every downstream
1075    /// per-member probe (`value_type`'s nullability test, narrowing's member
1076    /// walk) reads it as one opaque member. Deduping nominally leaves
1077    /// `N | number` as a two-member union that no operator is defined on.
1078    ///
1079    /// The alias label a union displays therefore survives only where it is
1080    /// still a single member: an alias of a union is replaced by its members,
1081    /// and among duplicates the alias-labelled spelling wins regardless of
1082    /// source order, so `N | number` and `number | N` both keep `N`.
1083    ///
1084    /// `peel` stops at a *recursive* alias (it is a name, not a body), so a
1085    /// recursive alias never dedups against its own expansion. Both spellings
1086    /// lower the same way, so this costs a redundant member, not correctness.
1087    pub fn union(members: Vec<Type>) -> Type {
1088        if members.iter().any(|m| matches!(m.peel(), Type::Error)) {
1089            return Type::Error;
1090        }
1091        // `unknown | T` → `unknown`; peels aliases so `type Dyn = unknown` still collapses.
1092        if members.iter().any(|m| matches!(m.peel(), Type::Unknown)) {
1093            return Type::Unknown;
1094        }
1095        // `T | never` → `T`. After Error/Unknown checks so cascading-silence wins.
1096        let members: Vec<Type> = members
1097            .into_iter()
1098            .filter(|m| !matches!(m.peel(), Type::Never))
1099            .collect();
1100        let mut flat: Vec<Type> = Vec::new();
1101        for m in members {
1102            match m.without_aliases() {
1103                Type::Union(inner) => flat.extend(inner.iter().cloned()),
1104                _ => flat.push(m),
1105            }
1106        }
1107        // Sorting by the peeled key groups alias-labelled duplicates next to
1108        // their body; aliases rank 0 so they sort first within the group, and
1109        // `dedup_by` keeps the earlier element — the name the user wrote.
1110        let alias_rank = |t: &Type| u8::from(!matches!(t, Type::Alias { .. }));
1111        flat.sort_by(|a, b| {
1112            a.without_aliases()
1113                .cmp(b.without_aliases())
1114                .then_with(|| alias_rank(a).cmp(&alias_rank(b)))
1115        });
1116        flat.dedup_by(|a, b| a.without_aliases() == b.without_aliases());
1117        fold_boolean_literals(&mut flat);
1118        fold_enum_members(&mut flat);
1119        // `T | (T & {})` holds `T`'s values: the refinement adds nothing.
1120        let refines_a_member = |member: &Type| {
1121            matches!(member, Type::Refined { original, .. }
1122                if flat.iter().any(|other| other.without_aliases() == original.without_aliases()))
1123        };
1124        let kept: Vec<Type> = flat
1125            .iter()
1126            .filter(|member| !refines_a_member(member))
1127            .cloned()
1128            .collect();
1129        flat = kept;
1130        // `object | {}` holds `{}`'s values: `object` adds nothing.
1131        if flat.iter().any(Type::is_empty_object) {
1132            flat.retain(|member| !matches!(member.peel(), Type::NonPrimitive));
1133        }
1134        if flat.len() > 1 {
1135            return Type::Union(flat);
1136        }
1137        match flat.into_iter().next() {
1138            Some(member) => member,
1139            None => Type::Never,
1140        }
1141    }
1142
1143    /// For method dispatch. Erased generics route to `Object`. Aliases peel. Returns `None`
1144    /// for function, void, null, and error. The first tuple element is the owning package
1145    /// for diagnostics; the mangled name is the structural lookup key. Built-in
1146    /// interfaces (`Number`, `Array`, `Object`, …) live in the prelude package.
1147    pub fn interface_routing(&self) -> Option<(MangledName, &str, &str, Vec<Type>)> {
1148        let prelude = crate::mangle::PRELUDE_PACKAGE;
1149        match self.primitive_behavior() {
1150            // A literal type routes to its base's interface: `"abc".at(0)` resolves the
1151            // same members a `string` receiver does. The prelude `Number`/`String`
1152            // interfaces expose no mutating members, so routing a literal there cannot
1153            // invalidate it.
1154            Type::Number | Type::NumberLiteral(_) => Some((
1155                crate::mangle::prelude("Number"),
1156                prelude,
1157                "Number",
1158                Vec::new(),
1159            )),
1160            Type::BigInt => Some((
1161                crate::mangle::prelude("BigInt"),
1162                prelude,
1163                "BigInt",
1164                Vec::new(),
1165            )),
1166            Type::Boolean => Some((
1167                crate::mangle::prelude("Boolean"),
1168                prelude,
1169                "Boolean",
1170                Vec::new(),
1171            )),
1172            Type::String | Type::StringLiteral(_) => Some((
1173                crate::mangle::prelude("String"),
1174                prelude,
1175                "String",
1176                Vec::new(),
1177            )),
1178            Type::Uint8Array => Some((
1179                crate::mangle::prelude("Uint8Array"),
1180                prelude,
1181                "Uint8Array",
1182                Vec::new(),
1183            )),
1184            Type::Array(elem) => Some((
1185                crate::mangle::prelude("Array"),
1186                prelude,
1187                "Array",
1188                vec![(**elem).clone()],
1189            )),
1190            // Tuples are arrays at runtime; route to `Array` with the positions'
1191            // union as the element type so reads (`length`, `map`, `at`, …) flow
1192            // through. Mutating methods are rejected separately at the call site.
1193            Type::Tuple(elements) => Some((
1194                crate::mangle::prelude("Array"),
1195                prelude,
1196                "Array",
1197                vec![Type::union(elements.elements.clone())],
1198            )),
1199            Type::Object { .. }
1200            | Type::NonPrimitive
1201            | Type::TypeVar(_)
1202            | Type::GenericParam { .. } => Some((
1203                crate::mangle::prelude("Object"),
1204                prelude,
1205                "Object",
1206                Vec::new(),
1207            )),
1208            Type::InterfaceRef {
1209                mangled,
1210                package,
1211                name,
1212                args,
1213                ..
1214            }
1215            | Type::ClassRef {
1216                mangled,
1217                package,
1218                name,
1219                args,
1220                ..
1221            } => Some((
1222                mangled.clone(),
1223                package.as_str(),
1224                name.as_str(),
1225                args.clone(),
1226            )),
1227            // Enum values route to Object (not Number/String) to keep the API surface minimal.
1228            Type::NumberEnum { .. } | Type::StringEnum { .. } => Some((
1229                crate::mangle::prelude("Object"),
1230                prelude,
1231                "Object",
1232                Vec::new(),
1233            )),
1234            // `unknown` routes to Object so vtable methods work.
1235            Type::Unknown => Some((
1236                crate::mangle::prelude("Object"),
1237                prelude,
1238                "Object",
1239                Vec::new(),
1240            )),
1241            _ => None,
1242        }
1243    }
1244}
1245
1246/// `ty` as written beside a `?` marker, which already admits `undefined`: without
1247/// its `undefined` member. A type that is only `undefined` stays as it is.
1248/// Every renderer of optional parameters shows them through this, except
1249/// `type_rendering`'s `Frame::Optional`, which applies the same rule to
1250/// borrowed members.
1251pub(crate) fn shown_beside_optional_marker(ty: &Type) -> Type {
1252    match ty.peel() {
1253        Type::Union(members) => Type::union(
1254            members
1255                .iter()
1256                .filter(|member| !matches!(member.peel(), Type::Undefined))
1257                .cloned()
1258                .collect(),
1259        ),
1260        _ => ty.clone(),
1261    }
1262}
1263
1264/// `s` escaped for a double-quoted string the way `tsc` prints a string literal
1265/// type (`escapeString` in TypeScript's `utilities.ts`): `"G\"HI"`, `"a\nb"`.
1266pub(crate) fn escape_string_literal(s: &str) -> String {
1267    let mut out = String::with_capacity(s.len());
1268    let mut chars = crate::literal_units::literal_chars(s).peekable();
1269    while let Some(c) = chars.next() {
1270        let c = match c {
1271            Ok(c) => c,
1272            Err(lone) => {
1273                out.push_str(&format!("\\u{lone:04X}"));
1274                continue;
1275            }
1276        };
1277        match c {
1278            '"' => out.push_str("\\\""),
1279            '\\' => out.push_str("\\\\"),
1280            '\n' => out.push_str("\\n"),
1281            '\r' => out.push_str("\\r"),
1282            '\t' => out.push_str("\\t"),
1283            '\u{8}' => out.push_str("\\b"),
1284            '\u{b}' => out.push_str("\\v"),
1285            '\u{c}' => out.push_str("\\f"),
1286            // `\0` before a digit would read as an octal escape.
1287            '\0' if chars
1288                .peek()
1289                .is_some_and(|next| next.is_ok_and(|d| d.is_ascii_digit())) =>
1290            {
1291                out.push_str("\\x00");
1292            }
1293            '\0' => out.push_str("\\0"),
1294            '\u{0}'..='\u{1f}' | '\u{85}' | '\u{2028}' | '\u{2029}' => {
1295                out.push_str(&format!("\\u{:04X}", u32::from(c)));
1296            }
1297            c => out.push(c),
1298        }
1299    }
1300    out
1301}
1302
1303/// The [`Type::BigIntLiteral`] of a bigint literal's decimal digits, as the
1304/// lexer writes them.
1305pub fn bigint_literal_type(digits: &str) -> Type {
1306    Type::BigIntLiteral(canonical_bigint_digits(digits))
1307}
1308
1309/// `digits` negated, in [`Type::BigIntLiteral`]'s spelling: `-0n` is `0n`.
1310pub fn negate_bigint_digits(digits: &str) -> String {
1311    let canonical = canonical_bigint_digits(digits);
1312    if canonical == "0" {
1313        return canonical;
1314    }
1315    match canonical.strip_prefix('-') {
1316        Some(magnitude) => magnitude.to_string(),
1317        None => format!("-{canonical}"),
1318    }
1319}
1320
1321/// `digits` without leading zeros, keeping a sign, and `0` for zero.
1322fn canonical_bigint_digits(digits: &str) -> String {
1323    let (sign, magnitude) = match digits.strip_prefix('-') {
1324        Some(magnitude) => ("-", magnitude),
1325        None => ("", digits),
1326    };
1327    match magnitude.trim_start_matches('0') {
1328        "" => "0".to_string(),
1329        trimmed => format!("{sign}{trimmed}"),
1330    }
1331}
1332
1333/// Drops the members a `{}` among `members` already holds: every one that
1334/// cannot be `null` or `undefined` and is no bare type parameter. TypeScript
1335/// reduces a union this way when it widens a literal, joins flow types and
1336/// types `a ?? b`.
1337pub fn without_members_of_empty_object(members: Vec<Type>) -> Vec<Type> {
1338    if !members.iter().any(Type::is_empty_object) {
1339        return members;
1340    }
1341    members
1342        .into_iter()
1343        .filter(|member| member.is_empty_object() || may_hold_values_outside_empty_object(member))
1344        .collect()
1345}
1346
1347/// Whether `ty` may hold a value `{}` does not: `null` or `undefined` (as
1348/// `T & ({} | undefined)` may), or any value of a type parameter.
1349fn may_hold_values_outside_empty_object(ty: &Type) -> bool {
1350    match ty.peel() {
1351        Type::Null
1352        | Type::Undefined
1353        | Type::Void
1354        | Type::Unknown
1355        | Type::GenericParam { .. }
1356        | Type::TypeVar(_) => true,
1357        Type::Union(members) => members.iter().any(may_hold_values_outside_empty_object),
1358        _ => false,
1359    }
1360}
1361
1362/// `boolean` is `true | false`: a union holding both literals, or `boolean`
1363/// and either literal, holds exactly `boolean`. `members` is sorted and
1364/// deduplicated, and stays so.
1365fn fold_boolean_literals(members: &mut Vec<Type>) {
1366    let is_boolean = |m: &Type| matches!(m.without_aliases(), Type::Boolean);
1367    let is_literal = |m: &Type| matches!(m.without_aliases(), Type::BooleanLiteral(_));
1368    let literals = members.iter().filter(|m| is_literal(m)).count();
1369    let has_boolean = members.iter().any(is_boolean);
1370    if literals == 0 || (literals == 1 && !has_boolean) {
1371        return;
1372    }
1373    members.retain(|m| !is_literal(m));
1374    if !has_boolean {
1375        let at = members.partition_point(|m| m.without_aliases() < &Type::Boolean);
1376        members.insert(at, Type::Boolean);
1377    }
1378}
1379
1380/// Reduces enum types as TypeScript does: a member beside its enum is absorbed
1381/// by it, members naming every member of their enum are the enum, and an enum
1382/// or member beside its primitive (`E | number`) is absorbed by the primitive.
1383/// Leaves `members` sorted and deduplicated.
1384fn fold_enum_members(members: &mut Vec<Type>) {
1385    absorb_enums_into_primitives(members);
1386    let complete = complete_enums(members);
1387    if complete.is_empty() {
1388        return;
1389    }
1390    for member in members.iter_mut() {
1391        if let Type::NumberEnum { mangled, .. } | Type::StringEnum { mangled, .. } =
1392            member.without_aliases()
1393            && complete.contains(mangled)
1394        {
1395            *member = member.without_aliases().without_enum_member();
1396        }
1397    }
1398    members.sort_by(|a, b| a.without_aliases().cmp(b.without_aliases()));
1399    members.dedup_by(|a, b| a.without_aliases() == b.without_aliases());
1400}
1401
1402/// Drops every enum type and member beside the primitive it holds.
1403fn absorb_enums_into_primitives(members: &mut Vec<Type>) {
1404    let has = |base: &Type| members.iter().any(|m| m.without_aliases() == base);
1405    let (has_number, has_string) = (has(&Type::Number), has(&Type::String));
1406    members.retain(|m| match m.without_aliases() {
1407        Type::NumberEnum { .. } => !has_number,
1408        Type::StringEnum { .. } => !has_string,
1409        _ => true,
1410    });
1411}
1412
1413/// The enums `members` holds whole: as the enum itself, or by naming every
1414/// one of its members.
1415fn complete_enums(members: &[Type]) -> BTreeSet<MangledName> {
1416    struct NamedMembers<'a> {
1417        member_count: usize,
1418        names: BTreeSet<&'a str>,
1419    }
1420    let mut named: BTreeMap<&MangledName, NamedMembers> = BTreeMap::new();
1421    let mut whole: BTreeSet<&MangledName> = BTreeSet::new();
1422    for member in members {
1423        let ty = member.without_aliases();
1424        if let Some((mangled, name, member_count)) = ty.enum_member_name() {
1425            named
1426                .entry(mangled)
1427                .or_insert_with(|| NamedMembers {
1428                    member_count,
1429                    names: BTreeSet::new(),
1430                })
1431                .names
1432                .insert(name);
1433        } else if let Type::NumberEnum { mangled, .. } | Type::StringEnum { mangled, .. } = ty {
1434            whole.insert(mangled);
1435        }
1436    }
1437    named
1438        .into_iter()
1439        .filter(|(mangled, named)| {
1440            whole.contains(mangled) || named.names.len() >= named.member_count
1441        })
1442        .map(|(mangled, _)| mangled.clone())
1443        .collect()
1444}
1445
1446impl Type {
1447    pub fn render_checked(
1448        &self,
1449        limits: crate::rendering::RenderLimits,
1450    ) -> Result<crate::rendering::RenderedText, crate::rendering::RenderError> {
1451        crate::type_rendering::render(self, limits)
1452    }
1453}
1454
1455/// A union's members in the order they are printed. Members are stored in
1456/// canonical order, which puts `null` and `undefined` first; they print last,
1457/// as TypeScript prints them: `string | null | undefined`.
1458pub fn union_display_order(members: &[Type]) -> Vec<&Type> {
1459    let mut ordered: Vec<&Type> = members.iter().collect();
1460    ordered.sort_by_key(|m| match m {
1461        Type::Null => 1,
1462        Type::Undefined => 2,
1463        _ => 0,
1464    });
1465    ordered
1466}
1467
1468impl fmt::Display for Type {
1469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1470        match self.render_checked(crate::rendering::RenderLimits::default()) {
1471            Ok(rendered) => f.write_str(&rendered.text),
1472            Err(_) => f.write_str("[diagnostic type unavailable]"),
1473        }
1474    }
1475}
1476
1477#[cfg(test)]
1478mod tests {
1479    use super::{Package, Type};
1480
1481    #[test]
1482    fn tuple_mapping_preserves_optional_positions() {
1483        let tuple = super::TupleType {
1484            elements: vec![Type::NumberLiteral(super::LiteralF64(1.0)), Type::Undefined],
1485            optional: 1,
1486        };
1487        let mapped = tuple.map(Type::widen_literal);
1488        assert_eq!(mapped.optional, 1);
1489        assert_eq!(mapped.required_len(), 1);
1490        assert_eq!(mapped.elements, vec![Type::Number, Type::Undefined]);
1491    }
1492
1493    #[test]
1494    fn optional_fields_read_as_undefined() {
1495        let field = super::ObjectField::optional(Type::String);
1496        assert_eq!(
1497            field.read_ty(),
1498            Type::union(vec![Type::String, Type::Undefined])
1499        );
1500    }
1501
1502    #[test]
1503    fn optional_function_and_tuple_display_preserve_omission() {
1504        let ty = Type::Function {
1505            params: vec![Type::union(vec![Type::String, Type::Undefined])],
1506            optional: 1,
1507            ret: Box::new(Type::Void),
1508            predicate: None,
1509            has_rest: false,
1510        };
1511        // An optional parameter admits `undefined` already, as `tsc` prints it.
1512        assert_eq!(ty.to_string(), "(arg0?: string) => void");
1513        let tuple = Type::Tuple(super::TupleType {
1514            elements: vec![
1515                Type::Number,
1516                Type::union(vec![Type::String, Type::Undefined]),
1517            ],
1518            optional: 1,
1519        });
1520        assert_eq!(tuple.to_string(), "[number, (string | undefined)?]");
1521    }
1522
1523    #[test]
1524    fn atomic_display() {
1525        assert_eq!(Type::Number.to_string(), "number");
1526        assert_eq!(Type::String.to_string(), "string");
1527        assert_eq!(Type::Boolean.to_string(), "boolean");
1528        assert_eq!(Type::Null.to_string(), "null");
1529        assert_eq!(Type::Void.to_string(), "void");
1530        assert_eq!(Type::Error.to_string(), "<error>");
1531    }
1532
1533    #[test]
1534    fn readonly_display_matches_typescript() {
1535        let numbers = Type::Array(Box::new(Type::Number));
1536        let readonly = Type::Readonly(Box::new(numbers.clone()));
1537        assert_eq!(readonly.to_string(), "readonly number[]");
1538        assert_eq!(
1539            Type::Array(Box::new(readonly.clone())).to_string(),
1540            "(readonly number[])[]"
1541        );
1542        assert_eq!(
1543            Type::Readonly(Box::new(Type::Array(Box::new(numbers)))).to_string(),
1544            "readonly number[][]"
1545        );
1546        assert_eq!(
1547            Type::Readonly(Box::new(Type::Tuple(
1548                vec![Type::Number, Type::String].into()
1549            )))
1550            .to_string(),
1551            "readonly [number, string]"
1552        );
1553        assert!(readonly.is_readonly_array());
1554        assert_eq!(readonly.peel(), &Type::Array(Box::new(Type::Number)));
1555    }
1556
1557    #[test]
1558    fn string_literal_display_escapes_like_typescript() {
1559        // Each expectation is what `tsc` 5.9 prints for the same literal type.
1560        let cases = [
1561            ("G\"HI\\", r#""G\"HI\\""#),
1562            ("a\nb\r\t", r#""a\nb\r\t""#),
1563            ("\u{8}\u{b}\u{c}", r#""\b\v\f""#),
1564            ("\0x", r#""\0x""#),
1565            ("\u{0}1", r#""\x001""#),
1566            ("\u{7}\u{1b}", r#""\u0007\u001B""#),
1567            ("\u{85}\u{2028}\u{2029}", r#""\u0085\u2028\u2029""#),
1568            ("\u{7f}é", "\"\u{7f}é\""),
1569        ];
1570        for (value, printed) in cases {
1571            assert_eq!(Type::StringLiteral(value.into()).to_string(), printed);
1572        }
1573    }
1574
1575    #[test]
1576    fn structural_equality() {
1577        assert_eq!(Type::Number, Type::Number);
1578        assert_ne!(Type::Number, Type::String);
1579
1580        let a = Type::Function {
1581            params: vec![Type::Number, Type::String],
1582            ret: Box::new(Type::Boolean),
1583            predicate: None,
1584            has_rest: false,
1585            optional: 0,
1586        };
1587        let b = Type::Function {
1588            params: vec![Type::Number, Type::String],
1589            ret: Box::new(Type::Boolean),
1590            predicate: None,
1591            has_rest: false,
1592            optional: 0,
1593        };
1594        let c = Type::Function {
1595            params: vec![Type::Number],
1596            ret: Box::new(Type::Boolean),
1597            predicate: None,
1598            has_rest: false,
1599            optional: 0,
1600        };
1601        assert_eq!(a, b);
1602        assert_ne!(a, c);
1603    }
1604
1605    #[test]
1606    fn function_display_no_params() {
1607        let t = Type::Function {
1608            params: vec![],
1609            ret: Box::new(Type::Number),
1610            predicate: None,
1611            has_rest: false,
1612            optional: 0,
1613        };
1614        assert_eq!(t.to_string(), "() => number");
1615    }
1616
1617    #[test]
1618    fn function_display_one_param() {
1619        let t = Type::Function {
1620            params: vec![Type::Number],
1621            ret: Box::new(Type::Boolean),
1622            predicate: None,
1623            has_rest: false,
1624            optional: 0,
1625        };
1626        assert_eq!(t.to_string(), "(arg0: number) => boolean");
1627    }
1628
1629    #[test]
1630    fn function_display_multi_param() {
1631        let t = Type::Function {
1632            params: vec![Type::Number, Type::String],
1633            ret: Box::new(Type::Void),
1634            predicate: None,
1635            has_rest: false,
1636            optional: 0,
1637        };
1638        assert_eq!(t.to_string(), "(arg0: number, arg1: string) => void");
1639    }
1640
1641    #[test]
1642    fn function_display_nested() {
1643        let inner = Type::Function {
1644            params: vec![],
1645            ret: Box::new(Type::Number),
1646            predicate: None,
1647            has_rest: false,
1648            optional: 0,
1649        };
1650        let outer = Type::Function {
1651            params: vec![],
1652            ret: Box::new(inner),
1653            predicate: None,
1654            has_rest: false,
1655            optional: 0,
1656        };
1657        assert_eq!(outer.to_string(), "() => () => number");
1658    }
1659
1660    #[test]
1661    fn clone_roundtrip() {
1662        let t = Type::Function {
1663            params: vec![Type::Number, Type::String],
1664            ret: Box::new(Type::Boolean),
1665            predicate: None,
1666            has_rest: false,
1667            optional: 0,
1668        };
1669        assert_eq!(t.clone(), t);
1670    }
1671
1672    fn point_type() -> Type {
1673        let mut fields = std::collections::BTreeMap::new();
1674        fields.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1675        fields.insert("y".to_string(), crate::ObjectField::required(Type::Number));
1676        Type::Object {
1677            index: None,
1678            fields,
1679        }
1680    }
1681
1682    #[test]
1683    fn object_structural_equality_ignores_field_insertion_order() {
1684        let mut a = std::collections::BTreeMap::new();
1685        a.insert("y".to_string(), crate::ObjectField::required(Type::Number));
1686        a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1687
1688        let mut b = std::collections::BTreeMap::new();
1689        b.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1690        b.insert("y".to_string(), crate::ObjectField::required(Type::Number));
1691
1692        assert_eq!(
1693            Type::Object {
1694                index: None,
1695                fields: a
1696            },
1697            Type::Object {
1698                index: None,
1699                fields: b
1700            }
1701        );
1702    }
1703
1704    #[test]
1705    fn object_inequality_on_different_field_set() {
1706        let mut a = std::collections::BTreeMap::new();
1707        a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1708        let mut b = std::collections::BTreeMap::new();
1709        b.insert("y".to_string(), crate::ObjectField::required(Type::Number));
1710        assert_ne!(
1711            Type::Object {
1712                index: None,
1713                fields: a
1714            },
1715            Type::Object {
1716                index: None,
1717                fields: b
1718            }
1719        );
1720    }
1721
1722    #[test]
1723    fn object_display() {
1724        assert_eq!(point_type().to_string(), "{ x: number; y: number }");
1725        let empty = Type::Object {
1726            index: None,
1727            fields: std::collections::BTreeMap::new(),
1728        };
1729        assert_eq!(empty.to_string(), "{}");
1730    }
1731
1732    #[test]
1733    fn object_display_with_optional_field() {
1734        let mut fields = std::collections::BTreeMap::new();
1735        fields.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1736        fields.insert("y".to_string(), crate::ObjectField::optional(Type::String));
1737        let t = Type::Object {
1738            index: None,
1739            fields,
1740        };
1741        assert_eq!(t.to_string(), "{ x: number; y?: string }");
1742    }
1743
1744    #[test]
1745    fn object_inequality_required_vs_optional() {
1746        let mut a = std::collections::BTreeMap::new();
1747        a.insert("x".to_string(), crate::ObjectField::required(Type::Number));
1748        let mut b = std::collections::BTreeMap::new();
1749        b.insert("x".to_string(), crate::ObjectField::optional(Type::Number));
1750        assert_ne!(
1751            Type::Object {
1752                index: None,
1753                fields: a
1754            },
1755            Type::Object {
1756                index: None,
1757                fields: b
1758            }
1759        );
1760    }
1761
1762    #[test]
1763    fn array_equality() {
1764        assert_eq!(
1765            Type::Array(Box::new(Type::Number)),
1766            Type::Array(Box::new(Type::Number))
1767        );
1768        assert_ne!(
1769            Type::Array(Box::new(Type::Number)),
1770            Type::Array(Box::new(Type::String))
1771        );
1772    }
1773
1774    #[test]
1775    fn array_display() {
1776        assert_eq!(Type::Array(Box::new(Type::Number)).to_string(), "number[]");
1777        assert_eq!(
1778            Type::Array(Box::new(Type::Array(Box::new(Type::Number)))).to_string(),
1779            "number[][]"
1780        );
1781    }
1782
1783    #[test]
1784    fn nested_object_in_array_display() {
1785        let arr = Type::Array(Box::new(point_type()));
1786        assert_eq!(arr.to_string(), "{ x: number; y: number }[]");
1787    }
1788
1789    #[test]
1790    fn type_var_display_uses_source_name() {
1791        assert_eq!(Type::TypeVar("T".to_string()).to_string(), "T");
1792        assert_eq!(Type::TypeVar("Key".to_string()).to_string(), "Key");
1793    }
1794
1795    #[test]
1796    fn type_var_structural_equality_by_name() {
1797        let t = Type::TypeVar("T".to_string());
1798        let t2 = Type::TypeVar("T".to_string());
1799        let u = Type::TypeVar("U".to_string());
1800        assert_eq!(t, t2);
1801        assert_ne!(t, u);
1802        assert_ne!(t, Type::Number);
1803    }
1804
1805    #[test]
1806    fn type_var_inside_array_and_function_displays_through() {
1807        let arr = Type::Array(Box::new(Type::TypeVar("T".to_string())));
1808        assert_eq!(arr.to_string(), "T[]");
1809        let func = Type::Function {
1810            params: vec![Type::TypeVar("T".to_string())],
1811            ret: Box::new(Type::TypeVar("U".to_string())),
1812            predicate: None,
1813            has_rest: false,
1814            optional: 0,
1815        };
1816        assert_eq!(func.to_string(), "(arg0: T) => U");
1817    }
1818
1819    #[test]
1820    fn generic_param_display_uses_name_not_id() {
1821        let gp = Type::GenericParam {
1822            id: 42,
1823            name: "T".to_string(),
1824        };
1825        assert_eq!(gp.to_string(), "T");
1826    }
1827
1828    #[test]
1829    fn generic_param_equality_by_id() {
1830        let a = Type::GenericParam {
1831            id: 5,
1832            name: "T".to_string(),
1833        };
1834        let b = Type::GenericParam {
1835            id: 5,
1836            name: "T".to_string(),
1837        };
1838        assert_eq!(a, b);
1839
1840        let c = Type::GenericParam {
1841            id: 6,
1842            name: "T".to_string(),
1843        };
1844        assert_ne!(a, c);
1845    }
1846
1847    #[test]
1848    fn union_canonical_dedup() {
1849        let t = Type::union(vec![Type::Number, Type::Null, Type::Number]);
1850        let Type::Union(members) = t else {
1851            panic!("expected Union, got {t:?}");
1852        };
1853        assert_eq!(members, vec![Type::Number, Type::Null]);
1854    }
1855
1856    #[test]
1857    fn union_canonical_order_independent() {
1858        let a = Type::union(vec![Type::Number, Type::Null]);
1859        let b = Type::union(vec![Type::Null, Type::Number]);
1860        assert_eq!(a, b);
1861    }
1862
1863    #[test]
1864    fn union_collapses_to_single_member() {
1865        let t = Type::union(vec![Type::Number, Type::Number]);
1866        assert_eq!(t, Type::Number);
1867    }
1868
1869    #[test]
1870    fn union_flattens_nested() {
1871        let inner = Type::union(vec![Type::String, Type::Null]);
1872        let outer = Type::union(vec![Type::Number, inner]);
1873        let expected = Type::union(vec![Type::Number, Type::String, Type::Null]);
1874        assert_eq!(outer, expected);
1875    }
1876
1877    #[test]
1878    fn union_error_member_collapses_to_error() {
1879        let t = Type::union(vec![Type::Number, Type::Error]);
1880        assert_eq!(t, Type::Error);
1881    }
1882
1883    #[test]
1884    fn union_display_basic() {
1885        let t = Type::union(vec![Type::Number, Type::String]);
1886        assert_eq!(t.to_string(), "number | string");
1887    }
1888
1889    #[test]
1890    fn union_display_with_null() {
1891        let t = Type::union(vec![Type::Number, Type::Null]);
1892        assert_eq!(t.to_string(), "number | null");
1893        let t2 = Type::union(vec![Type::Null, Type::Number]);
1894        assert_eq!(t2.to_string(), "number | null");
1895    }
1896
1897    #[test]
1898    fn union_display_wraps_function_member() {
1899        let fn_ty = Type::Function {
1900            params: vec![],
1901            ret: Box::new(Type::String),
1902            predicate: None,
1903            has_rest: false,
1904            optional: 0,
1905        };
1906        let t = Type::union(vec![fn_ty, Type::Boolean]);
1907        assert_eq!(t.to_string(), "boolean | (() => string)");
1908    }
1909
1910    use super::LiteralF64;
1911
1912    #[test]
1913    fn string_literal_display_is_quoted() {
1914        let t = Type::StringLiteral("north".to_string());
1915        assert_eq!(t.to_string(), "\"north\"");
1916    }
1917
1918    #[test]
1919    fn number_literal_display_is_unquoted_with_whole_number_shape() {
1920        let whole = Type::NumberLiteral(LiteralF64(42.0));
1921        assert_eq!(whole.to_string(), "42");
1922        let frac = Type::NumberLiteral(LiteralF64(4.5));
1923        assert_eq!(frac.to_string(), "4.5");
1924    }
1925
1926    #[test]
1927    fn string_literal_equality_by_value() {
1928        let a = Type::StringLiteral("hi".to_string());
1929        let b = Type::StringLiteral("hi".to_string());
1930        let c = Type::StringLiteral("bye".to_string());
1931        assert_eq!(a, b);
1932        assert_ne!(a, c);
1933    }
1934
1935    #[test]
1936    fn number_literal_equality_by_value() {
1937        let a = Type::NumberLiteral(LiteralF64(42.0));
1938        let b = Type::NumberLiteral(LiteralF64(42.0));
1939        let c = Type::NumberLiteral(LiteralF64(43.0));
1940        assert_eq!(a, b);
1941        assert_ne!(a, c);
1942    }
1943
1944    #[test]
1945    fn union_sorts_literals_next_to_base_types() {
1946        // NumberLiteral sorts after Number, StringLiteral after String per variant order.
1947        let t = Type::union(vec![
1948            Type::String,
1949            Type::StringLiteral("hi".to_string()),
1950            Type::Number,
1951            Type::NumberLiteral(LiteralF64(42.0)),
1952        ]);
1953        assert_eq!(t.to_string(), "number | 42 | string | \"hi\"");
1954    }
1955
1956    #[test]
1957    fn widen_literal_replaces_a_literal_with_its_base() {
1958        assert_eq!(
1959            Type::NumberLiteral(LiteralF64(1.0)).widen_literal(),
1960            Type::Number
1961        );
1962        assert_eq!(
1963            Type::StringLiteral("hi".to_string()).widen_literal(),
1964            Type::String
1965        );
1966    }
1967
1968    /// A union widens memberwise, and `Type::union` then deduplicates — so a union of
1969    /// literals over one base collapses to that base rather than repeating it.
1970    #[test]
1971    fn widen_literal_collapses_a_union_of_literals() {
1972        let t = Type::union(vec![
1973            Type::NumberLiteral(LiteralF64(1.0)),
1974            Type::NumberLiteral(LiteralF64(2.0)),
1975        ]);
1976        assert_eq!(t.widen_literal(), Type::Number);
1977    }
1978
1979    /// Enums are nominal, not literal: widening one would discard the identity its
1980    /// members are checked against. `primitive_behavior` is the enum-aware accessor.
1981    #[test]
1982    fn widen_literal_leaves_everything_else_alone() {
1983        assert_eq!(Type::Number.widen_literal(), Type::Number);
1984        assert_eq!(Type::Boolean.widen_literal(), Type::Boolean);
1985        let arr = Type::Array(Box::new(Type::NumberLiteral(LiteralF64(1.0))));
1986        assert_eq!(arr.widen_literal(), arr);
1987    }
1988
1989    #[test]
1990    fn union_of_two_string_literals_sorts_by_value() {
1991        let t = Type::union(vec![
1992            Type::StringLiteral("south".to_string()),
1993            Type::StringLiteral("north".to_string()),
1994        ]);
1995        assert_eq!(t.to_string(), "\"north\" | \"south\"");
1996    }
1997
1998    #[test]
1999    fn literal_f64_equality_distinguishes_negative_zero_at_bit_level() {
2000        // Bit-pattern equality distinguishes -0.0 and +0.0; parser canonicalizes -0.0→0.0 so
2001        // this case won't appear in practice.
2002        let pos = LiteralF64(0.0);
2003        let neg = LiteralF64(-0.0);
2004        assert_ne!(pos, neg);
2005    }
2006
2007    #[test]
2008    fn type_var_and_generic_param_are_distinct_types() {
2009        // TypeVar is signature form; GenericParam is body form.
2010        // Even with the same name they're different variants.
2011        let tv = Type::TypeVar("T".to_string());
2012        let gp = Type::GenericParam {
2013            id: 0,
2014            name: "T".to_string(),
2015        };
2016        assert_ne!(tv, gp);
2017    }
2018
2019    #[test]
2020    fn alias_display_renders_name_not_body() {
2021        let ty = user_alias("Circle", point_type());
2022        assert_eq!(ty.to_string(), "Circle");
2023    }
2024
2025    #[test]
2026    fn peel_walks_through_alias_to_underlying() {
2027        let inner = Type::Number;
2028        let aliased = user_alias("ID", inner.clone());
2029        assert_eq!(aliased.peel(), &inner);
2030    }
2031
2032    #[test]
2033    fn peel_is_idempotent_through_nested_aliases() {
2034        let nested = user_alias("A", user_alias("B", Type::Number));
2035        assert_eq!(nested.peel(), &Type::Number);
2036        assert_eq!(nested.peel().peel(), &Type::Number);
2037    }
2038
2039    #[test]
2040    fn alias_is_not_structurally_equal_to_underlying() {
2041        let aliased = user_alias("ID", Type::Number);
2042        assert_ne!(aliased, Type::Number);
2043        assert_eq!(aliased.peel(), &Type::Number);
2044    }
2045
2046    #[test]
2047    fn alias_routes_to_underlying_interface() {
2048        let aliased = user_alias("ID", Type::Number);
2049        let (_mangled, _pkg, iface, _args) = aliased.interface_routing().expect("number routes");
2050        assert_eq!(iface, "Number");
2051    }
2052
2053    #[test]
2054    fn union_of_error_alias_collapses_to_error() {
2055        let alias_err = user_alias("Bad", Type::Error);
2056        let t = Type::union(vec![Type::Number, alias_err]);
2057        assert_eq!(t, Type::Error);
2058    }
2059
2060    #[test]
2061    fn union_preserves_distinct_alias_members_for_display() {
2062        let circle = user_alias("Circle", point_type());
2063        let rect = user_alias("Rectangle", Type::Number);
2064        let t = Type::union(vec![circle, rect]);
2065        // Ordered by the peeled bodies, which puts `Number` before the object
2066        // shape — not by the order the members were written.
2067        assert_eq!(t.to_string(), "Rectangle | Circle");
2068    }
2069
2070    #[test]
2071    fn union_dedups_an_alias_against_its_own_body_keeping_the_label() {
2072        let n = user_alias("N", Type::Number);
2073        assert_eq!(Type::union(vec![n.clone(), Type::Number]), n);
2074        assert_eq!(Type::union(vec![Type::Number, n.clone()]), n);
2075    }
2076
2077    #[test]
2078    fn union_dedups_aliases_that_share_one_body() {
2079        let circle = user_alias("Circle", point_type());
2080        let rect = user_alias("Rectangle", point_type());
2081        assert_eq!(Type::union(vec![circle.clone(), rect]), circle);
2082    }
2083
2084    #[test]
2085    fn union_flattens_an_alias_whose_body_is_a_union() {
2086        let nullable = user_alias("MN", Type::union(vec![Type::Number, Type::Null]));
2087        assert_eq!(
2088            Type::union(vec![nullable, Type::Number]),
2089            Type::union(vec![Type::Number, Type::Null])
2090        );
2091    }
2092
2093    #[test]
2094    fn generic_alias_display_includes_args() {
2095        let ty = user_alias_args("Box", vec![Type::Number], Type::Number);
2096        assert_eq!(ty.to_string(), "Box<number>");
2097    }
2098
2099    fn iface(package: &str, name: &str) -> Type {
2100        Type::interface_ref(
2101            Package(package.to_string()),
2102            name,
2103            crate::mangle::package_symbol(package, name),
2104            Vec::new(),
2105        )
2106    }
2107
2108    fn user_alias(name: &str, ty: Type) -> Type {
2109        user_alias_args(name, Vec::new(), ty)
2110    }
2111
2112    fn user_alias_args(name: &str, args: Vec<Type>, ty: Type) -> Type {
2113        Type::alias_ty(
2114            Package::user(),
2115            name,
2116            crate::mangle::package_symbol(crate::mangle::USER_PACKAGE, name),
2117            args,
2118            Box::new(ty),
2119        )
2120    }
2121
2122    #[test]
2123    fn mangled_name_keys_type_identity() {
2124        // Identity is the mangled name. Same `(package, name)` ⇒ same mangled ⇒ equal;
2125        // a different owning package ⇒ different mangled ⇒ distinct (the multi-file
2126        // property: two same-named interfaces in different packages/modules are not
2127        // conflated).
2128        assert_eq!(iface("main", "Response"), iface("main", "Response"));
2129        let http = iface("submilli:http", "Response");
2130        let main = iface("main", "Response");
2131        assert_ne!(
2132            http, main,
2133            "different package ⇒ different mangled ⇒ distinct"
2134        );
2135        assert_ne!(
2136            http.cmp(&main),
2137            std::cmp::Ordering::Equal,
2138            "Ord must distinguish distinct mangled names"
2139        );
2140        assert_ne!(
2141            iface("main", "Response"),
2142            iface("main", "Other"),
2143            "different names stay distinct"
2144        );
2145    }
2146
2147    #[test]
2148    fn same_name_different_module_not_equal_nor_assignable() {
2149        // The core multi-file guarantee: a sibling module's `Logger`
2150        // (`mod:main#util#Logger`) is a distinct type from the root's `Logger`
2151        // (`main#Logger`), even though the bare name matches.
2152        let root = iface("main", "Logger");
2153        let sibling = Type::InterfaceRef {
2154            mangled: crate::mangle::package_module_symbol("main", "util", "Logger"),
2155            package: Package::user(),
2156            name: "Logger".to_string(),
2157            args: Vec::new(),
2158        };
2159        assert_ne!(root, sibling);
2160        // Same mangled ⇒ equal.
2161        let root2 = iface("main", "Logger");
2162        assert_eq!(root, root2);
2163    }
2164
2165    #[test]
2166    fn union_dedups_interface_refs_by_mangled() {
2167        // Same mangled collapses to one member; different mangled stays a 2-member union.
2168        let same = Type::union(vec![iface("main", "Response"), iface("main", "Response")]);
2169        assert!(
2170            !matches!(same, Type::Union(_)),
2171            "identical refs collapse to one member, got {same:?}"
2172        );
2173        let distinct = Type::union(vec![
2174            iface("submilli:http", "Response"),
2175            iface("main", "Response"),
2176        ]);
2177        assert!(
2178            matches!(distinct, Type::Union(ref ms) if ms.len() == 2),
2179            "distinct-package refs stay a 2-member union, got {distinct:?}"
2180        );
2181    }
2182
2183    #[test]
2184    fn generic_alias_display_multiple_args() {
2185        let ty = user_alias_args("Pair", vec![Type::String, Type::Number], Type::Number);
2186        assert_eq!(ty.to_string(), "Pair<string, number>");
2187    }
2188}