Skip to main content

mir_types/
atomic.rs

1use std::hash::Hash;
2use std::sync::Arc;
3
4use indexmap::IndexMap;
5use serde::{Deserialize, Serialize};
6
7use crate::symbol::Name;
8use crate::Type;
9
10// ---------------------------------------------------------------------------
11// FnParam — used inside callable/closure atomics
12// ---------------------------------------------------------------------------
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct FnParam {
16    pub name: Name,
17    /// Parameter type stored as SimpleType for compact representation.
18    /// Most params are simple scalars (string, int, etc.) and fit inline.
19    pub ty: Option<crate::compact::SimpleType>,
20    /// `@param-out` / `@psalm-param-out` writeback type. When `Some`, the
21    /// variable passed for this by-ref param is set to this type after the call
22    /// instead of the declared in-type (`ty`). Preserved through `TClosure` so
23    /// first-class callables honour out-param annotations.
24    #[serde(default)]
25    pub out_ty: Option<crate::compact::SimpleType>,
26    /// Default value stored as SimpleType. Usually None or a simple scalar.
27    pub default: Option<crate::compact::SimpleType>,
28    pub is_variadic: bool,
29    pub is_byref: bool,
30    pub is_optional: bool,
31}
32
33// ---------------------------------------------------------------------------
34// Variance — covariance / contravariance for template type parameters
35// ---------------------------------------------------------------------------
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
38pub enum Variance {
39    /// Default: exact type match required (no `@template-covariant` / `@template-contravariant`).
40    #[default]
41    Invariant,
42    /// `@template-covariant T` — `C<Sub>` is assignable to `C<Super>`.
43    Covariant,
44    /// `@template-contravariant T` — `C<Super>` is assignable to `C<Sub>`.
45    Contravariant,
46}
47
48// ---------------------------------------------------------------------------
49// TemplateParam — `@template T` / `@template T of Bound`
50// ---------------------------------------------------------------------------
51
52#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
53pub struct TemplateParam {
54    pub name: Name,
55    pub bound: Option<Type>,
56    pub variance: Variance,
57}
58
59// ---------------------------------------------------------------------------
60// KeyedProperty — entry in TKeyedArray
61// ---------------------------------------------------------------------------
62
63#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
64pub enum ArrayKey {
65    String(Arc<str>),
66    Int(i64),
67}
68
69impl PartialOrd for ArrayKey {
70    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
71        Some(self.cmp(other))
72    }
73}
74
75impl Ord for ArrayKey {
76    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
77        match (self, other) {
78            (ArrayKey::Int(a), ArrayKey::Int(b)) => a.cmp(b),
79            (ArrayKey::String(a), ArrayKey::String(b)) => a.cmp(b),
80            // Int < String
81            (ArrayKey::Int(_), ArrayKey::String(_)) => std::cmp::Ordering::Less,
82            (ArrayKey::String(_), ArrayKey::Int(_)) => std::cmp::Ordering::Greater,
83        }
84    }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
88pub struct KeyedProperty {
89    pub ty: Type,
90    pub optional: bool,
91}
92
93type KeyedMap = IndexMap<ArrayKey, KeyedProperty, rustc_hash::FxBuildHasher>;
94
95/// Entries of an `array{...}` shape, in declaration order. Remembers its
96/// order-independent hash, since a shared shape is hashed again whenever a
97/// type holding it is interned; any mutable access forgets it.
98#[derive(Default, Serialize, Deserialize)]
99#[serde(transparent)]
100pub struct KeyedProperties {
101    map: KeyedMap,
102    #[serde(skip)]
103    hash: std::sync::OnceLock<u64>,
104}
105
106impl KeyedProperties {
107    pub fn with_capacity_and_hasher(n: usize, hasher: rustc_hash::FxBuildHasher) -> Self {
108        KeyedMap::with_capacity_and_hasher(n, hasher).into()
109    }
110
111    /// Hash of the entries, independent of their order (equality ignores it too).
112    pub fn entries_hash(&self) -> u64 {
113        *self.hash.get_or_init(|| {
114            self.map.iter().fold(0u64, |combined, (k, v)| {
115                let mut entry_hasher = rustc_hash::FxHasher::default();
116                k.hash(&mut entry_hasher);
117                v.hash(&mut entry_hasher);
118                combined.wrapping_add(std::hash::Hasher::finish(&entry_hasher))
119            })
120        })
121    }
122}
123
124impl From<KeyedMap> for KeyedProperties {
125    fn from(map: KeyedMap) -> Self {
126        KeyedProperties {
127            map,
128            hash: std::sync::OnceLock::new(),
129        }
130    }
131}
132
133impl Clone for KeyedProperties {
134    fn clone(&self) -> Self {
135        KeyedProperties {
136            map: self.map.clone(),
137            hash: self.hash.clone(),
138        }
139    }
140}
141
142impl std::fmt::Debug for KeyedProperties {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        self.map.fmt(f)
145    }
146}
147
148impl PartialEq for KeyedProperties {
149    fn eq(&self, other: &Self) -> bool {
150        // Remembered hashes that differ settle it without visiting the entries.
151        if let (Some(a), Some(b)) = (self.hash.get(), other.hash.get()) {
152            if a != b {
153                return false;
154            }
155        }
156        self.map == other.map
157    }
158}
159
160impl Eq for KeyedProperties {}
161
162impl std::ops::Deref for KeyedProperties {
163    type Target = KeyedMap;
164    fn deref(&self) -> &KeyedMap {
165        &self.map
166    }
167}
168
169impl std::ops::DerefMut for KeyedProperties {
170    fn deref_mut(&mut self) -> &mut KeyedMap {
171        self.hash = std::sync::OnceLock::new();
172        &mut self.map
173    }
174}
175
176impl FromIterator<(ArrayKey, KeyedProperty)> for KeyedProperties {
177    fn from_iter<I: IntoIterator<Item = (ArrayKey, KeyedProperty)>>(iter: I) -> Self {
178        KeyedMap::from_iter(iter).into()
179    }
180}
181
182impl Extend<(ArrayKey, KeyedProperty)> for KeyedProperties {
183    fn extend<I: IntoIterator<Item = (ArrayKey, KeyedProperty)>>(&mut self, iter: I) {
184        std::ops::DerefMut::deref_mut(self).extend(iter);
185    }
186}
187
188impl IntoIterator for KeyedProperties {
189    type Item = (ArrayKey, KeyedProperty);
190    type IntoIter = indexmap::map::IntoIter<ArrayKey, KeyedProperty>;
191    fn into_iter(self) -> Self::IntoIter {
192        self.map.into_iter()
193    }
194}
195
196impl<'a> IntoIterator for &'a KeyedProperties {
197    type Item = (&'a ArrayKey, &'a KeyedProperty);
198    type IntoIter = indexmap::map::Iter<'a, ArrayKey, KeyedProperty>;
199    fn into_iter(self) -> Self::IntoIter {
200        self.map.iter()
201    }
202}
203
204impl<'a> IntoIterator for &'a mut KeyedProperties {
205    type Item = (&'a ArrayKey, &'a mut KeyedProperty);
206    type IntoIter = indexmap::map::IterMut<'a, ArrayKey, KeyedProperty>;
207    fn into_iter(self) -> Self::IntoIter {
208        std::ops::DerefMut::deref_mut(self).iter_mut()
209    }
210}
211
212// ---------------------------------------------------------------------------
213// Boxed variant payloads — keep `Atomic` (and `Type`, which inlines two) small
214// ---------------------------------------------------------------------------
215
216/// Payload of [`Atomic::TClosure`].
217#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
218pub struct ClosureData {
219    pub params: Box<[FnParam]>,
220    pub return_type: Type,
221    pub this_type: Option<Type>,
222    /// `pure-Closure(...)`, or a closure literal whose body is checked as pure.
223    pub is_pure: bool,
224    /// A `static` closure literal, which has no `$this` to mutate.
225    pub is_static: bool,
226    /// A first-class callable of a named function or method, so surplus arguments are reported.
227    #[serde(default)]
228    pub rejects_surplus_args: bool,
229    /// A closure literal whose body visibly has side effects (output, `exit`, `global`, `static`).
230    #[serde(default)]
231    pub is_impure: bool,
232}
233
234/// Payload of [`Atomic::TConditional`].
235#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
236pub struct ConditionalData {
237    /// The parameter name being tested (without `$`), e.g. `"classOrInterface"`.
238    /// `None` for conditionals that were not parsed from a `$param is` form.
239    pub param_name: Option<Name>,
240    pub subject: Type,
241    pub if_true: Type,
242    pub if_false: Type,
243}
244
245/// Which properties a [`Atomic::TPropertiesOf`] keeps.
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
247pub enum PropertyFilter {
248    All,
249    Public,
250    Protected,
251    Private,
252}
253
254/// What a [`Atomic::TRefinedInt`] guarantees about its value.
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
256pub enum IntRefinement {
257    /// `literal-int` — an int written in the source, not read at runtime.
258    Literal,
259    /// `int-mask-of<Cls::PATTERN>` over the constants of a class other than the declaring one.
260    MaskOf(Name),
261}
262
263/// What a [`Atomic::TRefinedString`] guarantees about its characters.
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
265pub enum StringRefinement {
266    Lowercase,
267    Uppercase,
268    /// `literal-string` — a value written in the source, not read at runtime.
269    Literal,
270}
271
272impl StringRefinement {
273    pub fn accepts(self, s: &str) -> bool {
274        match self {
275            StringRefinement::Lowercase => !s.bytes().any(|b| b.is_ascii_uppercase()),
276            StringRefinement::Uppercase => !s.bytes().any(|b| b.is_ascii_lowercase()),
277            StringRefinement::Literal => true,
278        }
279    }
280}
281
282// ---------------------------------------------------------------------------
283// Atomic — every distinct PHP type variant
284// ---------------------------------------------------------------------------
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
287pub enum Atomic {
288    // --- Scalars ---
289    /// `string`
290    TString,
291    /// `"hello"` — a specific string literal
292    TLiteralString(Arc<str>),
293    /// `callable-string` — a string containing a callable name
294    TCallableString,
295    /// `class-string` or `class-string<T>`
296    TClassString(Option<Name>),
297    /// `non-empty-string`
298    TNonEmptyString,
299    /// `non-falsy-string` — neither `""` nor `"0"`
300    TNonFalsyString,
301    /// `numeric-string`
302    TNumericString,
303    /// `lowercase-string`, `uppercase-string`, `literal-string` and their `non-empty-` forms.
304    TRefinedString {
305        refinement: StringRefinement,
306        non_empty: bool,
307    },
308
309    /// `int`
310    TInt,
311    /// `42` — a specific integer literal
312    TLiteralInt(i64),
313    /// `int<min, max>` — bounded integer range
314    TIntRange { min: Option<i64>, max: Option<i64> },
315    /// `positive-int`
316    TPositiveInt,
317    /// `negative-int`
318    TNegativeInt,
319    /// `non-negative-int`
320    TNonNegativeInt,
321    /// `literal-int` or an unresolved `int-mask-of<Cls::*>`.
322    TRefinedInt(IntRefinement),
323
324    /// `float`
325    TFloat,
326    /// `float` that is always integral (whole-number value, no fractional part).
327    /// Returned by `floor()`, `ceil()`, and zero-precision `round()`. Can be passed to `int`
328    /// parameters without `ImplicitFloatToIntCast` because the conversion is lossless.
329    TIntegralFloat,
330    /// `3.14` — a specific float literal
331    TLiteralFloat(i64, i64), // stored as (int_bits, frac_bits) to be PartialEq+Hash-friendly
332    // We use ordered_float or just store as ordered pair for equality purposes.
333    /// `bool`
334    TBool,
335    /// `true`
336    TTrue,
337    /// `false`
338    TFalse,
339
340    /// `null`
341    TNull,
342
343    // --- Bottom / top ---
344    /// `void` — return-only; can't be used as a value
345    TVoid,
346    /// `never` — function that never returns (throws or infinite loop)
347    TNever,
348    /// `mixed` — top type; accepts anything
349    TMixed,
350    /// `scalar` — int | float | string | bool
351    TScalar,
352    /// `numeric` — int | float | numeric-string
353    TNumeric,
354
355    // --- Objects ---
356    /// `object` — any object
357    TObject,
358    /// `ClassName` / `ClassName<T1, T2>` — specific named class/interface
359    TNamedObject {
360        fqcn: Name,
361        /// Resolved generic type arguments (e.g. `Collection<int>`)
362        type_params: Arc<[Type]>,
363    },
364    /// `static` — late static binding type; resolved to calling class at call site
365    TStaticObject { fqcn: Name },
366    /// `self` — the class in whose body the type appears
367    TSelf { fqcn: Name },
368    /// `parent` — the parent class
369    TParent { fqcn: Name },
370
371    // --- Callables ---
372    /// `callable` or `callable(T): R`
373    TCallable {
374        /// Thin box: an inline `Vec` or boxed slice here, next to `is_pure`,
375        /// would make this the largest variant and grow every `Atomic` (and
376        /// `Type` inlines two of them).
377        params: Option<Box<Vec<FnParam>>>,
378        return_type: Option<Box<Type>>,
379        /// `pure-callable`.
380        is_pure: bool,
381    },
382    /// `Closure` or `Closure(T): R` — more specific than TCallable.
383    /// Payload boxed to keep `Atomic` at 32 bytes (see [`ClosureData`]).
384    TClosure { data: Box<ClosureData> },
385
386    // --- Arrays ---
387    /// `array` or `array<K, V>`
388    TArray { key: Box<Type>, value: Box<Type> },
389    /// `list<T>` — integer-keyed sequential array (keys 0, 1, 2, …)
390    TList { value: Box<Type> },
391    /// `non-empty-array<K, V>`
392    TNonEmptyArray { key: Box<Type>, value: Box<Type> },
393    /// `non-empty-list<T>`
394    TNonEmptyList { value: Box<Type> },
395    /// `array{key: T, ...}` — shape / keyed array
396    TKeyedArray {
397        /// Shared so cloning a shape copies a pointer and equal clones compare by address.
398        properties: Arc<KeyedProperties>,
399        /// If true, additional keys beyond the declared ones may exist
400        is_open: bool,
401        /// If true, the shape represents a list (integer keys only)
402        is_list: bool,
403    },
404
405    // --- Generics / meta-types ---
406    /// `T` — a template type parameter
407    TTemplateParam {
408        name: Name,
409        as_type: Box<Type>,
410        /// The entity (class or function FQN) that declared this template
411        defining_entity: Name,
412    },
413    /// `key-of<T>` — preserved when the operand cannot yet be reduced.
414    TKeyOf { target: Box<Type> },
415    /// `value-of<T>` — preserved when the operand cannot yet be reduced.
416    TValueOf { target: Box<Type> },
417    /// `($param is TypeName ? A : B)` — conditional type.
418    /// Payload boxed to keep `Atomic` at 32 bytes (see [`ConditionalData`]).
419    TConditional { data: Box<ConditionalData> },
420
421    // --- Special object strings ---
422    /// `interface-string` or `interface-string<T>`
423    TInterfaceString(Option<Name>),
424    /// `enum-string`
425    TEnumString,
426    /// `trait-string`
427    TTraitString,
428
429    // --- Enum cases ---
430    /// `EnumName::CaseName` — a specific enum case literal
431    TLiteralEnumCase { enum_fqcn: Name, case_name: Name },
432
433    // --- Intersection ---
434    /// `A&B&C` — PHP 8.1+ pure intersection type
435    TIntersection { parts: Arc<[Type]> },
436
437    /// `object{prop: T, ...}` — an object with these public properties.
438    TObjectShape { properties: Arc<KeyedProperties> },
439
440    /// `resource` — a legacy resource handle (open or closed); docblock-only, never a native type.
441    TResource,
442    /// `closed-resource` — a handle known to be closed, as after `fclose()`.
443    TClosedResource,
444
445    /// `properties-of<Cls>` and its visibility-filtered forms: a shape built from the class when checked.
446    TPropertiesOf { class: Name, filter: PropertyFilter },
447}
448
449impl Atomic {
450    /// Whether this atomic type can ever evaluate to a falsy value.
451    pub fn can_be_falsy(&self) -> bool {
452        match self {
453            Atomic::TNull
454            | Atomic::TFalse
455            | Atomic::TBool
456            | Atomic::TNever
457            | Atomic::TLiteralInt(0)
458            | Atomic::TLiteralFloat(0, 0)
459            | Atomic::TInt
460            | Atomic::TRefinedInt(_)
461            | Atomic::TFloat
462            | Atomic::TNumeric
463            | Atomic::TScalar
464            | Atomic::TMixed
465            | Atomic::TString
466            | Atomic::TNonEmptyString  // "0" is both non-empty and falsy in PHP
467            | Atomic::TNumericString   // "0" is a valid numeric-string and is falsy
468            | Atomic::TRefinedString { .. }
469            | Atomic::TKeyOf { .. }
470            | Atomic::TValueOf { .. }
471            | Atomic::TArray { .. }
472            | Atomic::TList { .. } => true,
473            // Non-empty collections always have at least one element — never falsy in PHP.
474            // TNonEmptyArray and TNonEmptyList are intentionally excluded here.
475
476            Atomic::TLiteralString(s) => s.as_ref().is_empty() || s.as_ref() == "0",
477
478            Atomic::TKeyedArray { properties, .. } => properties.values().all(|p| p.optional),
479
480            // An int range can be falsy (== 0) when 0 is within the bounds.
481            Atomic::TIntRange { min, max } => {
482                min.is_none_or(|lo| lo <= 0) && max.is_none_or(|hi| hi >= 0)
483            }
484            // non-negative-int includes 0
485            Atomic::TNonNegativeInt => true,
486
487            _ => false,
488        }
489    }
490
491    /// A template parameter or a `key-of`/`value-of` over one: its concrete type is unknown here.
492    pub fn is_deferred(&self) -> bool {
493        matches!(
494            self,
495            Atomic::TTemplateParam { .. } | Atomic::TKeyOf { .. } | Atomic::TValueOf { .. }
496        )
497    }
498
499    /// Whether this atomic type can ever evaluate to a truthy value.
500    pub fn can_be_truthy(&self) -> bool {
501        match self {
502            Atomic::TNever
503            | Atomic::TVoid
504            | Atomic::TNull
505            | Atomic::TFalse
506            | Atomic::TLiteralInt(0)
507            | Atomic::TLiteralFloat(0, 0) => false,
508            Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => false,
509            // int<0, 0> always equals zero — never truthy.
510            Atomic::TIntRange {
511                min: Some(0),
512                max: Some(0),
513            } => false,
514            // array{} — a closed empty keyed array — is always falsy.
515            Atomic::TKeyedArray {
516                properties,
517                is_open,
518                ..
519            } if !is_open && properties.is_empty() => false,
520            _ => true,
521        }
522    }
523
524    /// Whether this atomic represents a numeric type (int, float, or numeric-string).
525    pub fn is_numeric(&self) -> bool {
526        matches!(
527            self,
528            Atomic::TInt
529                | Atomic::TLiteralInt(_)
530                | Atomic::TIntRange { .. }
531                | Atomic::TPositiveInt
532                | Atomic::TNegativeInt
533                | Atomic::TNonNegativeInt
534                | Atomic::TRefinedInt(_)
535                | Atomic::TFloat
536                | Atomic::TIntegralFloat
537                | Atomic::TLiteralFloat(..)
538                | Atomic::TNumeric
539                | Atomic::TNumericString
540        )
541    }
542
543    /// Whether this atomic is an integer variant.
544    pub fn is_int(&self) -> bool {
545        matches!(
546            self,
547            Atomic::TInt
548                | Atomic::TLiteralInt(_)
549                | Atomic::TIntRange { .. }
550                | Atomic::TPositiveInt
551                | Atomic::TNegativeInt
552                | Atomic::TNonNegativeInt
553                | Atomic::TRefinedInt(_)
554        )
555    }
556
557    /// Whether this atomic is a string variant.
558    pub fn is_string(&self) -> bool {
559        matches!(
560            self,
561            Atomic::TString
562                | Atomic::TLiteralString(_)
563                | Atomic::TCallableString
564                | Atomic::TClassString(_)
565                | Atomic::TNonEmptyString
566                | Atomic::TNonFalsyString
567                | Atomic::TRefinedString { .. }
568                | Atomic::TNumericString
569                | Atomic::TInterfaceString(_)
570                | Atomic::TEnumString
571                | Atomic::TTraitString
572        )
573    }
574
575    /// Whether this atomic is an array variant.
576    pub fn is_array(&self) -> bool {
577        matches!(
578            self,
579            Atomic::TArray { .. }
580                | Atomic::TList { .. }
581                | Atomic::TNonEmptyArray { .. }
582                | Atomic::TNonEmptyList { .. }
583                | Atomic::TKeyedArray { .. }
584        )
585    }
586
587    /// Whether this atomic is an object variant.
588    pub fn is_object(&self) -> bool {
589        matches!(
590            self,
591            Atomic::TObject
592                | Atomic::TObjectShape { .. }
593                | Atomic::TNamedObject { .. }
594                | Atomic::TStaticObject { .. }
595                | Atomic::TSelf { .. }
596                | Atomic::TParent { .. }
597                | Atomic::TIntersection { .. }
598        )
599    }
600
601    /// Whether this atomic can never be an object instance — so `clone`-ing it
602    /// is invalid. Conservative: ambiguous atomics (`mixed`, `callable`,
603    /// `never`, conditionals, template params, enum cases, intersections,
604    /// object types) all return `false` so they never trigger a false positive.
605    pub fn is_definitely_non_object(&self) -> bool {
606        matches!(
607            self,
608            Atomic::TString
609                | Atomic::TLiteralString(_)
610                | Atomic::TCallableString
611                | Atomic::TClassString(_)
612                | Atomic::TNonEmptyString
613                | Atomic::TNonFalsyString
614                | Atomic::TRefinedString { .. }
615                | Atomic::TNumericString
616                | Atomic::TInterfaceString(_)
617                | Atomic::TEnumString
618                | Atomic::TTraitString
619                | Atomic::TInt
620                | Atomic::TLiteralInt(_)
621                | Atomic::TIntRange { .. }
622                | Atomic::TPositiveInt
623                | Atomic::TNegativeInt
624                | Atomic::TNonNegativeInt
625                | Atomic::TRefinedInt(_)
626                | Atomic::TFloat
627                | Atomic::TIntegralFloat
628                | Atomic::TLiteralFloat(..)
629                | Atomic::TBool
630                | Atomic::TTrue
631                | Atomic::TFalse
632                | Atomic::TNull
633                | Atomic::TVoid
634                | Atomic::TArray { .. }
635                | Atomic::TList { .. }
636                | Atomic::TNonEmptyArray { .. }
637                | Atomic::TNonEmptyList { .. }
638                | Atomic::TKeyedArray { .. }
639                | Atomic::TScalar
640                | Atomic::TNumeric
641        )
642    }
643
644    /// Whether this atomic is a callable variant.
645    ///
646    /// `TCallableString` is included: it denotes a string *known* to be a
647    /// valid callable, so `!is_callable()` must remove it from the type.
648    pub fn is_callable(&self) -> bool {
649        matches!(
650            self,
651            Atomic::TCallable { .. } | Atomic::TClosure { .. } | Atomic::TCallableString
652        )
653    }
654
655    /// Returns the FQCN if this is a named object type.
656    pub fn named_object_fqcn(&self) -> Option<&str> {
657        match self {
658            Atomic::TNamedObject { fqcn, .. }
659            | Atomic::TStaticObject { fqcn }
660            | Atomic::TSelf { fqcn }
661            | Atomic::TParent { fqcn } => Some(fqcn.as_ref()),
662            _ => None,
663        }
664    }
665
666    /// A human-readable name for this type (used in error messages).
667    pub fn type_name(&self) -> &'static str {
668        match self {
669            Atomic::TString
670            | Atomic::TLiteralString(_)
671            | Atomic::TNonEmptyString
672            | Atomic::TNonFalsyString
673            | Atomic::TRefinedString { .. }
674            | Atomic::TNumericString => "string",
675            Atomic::TCallableString => "callable-string",
676            Atomic::TClassString(_) => "class-string",
677            Atomic::TInt
678            | Atomic::TLiteralInt(_)
679            | Atomic::TIntRange { .. }
680            | Atomic::TRefinedInt(_) => "int",
681            Atomic::TPositiveInt => "positive-int",
682            Atomic::TNegativeInt => "negative-int",
683            Atomic::TNonNegativeInt => "non-negative-int",
684            Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..) => "float",
685            Atomic::TBool => "bool",
686            Atomic::TTrue => "true",
687            Atomic::TFalse => "false",
688            Atomic::TNull => "null",
689            Atomic::TVoid => "void",
690            Atomic::TNever => "never",
691            Atomic::TMixed => "mixed",
692            Atomic::TScalar => "scalar",
693            Atomic::TNumeric => "numeric",
694            Atomic::TObject => "object",
695            Atomic::TResource | Atomic::TClosedResource => "resource",
696            Atomic::TPropertiesOf { .. } => "array",
697            Atomic::TNamedObject { .. } => "object",
698            Atomic::TStaticObject { .. } => "static",
699            Atomic::TSelf { .. } => "self",
700            Atomic::TParent { .. } => "parent",
701            Atomic::TCallable { .. } => "callable",
702            Atomic::TClosure { .. } => "Closure",
703            Atomic::TArray { .. } => "array",
704            Atomic::TList { .. } => "list",
705            Atomic::TNonEmptyArray { .. } => "non-empty-array",
706            Atomic::TNonEmptyList { .. } => "non-empty-list",
707            Atomic::TKeyedArray { .. } => "array",
708            Atomic::TTemplateParam { .. } => "template-param",
709            Atomic::TKeyOf { .. } => "key-of",
710            Atomic::TValueOf { .. } => "value-of",
711            Atomic::TConditional { .. } => "conditional-type",
712            Atomic::TInterfaceString(_) => "interface-string",
713            Atomic::TEnumString => "enum-string",
714            Atomic::TTraitString => "trait-string",
715            Atomic::TLiteralEnumCase { .. } => "enum-case",
716            Atomic::TIntersection { .. } => "intersection",
717            Atomic::TObjectShape { .. } => "object",
718        }
719    }
720}
721
722// ---------------------------------------------------------------------------
723// Hash impls
724// ---------------------------------------------------------------------------
725
726impl Hash for FnParam {
727    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
728        self.name.hash(state);
729        self.ty.hash(state);
730        self.out_ty.hash(state);
731        self.default.hash(state);
732        self.is_variadic.hash(state);
733        self.is_byref.hash(state);
734        self.is_optional.hash(state);
735    }
736}
737
738/// Discriminant tags for `Atomic` used in the manual `Hash` impl below.
739#[allow(non_camel_case_types, clippy::enum_variant_names)]
740#[repr(u8)]
741enum AtomicTag {
742    TString = 0,
743    TLiteralString,
744    TCallableString,
745    TClassString,
746    TNonEmptyString,
747    TNonFalsyString,
748    TNumericString,
749    TRefinedString,
750    TInt,
751    TLiteralInt,
752    TIntRange,
753    TPositiveInt,
754    TNegativeInt,
755    TNonNegativeInt,
756    TRefinedInt,
757    TFloat,
758    TIntegralFloat,
759    TLiteralFloat,
760    TBool,
761    TTrue,
762    TFalse,
763    TNull,
764    TVoid,
765    TNever,
766    TMixed,
767    TScalar,
768    TNumeric,
769    TObject,
770    TNamedObject,
771    TStaticObject,
772    TSelf,
773    TParent,
774    TCallable,
775    TClosure,
776    TArray,
777    TList,
778    TNonEmptyArray,
779    TNonEmptyList,
780    TKeyedArray,
781    TTemplateParam,
782    TKeyOf,
783    TValueOf,
784    TConditional,
785    TInterfaceString,
786    TEnumString,
787    TTraitString,
788    TLiteralEnumCase,
789    TIntersection,
790    TObjectShape,
791    TResource,
792    TClosedResource,
793    TPropertiesOf,
794}
795
796impl Hash for Atomic {
797    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
798        use AtomicTag as T;
799        match self {
800            // --- tag-only variants ---
801            Atomic::TString => (T::TString as u8).hash(state),
802            Atomic::TCallableString => (T::TCallableString as u8).hash(state),
803            Atomic::TNonEmptyString => (T::TNonEmptyString as u8).hash(state),
804            Atomic::TNonFalsyString => (T::TNonFalsyString as u8).hash(state),
805            Atomic::TNumericString => (T::TNumericString as u8).hash(state),
806            Atomic::TRefinedString {
807                refinement,
808                non_empty,
809            } => {
810                (T::TRefinedString as u8).hash(state);
811                refinement.hash(state);
812                non_empty.hash(state);
813            }
814            Atomic::TInt => (T::TInt as u8).hash(state),
815            Atomic::TPositiveInt => (T::TPositiveInt as u8).hash(state),
816            Atomic::TNegativeInt => (T::TNegativeInt as u8).hash(state),
817            Atomic::TNonNegativeInt => (T::TNonNegativeInt as u8).hash(state),
818            Atomic::TRefinedInt(refinement) => {
819                (T::TRefinedInt as u8).hash(state);
820                refinement.hash(state);
821            }
822            Atomic::TFloat => (T::TFloat as u8).hash(state),
823            Atomic::TIntegralFloat => (T::TIntegralFloat as u8).hash(state),
824            Atomic::TBool => (T::TBool as u8).hash(state),
825            Atomic::TTrue => (T::TTrue as u8).hash(state),
826            Atomic::TFalse => (T::TFalse as u8).hash(state),
827            Atomic::TNull => (T::TNull as u8).hash(state),
828            Atomic::TVoid => (T::TVoid as u8).hash(state),
829            Atomic::TNever => (T::TNever as u8).hash(state),
830            Atomic::TMixed => (T::TMixed as u8).hash(state),
831            Atomic::TScalar => (T::TScalar as u8).hash(state),
832            Atomic::TNumeric => (T::TNumeric as u8).hash(state),
833            Atomic::TObject => (T::TObject as u8).hash(state),
834            Atomic::TEnumString => (T::TEnumString as u8).hash(state),
835            Atomic::TTraitString => (T::TTraitString as u8).hash(state),
836            Atomic::TResource => (T::TResource as u8).hash(state),
837            Atomic::TClosedResource => (T::TClosedResource as u8).hash(state),
838            Atomic::TPropertiesOf { class, filter } => {
839                (T::TPropertiesOf as u8).hash(state);
840                class.hash(state);
841                filter.hash(state);
842            }
843
844            // --- variants with fields ---
845            Atomic::TLiteralString(s) => {
846                (T::TLiteralString as u8).hash(state);
847                s.hash(state);
848            }
849            Atomic::TClassString(opt) => {
850                (T::TClassString as u8).hash(state);
851                opt.hash(state);
852            }
853            Atomic::TInterfaceString(opt) => {
854                (T::TInterfaceString as u8).hash(state);
855                opt.hash(state);
856            }
857            Atomic::TLiteralInt(n) => {
858                (T::TLiteralInt as u8).hash(state);
859                n.hash(state);
860            }
861            Atomic::TIntRange { min, max } => {
862                (T::TIntRange as u8).hash(state);
863                min.hash(state);
864                max.hash(state);
865            }
866            Atomic::TLiteralFloat(int_bits, frac_bits) => {
867                (T::TLiteralFloat as u8).hash(state);
868                int_bits.hash(state);
869                frac_bits.hash(state);
870            }
871            Atomic::TNamedObject { fqcn, type_params } => {
872                (T::TNamedObject as u8).hash(state);
873                fqcn.hash(state);
874                type_params.hash(state);
875            }
876            Atomic::TStaticObject { fqcn } => {
877                (T::TStaticObject as u8).hash(state);
878                fqcn.hash(state);
879            }
880            Atomic::TSelf { fqcn } => {
881                (T::TSelf as u8).hash(state);
882                fqcn.hash(state);
883            }
884            Atomic::TParent { fqcn } => {
885                (T::TParent as u8).hash(state);
886                fqcn.hash(state);
887            }
888            Atomic::TCallable {
889                params,
890                return_type,
891                is_pure,
892            } => {
893                (T::TCallable as u8).hash(state);
894                params.hash(state);
895                return_type.hash(state);
896                is_pure.hash(state);
897            }
898            Atomic::TClosure { data } => {
899                (T::TClosure as u8).hash(state);
900                data.hash(state);
901            }
902            Atomic::TArray { key, value } => {
903                (T::TArray as u8).hash(state);
904                key.hash(state);
905                value.hash(state);
906            }
907            Atomic::TList { value } => {
908                (T::TList as u8).hash(state);
909                value.hash(state);
910            }
911            Atomic::TNonEmptyArray { key, value } => {
912                (T::TNonEmptyArray as u8).hash(state);
913                key.hash(state);
914                value.hash(state);
915            }
916            Atomic::TNonEmptyList { value } => {
917                (T::TNonEmptyList as u8).hash(state);
918                value.hash(state);
919            }
920            Atomic::TObjectShape { properties } => {
921                (T::TObjectShape as u8).hash(state);
922                properties.entries_hash().hash(state);
923                properties.len().hash(state);
924            }
925            Atomic::TKeyedArray {
926                properties,
927                is_open,
928                is_list,
929            } => {
930                (T::TKeyedArray as u8).hash(state);
931                properties.entries_hash().hash(state);
932                properties.len().hash(state);
933                is_open.hash(state);
934                is_list.hash(state);
935            }
936            Atomic::TTemplateParam {
937                name,
938                as_type,
939                defining_entity,
940            } => {
941                (T::TTemplateParam as u8).hash(state);
942                name.hash(state);
943                as_type.hash(state);
944                defining_entity.hash(state);
945            }
946            Atomic::TKeyOf { target } => {
947                (T::TKeyOf as u8).hash(state);
948                target.hash(state);
949            }
950            Atomic::TValueOf { target } => {
951                (T::TValueOf as u8).hash(state);
952                target.hash(state);
953            }
954            Atomic::TConditional { data } => {
955                (T::TConditional as u8).hash(state);
956                data.hash(state);
957            }
958            Atomic::TLiteralEnumCase {
959                enum_fqcn,
960                case_name,
961            } => {
962                (T::TLiteralEnumCase as u8).hash(state);
963                enum_fqcn.hash(state);
964                case_name.hash(state);
965            }
966            Atomic::TIntersection { parts } => {
967                (T::TIntersection as u8).hash(state);
968                parts.hash(state);
969            }
970        }
971    }
972}