Skip to main content

mago_codex/ttype/atomic/
mod.rs

1use std::sync::Arc;
2
3use mago_word::Word;
4use mago_word::concat_word;
5use mago_word::word;
6
7use crate::consts::POSSIBLY_FALSY_CLASS_NAMES;
8use crate::metadata::CodebaseMetadata;
9use crate::reference::ReferenceSource;
10use crate::reference::SymbolReferences;
11use crate::symbol::SymbolKind;
12use crate::symbol::Symbols;
13use crate::ttype::TType;
14use crate::ttype::TypeRef;
15use crate::ttype::atomic::alias::TAlias;
16use crate::ttype::atomic::array::TArray;
17use crate::ttype::atomic::array::key::ArrayKey;
18use crate::ttype::atomic::callable::TCallable;
19use crate::ttype::atomic::conditional::TConditional;
20use crate::ttype::atomic::derived::TDerived;
21use crate::ttype::atomic::generic::TGenericParameter;
22use crate::ttype::atomic::iterable::TIterable;
23use crate::ttype::atomic::mixed::TMixed;
24use crate::ttype::atomic::object::TObject;
25use crate::ttype::atomic::object::r#enum::TEnum;
26use crate::ttype::atomic::object::named::TNamedObject;
27use crate::ttype::atomic::reference::TGlobalReferenceSelector;
28use crate::ttype::atomic::reference::TReference;
29use crate::ttype::atomic::reference::TReferenceMemberSelector;
30use crate::ttype::atomic::resource::TResource;
31use crate::ttype::atomic::scalar::TScalar;
32use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
33use crate::ttype::atomic::scalar::int::TInteger;
34use crate::ttype::atomic::scalar::string::TString;
35use crate::ttype::atomic::scalar::string::TStringLiteral;
36use crate::ttype::get_arraykey;
37use crate::ttype::get_mixed;
38use crate::ttype::union::TUnion;
39use crate::ttype::union::populate_union_type;
40
41pub mod alias;
42pub mod array;
43pub mod callable;
44pub mod conditional;
45pub mod derived;
46pub mod generic;
47pub mod iterable;
48pub mod mixed;
49pub mod object;
50pub mod reference;
51pub mod resource;
52pub mod scalar;
53
54#[allow(clippy::derived_hash_with_manual_eq)]
55#[derive(Debug, Clone, Eq, Hash, PartialOrd, Ord)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
57pub enum TAtomic {
58    Scalar(TScalar),
59    Callable(TCallable),
60    Mixed(TMixed),
61    Object(TObject),
62    Array(TArray),
63    Iterable(TIterable),
64    Resource(TResource),
65    Reference(TReference),
66    GenericParameter(TGenericParameter),
67    Variable(Word),
68    Conditional(TConditional),
69    Derived(TDerived),
70    Alias(TAlias),
71    Never,
72    Null,
73    Void,
74    Placeholder,
75}
76
77impl PartialEq for TAtomic {
78    #[inline]
79    fn eq(&self, other: &Self) -> bool {
80        if std::ptr::eq(self, other) {
81            return true;
82        }
83
84        match (self, other) {
85            (TAtomic::Scalar(a), TAtomic::Scalar(b)) => a == b,
86            (TAtomic::Callable(a), TAtomic::Callable(b)) => a == b,
87            (TAtomic::Mixed(a), TAtomic::Mixed(b)) => a == b,
88            (TAtomic::Object(a), TAtomic::Object(b)) => a == b,
89            (TAtomic::Array(a), TAtomic::Array(b)) => a == b,
90            (TAtomic::Iterable(a), TAtomic::Iterable(b)) => a == b,
91            (TAtomic::Resource(a), TAtomic::Resource(b)) => a == b,
92            (TAtomic::Reference(a), TAtomic::Reference(b)) => a == b,
93            (TAtomic::GenericParameter(a), TAtomic::GenericParameter(b)) => a == b,
94            (TAtomic::Variable(a), TAtomic::Variable(b)) => a == b,
95            (TAtomic::Conditional(a), TAtomic::Conditional(b)) => a == b,
96            (TAtomic::Derived(a), TAtomic::Derived(b)) => a == b,
97            (TAtomic::Alias(a), TAtomic::Alias(b)) => a == b,
98            (TAtomic::Never, TAtomic::Never)
99            | (TAtomic::Null, TAtomic::Null)
100            | (TAtomic::Void, TAtomic::Void)
101            | (TAtomic::Placeholder, TAtomic::Placeholder) => true,
102            _ => false,
103        }
104    }
105}
106
107impl TAtomic {
108    /// Returns true if this atomic is a Placeholder or contains Placeholder in type parameters.
109    #[must_use]
110    pub fn contains_placeholder(&self) -> bool {
111        match self {
112            TAtomic::Placeholder => true,
113            TAtomic::Object(TObject::Named(named)) => {
114                named.get_type_parameters().is_some_and(|params| params.iter().any(|p| p.contains_placeholder()))
115            }
116            TAtomic::Array(array) => array.contains_placeholder(),
117            _ => false,
118        }
119    }
120
121    /// Intersects two string atomics, returning `None` if either is not a string or no string satisfies both.
122    #[must_use]
123    pub fn intersect_strings(&self, other: &TAtomic) -> Option<TAtomic> {
124        let (TAtomic::Scalar(TScalar::String(left)), TAtomic::Scalar(TScalar::String(right))) = (self, other) else {
125            return None;
126        };
127
128        left.intersect(right).map(|string| TAtomic::Scalar(TScalar::String(string)))
129    }
130
131    #[must_use]
132    pub fn is_numeric(&self) -> bool {
133        match self {
134            TAtomic::Scalar(scalar) => scalar.is_numeric(),
135            TAtomic::GenericParameter(parameter) => parameter.constraint.is_numeric(),
136            _ => false,
137        }
138    }
139
140    #[must_use]
141    pub fn is_int_or_float(&self) -> bool {
142        match self {
143            TAtomic::Scalar(scalar) => scalar.is_int_or_float(),
144            TAtomic::GenericParameter(parameter) => parameter.constraint.is_int_or_float(),
145            _ => false,
146        }
147    }
148
149    /// Returns `Some(true)` if this type is effectively an int, `Some(false)` if effectively a float,
150    /// or `None` if neither. Considers generic parameter constraints (e.g., `T of int` is treated as int).
151    #[must_use]
152    pub fn effective_int_or_float(&self) -> Option<bool> {
153        match self {
154            TAtomic::Scalar(TScalar::Integer(_)) => Some(true),
155            TAtomic::Scalar(TScalar::Float(_)) => Some(false),
156            TAtomic::GenericParameter(parameter) => parameter.constraint.effective_int_or_float(),
157            _ => None,
158        }
159    }
160
161    #[must_use]
162    pub const fn is_mixed(&self) -> bool {
163        matches!(self, TAtomic::Mixed(_))
164    }
165
166    #[must_use]
167    pub const fn is_vanilla_mixed(&self) -> bool {
168        matches!(self, TAtomic::Mixed(_))
169    }
170
171    #[must_use]
172    pub const fn is_mixed_isset_from_loop(&self) -> bool {
173        matches!(self, TAtomic::Mixed(mixed) if mixed.is_isset_from_loop())
174    }
175
176    #[must_use]
177    pub const fn is_never(&self) -> bool {
178        matches!(self, TAtomic::Never)
179    }
180
181    #[must_use]
182    pub fn is_templated_as_never(&self) -> bool {
183        matches!(self, TAtomic::GenericParameter(parameter) if parameter.constraint.is_never())
184    }
185
186    #[must_use]
187    pub fn is_templated_as_mixed(&self) -> bool {
188        matches!(self, TAtomic::GenericParameter(parameter) if parameter.is_constrained_as_mixed())
189    }
190
191    #[must_use]
192    pub fn is_templated_as_vanilla_mixed(&self) -> bool {
193        matches!(self, TAtomic::GenericParameter(parameter) if parameter.is_constrained_as_vanilla_mixed())
194    }
195
196    pub fn map_generic_parameter_constraint<F, T>(&self, f: F) -> Option<T>
197    where
198        F: FnOnce(&TUnion) -> T,
199    {
200        if let TAtomic::GenericParameter(parameter) = self { Some(f(parameter.constraint.as_ref())) } else { None }
201    }
202
203    #[must_use]
204    pub fn is_enum(&self) -> bool {
205        matches!(self, TAtomic::Object(TObject::Enum(TEnum { .. })))
206    }
207
208    #[must_use]
209    pub fn is_object_type(&self) -> bool {
210        match self {
211            TAtomic::Object(_) => true,
212            TAtomic::Callable(callable) => callable.is_closure(),
213            TAtomic::GenericParameter(parameter) => parameter.is_constrained_as_objecty(),
214            _ => false,
215        }
216    }
217
218    #[must_use]
219    pub fn is_static(&self) -> bool {
220        matches!(self, TAtomic::Object(TObject::Named(named_object)) if named_object.is_static)
221    }
222
223    #[must_use]
224    pub fn is_this(&self) -> bool {
225        matches!(self, TAtomic::Object(TObject::Named(named_object)) if named_object.is_this())
226    }
227
228    #[must_use]
229    pub fn get_object_or_enum_name(&self) -> Option<Word> {
230        match self {
231            TAtomic::Object(object) => match object {
232                TObject::Named(named_object) => Some(named_object.get_name()),
233                TObject::Enum(r#enum) => Some(r#enum.get_name()),
234                _ => None,
235            },
236            _ => None,
237        }
238    }
239
240    #[must_use]
241    pub fn get_all_object_names(&self) -> Vec<Word> {
242        let mut object_names = vec![];
243
244        if let TAtomic::Object(object) = self {
245            match object {
246                TObject::Named(named_object) => object_names.push(named_object.get_name()),
247                TObject::Enum(r#enum) => object_names.push(r#enum.get_name()),
248                _ => {}
249            }
250        }
251
252        for intersection_type in self.get_intersection_types().unwrap_or_default() {
253            object_names.extend(intersection_type.get_all_object_names());
254        }
255
256        object_names
257    }
258
259    #[must_use]
260    pub fn is_generator(&self) -> bool {
261        matches!(&self, TAtomic::Object(object) if {
262            object.get_name().is_some_and(|name| name.as_bytes().eq_ignore_ascii_case(b"Generator"))
263        })
264    }
265
266    #[must_use]
267    pub fn get_generator_parameters(&self) -> Option<(TUnion, TUnion, TUnion, TUnion)> {
268        let generator_parameters = 'parameters: {
269            let TAtomic::Object(TObject::Named(named_object)) = self else {
270                break 'parameters None;
271            };
272
273            let object_name = named_object.get_name();
274            if !object_name.as_bytes().eq_ignore_ascii_case(b"Generator") {
275                break 'parameters None;
276            }
277
278            let parameters = named_object.get_type_parameters().unwrap_or_default();
279            match parameters {
280                [] => Some((get_mixed(), get_mixed(), get_mixed(), get_mixed())),
281                [a] => Some((get_mixed(), a.clone(), get_mixed(), get_mixed())),
282                [a, b] => Some((a.clone(), b.clone(), get_mixed(), get_mixed())),
283                [a, b, c] => Some((a.clone(), b.clone(), c.clone(), get_mixed())),
284                [a, b, c, d] => Some((a.clone(), b.clone(), c.clone(), d.clone())),
285                _ => None,
286            }
287        };
288
289        if let Some(parameters) = generator_parameters {
290            return Some(parameters);
291        }
292
293        if let Some(intersection_types) = self.get_intersection_types() {
294            for intersection_type in intersection_types {
295                if let Some(parameters) = intersection_type.get_generator_parameters() {
296                    return Some(parameters);
297                }
298            }
299        }
300
301        None
302    }
303
304    #[must_use]
305    pub fn is_templated_as_object(&self) -> bool {
306        matches!(self, TAtomic::GenericParameter(parameter) if {
307            parameter.constraint.is_objecty() && parameter.intersection_types.is_none()
308        })
309    }
310
311    #[inline]
312    #[must_use]
313    pub const fn is_list(&self) -> bool {
314        matches!(self, TAtomic::Array(array) if array.is_list())
315    }
316
317    #[inline]
318    #[must_use]
319    pub fn is_vanilla_array(&self) -> bool {
320        matches!(self, TAtomic::Array(array) if array.is_vanilla())
321    }
322
323    pub fn get_list_element_type(&self) -> Option<&TUnion> {
324        match self {
325            TAtomic::Array(array) => array.get_list().map(array::list::TList::get_element_type),
326            _ => None,
327        }
328    }
329
330    #[inline]
331    pub fn is_non_empty_list(&self) -> bool {
332        matches!(self, TAtomic::Array(array) if array.get_list().is_some_and(array::list::TList::is_non_empty))
333    }
334
335    #[inline]
336    #[must_use]
337    pub fn is_empty_array(&self) -> bool {
338        matches!(self, TAtomic::Array(array) if array.is_empty())
339    }
340
341    #[inline]
342    #[must_use]
343    pub const fn is_keyed_array(&self) -> bool {
344        matches!(self, TAtomic::Array(array) if array.is_keyed())
345    }
346
347    #[inline]
348    #[must_use]
349    pub const fn is_array(&self) -> bool {
350        matches!(self, TAtomic::Array(_))
351    }
352
353    #[inline]
354    #[must_use]
355    pub const fn is_iterable(&self) -> bool {
356        matches!(self, TAtomic::Iterable(_))
357    }
358
359    #[inline]
360    #[must_use]
361    pub fn extends_or_implements(&self, codebase: &CodebaseMetadata, interface: &[u8]) -> bool {
362        let object = match self {
363            TAtomic::Object(object) => object,
364            TAtomic::GenericParameter(parameter) => {
365                if let Some(intersection_types) = parameter.get_intersection_types() {
366                    for intersection_type in intersection_types {
367                        if intersection_type.extends_or_implements(codebase, interface) {
368                            return true;
369                        }
370                    }
371                }
372
373                for constraint_atomic in parameter.constraint.types.as_ref() {
374                    if constraint_atomic.extends_or_implements(codebase, interface) {
375                        return true;
376                    }
377                }
378
379                return false;
380            }
381            TAtomic::Iterable(iterable) => {
382                if let Some(intersection_types) = iterable.get_intersection_types() {
383                    for intersection_type in intersection_types {
384                        if intersection_type.extends_or_implements(codebase, interface) {
385                            return true;
386                        }
387                    }
388                }
389
390                return false;
391            }
392            // bottom type: subtype of all types
393            TAtomic::Never => return true,
394            _ => return false,
395        };
396
397        if let Some(object_name) = object.get_name() {
398            if object_name.as_bytes() == interface {
399                return true;
400            }
401
402            if codebase.is_instance_of(object_name.as_bytes(), interface) {
403                return true;
404            }
405        }
406
407        if let Some(intersection_types) = object.get_intersection_types() {
408            for intersection_type in intersection_types {
409                if intersection_type.extends_or_implements(codebase, interface) {
410                    return true;
411                }
412            }
413        }
414
415        false
416    }
417
418    #[inline]
419    #[must_use]
420    pub fn is_countable(&self, codebase: &CodebaseMetadata) -> bool {
421        match self {
422            TAtomic::Array(_) => true,
423            _ => self.extends_or_implements(codebase, b"Countable"),
424        }
425    }
426
427    #[inline]
428    #[must_use]
429    pub fn is_traversable(&self, codebase: &CodebaseMetadata) -> bool {
430        self.extends_or_implements(codebase, b"Traversable")
431            || self.extends_or_implements(codebase, b"Iterator")
432            || self.extends_or_implements(codebase, b"IteratorAggregate")
433            || self.extends_or_implements(codebase, b"Generator")
434    }
435
436    #[inline]
437    #[must_use]
438    pub fn is_array_or_traversable(&self, codebase: &CodebaseMetadata) -> bool {
439        match self {
440            TAtomic::Iterable(_) => true,
441            TAtomic::Array(_) => true,
442            _ => self.is_traversable(codebase),
443        }
444    }
445
446    #[inline]
447    #[must_use]
448    pub fn could_be_array_or_traversable(&self, codebase: &CodebaseMetadata) -> bool {
449        self.is_mixed() || self.is_array_or_traversable(codebase)
450    }
451
452    #[must_use]
453    pub fn is_non_empty_array(&self) -> bool {
454        matches!(self, TAtomic::Array(array) if array.is_non_empty())
455    }
456
457    pub fn to_array_key(&self) -> Option<ArrayKey> {
458        match self {
459            TAtomic::Scalar(TScalar::Integer(int)) => int.get_literal_value().map(ArrayKey::Integer),
460            TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(value)), .. })) => {
461                Some(ArrayKey::from_string(*value))
462            }
463            TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Literal { value })) => {
464                Some(ArrayKey::String(*value))
465            }
466            _ => None,
467        }
468    }
469
470    #[inline]
471    #[must_use]
472    pub const fn is_generic_scalar(&self) -> bool {
473        matches!(self, TAtomic::Scalar(TScalar::Generic))
474    }
475
476    #[inline]
477    #[must_use]
478    pub const fn is_some_scalar(&self) -> bool {
479        matches!(self, TAtomic::Scalar(_))
480    }
481
482    #[inline]
483    #[must_use]
484    pub const fn is_null(&self) -> bool {
485        matches!(self, TAtomic::Null)
486    }
487
488    #[inline]
489    #[must_use]
490    pub const fn is_void(&self) -> bool {
491        matches!(self, TAtomic::Void)
492    }
493
494    #[inline]
495    #[must_use]
496    pub const fn is_falsable(&self) -> bool {
497        matches!(
498            self,
499            TAtomic::Scalar(scalar) if scalar.is_false() || scalar.is_general_bool() || scalar.is_generic()
500        )
501    }
502
503    #[inline]
504    #[must_use]
505    pub const fn is_resource(&self) -> bool {
506        matches!(self, TAtomic::Resource(_))
507    }
508
509    #[inline]
510    #[must_use]
511    pub const fn is_literal(&self) -> bool {
512        match self {
513            TAtomic::Scalar(scalar) => scalar.is_literal_value(),
514            TAtomic::Null => true,
515            _ => false,
516        }
517    }
518
519    #[inline]
520    #[must_use]
521    pub const fn is_callable(&self) -> bool {
522        matches!(self, TAtomic::Callable(_))
523    }
524
525    #[inline]
526    #[must_use]
527    pub const fn is_conditional(&self) -> bool {
528        matches!(self, TAtomic::Conditional(_))
529    }
530
531    #[inline]
532    #[must_use]
533    pub const fn is_generic_parameter(&self) -> bool {
534        matches!(self, TAtomic::GenericParameter(_))
535    }
536
537    #[inline]
538    #[must_use]
539    pub const fn get_generic_parameter_name(&self) -> Option<Word> {
540        match self {
541            TAtomic::GenericParameter(parameter) => Some(parameter.parameter_name),
542            _ => None,
543        }
544    }
545
546    /// Is this a type that could potentially be callable at runtime?
547    #[inline]
548    #[must_use]
549    pub const fn can_be_callable(&self) -> bool {
550        matches!(
551            self,
552            TAtomic::Callable(_)
553                | TAtomic::Scalar(TScalar::String(_))
554                | TAtomic::Array(TArray::List(_) | TArray::Keyed(_))
555                | TAtomic::Object(TObject::Named(_))
556        )
557    }
558
559    #[must_use]
560    pub fn is_truthy(&self) -> bool {
561        match &self {
562            TAtomic::Scalar(scalar) => scalar.is_truthy(),
563            TAtomic::Array(array) => array.is_truthy(),
564            TAtomic::Mixed(mixed) => mixed.is_truthy(),
565            TAtomic::Resource(resource) => resource.closed.is_none_or(|closed| !closed),
566            // Instances of some classes (e.g. an empty `SimpleXMLElement`) can cast to `false`,
567            // so they are neither always truthy nor always falsy.
568            TAtomic::Object(TObject::Named(named_object)) => {
569                let name = named_object.name.as_bytes().trim_prefix(b"\\");
570                if POSSIBLY_FALSY_CLASS_NAMES.iter().any(|class_name| name.eq_ignore_ascii_case(class_name)) {
571                    return false;
572                }
573
574                if let Some(intersection_types) = named_object.get_intersection_types() {
575                    for intersection_type in intersection_types {
576                        if !intersection_type.is_truthy() {
577                            return false;
578                        }
579                    }
580                }
581
582                true
583            }
584            TAtomic::Object(_) | TAtomic::Callable(_) => true,
585            _ => false,
586        }
587    }
588
589    #[must_use]
590    pub fn is_falsy(&self) -> bool {
591        match &self {
592            TAtomic::Scalar(scalar) if scalar.is_falsy() => true,
593            TAtomic::Array(array) if array.is_falsy() => true,
594            TAtomic::Mixed(mixed) if mixed.is_falsy() => true,
595            TAtomic::Resource(resource) => resource.closed.is_some_and(|closed| closed),
596            TAtomic::Null | TAtomic::Void => true,
597            _ => false,
598        }
599    }
600
601    #[must_use]
602    pub fn is_array_accessible_with_string_key(&self) -> bool {
603        matches!(self, TAtomic::Array(array) if array.is_keyed())
604    }
605
606    #[must_use]
607    pub fn is_array_accessible_with_int_or_string_key(&self) -> bool {
608        matches!(self, TAtomic::Array(_))
609    }
610
611    #[must_use]
612    pub fn is_derived(&self) -> bool {
613        matches!(self, TAtomic::Derived(_))
614    }
615
616    pub fn remove_placeholders(&mut self) {
617        match self {
618            TAtomic::Array(array) => {
619                array.remove_placeholders();
620            }
621            TAtomic::Object(TObject::Named(named_object)) => {
622                let name = named_object.get_name();
623                if let Some(type_parameters) = named_object.get_type_parameters_mut() {
624                    if name.as_bytes().eq_ignore_ascii_case(b"Traversable") {
625                        let has_kv_pair = type_parameters.len() == 2;
626
627                        if let Some(key_or_value_param) = type_parameters.get_mut(0)
628                            && matches!(key_or_value_param.get_single(), TAtomic::Placeholder)
629                        {
630                            *key_or_value_param = if has_kv_pair { get_arraykey() } else { get_mixed() };
631                        }
632
633                        if has_kv_pair
634                            && let Some(value_param) = type_parameters.get_mut(1)
635                            && matches!(value_param.get_single(), TAtomic::Placeholder)
636                        {
637                            *value_param = get_mixed();
638                        }
639                    } else {
640                        for type_param in type_parameters {
641                            if matches!(type_param.get_single(), TAtomic::Placeholder) {
642                                *type_param = get_mixed();
643                            }
644                        }
645                    }
646                }
647            }
648            _ => {}
649        }
650    }
651
652    #[must_use]
653    pub fn get_integer(&self) -> Option<TInteger> {
654        match self {
655            TAtomic::Scalar(TScalar::Integer(integer)) => Some(*integer),
656            _ => None,
657        }
658    }
659}
660
661macro_rules! scalar_forwarding_predicates {
662    ($($method:ident => $scalar_method:ident),* $(,)?) => {
663        $(
664            #[inline]
665            #[must_use]
666            pub const fn $method(&self) -> bool {
667                matches!(self, TAtomic::Scalar(scalar) if scalar.$scalar_method())
668            }
669        )*
670    };
671}
672
673macro_rules! scalar_forwarding_getters {
674    ($($method:ident => $scalar_method:ident -> $return_type:ty),* $(,)?) => {
675        $(
676            #[inline]
677            #[must_use]
678            pub fn $method(&self) -> Option<$return_type> {
679                match self {
680                    TAtomic::Scalar(scalar) => scalar.$scalar_method(),
681                    _ => None,
682                }
683            }
684        )*
685    };
686}
687
688impl TAtomic {
689    scalar_forwarding_predicates! {
690        is_any_string => is_any_string,
691        is_string => is_string,
692        is_string_of_literal_origin => is_literal_origin_string,
693        is_non_empty_string => is_non_empty_string,
694        is_known_literal_string => is_known_literal_string,
695        is_literal_class_string => is_literal_class_string,
696        is_string_subtype => is_non_boring_string,
697        is_array_key => is_array_key,
698        is_int => is_int,
699        is_literal_int => is_literal_int,
700        is_float => is_float,
701        is_literal_float => is_literal_float,
702        is_bool => is_bool,
703        is_general_bool => is_general_bool,
704        is_general_string => is_general_string,
705        is_true => is_true,
706        is_false => is_false,
707    }
708
709    scalar_forwarding_getters! {
710        get_literal_string_value => get_known_literal_string_value -> &[u8],
711        get_class_string_value => get_literal_class_string_value -> Word,
712        get_literal_int_value => get_literal_int_value -> i64,
713        get_maximum_int_value => get_maximum_int_value -> i64,
714        get_minimum_int_value => get_minimum_int_value -> i64,
715        get_literal_float_value => get_literal_float_value -> f64,
716    }
717}
718
719macro_rules! with_inner_ttype {
720    ($self:expr, $ttype:ident => $body:expr, $fallback:expr) => {
721        match $self {
722            TAtomic::Scalar($ttype) => $body,
723            TAtomic::Callable($ttype) => $body,
724            TAtomic::Mixed($ttype) => $body,
725            TAtomic::Object($ttype) => $body,
726            TAtomic::Array($ttype) => $body,
727            TAtomic::Iterable($ttype) => $body,
728            TAtomic::Resource($ttype) => $body,
729            TAtomic::Reference($ttype) => $body,
730            TAtomic::GenericParameter($ttype) => $body,
731            TAtomic::Conditional($ttype) => $body,
732            TAtomic::Derived($ttype) => $body,
733            TAtomic::Alias($ttype) => $body,
734            _ => $fallback,
735        }
736    };
737}
738
739impl TType for TAtomic {
740    fn append_child_nodes<'types>(&'types self, children: &mut Vec<TypeRef<'types>>) {
741        with_inner_ttype!(self, ttype => ttype.append_child_nodes(children), ())
742    }
743
744    fn can_be_intersected(&self) -> bool {
745        with_inner_ttype!(self, ttype => ttype.can_be_intersected(), false)
746    }
747
748    fn get_intersection_types(&self) -> Option<&[TAtomic]> {
749        with_inner_ttype!(self, ttype => ttype.get_intersection_types(), None)
750    }
751
752    fn get_intersection_types_mut(&mut self) -> Option<&mut Vec<TAtomic>> {
753        with_inner_ttype!(self, ttype => ttype.get_intersection_types_mut(), None)
754    }
755
756    fn has_intersection_types(&self) -> bool {
757        with_inner_ttype!(self, ttype => ttype.has_intersection_types(), false)
758    }
759
760    fn add_intersection_type(&mut self, intersection_type: TAtomic) -> bool {
761        with_inner_ttype!(self, ttype => ttype.add_intersection_type(intersection_type), false)
762    }
763
764    fn needs_population(&self) -> bool {
765        if let Some(intersection) = self.get_intersection_types()
766            && intersection.iter().any(|intersection_type| intersection_type.needs_population())
767        {
768            return true;
769        }
770
771        with_inner_ttype!(self, ttype => ttype.needs_population(), false)
772    }
773
774    #[inline]
775    fn is_expandable(&self) -> bool {
776        if let Some(intersection) = self.get_intersection_types()
777            && intersection.iter().any(|intersection_type| intersection_type.is_expandable())
778        {
779            return true;
780        }
781
782        with_inner_ttype!(self, ttype => ttype.is_expandable(), false)
783    }
784
785    fn is_complex(&self) -> bool {
786        if let Some(intersection) = self.get_intersection_types()
787            && intersection.iter().any(|intersection_type| intersection_type.is_complex())
788        {
789            return true;
790        }
791
792        with_inner_ttype!(self, ttype => ttype.is_complex(), false)
793    }
794
795    fn get_id(&self) -> Word {
796        with_inner_ttype!(self, ttype => ttype.get_id(), match self {
797            TAtomic::Variable(name) => *name,
798            TAtomic::Never => word("never"),
799            TAtomic::Null => word("null"),
800            TAtomic::Void => word("void"),
801            _ => word("_"),
802        })
803    }
804
805    fn get_pretty_id_with_indent(&self, indent: usize) -> Word {
806        with_inner_ttype!(self, ttype => ttype.get_pretty_id_with_indent(indent), match self {
807            TAtomic::Variable(name) => *name,
808            TAtomic::Never => word("never"),
809            TAtomic::Null => word("null"),
810            TAtomic::Void => word("void"),
811            _ => word("_"),
812        })
813    }
814}
815
816pub(crate) fn append_intersection_ids(mut base: Word, intersection_types: &[TAtomic], indent: Option<usize>) -> Word {
817    for atomic in intersection_types {
818        let atomic_id = match indent {
819            Some(indent) => atomic.get_pretty_id_with_indent(indent),
820            None => atomic.get_id(),
821        };
822
823        base = if atomic.has_intersection_types() {
824            concat_word!(base, b"&(", atomic_id, b")")
825        } else {
826            concat_word!(base, b"&", atomic_id)
827        };
828    }
829
830    base
831}
832
833fn add_symbol_reference(reference_source: &ReferenceSource, symbol_references: &mut SymbolReferences, name: Word) {
834    let name = name.to_ascii_lowercase();
835    match reference_source {
836        ReferenceSource::Symbol(in_signature, a) => {
837            symbol_references.add_symbol_reference_to_symbol(*a, name, *in_signature);
838        }
839        ReferenceSource::ClassLikeMember(in_signature, a, b) => {
840            symbol_references.add_class_member_reference_to_symbol((*a, *b), name, *in_signature);
841        }
842        ReferenceSource::File(in_signature, file) => {
843            symbol_references.add_file_reference_to_class_member(*file, (name, mago_word::empty_word()), *in_signature);
844        }
845    }
846}
847
848pub fn populate_atomic_type(
849    unpopulated_atomic: &mut TAtomic,
850    codebase_symbols: &Symbols,
851    reference_source: Option<&ReferenceSource>,
852    symbol_references: &mut SymbolReferences,
853    force: bool,
854) {
855    macro_rules! populate {
856        (union $target:expr) => {
857            populate_union_type($target, codebase_symbols, reference_source, symbol_references, force)
858        };
859        (atomic $target:expr) => {
860            populate_atomic_type($target, codebase_symbols, reference_source, symbol_references, force)
861        };
862    }
863
864    match unpopulated_atomic {
865        TAtomic::Array(array) => match array {
866            TArray::List(list) => {
867                populate!(union Arc::make_mut(&mut list.element_type));
868
869                if let Some(known_elements) = list.known_elements.as_mut().map(Arc::make_mut) {
870                    for (_, element_type) in known_elements.values_mut() {
871                        populate!(union element_type);
872                    }
873                }
874            }
875            TArray::Keyed(keyed_array) => {
876                if let Some(known_items) = keyed_array.known_items.as_mut().map(Arc::make_mut) {
877                    for (_, item_type) in known_items.values_mut() {
878                        populate!(union item_type);
879                    }
880                }
881
882                if let Some(parameters) = &mut keyed_array.parameters {
883                    populate!(union Arc::make_mut(&mut parameters.0));
884
885                    populate!(union Arc::make_mut(&mut parameters.1));
886                }
887            }
888        },
889        TAtomic::Callable(TCallable::Signature(signature)) => {
890            if let Some(return_type) = signature.get_return_type_mut() {
891                populate!(union return_type);
892            }
893
894            for param in signature.get_parameters_mut() {
895                if let Some(param_type) = param.get_type_signature_mut() {
896                    populate!(union param_type);
897                }
898                if let Some(out_type) = param.get_out_type_mut() {
899                    populate!(union out_type);
900                }
901                if let Some(closure_this_type) = param.get_closure_this_type_mut() {
902                    populate!(union closure_this_type);
903                }
904            }
905
906            for constraint in Arc::make_mut(&mut signature.constraints).iter_mut() {
907                populate!(union Arc::make_mut(&mut constraint.input_type));
908                populate!(union Arc::make_mut(&mut constraint.parameter_type));
909            }
910        }
911        TAtomic::Object(TObject::Named(named_object)) => {
912            let name = named_object.get_name();
913
914            if !named_object.is_intersection()
915                && !named_object.has_type_parameters()
916                && codebase_symbols.contains_enum(name)
917            {
918                *unpopulated_atomic = TAtomic::Object(TObject::new_enum(name));
919            } else {
920                if let Some(type_parameters) = named_object.get_type_parameters_mut() {
921                    for parameter in type_parameters {
922                        populate!(union parameter);
923                    }
924                }
925
926                if let Some(intersection_types) = named_object.get_intersection_types_mut() {
927                    for intersection_type in intersection_types {
928                        populate!(atomic intersection_type);
929                    }
930                }
931            }
932
933            if let Some(reference_source) = reference_source {
934                add_symbol_reference(reference_source, symbol_references, name);
935            }
936        }
937        TAtomic::Object(TObject::WithProperties(keyed_array)) => {
938            for (_, item_type) in keyed_array.known_properties.values_mut() {
939                populate!(union item_type);
940            }
941        }
942        TAtomic::Iterable(iterable) => {
943            populate!(union iterable.get_key_type_mut());
944
945            populate!(union iterable.get_value_type_mut());
946
947            if let Some(intersection_types) = iterable.get_intersection_types_mut() {
948                for intersection_type in intersection_types {
949                    populate!(atomic intersection_type);
950                }
951            }
952        }
953        TAtomic::Reference(reference) => match reference {
954            TReference::Symbol { name, parameters, variances, intersection_types } => {
955                if let Some(parameters) = parameters {
956                    for parameter in parameters {
957                        populate!(union parameter);
958                    }
959                }
960
961                if let Some(reference_source) = reference_source {
962                    add_symbol_reference(reference_source, symbol_references, *name);
963                }
964
965                if let Some(symbol_kind) = codebase_symbols.get_kind(name.to_ascii_lowercase()) {
966                    if symbol_kind == SymbolKind::Enum && parameters.is_none() {
967                        *unpopulated_atomic = TAtomic::Object(TObject::new_enum(*name));
968                    } else {
969                        let intersection_types = intersection_types.take().map(|intersection_types| {
970                            intersection_types
971                                .into_iter()
972                                .map(|mut intersection_type| {
973                                    populate!(atomic &mut intersection_type);
974
975                                    intersection_type
976                                })
977                                .collect::<Vec<_>>()
978                        });
979
980                        let mut named_object = TNamedObject::new(*name)
981                            .with_type_parameters(parameters.take())
982                            .with_variances(variances.take().map(|variances| *variances));
983                        if let Some(intersection_types) = intersection_types {
984                            for intersection_type in intersection_types {
985                                named_object.add_intersection_type(intersection_type);
986                            }
987                        }
988
989                        *unpopulated_atomic = TAtomic::Object(TObject::Named(named_object));
990                    }
991                }
992            }
993            TReference::Member { class_like_name, member_selector } => {
994                if let TReferenceMemberSelector::Identifier(member_name) = member_selector
995                    && let Some(reference_source) = reference_source
996                {
997                    match reference_source {
998                        ReferenceSource::Symbol(in_signature, a) => symbol_references
999                            .add_symbol_reference_to_class_member(*a, (*class_like_name, *member_name), *in_signature),
1000                        ReferenceSource::ClassLikeMember(in_signature, a, b) => symbol_references
1001                            .add_class_member_reference_to_class_member(
1002                                (*a, *b),
1003                                (*class_like_name, *member_name),
1004                                *in_signature,
1005                            ),
1006                        ReferenceSource::File(in_signature, file) => symbol_references
1007                            .add_file_reference_to_class_member(*file, (*class_like_name, *member_name), *in_signature),
1008                    }
1009                }
1010            }
1011            TReference::Global { selector } => {
1012                if let Some(reference_source) = reference_source {
1013                    match selector {
1014                        TGlobalReferenceSelector::Identifier(name) => {
1015                            add_symbol_reference(reference_source, symbol_references, *name);
1016                        }
1017                        TGlobalReferenceSelector::Fallback { name, fallback } => {
1018                            add_symbol_reference(reference_source, symbol_references, *name);
1019                            add_symbol_reference(reference_source, symbol_references, *fallback);
1020                        }
1021                        _ => {}
1022                    }
1023                }
1024            }
1025        },
1026        TAtomic::GenericParameter(TGenericParameter { constraint, intersection_types, .. }) => {
1027            populate!(union Arc::make_mut(constraint));
1028
1029            if let Some(intersection_types) = intersection_types.as_mut() {
1030                for intersection_type in intersection_types {
1031                    populate!(atomic intersection_type);
1032                }
1033            }
1034        }
1035        TAtomic::Scalar(TScalar::ClassLikeString(
1036            TClassLikeString::OfType { constraint, .. } | TClassLikeString::Generic { constraint, .. },
1037        )) => {
1038            populate!(atomic Arc::make_mut(constraint));
1039        }
1040        TAtomic::Conditional(conditional) => {
1041            populate!(union conditional.get_subject_mut());
1042
1043            populate!(union conditional.get_target_mut());
1044
1045            populate!(union conditional.get_then_mut());
1046
1047            populate!(union conditional.get_otherwise_mut());
1048        }
1049        TAtomic::Derived(derived) => match derived {
1050            TDerived::IntMask(int_mask) => {
1051                for value in int_mask.get_values_mut() {
1052                    populate!(union value);
1053                }
1054            }
1055            TDerived::IndexAccess(index_access) => {
1056                populate!(union index_access.get_target_type_mut());
1057
1058                populate!(union index_access.get_index_type_mut());
1059            }
1060            TDerived::TemplateType(template_type) => {
1061                populate!(union template_type.get_object_mut());
1062
1063                populate!(union template_type.get_class_name_mut());
1064
1065                populate!(union template_type.get_template_name_mut());
1066            }
1067            TDerived::Intersection(intersection) => {
1068                populate!(union intersection.get_base_type_mut());
1069                if let Some(intersection_types) = intersection.get_intersection_types_mut() {
1070                    for intersection_type in intersection_types {
1071                        populate!(atomic intersection_type);
1072                    }
1073                }
1074            }
1075            _ => {
1076                if let Some(target) = derived.get_target_type_mut() {
1077                    populate!(union target);
1078                }
1079            }
1080        },
1081        _ => {}
1082    }
1083}