Skip to main content

mago_codex/ttype/atomic/
mod.rs

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