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