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