Skip to main content

mago_codex/ttype/
expander.rs

1use std::borrow::Cow;
2use std::cell::RefCell;
3use std::sync::Arc;
4
5use std::collections::HashSet;
6
7use foldhash::fast::FixedState;
8use mago_atom::Atom;
9use mago_atom::ascii_lowercase_atom;
10
11use crate::identifier::function_like::FunctionLikeIdentifier;
12use crate::metadata::CodebaseMetadata;
13use crate::metadata::function_like::FunctionLikeMetadata;
14use crate::ttype::TType;
15use crate::ttype::atomic::TAtomic;
16use crate::ttype::atomic::alias::TAlias;
17use crate::ttype::atomic::array::TArray;
18use crate::ttype::atomic::array::key::ArrayKey;
19use crate::ttype::atomic::callable::TCallable;
20use crate::ttype::atomic::callable::TCallableSignature;
21use crate::ttype::atomic::callable::parameter::TCallableParameter;
22use crate::ttype::atomic::derived::TDerived;
23use crate::ttype::atomic::derived::index_access::TIndexAccess;
24use crate::ttype::atomic::derived::int_mask::TIntMask;
25use crate::ttype::atomic::derived::int_mask_of::TIntMaskOf;
26use crate::ttype::atomic::derived::key_of::TKeyOf;
27use crate::ttype::atomic::derived::new::TNew;
28use crate::ttype::atomic::derived::properties_of::TPropertiesOf;
29use crate::ttype::atomic::derived::template_type::TTemplateType;
30use crate::ttype::atomic::derived::value_of::TValueOf;
31use crate::ttype::atomic::mixed::TMixed;
32use crate::ttype::atomic::object::TObject;
33use crate::ttype::atomic::object::named::TNamedObject;
34use crate::ttype::atomic::reference::TGlobalReferenceSelector;
35use crate::ttype::atomic::reference::TReference;
36use crate::ttype::atomic::reference::TReferenceMemberSelector;
37use crate::ttype::atomic::scalar::TScalar;
38use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
39use crate::ttype::atomic::scalar::int::TInteger;
40use crate::ttype::atomic::scalar::string::TString;
41use crate::ttype::atomic::scalar::string::TStringLiteral;
42use crate::ttype::combiner;
43use crate::ttype::union::TUnion;
44
45thread_local! {
46    /// Thread-local set for tracking currently expanding aliases (cycle detection).
47    /// Uses a HashSet for accurate tracking without false positives from hash collisions.
48    static EXPANDING_ALIASES: RefCell<HashSet<(Atom, Atom), FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
49
50    /// Thread-local set for tracking objects whose type parameters are being expanded (cycle detection).
51    static EXPANDING_OBJECT_PARAMS: RefCell<HashSet<Atom, FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
52
53    /// Thread-local set for tracking class constants whose inferred initializer is currently
54    /// being expanded. Used to break cycles like `const int b = self::b;` where the inferred
55    /// type of a constant is a reference to itself.
56    static EXPANDING_CONSTANTS: RefCell<HashSet<(Atom, Atom), FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
57}
58
59/// Resets the thread-local alias expansion state.
60///
61/// This is primarily useful for testing to ensure a clean state between tests.
62/// In normal usage, the RAII guards handle cleanup automatically.
63#[inline]
64pub fn reset_expansion_state() {
65    EXPANDING_ALIASES.with(|set| set.borrow_mut().clear());
66    EXPANDING_OBJECT_PARAMS.with(|set| set.borrow_mut().clear());
67    EXPANDING_CONSTANTS.with(|set| set.borrow_mut().clear());
68}
69
70/// RAII guard to ensure alias expansion state is properly cleaned up.
71/// This guarantees the alias is removed from the set even if the expansion panics.
72struct AliasExpansionGuard {
73    class_name: Atom,
74    alias_name: Atom,
75}
76
77impl AliasExpansionGuard {
78    #[must_use]
79    fn new(class_name: Atom, alias_name: Atom) -> Self {
80        EXPANDING_ALIASES.with(|set| set.borrow_mut().insert((class_name, alias_name)));
81        Self { class_name, alias_name }
82    }
83}
84
85impl Drop for AliasExpansionGuard {
86    fn drop(&mut self) {
87        EXPANDING_ALIASES.with(|set| set.borrow_mut().remove(&(self.class_name, self.alias_name)));
88    }
89}
90
91/// RAII guard for object type parameter expansion cycle detection.
92struct ObjectParamsExpansionGuard {
93    object_name: Atom,
94}
95
96impl ObjectParamsExpansionGuard {
97    #[must_use]
98    fn try_new(object_name: Atom) -> Option<Self> {
99        EXPANDING_OBJECT_PARAMS.with(|set| {
100            let mut set = set.borrow_mut();
101            if set.contains(&object_name) {
102                None
103            } else {
104                set.insert(object_name);
105                Some(Self { object_name })
106            }
107        })
108    }
109}
110
111impl Drop for ObjectParamsExpansionGuard {
112    fn drop(&mut self) {
113        EXPANDING_OBJECT_PARAMS.with(|set| set.borrow_mut().remove(&self.object_name));
114    }
115}
116
117/// RAII guard for class constant inferred-initializer expansion cycle detection.
118///
119/// A constant whose initializer references itself (directly via `self::FOO` or
120/// transitively via another constant) would otherwise drive `expand_member_reference`
121/// into infinite recursion. The guard tracks `(class_name, constant_name)` pairs that
122/// are currently being expanded and refuses re-entry.
123struct ConstantExpansionGuard {
124    class_name: Atom,
125    constant_name: Atom,
126}
127
128impl ConstantExpansionGuard {
129    #[must_use]
130    fn try_new(class_name: Atom, constant_name: Atom) -> Option<Self> {
131        EXPANDING_CONSTANTS.with(|set| {
132            let mut set = set.borrow_mut();
133            if set.contains(&(class_name, constant_name)) {
134                None
135            } else {
136                set.insert((class_name, constant_name));
137                Some(Self { class_name, constant_name })
138            }
139        })
140    }
141}
142
143impl Drop for ConstantExpansionGuard {
144    fn drop(&mut self) {
145        EXPANDING_CONSTANTS.with(|set| set.borrow_mut().remove(&(self.class_name, self.constant_name)));
146    }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
150pub enum StaticClassType {
151    #[default]
152    None,
153    Name(Atom),
154    Object(TObject),
155}
156
157#[derive(Debug)]
158pub struct TypeExpansionOptions {
159    pub self_class: Option<Atom>,
160    pub static_class_type: StaticClassType,
161    pub parent_class: Option<Atom>,
162    pub evaluate_class_constants: bool,
163    pub evaluate_conditional_types: bool,
164    pub function_is_final: bool,
165    pub expand_generic: bool,
166    pub expand_templates: bool,
167}
168
169impl Default for TypeExpansionOptions {
170    fn default() -> Self {
171        Self {
172            self_class: None,
173            static_class_type: StaticClassType::default(),
174            parent_class: None,
175            evaluate_class_constants: true,
176            evaluate_conditional_types: false,
177            function_is_final: false,
178            expand_generic: false,
179            expand_templates: true,
180        }
181    }
182}
183
184/// Expands a type union, resolving special types like `self`, `static`, `parent`,
185/// type aliases, class constants, and generic type parameters.
186pub fn expand_union(codebase: &CodebaseMetadata, return_type: &mut TUnion, options: &TypeExpansionOptions) {
187    if !return_type.is_expandable() {
188        return;
189    }
190
191    let mut types = std::mem::take(&mut return_type.types).into_owned();
192    let mut new_return_type_parts: Vec<TAtomic> = Vec::new();
193    let mut skip_mask: u64 = 0;
194
195    for (i, return_type_part) in types.iter_mut().enumerate() {
196        let mut skip_key = false;
197        expand_atomic(return_type_part, codebase, options, &mut skip_key, &mut new_return_type_parts);
198
199        if skip_key && i < 64 {
200            skip_mask |= 1u64 << i;
201        }
202    }
203
204    if skip_mask != 0 {
205        let mut idx = 0usize;
206        types.retain(|_| {
207            let retain = idx >= 64 || (skip_mask & (1u64 << idx)) == 0;
208            idx += 1;
209            retain
210        });
211
212        new_return_type_parts.append(&mut types);
213
214        if new_return_type_parts.is_empty() {
215            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
216        }
217
218        types = if new_return_type_parts.len() > 1 {
219            combiner::combine(new_return_type_parts, codebase, combiner::CombinerOptions::default())
220        } else {
221            new_return_type_parts
222        };
223    } else if types.len() > 1 {
224        types = combiner::combine(types, codebase, combiner::CombinerOptions::default());
225    }
226
227    return_type.types = Cow::Owned(types);
228}
229
230pub(crate) fn expand_atomic(
231    return_type_part: &mut TAtomic,
232    codebase: &CodebaseMetadata,
233    options: &TypeExpansionOptions,
234    skip_key: &mut bool,
235    new_return_type_parts: &mut Vec<TAtomic>,
236) {
237    match return_type_part {
238        TAtomic::Array(array_type) => match array_type {
239            TArray::Keyed(keyed_data) => {
240                if let Some((key_parameter, value_parameter)) = &mut keyed_data.parameters {
241                    expand_union(codebase, Arc::make_mut(key_parameter), options);
242                    expand_union(codebase, Arc::make_mut(value_parameter), options);
243                }
244
245                if let Some(known_items) = &mut keyed_data.known_items {
246                    // Check if any keys need resolution
247                    let needs_key_resolution = known_items.keys().any(|k| k.is_class_like_constant());
248
249                    if needs_key_resolution {
250                        let old_items = std::mem::take(known_items);
251                        for (key, (is_optional, mut value_type)) in old_items {
252                            expand_union(codebase, &mut value_type, options);
253                            let resolved_key = resolve_array_key(key, codebase, options);
254                            known_items.insert(resolved_key, (is_optional, value_type));
255                        }
256                    } else {
257                        for (_, item_type) in known_items.values_mut() {
258                            expand_union(codebase, item_type, options);
259                        }
260                    }
261                }
262            }
263            TArray::List(list_data) => {
264                expand_union(codebase, Arc::make_mut(&mut list_data.element_type), options);
265
266                if let Some(known_elements) = &mut list_data.known_elements {
267                    for (_, element_type) in known_elements.values_mut() {
268                        expand_union(codebase, element_type, options);
269                    }
270                }
271            }
272        },
273        TAtomic::Object(object) => {
274            expand_object(object, codebase, options);
275        }
276        TAtomic::Callable(TCallable::Signature(signature)) => {
277            if let Some(return_type) = signature.get_return_type_mut() {
278                expand_union(codebase, return_type, options);
279            }
280
281            for param in signature.get_parameters_mut() {
282                if let Some(param_type) = param.get_type_signature_mut() {
283                    expand_union(codebase, param_type, options);
284                }
285            }
286        }
287        TAtomic::GenericParameter(parameter) => {
288            expand_union(codebase, Arc::make_mut(&mut parameter.constraint), options);
289        }
290        TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) => {
291            let mut atomic_return_type_parts = vec![];
292            expand_atomic(Arc::make_mut(constraint), codebase, options, &mut false, &mut atomic_return_type_parts);
293
294            if !atomic_return_type_parts.is_empty() {
295                *Arc::make_mut(constraint) = atomic_return_type_parts.remove(0);
296            }
297        }
298        TAtomic::Reference(TReference::Member { class_like_name, member_selector }) => {
299            *skip_key = true;
300            expand_member_reference(*class_like_name, member_selector, codebase, options, new_return_type_parts);
301        }
302        TAtomic::Reference(TReference::Global { selector }) => {
303            *skip_key = true;
304            expand_global_reference(selector, codebase, options, new_return_type_parts);
305        }
306        TAtomic::Callable(TCallable::Alias(id)) => {
307            if let Some(value) = get_atomic_of_function_like_identifier(id, codebase) {
308                *skip_key = true;
309                new_return_type_parts.push(value);
310            }
311        }
312        TAtomic::Conditional(conditional) => {
313            *skip_key = true;
314
315            let mut then = (*conditional.then).clone();
316            let mut otherwise = (*conditional.otherwise).clone();
317
318            expand_union(codebase, &mut then, options);
319            expand_union(codebase, &mut otherwise, options);
320
321            new_return_type_parts.extend(then.types.into_owned());
322            new_return_type_parts.extend(otherwise.types.into_owned());
323        }
324        TAtomic::Alias(alias) => {
325            *skip_key = true;
326            new_return_type_parts.extend(expand_alias(alias, codebase, options));
327        }
328        TAtomic::Derived(derived) => match derived {
329            TDerived::KeyOf(key_of) => {
330                *skip_key = true;
331                new_return_type_parts.extend(expand_key_of(key_of, codebase, options));
332            }
333            TDerived::ValueOf(value_of) => {
334                *skip_key = true;
335                new_return_type_parts.extend(expand_value_of(value_of, codebase, options));
336            }
337            TDerived::IndexAccess(index_access) => {
338                *skip_key = true;
339                new_return_type_parts.extend(expand_index_access(index_access, codebase, options));
340            }
341            TDerived::IntMask(int_mask) => {
342                *skip_key = true;
343                new_return_type_parts.extend(expand_int_mask(int_mask, codebase, options));
344            }
345            TDerived::IntMaskOf(int_mask_of) => {
346                *skip_key = true;
347                new_return_type_parts.extend(expand_int_mask_of(int_mask_of, codebase, options));
348            }
349            TDerived::PropertiesOf(properties_of) => {
350                *skip_key = true;
351                new_return_type_parts.extend(expand_properties_of(properties_of, codebase, options));
352            }
353            TDerived::New(new_type) => {
354                *skip_key = true;
355                new_return_type_parts.extend(expand_new(new_type, codebase, options));
356            }
357            TDerived::TemplateType(template_type) => {
358                *skip_key = true;
359                new_return_type_parts.extend(expand_template_type(template_type, codebase, options));
360            }
361        },
362        TAtomic::Iterable(iterable) => {
363            expand_union(codebase, Arc::make_mut(&mut iterable.key_type), options);
364            expand_union(codebase, Arc::make_mut(&mut iterable.value_type), options);
365        }
366        _ => {}
367    }
368}
369
370/// Resolves a `ClassLikeConstant` array key to its concrete `Integer` or `String` value.
371///
372/// Looks up the class constant or enum case in the codebase metadata and returns:
373/// - `ArrayKey::Integer(value)` if the constant resolves to a literal integer
374/// - `ArrayKey::String(value)` if the constant resolves to a literal string
375/// - The original key unchanged if it cannot be resolved
376fn resolve_array_key(key: ArrayKey, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> ArrayKey {
377    let ArrayKey::ClassLikeConstant { class_like_name, constant_name } = key else {
378        return key;
379    };
380
381    // Resolve self/static/this/parent to the actual class name
382    let resolved_class_name = {
383        let name_lc = ascii_lowercase_atom(&class_like_name);
384        match name_lc.as_str() {
385            "self" => options.self_class.unwrap_or(class_like_name),
386            "static" | "$this" => {
387                if let StaticClassType::Name(name) = &options.static_class_type {
388                    *name
389                } else {
390                    options.self_class.unwrap_or(class_like_name)
391                }
392            }
393            "parent" => {
394                if let Some(self_class) = options.self_class
395                    && let Some(class_metadata) = codebase.get_class_like(&self_class)
396                    && let Some(parent) = class_metadata.direct_parent_class
397                {
398                    parent
399                } else {
400                    class_like_name
401                }
402            }
403            _ => class_like_name,
404        }
405    };
406
407    let Some(class_like) = codebase.get_class_like(&resolved_class_name) else {
408        return ArrayKey::ClassLikeConstant { class_like_name, constant_name };
409    };
410
411    // Try class constants first
412    if let Some(constant) = class_like.constants.get(&constant_name)
413        && let Some(inferred) = &constant.inferred_type
414    {
415        match inferred {
416            TAtomic::Scalar(TScalar::Integer(TInteger::Literal(i))) => {
417                return ArrayKey::Integer(*i);
418            }
419            TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(s)), .. })) => {
420                return ArrayKey::String(*s);
421            }
422            _ => {}
423        }
424    }
425
426    // Try enum cases
427    if let Some(enum_case) = class_like.enum_cases.get(&constant_name)
428        && let Some(value_type) = &enum_case.value_type
429    {
430        match value_type {
431            TAtomic::Scalar(TScalar::Integer(TInteger::Literal(i))) => {
432                return ArrayKey::Integer(*i);
433            }
434            TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(s)), .. })) => {
435                return ArrayKey::String(*s);
436            }
437            _ => {}
438        }
439    }
440
441    // Cannot resolve - keep as-is
442    ArrayKey::ClassLikeConstant { class_like_name, constant_name }
443}
444
445#[cold]
446fn expand_member_reference(
447    class_like_name: Atom,
448    member_selector: &TReferenceMemberSelector,
449    codebase: &CodebaseMetadata,
450    options: &TypeExpansionOptions,
451    new_return_type_parts: &mut Vec<TAtomic>,
452) {
453    if let TReferenceMemberSelector::Identifier(member_name) = member_selector
454        && member_name.eq_ignore_ascii_case("class")
455    {
456        new_return_type_parts.push(TAtomic::Scalar(TScalar::literal_class_string(class_like_name)));
457        return;
458    }
459
460    let Some(class_like) = codebase.get_class_like(&class_like_name) else {
461        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
462        return;
463    };
464
465    for (constant_name, constant) in &class_like.constants {
466        if !member_selector.matches(*constant_name) {
467            continue;
468        }
469
470        if let Some(inferred_type) = constant.inferred_type.as_ref() {
471            let Some(_guard) = ConstantExpansionGuard::try_new(class_like_name, *constant_name) else {
472                new_return_type_parts.push(TAtomic::Never);
473                continue;
474            };
475
476            let mut inferred_type = inferred_type.clone();
477            let mut skip_inferred_type = false;
478            expand_atomic(&mut inferred_type, codebase, options, &mut skip_inferred_type, new_return_type_parts);
479
480            if !skip_inferred_type {
481                new_return_type_parts.push(inferred_type);
482            }
483        } else if let Some(type_metadata) = constant.type_metadata.as_ref() {
484            let mut constant_type = type_metadata.type_union.clone();
485            expand_union(codebase, &mut constant_type, options);
486            new_return_type_parts.extend(constant_type.types.into_owned());
487        } else {
488            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
489        }
490    }
491
492    for enum_case_name in class_like.enum_cases.keys() {
493        if !member_selector.matches(*enum_case_name) {
494            continue;
495        }
496        new_return_type_parts.push(TAtomic::Object(TObject::new_enum_case(class_like.original_name, *enum_case_name)));
497    }
498
499    if let TReferenceMemberSelector::Identifier(member_name) = member_selector
500        && let Some(type_alias) = class_like.type_aliases.get(member_name)
501    {
502        let mut alias_type = type_alias.type_union.clone();
503        expand_union(codebase, &mut alias_type, options);
504        new_return_type_parts.extend(alias_type.types.into_owned());
505    }
506
507    if new_return_type_parts.is_empty() {
508        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
509    }
510}
511
512fn expand_global_reference(
513    selector: &TGlobalReferenceSelector,
514    codebase: &CodebaseMetadata,
515    options: &TypeExpansionOptions,
516    new_return_type_parts: &mut Vec<TAtomic>,
517) {
518    for (constant_name, constant) in &codebase.constants {
519        if !selector.matches(*constant_name) {
520            continue;
521        }
522
523        if let Some(inferred_type) = constant.inferred_type.as_ref() {
524            let mut inferred_type = inferred_type.clone();
525            expand_union(codebase, &mut inferred_type, options);
526            new_return_type_parts.extend(inferred_type.types.into_owned());
527        } else if let Some(type_metadata) = constant.type_metadata.as_ref() {
528            let mut constant_type = type_metadata.type_union.clone();
529            expand_union(codebase, &mut constant_type, options);
530            new_return_type_parts.extend(constant_type.types.into_owned());
531        } else {
532            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
533        }
534    }
535
536    if new_return_type_parts.is_empty() {
537        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
538    }
539}
540
541fn expand_object(object: &mut TObject, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) {
542    resolve_special_class_names(object, codebase, options);
543
544    let TObject::Named(named) = object else {
545        return;
546    };
547
548    let has_params = named.type_parameters.as_ref().is_some_and(|p| !p.is_empty());
549    let class_metadata = codebase.get_class_like(&named.name);
550    let has_required_intersections =
551        class_metadata.map(|m| !m.require_extends.is_empty() || !m.require_implements.is_empty()).unwrap_or(false);
552    let needs_default_params = !has_params && class_metadata.map(|m| !m.template_types.is_empty()).unwrap_or(false);
553
554    if !has_params && !has_required_intersections && !needs_default_params {
555        return;
556    }
557
558    let Some(_guard) = ObjectParamsExpansionGuard::try_new(named.name) else {
559        return;
560    };
561
562    if has_required_intersections && let Some(class_metadata) = class_metadata {
563        for &required in class_metadata.require_extends.iter().chain(&class_metadata.require_implements) {
564            named.add_intersection_type(TAtomic::Object(TObject::Named(TNamedObject::new(required))));
565        }
566    }
567
568    expand_or_fill_type_parameters(named, codebase, options);
569}
570
571/// Classifies a class-like name as one of the PHP "special" tokens that require
572/// resolution against the expansion options. The check is case-insensitive but
573/// avoids the (relatively expensive) `ascii_lowercase_atom` interning step on
574/// the common path where the input is not a special name at all.
575#[derive(Copy, Clone, Eq, PartialEq)]
576enum SpecialClassName {
577    None,
578    SelfType,
579    Static,
580    Parent,
581    This,
582}
583
584#[inline]
585fn classify_special_class_name(name: &str) -> SpecialClassName {
586    match name.len() {
587        4 => {
588            if name.eq_ignore_ascii_case("self") {
589                SpecialClassName::SelfType
590            } else {
591                SpecialClassName::None
592            }
593        }
594        5 => {
595            if name == "$this" || name.eq_ignore_ascii_case("$this") {
596                SpecialClassName::This
597            } else {
598                SpecialClassName::None
599            }
600        }
601        6 => {
602            if name.eq_ignore_ascii_case("static") {
603                SpecialClassName::Static
604            } else if name.eq_ignore_ascii_case("parent") {
605                SpecialClassName::Parent
606            } else {
607                SpecialClassName::None
608            }
609        }
610        _ => SpecialClassName::None,
611    }
612}
613
614/// Resolves `static`, `$this`, `self`, and `parent` to their concrete class names.
615fn resolve_special_class_names(object: &mut TObject, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) {
616    let TObject::Named(named) = object else {
617        return;
618    };
619
620    let special = classify_special_class_name(named.name.as_str());
621    if matches!(special, SpecialClassName::None) && !named.is_static && !named.is_this {
622        return;
623    }
624
625    let needs_static_resolution = matches!(special, SpecialClassName::Static | SpecialClassName::This) || named.is_this;
626
627    if needs_static_resolution && let StaticClassType::Object(TObject::Enum(static_enum)) = &options.static_class_type {
628        *object = TObject::Enum(static_enum.clone());
629        return;
630    }
631
632    let TObject::Named(named) = object else {
633        return;
634    };
635
636    let was_this = named.is_this;
637    match special {
638        SpecialClassName::Static | SpecialClassName::This => {
639            resolve_static_type(named, was_this, false, codebase, options)
640        }
641        SpecialClassName::SelfType => {
642            if let Some(self_class) = options.self_class {
643                named.name = self_class;
644            }
645        }
646        SpecialClassName::Parent => {
647            if let Some(self_class) = options.self_class
648                && let Some(class_metadata) = codebase.get_class_like(&self_class)
649                && let Some(parent) = class_metadata.direct_parent_class
650            {
651                named.name = parent;
652            }
653        }
654        SpecialClassName::None if named.is_static => resolve_static_type(named, was_this, true, codebase, options),
655        SpecialClassName::None => {}
656    }
657}
658
659/// Resolves a `static` or `$this` type to a named object using the static class type from options.
660///
661/// `is_this_type`: true when the original type was `$this` (same instance), false for `static`.
662/// `check_compatibility`: when true, verifies the static type is compatible before resolving.
663fn resolve_static_type(
664    named: &mut TNamedObject,
665    is_this_type: bool,
666    check_compatibility: bool,
667    codebase: &CodebaseMetadata,
668    options: &TypeExpansionOptions,
669) {
670    match &options.static_class_type {
671        StaticClassType::Object(TObject::Named(static_obj)) => {
672            if check_compatibility && !is_static_type_compatible(named, static_obj, codebase) {
673                return;
674            }
675
676            if let Some(intersections) = &static_obj.intersection_types {
677                named.intersection_types.get_or_insert_with(Vec::new).extend(intersections.iter().cloned());
678            }
679
680            if static_obj.type_parameters.is_some() && should_use_static_type_params(named, static_obj, codebase) {
681                named.type_parameters.clone_from(&static_obj.type_parameters);
682            }
683
684            named.name = static_obj.name;
685            let effectively_final = is_effectively_final(&static_obj.name, codebase, options);
686            named.is_static = !effectively_final;
687            named.is_this = !effectively_final && is_this_type;
688        }
689        StaticClassType::Name(static_class)
690            if (!check_compatibility || codebase.is_instance_of(static_class, &named.name)) =>
691        {
692            named.name = *static_class;
693            let effectively_final = is_effectively_final(static_class, codebase, options);
694            named.is_static = !effectively_final;
695            named.is_this = !effectively_final && is_this_type;
696        }
697        _ => {}
698    }
699}
700
701/// Checks whether a class is effectively final for the purpose of `$this`/`static` resolution.
702///
703/// A class is effectively final when it cannot be extended, meaning `static` === `self`:
704///
705/// - The class is declared `final`
706/// - The class is anonymous
707/// - The method is declared `final`
708fn is_effectively_final(class_name: &Atom, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> bool {
709    if options.function_is_final {
710        return true;
711    }
712
713    codebase.get_class_like(class_name).is_some_and(|meta| meta.name_span.is_none() || meta.flags.is_final())
714}
715
716/// Checks if the static object type is compatible with a type that has is_this=true.
717fn is_static_type_compatible(named: &TNamedObject, static_obj: &TNamedObject, codebase: &CodebaseMetadata) -> bool {
718    codebase.is_instance_of(&static_obj.name, &named.name)
719        || static_obj
720            .intersection_types
721            .iter()
722            .flatten()
723            .filter_map(|t| if let TAtomic::Object(obj) = t { obj.get_name() } else { None })
724            .any(|name| codebase.is_instance_of(&name, &named.name))
725}
726
727/// Returns true if we should use the static object's type parameters instead of the current ones.
728/// This is true when current params are None or match the class's default template bounds.
729fn should_use_static_type_params(named: &TNamedObject, static_obj: &TNamedObject, codebase: &CodebaseMetadata) -> bool {
730    let Some(current_params) = &named.type_parameters else {
731        return true;
732    };
733
734    let Some(class_metadata) = codebase.get_class_like(&static_obj.name) else {
735        return false;
736    };
737
738    let templates = &class_metadata.template_types;
739
740    current_params.len() == templates.len()
741        && current_params.iter().zip(templates.values()).all(|(current, template)| {
742            current == &template.constraint || template.default.as_ref().is_some_and(|default| current == default)
743        })
744}
745
746/// Expands existing type parameters or fills them with default template bounds.
747fn expand_or_fill_type_parameters(
748    named: &mut TNamedObject,
749    codebase: &CodebaseMetadata,
750    options: &TypeExpansionOptions,
751) {
752    if let Some(class_metadata) = codebase.get_class_like(&named.name) {
753        let template_count = class_metadata.template_types.len();
754        let supplied_count = named.type_parameters.as_ref().map_or(0, Vec::len);
755
756        if supplied_count < template_count {
757            let mut params = named.type_parameters.take().unwrap_or_default();
758            params.extend(class_metadata.template_types.values().skip(supplied_count).map(|template| {
759                let mut fallback = template.default.clone().unwrap_or_else(|| template.constraint.clone());
760                fallback.set_from_template_default(true);
761                fallback
762            }));
763            named.type_parameters = Some(params);
764        }
765    }
766
767    if let Some(params) = &mut named.type_parameters {
768        for param in params.iter_mut() {
769            expand_union(codebase, param, options);
770        }
771    }
772}
773
774#[must_use]
775pub fn get_signature_of_function_like_identifier(
776    function_like_identifier: &FunctionLikeIdentifier,
777    codebase: &CodebaseMetadata,
778) -> Option<TCallableSignature> {
779    Some(match function_like_identifier {
780        FunctionLikeIdentifier::Function(name) => {
781            let function_like_metadata = codebase.get_function(name)?;
782
783            get_signature_of_function_like_metadata(
784                function_like_identifier,
785                function_like_metadata,
786                codebase,
787                &TypeExpansionOptions::default(),
788            )
789        }
790        FunctionLikeIdentifier::Closure(file_id, position) => {
791            let function_like_metadata = codebase.get_closure(file_id, position)?;
792
793            get_signature_of_function_like_metadata(
794                function_like_identifier,
795                function_like_metadata,
796                codebase,
797                &TypeExpansionOptions::default(),
798            )
799        }
800        FunctionLikeIdentifier::Method(classlike_name, method_name) => {
801            let function_like_metadata = codebase.get_declaring_method(classlike_name, method_name)?;
802
803            get_signature_of_function_like_metadata(
804                function_like_identifier,
805                function_like_metadata,
806                codebase,
807                &TypeExpansionOptions {
808                    self_class: Some(*classlike_name),
809                    static_class_type: StaticClassType::Name(*classlike_name),
810                    ..Default::default()
811                },
812            )
813        }
814    })
815}
816
817#[must_use]
818pub fn get_atomic_of_function_like_identifier(
819    function_like_identifier: &FunctionLikeIdentifier,
820    codebase: &CodebaseMetadata,
821) -> Option<TAtomic> {
822    let signature = get_signature_of_function_like_identifier(function_like_identifier, codebase)?;
823
824    Some(TAtomic::Callable(TCallable::Signature(signature)))
825}
826
827#[must_use]
828pub fn get_signature_of_function_like_metadata(
829    function_like_identifier: &FunctionLikeIdentifier,
830    function_like_metadata: &FunctionLikeMetadata,
831    codebase: &CodebaseMetadata,
832    options: &TypeExpansionOptions,
833) -> TCallableSignature {
834    let parameters: Vec<_> = function_like_metadata
835        .parameters
836        .iter()
837        .map(|parameter_metadata| {
838            let type_signature = if let Some(t) = parameter_metadata.get_type_metadata() {
839                let mut t = t.type_union.clone();
840                expand_union(codebase, &mut t, options);
841                Some(Arc::new(t))
842            } else {
843                None
844            };
845
846            TCallableParameter::new(
847                type_signature,
848                parameter_metadata.flags.is_by_reference(),
849                parameter_metadata.flags.is_variadic(),
850                parameter_metadata.flags.has_default(),
851            )
852        })
853        .collect();
854
855    let return_type = if let Some(type_metadata) = function_like_metadata.return_type_metadata.as_ref() {
856        let mut return_type = type_metadata.type_union.clone();
857        expand_union(codebase, &mut return_type, options);
858        Some(Arc::new(return_type))
859    } else {
860        None
861    };
862
863    let is_closure = matches!(function_like_identifier, FunctionLikeIdentifier::Closure(..));
864    let mut signature = TCallableSignature::new(function_like_metadata.flags.is_pure(), is_closure)
865        .with_parameters(parameters)
866        .with_return_type(return_type)
867        .with_source(Some(*function_like_identifier));
868
869    if let FunctionLikeIdentifier::Closure(file_id, closure_position) = function_like_identifier {
870        signature = signature.with_closure_location(Some((*file_id, *closure_position)));
871    }
872
873    signature
874}
875
876#[cold]
877fn expand_key_of(
878    return_type_key_of: &TKeyOf,
879    codebase: &CodebaseMetadata,
880    options: &TypeExpansionOptions,
881) -> Vec<TAtomic> {
882    let mut target_type = return_type_key_of.get_target_type().clone();
883    expand_union(codebase, &mut target_type, options);
884
885    let Some(new_return_types) = TKeyOf::get_key_of_targets(&target_type.types, codebase, false) else {
886        return vec![TAtomic::Derived(TDerived::KeyOf(return_type_key_of.clone()))];
887    };
888
889    new_return_types.types.into_owned()
890}
891
892#[cold]
893fn expand_value_of(
894    return_type_value_of: &TValueOf,
895    codebase: &CodebaseMetadata,
896    options: &TypeExpansionOptions,
897) -> Vec<TAtomic> {
898    let mut target_type = return_type_value_of.get_target_type().clone();
899    expand_union(codebase, &mut target_type, options);
900
901    let Some(new_return_types) = TValueOf::get_value_of_targets(&target_type.types, codebase, false) else {
902        return vec![TAtomic::Derived(TDerived::ValueOf(return_type_value_of.clone()))];
903    };
904
905    new_return_types.types.into_owned()
906}
907
908#[cold]
909fn expand_index_access(
910    return_type_index_access: &TIndexAccess,
911    codebase: &CodebaseMetadata,
912    options: &TypeExpansionOptions,
913) -> Vec<TAtomic> {
914    let mut target_type = return_type_index_access.get_target_type().clone();
915    expand_union(codebase, &mut target_type, options);
916
917    let mut index_type = return_type_index_access.get_index_type().clone();
918    expand_union(codebase, &mut index_type, options);
919
920    let Some(new_return_types) = TIndexAccess::get_indexed_access_result(&target_type.types, &index_type.types, false)
921    else {
922        return vec![TAtomic::Derived(TDerived::IndexAccess(return_type_index_access.clone()))];
923    };
924
925    new_return_types.types.into_owned()
926}
927
928#[cold]
929fn expand_new(new_type: &TNew, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
930    let mut target_type = new_type.get_target_type().clone();
931    expand_union(codebase, &mut target_type, options);
932
933    let Some(new_return_types) = TNew::get_new_targets(&target_type.types, codebase) else {
934        return vec![TAtomic::Derived(TDerived::New(new_type.clone()))];
935    };
936
937    new_return_types.types.into_owned()
938}
939
940#[cold]
941fn expand_template_type(
942    template_type: &TTemplateType,
943    codebase: &CodebaseMetadata,
944    options: &TypeExpansionOptions,
945) -> Vec<TAtomic> {
946    let mut expanded = template_type.clone();
947    expand_union(codebase, expanded.get_object_mut(), options);
948    expand_union(codebase, expanded.get_class_name_mut(), options);
949    expand_union(codebase, expanded.get_template_name_mut(), options);
950
951    let Some(resolved) = expanded.resolve(codebase) else {
952        return vec![TAtomic::Mixed(TMixed::new())];
953    };
954
955    resolved.types.into_owned()
956}
957
958#[cold]
959fn expand_int_mask(int_mask: &TIntMask, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
960    let mut literal_values = Vec::new();
961
962    for value in int_mask.get_values() {
963        let mut expanded = value.clone();
964        expand_union(codebase, &mut expanded, options);
965
966        if let Some(int_val) = expanded.get_single_literal_int_value() {
967            literal_values.push(int_val);
968        }
969    }
970
971    if literal_values.is_empty() {
972        return vec![TAtomic::Scalar(TScalar::int())];
973    }
974
975    let combinations = TIntMask::calculate_mask_combinations(&literal_values);
976    combinations.into_iter().map(|v| TAtomic::Scalar(TScalar::literal_int(v))).collect()
977}
978
979#[cold]
980fn expand_int_mask_of(
981    int_mask_of: &TIntMaskOf,
982    codebase: &CodebaseMetadata,
983    options: &TypeExpansionOptions,
984) -> Vec<TAtomic> {
985    let mut target = int_mask_of.get_target_type().clone();
986    expand_union(codebase, &mut target, options);
987
988    let mut literal_values = Vec::new();
989    for atomic in target.types.iter() {
990        if let Some(int_val) = atomic.get_literal_int_value() {
991            literal_values.push(int_val);
992        }
993    }
994
995    if literal_values.is_empty() {
996        return vec![TAtomic::Scalar(TScalar::int())];
997    }
998
999    let combinations = TIntMask::calculate_mask_combinations(&literal_values);
1000    combinations.into_iter().map(|v| TAtomic::Scalar(TScalar::literal_int(v))).collect()
1001}
1002
1003#[cold]
1004fn expand_properties_of(
1005    properties_of: &TPropertiesOf,
1006    codebase: &CodebaseMetadata,
1007    options: &TypeExpansionOptions,
1008) -> Vec<TAtomic> {
1009    let mut target_type = properties_of.get_target_type().clone();
1010    expand_union(codebase, &mut target_type, options);
1011
1012    let Some(keyed_array) =
1013        TPropertiesOf::get_properties_of_targets(&target_type.types, codebase, properties_of.visibility(), false)
1014    else {
1015        return vec![TAtomic::Derived(TDerived::PropertiesOf(properties_of.clone()))];
1016    };
1017
1018    vec![keyed_array]
1019}
1020
1021#[cold]
1022fn expand_alias(alias: &TAlias, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
1023    let class_name = alias.get_class_name();
1024    let alias_name = alias.get_alias_name();
1025
1026    // Check for cycle using the HashSet
1027    let is_cycle = EXPANDING_ALIASES.with(|set| set.borrow().contains(&(class_name, alias_name)));
1028
1029    if is_cycle {
1030        return vec![TAtomic::Alias(alias.clone())];
1031    }
1032
1033    let Some(mut expanded_union) = alias.resolve(codebase).cloned() else {
1034        return vec![TAtomic::Alias(alias.clone())];
1035    };
1036
1037    let _guard = AliasExpansionGuard::new(class_name, alias_name);
1038
1039    expand_union(codebase, &mut expanded_union, options);
1040
1041    expanded_union.types.into_owned()
1042}
1043
1044#[cfg(test)]
1045#[allow(clippy::unwrap_used, clippy::expect_used)]
1046mod tests {
1047    use super::*;
1048
1049    use std::borrow::Cow;
1050    use std::collections::HashSet;
1051    use std::sync::Arc;
1052
1053    use bumpalo::Bump;
1054
1055    use mago_atom::AtomSet;
1056    use mago_atom::atom;
1057    use mago_database::Database;
1058    use mago_database::DatabaseReader;
1059    use mago_database::file::File;
1060    use mago_database::file::FileId;
1061    use mago_names::resolver::NameResolver;
1062    use mago_span::Position;
1063    use mago_syntax::parser::parse_file;
1064
1065    use crate::metadata::CodebaseMetadata;
1066    use crate::misc::GenericParent;
1067    use crate::populator::populate_codebase;
1068    use crate::reference::SymbolReferences;
1069    use crate::scanner::scan_program;
1070    use crate::ttype::atomic::array::TArray;
1071    use crate::ttype::atomic::array::keyed::TKeyedArray;
1072    use crate::ttype::atomic::array::list::TList;
1073    use crate::ttype::atomic::callable::TCallable;
1074    use crate::ttype::atomic::callable::TCallableSignature;
1075    use crate::ttype::atomic::callable::parameter::TCallableParameter;
1076    use crate::ttype::atomic::conditional::TConditional;
1077    use crate::ttype::atomic::derived::TDerived;
1078    use crate::ttype::atomic::derived::index_access::TIndexAccess;
1079    use crate::ttype::atomic::derived::key_of::TKeyOf;
1080    use crate::ttype::atomic::derived::value_of::TValueOf;
1081    use crate::ttype::atomic::generic::TGenericParameter;
1082    use crate::ttype::atomic::iterable::TIterable;
1083    use crate::ttype::atomic::object::r#enum::TEnum;
1084    use crate::ttype::atomic::object::named::TNamedObject;
1085    use crate::ttype::atomic::reference::TReference;
1086    use crate::ttype::atomic::reference::TReferenceMemberSelector;
1087    use crate::ttype::atomic::scalar::TScalar;
1088    use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
1089    use crate::ttype::atomic::scalar::class_like_string::TClassLikeStringKind;
1090    use crate::ttype::flags::UnionFlags;
1091    use crate::ttype::get_int;
1092    use crate::ttype::get_mixed;
1093    use crate::ttype::get_never;
1094    use crate::ttype::get_null;
1095    use crate::ttype::get_string;
1096    use crate::ttype::get_void;
1097
1098    fn create_test_codebase(code: &'static str) -> CodebaseMetadata {
1099        let file = File::ephemeral(Cow::Borrowed("code.php"), Cow::Borrowed(code));
1100        let config =
1101            mago_database::DatabaseConfiguration::new(std::path::Path::new("/"), vec![], vec![], vec![], vec![])
1102                .into_static();
1103        let database = Database::single(file, config);
1104
1105        let mut codebase = CodebaseMetadata::new();
1106        let arena = Bump::new();
1107        for file in database.files() {
1108            let program = parse_file(&arena, &file);
1109            assert!(!program.has_errors(), "Parse failed: {:?}", program.errors);
1110            let resolved_names = NameResolver::new(&arena).resolve(program);
1111            let program_codebase =
1112                scan_program(&arena, &file, program, &resolved_names, mago_php_version::PHPVersion::LATEST);
1113
1114            codebase.extend(program_codebase);
1115        }
1116
1117        populate_codebase(&mut codebase, &mut SymbolReferences::new(), AtomSet::default(), HashSet::default());
1118
1119        codebase
1120    }
1121
1122    fn options_with_self(self_class: &str) -> TypeExpansionOptions {
1123        TypeExpansionOptions { self_class: Some(ascii_lowercase_atom(self_class)), ..Default::default() }
1124    }
1125
1126    fn options_with_static(static_class: &str) -> TypeExpansionOptions {
1127        TypeExpansionOptions {
1128            self_class: Some(ascii_lowercase_atom(static_class)),
1129            static_class_type: StaticClassType::Name(ascii_lowercase_atom(static_class)),
1130            ..Default::default()
1131        }
1132    }
1133
1134    fn options_with_static_object(object: TObject) -> TypeExpansionOptions {
1135        TypeExpansionOptions {
1136            self_class: object.get_name(),
1137            static_class_type: StaticClassType::Object(object),
1138            ..Default::default()
1139        }
1140    }
1141
1142    macro_rules! assert_expands_to {
1143        ($codebase:expr, $input:expr, $expected:expr) => {
1144            assert_expands_to!($codebase, $input, $expected, &TypeExpansionOptions::default())
1145        };
1146        ($codebase:expr, $input:expr, $expected:expr, $options:expr) => {{
1147            let mut actual = $input.clone();
1148            expand_union($codebase, &mut actual, $options);
1149            assert_eq!(
1150                actual.types.as_ref(),
1151                $expected.types.as_ref(),
1152                "Type expansion mismatch.\nInput: {:?}\nExpected: {:?}\nActual: {:?}",
1153                $input,
1154                $expected,
1155                actual
1156            );
1157        }};
1158    }
1159
1160    fn make_self_object() -> TUnion {
1161        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(atom("self")))))
1162    }
1163
1164    fn make_static_object() -> TUnion {
1165        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(atom("static")))))
1166    }
1167
1168    fn make_parent_object() -> TUnion {
1169        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(atom("parent")))))
1170    }
1171
1172    fn make_named_object(name: &str) -> TUnion {
1173        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_atom(name)))))
1174    }
1175
1176    #[test]
1177    fn test_expand_null_type() {
1178        let codebase = CodebaseMetadata::new();
1179        let null_type = get_null();
1180        assert_expands_to!(&codebase, null_type, get_null());
1181    }
1182
1183    #[test]
1184    fn test_expand_void_type() {
1185        let codebase = CodebaseMetadata::new();
1186        let void_type = get_void();
1187        assert_expands_to!(&codebase, void_type, get_void());
1188    }
1189
1190    #[test]
1191    fn test_expand_never_type() {
1192        let codebase = CodebaseMetadata::new();
1193        let never_type = get_never();
1194        assert_expands_to!(&codebase, never_type, get_never());
1195    }
1196
1197    #[test]
1198    fn test_expand_int_type() {
1199        let codebase = CodebaseMetadata::new();
1200        let int_type = get_int();
1201        assert_expands_to!(&codebase, int_type, get_int());
1202    }
1203
1204    #[test]
1205    fn test_expand_mixed_type() {
1206        let codebase = CodebaseMetadata::new();
1207        let mixed_type = get_mixed();
1208        assert_expands_to!(&codebase, mixed_type, get_mixed());
1209    }
1210
1211    #[test]
1212    fn test_expand_keyed_array_with_self_key() {
1213        let code = "<?php class Foo {}";
1214        let codebase = create_test_codebase(code);
1215
1216        let mut keyed = TKeyedArray::new();
1217        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
1218        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1219
1220        let options = options_with_self("Foo");
1221        let mut actual = input;
1222        expand_union(&codebase, &mut actual, &options);
1223
1224        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1225            && let Some((key, _)) = &keyed.parameters
1226        {
1227            assert!(key.types.iter().any(|t| {
1228                if let TAtomic::Object(TObject::Named(named)) = t {
1229                    named.name == ascii_lowercase_atom("foo")
1230                } else {
1231                    false
1232                }
1233            }));
1234        }
1235    }
1236
1237    #[test]
1238    fn test_expand_keyed_array_with_self_value() {
1239        let code = "<?php class Foo {}";
1240        let codebase = create_test_codebase(code);
1241
1242        let mut keyed = TKeyedArray::new();
1243        keyed.parameters = Some((Arc::new(get_string()), Arc::new(make_self_object())));
1244        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1245
1246        let options = options_with_self("Foo");
1247        let mut actual = input;
1248        expand_union(&codebase, &mut actual, &options);
1249
1250        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1251            && let Some((_, value)) = &keyed.parameters
1252        {
1253            assert!(value.types.iter().any(|t| {
1254                if let TAtomic::Object(TObject::Named(named)) = t {
1255                    named.name == ascii_lowercase_atom("foo")
1256                } else {
1257                    false
1258                }
1259            }));
1260        }
1261    }
1262
1263    #[test]
1264    fn test_expand_keyed_array_known_items() {
1265        let code = "<?php class Foo {}";
1266        let codebase = create_test_codebase(code);
1267
1268        use crate::ttype::atomic::array::key::ArrayKey;
1269        use std::collections::BTreeMap;
1270
1271        let mut keyed = TKeyedArray::new();
1272        let mut known_items = BTreeMap::new();
1273        known_items.insert(ArrayKey::String(atom("key")), (false, make_self_object()));
1274        keyed.known_items = Some(known_items);
1275        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1276
1277        let options = options_with_self("Foo");
1278        let mut actual = input;
1279        expand_union(&codebase, &mut actual, &options);
1280
1281        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1282            && let Some(items) = &keyed.known_items
1283        {
1284            let (_, item_type) = items.get(&ArrayKey::String(atom("key"))).unwrap();
1285            assert!(item_type.types.iter().any(|t| {
1286                if let TAtomic::Object(TObject::Named(named)) = t {
1287                    named.name == ascii_lowercase_atom("foo")
1288                } else {
1289                    false
1290                }
1291            }));
1292        }
1293    }
1294
1295    #[test]
1296    fn test_expand_list_with_self_element() {
1297        let code = "<?php class Foo {}";
1298        let codebase = create_test_codebase(code);
1299
1300        let list = TList::new(Arc::new(make_self_object()));
1301        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1302
1303        let options = options_with_self("Foo");
1304        let mut actual = input;
1305        expand_union(&codebase, &mut actual, &options);
1306
1307        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1308            assert!(list.element_type.types.iter().any(|t| {
1309                if let TAtomic::Object(TObject::Named(named)) = t {
1310                    named.name == ascii_lowercase_atom("foo")
1311                } else {
1312                    false
1313                }
1314            }));
1315        }
1316    }
1317
1318    #[test]
1319    fn test_expand_list_known_elements() {
1320        let code = "<?php class Foo {}";
1321        let codebase = create_test_codebase(code);
1322
1323        use std::collections::BTreeMap;
1324
1325        let mut list = TList::new(Arc::new(get_mixed()));
1326        let mut known_elements = BTreeMap::new();
1327        known_elements.insert(0, (false, make_self_object()));
1328        list.known_elements = Some(known_elements);
1329        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1330
1331        let options = options_with_self("Foo");
1332        let mut actual = input;
1333        expand_union(&codebase, &mut actual, &options);
1334
1335        if let TAtomic::Array(TArray::List(list)) = &actual.types[0]
1336            && let Some(elements) = &list.known_elements
1337        {
1338            let (_, element_type) = elements.get(&0).unwrap();
1339            assert!(element_type.types.iter().any(|t| {
1340                if let TAtomic::Object(TObject::Named(named)) = t {
1341                    named.name == ascii_lowercase_atom("foo")
1342                } else {
1343                    false
1344                }
1345            }));
1346        }
1347    }
1348
1349    #[test]
1350    fn test_expand_nested_array() {
1351        let code = "<?php class Foo {}";
1352        let codebase = create_test_codebase(code);
1353
1354        let inner_list = TList::new(Arc::new(make_self_object()));
1355        let inner_array = TUnion::from_atomic(TAtomic::Array(TArray::List(inner_list)));
1356
1357        let mut outer = TKeyedArray::new();
1358        outer.parameters = Some((Arc::new(make_self_object()), Arc::new(inner_array)));
1359        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(outer)));
1360
1361        let options = options_with_self("Foo");
1362        let mut actual = input;
1363        expand_union(&codebase, &mut actual, &options);
1364
1365        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1366            && let Some((key, value)) = &keyed.parameters
1367        {
1368            assert!(key.types.iter().any(|t| {
1369                if let TAtomic::Object(TObject::Named(named)) = t {
1370                    named.name == ascii_lowercase_atom("foo")
1371                } else {
1372                    false
1373                }
1374            }));
1375            if let TAtomic::Array(TArray::List(inner)) = &value.types[0] {
1376                assert!(inner.element_type.types.iter().any(|t| {
1377                    if let TAtomic::Object(TObject::Named(named)) = t {
1378                        named.name == ascii_lowercase_atom("foo")
1379                    } else {
1380                        false
1381                    }
1382                }));
1383            }
1384        }
1385    }
1386
1387    #[test]
1388    fn test_expand_empty_array() {
1389        let codebase = CodebaseMetadata::new();
1390        let keyed = TKeyedArray::new();
1391        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed.clone())));
1392        let expected = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1393        assert_expands_to!(&codebase, input, expected);
1394    }
1395
1396    #[test]
1397    fn test_expand_non_empty_list() {
1398        let code = "<?php class Foo {}";
1399        let codebase = create_test_codebase(code);
1400
1401        let mut list = TList::new(Arc::new(make_self_object()));
1402        list.non_empty = true;
1403        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1404
1405        let options = options_with_self("Foo");
1406        let mut actual = input;
1407        expand_union(&codebase, &mut actual, &options);
1408
1409        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1410            assert!(list.non_empty);
1411            assert!(list.element_type.types.iter().any(|t| {
1412                if let TAtomic::Object(TObject::Named(named)) = t {
1413                    named.name == ascii_lowercase_atom("foo")
1414                } else {
1415                    false
1416                }
1417            }));
1418        }
1419    }
1420
1421    #[test]
1422    fn test_expand_self_to_class_name() {
1423        let code = "<?php class Foo {}";
1424        let codebase = create_test_codebase(code);
1425
1426        let input = make_self_object();
1427        let options = options_with_self("Foo");
1428        let mut actual = input;
1429        expand_union(&codebase, &mut actual, &options);
1430
1431        assert!(actual.types.iter().any(|t| {
1432            if let TAtomic::Object(TObject::Named(named)) = t {
1433                named.name == ascii_lowercase_atom("foo")
1434            } else {
1435                false
1436            }
1437        }));
1438    }
1439
1440    #[test]
1441    fn test_expand_static_to_class_name() {
1442        let code = "<?php class Foo {}";
1443        let codebase = create_test_codebase(code);
1444
1445        let input = make_static_object();
1446        let options = options_with_static("Foo");
1447        let mut actual = input;
1448        expand_union(&codebase, &mut actual, &options);
1449
1450        assert!(actual.types.iter().any(|t| {
1451            if let TAtomic::Object(TObject::Named(named)) = t {
1452                named.name == ascii_lowercase_atom("foo")
1453            } else {
1454                false
1455            }
1456        }));
1457    }
1458
1459    #[test]
1460    fn test_expand_static_with_object_type() {
1461        let code = "<?php class Foo {}";
1462        let codebase = create_test_codebase(code);
1463
1464        let input = make_static_object();
1465        let static_obj = TObject::Named(TNamedObject::new(ascii_lowercase_atom("foo")));
1466        let options = options_with_static_object(static_obj);
1467        let mut actual = input;
1468        expand_union(&codebase, &mut actual, &options);
1469
1470        assert!(actual.types.iter().any(|t| {
1471            if let TAtomic::Object(TObject::Named(named)) = t {
1472                named.name == ascii_lowercase_atom("foo") && named.is_static && !named.is_this
1473            } else {
1474                false
1475            }
1476        }));
1477    }
1478
1479    #[test]
1480    fn test_expand_static_with_enum_type() {
1481        let code = "<?php enum Status { case Active; case Inactive; }";
1482        let codebase = create_test_codebase(code);
1483
1484        let input = make_static_object();
1485        let static_enum = TObject::Enum(TEnum::new(ascii_lowercase_atom("status")));
1486        let options = options_with_static_object(static_enum);
1487        let mut actual = input;
1488        expand_union(&codebase, &mut actual, &options);
1489
1490        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Object(TObject::Enum(_)))));
1491    }
1492
1493    #[test]
1494    fn test_expand_parent_to_parent_class() {
1495        let code = "<?php
1496            class BaseClass {}
1497            class ChildClass extends BaseClass {}
1498        ";
1499        let codebase = create_test_codebase(code);
1500
1501        let input = make_parent_object();
1502        let options = options_with_self("ChildClass");
1503        let mut actual = input;
1504        expand_union(&codebase, &mut actual, &options);
1505
1506        assert!(actual.types.iter().any(|t| {
1507            if let TAtomic::Object(TObject::Named(named)) = t {
1508                named.name == ascii_lowercase_atom("baseclass")
1509            } else {
1510                false
1511            }
1512        }));
1513    }
1514
1515    #[test]
1516    fn test_expand_parent_without_parent_class() {
1517        let code = "<?php class Foo {}";
1518        let codebase = create_test_codebase(code);
1519
1520        let input = make_parent_object();
1521        let options = options_with_self("Foo");
1522        let mut actual = input;
1523        expand_union(&codebase, &mut actual, &options);
1524
1525        assert!(actual.types.iter().any(|t| {
1526            if let TAtomic::Object(TObject::Named(named)) = t { named.name == atom("parent") } else { false }
1527        }));
1528    }
1529
1530    #[test]
1531    fn test_expand_this_variable() {
1532        let code = "<?php class Foo {}";
1533        let codebase = create_test_codebase(code);
1534
1535        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new_this(atom("$this")))));
1536        let options = options_with_static("Foo");
1537        let mut actual = input;
1538        expand_union(&codebase, &mut actual, &options);
1539
1540        assert!(actual.types.iter().any(|t| {
1541            if let TAtomic::Object(TObject::Named(named)) = t {
1542                named.name == ascii_lowercase_atom("foo")
1543            } else {
1544                false
1545            }
1546        }));
1547    }
1548
1549    #[test]
1550    fn test_expand_this_with_final_function() {
1551        let code = "<?php class Foo {}";
1552        let codebase = create_test_codebase(code);
1553
1554        let input = make_static_object();
1555        let options = TypeExpansionOptions {
1556            self_class: Some(ascii_lowercase_atom("foo")),
1557            static_class_type: StaticClassType::Name(ascii_lowercase_atom("foo")),
1558            function_is_final: true,
1559            ..Default::default()
1560        };
1561        let mut actual = input;
1562        expand_union(&codebase, &mut actual, &options);
1563
1564        assert!(actual.types.iter().any(|t| {
1565            if let TAtomic::Object(TObject::Named(named)) = t {
1566                named.name == ascii_lowercase_atom("foo") && !named.is_this
1567            } else {
1568                false
1569            }
1570        }));
1571    }
1572
1573    #[test]
1574    fn test_expand_object_with_type_parameters() {
1575        let code = "<?php class Container {}";
1576        let codebase = create_test_codebase(code);
1577
1578        let named =
1579            TNamedObject::new_with_type_parameters(ascii_lowercase_atom("container"), Some(vec![make_self_object()]));
1580        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
1581
1582        let options = options_with_self("Foo");
1583        let mut actual = input;
1584        expand_union(&codebase, &mut actual, &options);
1585
1586        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
1587            && let Some(params) = &named.type_parameters
1588        {
1589            assert!(params[0].types.iter().any(|t| {
1590                if let TAtomic::Object(TObject::Named(named)) = t {
1591                    named.name == ascii_lowercase_atom("foo")
1592                } else {
1593                    false
1594                }
1595            }));
1596        }
1597    }
1598
1599    #[test]
1600    fn test_expand_object_gets_default_type_params() {
1601        let code = "<?php
1602            /** @template T */
1603            class Container {}
1604        ";
1605        let codebase = create_test_codebase(code);
1606
1607        let named = TNamedObject::new(ascii_lowercase_atom("container"));
1608        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
1609
1610        let mut actual = input;
1611        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1612
1613        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0] {
1614            assert!(named.type_parameters.is_some());
1615        }
1616    }
1617
1618    #[test]
1619    fn test_expand_object_intersection_from_static() {
1620        let code = "<?php
1621            interface Stringable {}
1622            class Foo implements Stringable {}
1623        ";
1624        let codebase = create_test_codebase(code);
1625
1626        let input = make_static_object();
1627
1628        let mut static_named = TNamedObject::new(ascii_lowercase_atom("foo"));
1629        static_named.intersection_types =
1630            Some(vec![TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_atom("stringable"))))]);
1631        let static_obj = TObject::Named(static_named);
1632        let options = options_with_static_object(static_obj);
1633
1634        let mut actual = input;
1635        expand_union(&codebase, &mut actual, &options);
1636
1637        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0] {
1638            assert!(named.intersection_types.is_some());
1639        }
1640    }
1641
1642    #[test]
1643    fn test_expand_self_without_self_class_option() {
1644        let codebase = CodebaseMetadata::new();
1645
1646        let input = make_self_object();
1647        let mut actual = input;
1648        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1649
1650        assert!(actual.types.iter().any(|t| {
1651            if let TAtomic::Object(TObject::Named(named)) = t { named.name == atom("self") } else { false }
1652        }));
1653    }
1654
1655    #[test]
1656    fn test_expand_callable_return_type() {
1657        let code = "<?php class Foo {}";
1658        let codebase = create_test_codebase(code);
1659
1660        let sig = TCallableSignature::new(false, false).with_return_type(Some(Arc::new(make_self_object())));
1661        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1662
1663        let options = options_with_self("Foo");
1664        let mut actual = input;
1665        expand_union(&codebase, &mut actual, &options);
1666
1667        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1668            && let Some(ret) = sig.get_return_type()
1669        {
1670            assert!(ret.types.iter().any(|t| {
1671                if let TAtomic::Object(TObject::Named(named)) = t {
1672                    named.name == ascii_lowercase_atom("foo")
1673                } else {
1674                    false
1675                }
1676            }));
1677        }
1678    }
1679
1680    #[test]
1681    fn test_expand_callable_parameter_types() {
1682        let code = "<?php class Foo {}";
1683        let codebase = create_test_codebase(code);
1684
1685        let param = TCallableParameter::new(Some(Arc::new(make_self_object())), false, false, false);
1686        let sig = TCallableSignature::new(false, false).with_parameters(vec![param]);
1687        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1688
1689        let options = options_with_self("Foo");
1690        let mut actual = input;
1691        expand_union(&codebase, &mut actual, &options);
1692
1693        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1694            && let Some(param) = sig.get_parameters().first()
1695            && let Some(param_type) = param.get_type_signature()
1696        {
1697            assert!(param_type.types.iter().any(|t| {
1698                if let TAtomic::Object(TObject::Named(named)) = t {
1699                    named.name == ascii_lowercase_atom("foo")
1700                } else {
1701                    false
1702                }
1703            }));
1704        }
1705    }
1706
1707    #[test]
1708    fn test_expand_callable_alias_to_function() {
1709        let code = "<?php
1710            function myFunc(): int { return 1; }
1711        ";
1712        let codebase = create_test_codebase(code);
1713
1714        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(ascii_lowercase_atom("myfunc")));
1715        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1716
1717        let mut actual = input;
1718        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1719
1720        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
1721    }
1722
1723    #[test]
1724    fn test_expand_callable_alias_to_method() {
1725        let code = "<?php
1726            class Foo {
1727                public function bar(): int { return 1; }
1728            }
1729        ";
1730        let codebase = create_test_codebase(code);
1731
1732        let alias =
1733            TCallable::Alias(FunctionLikeIdentifier::Method(ascii_lowercase_atom("foo"), ascii_lowercase_atom("bar")));
1734        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1735
1736        let mut actual = input;
1737        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1738
1739        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
1740    }
1741
1742    #[test]
1743    fn test_expand_callable_alias_unknown() {
1744        let codebase = CodebaseMetadata::new();
1745
1746        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(atom("nonexistent")));
1747        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1748
1749        let mut actual = input;
1750        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1751
1752        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Alias(_)))));
1753    }
1754
1755    #[test]
1756    fn test_expand_closure_signature() {
1757        let code = "<?php class Foo {}";
1758        let codebase = create_test_codebase(code);
1759
1760        let sig = TCallableSignature::new(false, true).with_return_type(Some(Arc::new(make_self_object())));
1761        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1762
1763        let options = options_with_self("Foo");
1764        let mut actual = input;
1765        expand_union(&codebase, &mut actual, &options);
1766
1767        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1768            && let Some(ret) = sig.get_return_type()
1769        {
1770            assert!(ret.types.iter().any(|t| {
1771                if let TAtomic::Object(TObject::Named(named)) = t {
1772                    named.name == ascii_lowercase_atom("foo")
1773                } else {
1774                    false
1775                }
1776            }));
1777        }
1778    }
1779
1780    #[test]
1781    fn test_expand_generic_parameter_constraint() {
1782        let code = "<?php class Foo {}";
1783        let codebase = create_test_codebase(code);
1784
1785        let generic = TGenericParameter::new(
1786            atom("T"),
1787            Arc::new(make_self_object()),
1788            GenericParent::ClassLike(ascii_lowercase_atom("foo")),
1789        );
1790        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1791
1792        let options = options_with_self("Foo");
1793        let mut actual = input;
1794        expand_union(&codebase, &mut actual, &options);
1795
1796        if let TAtomic::GenericParameter(param) = &actual.types[0] {
1797            assert!(param.constraint.types.iter().any(|t| {
1798                if let TAtomic::Object(TObject::Named(named)) = t {
1799                    named.name == ascii_lowercase_atom("foo")
1800                } else {
1801                    false
1802                }
1803            }));
1804        }
1805    }
1806
1807    #[test]
1808    fn test_expand_nested_generic_constraint() {
1809        let code = "<?php class Foo {} class Bar {}";
1810        let codebase = create_test_codebase(code);
1811
1812        let container =
1813            TNamedObject::new_with_type_parameters(ascii_lowercase_atom("container"), Some(vec![make_self_object()]));
1814        let constraint = TUnion::from_atomic(TAtomic::Object(TObject::Named(container)));
1815
1816        let generic = TGenericParameter::new(
1817            atom("T"),
1818            Arc::new(constraint),
1819            GenericParent::ClassLike(ascii_lowercase_atom("bar")),
1820        );
1821        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1822
1823        let options = options_with_self("Foo");
1824        let mut actual = input;
1825        expand_union(&codebase, &mut actual, &options);
1826
1827        if let TAtomic::GenericParameter(param) = &actual.types[0]
1828            && let TAtomic::Object(TObject::Named(named)) = &param.constraint.types[0]
1829            && let Some(params) = &named.type_parameters
1830        {
1831            assert!(params[0].types.iter().any(|t| {
1832                if let TAtomic::Object(TObject::Named(named)) = t {
1833                    named.name == ascii_lowercase_atom("foo")
1834                } else {
1835                    false
1836                }
1837            }));
1838        }
1839    }
1840
1841    #[test]
1842    fn test_expand_generic_with_intersection() {
1843        let code = "<?php
1844            interface Stringable {}
1845            class Foo {}
1846        ";
1847        let codebase = create_test_codebase(code);
1848
1849        let mut generic = TGenericParameter::new(
1850            atom("T"),
1851            Arc::new(make_self_object()),
1852            GenericParent::ClassLike(ascii_lowercase_atom("foo")),
1853        );
1854        generic.intersection_types =
1855            Some(vec![TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_atom("stringable"))))]);
1856        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1857
1858        let options = options_with_self("Foo");
1859        let mut actual = input;
1860        expand_union(&codebase, &mut actual, &options);
1861
1862        if let TAtomic::GenericParameter(param) = &actual.types[0] {
1863            assert!(param.intersection_types.is_some());
1864            assert!(param.constraint.types.iter().any(|t| {
1865                if let TAtomic::Object(TObject::Named(named)) = t {
1866                    named.name == ascii_lowercase_atom("foo")
1867                } else {
1868                    false
1869                }
1870            }));
1871        }
1872    }
1873
1874    #[test]
1875    fn test_expand_class_string_of_self() {
1876        let code = "<?php class Foo {}";
1877        let codebase = create_test_codebase(code);
1878
1879        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(atom("self")))));
1880        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
1881        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1882
1883        let options = options_with_self("Foo");
1884        let mut actual = input;
1885        expand_union(&codebase, &mut actual, &options);
1886
1887        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
1888            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
1889        {
1890            assert_eq!(named.name, ascii_lowercase_atom("foo"));
1891        }
1892    }
1893
1894    #[test]
1895    fn test_expand_class_string_of_static() {
1896        let code = "<?php class Foo {}";
1897        let codebase = create_test_codebase(code);
1898
1899        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(atom("static")))));
1900        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
1901        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1902
1903        let options = options_with_static("Foo");
1904        let mut actual = input;
1905        expand_union(&codebase, &mut actual, &options);
1906
1907        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
1908            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
1909        {
1910            assert_eq!(named.name, ascii_lowercase_atom("foo"));
1911        }
1912    }
1913
1914    #[test]
1915    fn test_expand_interface_string_of_type() {
1916        let code = "<?php interface MyInterface {}";
1917        let codebase = create_test_codebase(code);
1918
1919        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(atom("self")))));
1920        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Interface, constraint };
1921        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1922
1923        let options = options_with_self("MyInterface");
1924        let mut actual = input;
1925        expand_union(&codebase, &mut actual, &options);
1926
1927        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { kind, constraint })) =
1928            &actual.types[0]
1929        {
1930            assert!(matches!(kind, TClassLikeStringKind::Interface));
1931            if let TAtomic::Object(TObject::Named(named)) = constraint.as_ref() {
1932                assert_eq!(named.name, ascii_lowercase_atom("myinterface"));
1933            }
1934        }
1935    }
1936
1937    #[test]
1938    fn test_expand_member_reference_wildcard_constants() {
1939        let code = "<?php
1940            class Foo {
1941                public const A = 1;
1942                public const B = 2;
1943            }
1944        ";
1945        let codebase = create_test_codebase(code);
1946
1947        let reference = TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::Wildcard);
1948        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1949
1950        let mut actual = input;
1951        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1952
1953        assert!(!actual.types.is_empty());
1954    }
1955
1956    #[test]
1957    fn test_expand_member_reference_wildcard_enum_cases() {
1958        let code = "<?php
1959            enum Status {
1960                case Active;
1961                case Inactive;
1962            }
1963        ";
1964        let codebase = create_test_codebase(code);
1965
1966        let reference = TReference::new_member(ascii_lowercase_atom("status"), TReferenceMemberSelector::Wildcard);
1967        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1968
1969        let mut actual = input;
1970        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1971
1972        assert_eq!(actual.types.len(), 2);
1973        assert!(actual.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Enum(_)))));
1974    }
1975
1976    #[test]
1977    fn test_expand_member_reference_starts_with() {
1978        let code = "<?php
1979            class Foo {
1980                public const STATUS_ACTIVE = 1;
1981                public const STATUS_INACTIVE = 2;
1982                public const OTHER = 3;
1983            }
1984        ";
1985        let codebase = create_test_codebase(code);
1986
1987        let reference =
1988            TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::StartsWith(atom("STATUS_")));
1989        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1990
1991        let mut actual = input;
1992        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1993
1994        assert!(!actual.types.is_empty());
1995    }
1996
1997    #[test]
1998    fn test_expand_member_reference_ends_with() {
1999        let code = "<?php
2000            class Foo {
2001                public const READ_ERROR = 1;
2002                public const WRITE_ERROR = 2;
2003                public const SUCCESS = 0;
2004            }
2005        ";
2006        let codebase = create_test_codebase(code);
2007
2008        let reference =
2009            TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::EndsWith(atom("_ERROR")));
2010        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2011
2012        let mut actual = input;
2013        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2014
2015        assert!(!actual.types.is_empty());
2016    }
2017
2018    #[test]
2019    fn test_expand_member_reference_identifier_constant() {
2020        let code = "<?php
2021            class Foo {
2022                public const BAR = 42;
2023            }
2024        ";
2025        let codebase = create_test_codebase(code);
2026
2027        let reference =
2028            TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::Identifier(atom("BAR")));
2029        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2030
2031        let mut actual = input;
2032        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2033
2034        assert_eq!(actual.types.len(), 1);
2035    }
2036
2037    #[test]
2038    fn test_expand_member_reference_identifier_enum_case() {
2039        let code = "<?php
2040            enum Status {
2041                case Active;
2042            }
2043        ";
2044        let codebase = create_test_codebase(code);
2045
2046        let reference = TReference::new_member(
2047            ascii_lowercase_atom("status"),
2048            TReferenceMemberSelector::Identifier(atom("Active")),
2049        );
2050        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2051
2052        let mut actual = input;
2053        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2054
2055        assert_eq!(actual.types.len(), 1);
2056        assert!(matches!(&actual.types[0], TAtomic::Object(TObject::Enum(_))));
2057    }
2058
2059    #[test]
2060    fn test_expand_member_reference_unknown_class() {
2061        let codebase = CodebaseMetadata::new();
2062
2063        let reference = TReference::new_member(atom("NonExistent"), TReferenceMemberSelector::Identifier(atom("FOO")));
2064        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2065
2066        let mut actual = input;
2067        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2068
2069        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2070    }
2071
2072    #[test]
2073    fn test_expand_member_reference_unknown_member() {
2074        let code = "<?php class Foo {}";
2075        let codebase = create_test_codebase(code);
2076
2077        let reference = TReference::new_member(
2078            ascii_lowercase_atom("foo"),
2079            TReferenceMemberSelector::Identifier(atom("NONEXISTENT")),
2080        );
2081        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2082
2083        let mut actual = input;
2084        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2085
2086        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2087    }
2088
2089    #[test]
2090    fn test_expand_member_reference_constant_with_inferred_type() {
2091        let code = r#"<?php
2092            class Foo {
2093                public const VALUE = "hello";
2094            }
2095        "#;
2096        let codebase = create_test_codebase(code);
2097
2098        let reference =
2099            TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::Identifier(atom("VALUE")));
2100        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2101
2102        let mut actual = input;
2103        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2104
2105        assert_eq!(actual.types.len(), 1);
2106    }
2107
2108    #[test]
2109    fn test_expand_member_reference_constant_with_type_metadata() {
2110        let code = "<?php
2111            class Foo {
2112                /** @var int */
2113                public const VALUE = 42;
2114            }
2115        ";
2116        let codebase = create_test_codebase(code);
2117
2118        let reference =
2119            TReference::new_member(ascii_lowercase_atom("foo"), TReferenceMemberSelector::Identifier(atom("VALUE")));
2120        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2121
2122        let mut actual = input;
2123        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2124
2125        assert_eq!(actual.types.len(), 1);
2126    }
2127
2128    #[test]
2129    fn test_expand_conditional_both_branches() {
2130        let code = "<?php class Foo {} class Bar {}";
2131        let codebase = create_test_codebase(code);
2132
2133        let conditional = TConditional::new(
2134            Arc::new(get_mixed()),
2135            Arc::new(get_string()),
2136            Arc::new(make_self_object()),
2137            Arc::new(make_self_object()),
2138            false,
2139        );
2140        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2141
2142        let options = options_with_self("Foo");
2143        let mut actual = input;
2144        expand_union(&codebase, &mut actual, &options);
2145
2146        assert!(actual.types.iter().any(|t| {
2147            if let TAtomic::Object(TObject::Named(named)) = t {
2148                named.name == ascii_lowercase_atom("foo")
2149            } else {
2150                false
2151            }
2152        }));
2153    }
2154
2155    #[test]
2156    fn test_expand_conditional_with_self_in_then() {
2157        let code = "<?php class Foo {}";
2158        let codebase = create_test_codebase(code);
2159
2160        let conditional = TConditional::new(
2161            Arc::new(get_mixed()),
2162            Arc::new(get_string()),
2163            Arc::new(make_self_object()),
2164            Arc::new(get_int()),
2165            false,
2166        );
2167        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2168
2169        let options = options_with_self("Foo");
2170        let mut actual = input;
2171        expand_union(&codebase, &mut actual, &options);
2172
2173        assert!(!actual.types.is_empty());
2174    }
2175
2176    #[test]
2177    fn test_expand_conditional_with_self_in_otherwise() {
2178        let code = "<?php class Foo {}";
2179        let codebase = create_test_codebase(code);
2180
2181        let conditional = TConditional::new(
2182            Arc::new(get_mixed()),
2183            Arc::new(get_string()),
2184            Arc::new(get_int()),
2185            Arc::new(make_self_object()),
2186            false,
2187        );
2188        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2189
2190        let options = options_with_self("Foo");
2191        let mut actual = input;
2192        expand_union(&codebase, &mut actual, &options);
2193
2194        assert!(!actual.types.is_empty());
2195    }
2196
2197    #[test]
2198    fn test_expand_simple_alias() {
2199        let code = "<?php
2200            class Foo {
2201                /** @phpstan-type MyInt = int */
2202            }
2203        ";
2204        let codebase = create_test_codebase(code);
2205
2206        let alias = TAlias::new(ascii_lowercase_atom("foo"), atom("MyInt"));
2207        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2208
2209        let mut actual = input;
2210        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2211
2212        assert!(!actual.types.is_empty());
2213    }
2214
2215    #[test]
2216    fn test_expand_nested_alias() {
2217        let code = "<?php
2218            class Foo {
2219                /** @phpstan-type Inner = int */
2220                /** @phpstan-type Outer = Inner */
2221            }
2222        ";
2223        let codebase = create_test_codebase(code);
2224
2225        let alias = TAlias::new(ascii_lowercase_atom("foo"), atom("Outer"));
2226        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2227
2228        let mut actual = input;
2229        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2230
2231        assert!(!actual.types.is_empty());
2232    }
2233
2234    #[test]
2235    fn test_expand_alias_cycle_detection() {
2236        let code = "<?php
2237            /** @phpstan-type SelfRef = int|array<int, SelfRef> */
2238            class Foo {}
2239        ";
2240        let codebase = create_test_codebase(code);
2241
2242        let alias = TAlias::new(ascii_lowercase_atom("foo"), atom("SelfRef"));
2243        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2244
2245        let mut actual = input;
2246        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2247
2248        assert!(!actual.types.is_empty());
2249    }
2250
2251    #[test]
2252    fn test_expand_alias_unknown() {
2253        let codebase = CodebaseMetadata::new();
2254
2255        let alias = TAlias::new(atom("NonExistent"), atom("Unknown"));
2256        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2257
2258        let mut actual = input;
2259        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2260
2261        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Alias(_))));
2262    }
2263
2264    #[test]
2265    fn test_expand_alias_with_self_inside() {
2266        let code = "<?php
2267            class Foo {
2268                /** @phpstan-type MySelf = self */
2269            }
2270        ";
2271        let codebase = create_test_codebase(code);
2272
2273        let alias = TAlias::new(ascii_lowercase_atom("foo"), atom("MySelf"));
2274        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2275
2276        let options = options_with_self("Foo");
2277        let mut actual = input;
2278        expand_union(&codebase, &mut actual, &options);
2279
2280        assert!(!actual.types.is_empty());
2281    }
2282
2283    #[test]
2284    fn test_expand_key_of_array() {
2285        let codebase = CodebaseMetadata::new();
2286
2287        let mut keyed = TKeyedArray::new();
2288        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2289        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2290
2291        let key_of = TKeyOf::new(Arc::new(array_type));
2292        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2293
2294        let mut actual = input;
2295        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2296
2297        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_string));
2298    }
2299
2300    #[test]
2301    fn test_expand_key_of_with_self() {
2302        let code = "<?php class Foo {}";
2303        let codebase = create_test_codebase(code);
2304
2305        let mut keyed = TKeyedArray::new();
2306        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
2307        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2308
2309        let key_of = TKeyOf::new(Arc::new(array_type));
2310        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2311
2312        let options = options_with_self("Foo");
2313        let mut actual = input;
2314        expand_union(&codebase, &mut actual, &options);
2315
2316        assert!(!actual.types.is_empty());
2317    }
2318
2319    #[test]
2320    fn test_expand_value_of_array() {
2321        let codebase = CodebaseMetadata::new();
2322
2323        let mut keyed = TKeyedArray::new();
2324        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2325        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2326
2327        let value_of = TValueOf::new(Arc::new(array_type));
2328        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2329
2330        let mut actual = input;
2331        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2332
2333        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_int));
2334    }
2335
2336    #[test]
2337    fn test_expand_value_of_enum() {
2338        let code = "<?php
2339            enum Status: string {
2340                case Active = 'active';
2341                case Inactive = 'inactive';
2342            }
2343        ";
2344        let codebase = create_test_codebase(code);
2345
2346        let enum_type = TUnion::from_atomic(TAtomic::Object(TObject::Enum(TEnum::new(ascii_lowercase_atom("status")))));
2347
2348        let value_of = TValueOf::new(Arc::new(enum_type));
2349        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2350
2351        let mut actual = input;
2352        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2353
2354        assert!(!actual.types.is_empty());
2355    }
2356
2357    #[test]
2358    fn test_expand_index_access() {
2359        let codebase = CodebaseMetadata::new();
2360
2361        use crate::ttype::atomic::array::key::ArrayKey;
2362        use std::collections::BTreeMap;
2363
2364        let mut keyed = TKeyedArray::new();
2365        let mut known_items = BTreeMap::new();
2366        known_items.insert(ArrayKey::String(atom("key")), (false, get_int()));
2367        keyed.known_items = Some(known_items);
2368        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2369
2370        use crate::ttype::get_literal_string;
2371        let index_type = get_literal_string(atom("key"));
2372
2373        let index_access = TIndexAccess::new(array_type, index_type);
2374        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2375
2376        let mut actual = input;
2377        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2378
2379        assert!(!actual.types.is_empty());
2380    }
2381
2382    #[test]
2383    fn test_expand_index_access_with_self() {
2384        let code = "<?php class Foo {}";
2385        let codebase = create_test_codebase(code);
2386
2387        use crate::ttype::atomic::array::key::ArrayKey;
2388        use std::collections::BTreeMap;
2389
2390        let mut keyed = TKeyedArray::new();
2391        let mut known_items = BTreeMap::new();
2392        known_items.insert(ArrayKey::String(atom("key")), (false, make_self_object()));
2393        keyed.known_items = Some(known_items);
2394        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2395
2396        use crate::ttype::get_literal_string;
2397        let index_type = get_literal_string(atom("key"));
2398
2399        let index_access = TIndexAccess::new(array_type, index_type);
2400        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2401
2402        let options = options_with_self("Foo");
2403        let mut actual = input;
2404        expand_union(&codebase, &mut actual, &options);
2405
2406        assert!(!actual.types.is_empty());
2407    }
2408
2409    #[test]
2410    fn test_expand_iterable_key_type() {
2411        let code = "<?php class Foo {}";
2412        let codebase = create_test_codebase(code);
2413
2414        let iterable = TIterable::new(Arc::new(make_self_object()), Arc::new(get_int()));
2415        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2416
2417        let options = options_with_self("Foo");
2418        let mut actual = input;
2419        expand_union(&codebase, &mut actual, &options);
2420
2421        if let TAtomic::Iterable(iter) = &actual.types[0] {
2422            assert!(iter.get_key_type().types.iter().any(|t| {
2423                if let TAtomic::Object(TObject::Named(named)) = t {
2424                    named.name == ascii_lowercase_atom("foo")
2425                } else {
2426                    false
2427                }
2428            }));
2429        }
2430    }
2431
2432    #[test]
2433    fn test_expand_iterable_value_type() {
2434        let code = "<?php class Foo {}";
2435        let codebase = create_test_codebase(code);
2436
2437        let iterable = TIterable::new(Arc::new(get_int()), Arc::new(make_self_object()));
2438        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2439
2440        let options = options_with_self("Foo");
2441        let mut actual = input;
2442        expand_union(&codebase, &mut actual, &options);
2443
2444        if let TAtomic::Iterable(iter) = &actual.types[0] {
2445            assert!(iter.get_value_type().types.iter().any(|t| {
2446                if let TAtomic::Object(TObject::Named(named)) = t {
2447                    named.name == ascii_lowercase_atom("foo")
2448                } else {
2449                    false
2450                }
2451            }));
2452        }
2453    }
2454
2455    #[test]
2456    fn test_get_signature_of_function() {
2457        let code = r#"<?php
2458            function myFunc(int $a): string { return ""; }
2459        "#;
2460        let codebase = create_test_codebase(code);
2461
2462        let id = FunctionLikeIdentifier::Function(ascii_lowercase_atom("myfunc"));
2463
2464        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2465        assert!(sig.is_some());
2466
2467        let sig = sig.unwrap();
2468        assert_eq!(sig.get_parameters().len(), 1);
2469        assert!(sig.get_return_type().is_some());
2470    }
2471
2472    #[test]
2473    fn test_get_signature_of_method() {
2474        let code = "<?php
2475            class Foo {
2476                public function bar(string $s): int { return 0; }
2477            }
2478        ";
2479        let codebase = create_test_codebase(code);
2480
2481        let id = FunctionLikeIdentifier::Method(ascii_lowercase_atom("foo"), ascii_lowercase_atom("bar"));
2482
2483        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2484        assert!(sig.is_some());
2485
2486        let sig = sig.unwrap();
2487        assert_eq!(sig.get_parameters().len(), 1);
2488    }
2489
2490    #[test]
2491    fn test_get_signature_of_closure() {
2492        let codebase = CodebaseMetadata::new();
2493
2494        let id = FunctionLikeIdentifier::Closure(FileId::new("test"), Position::new(0));
2495        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2496
2497        assert!(sig.is_none());
2498    }
2499
2500    #[test]
2501    fn test_get_atomic_of_function() {
2502        let code = "<?php
2503            function myFunc(): void {}
2504        ";
2505        let codebase = create_test_codebase(code);
2506
2507        let id = FunctionLikeIdentifier::Function(ascii_lowercase_atom("myfunc"));
2508
2509        let atomic = get_atomic_of_function_like_identifier(&id, &codebase);
2510        assert!(atomic.is_some());
2511        assert!(matches!(atomic.unwrap(), TAtomic::Callable(TCallable::Signature(_))));
2512    }
2513
2514    #[test]
2515    fn test_get_signature_with_parameters() {
2516        let code = "<?php
2517            function multiParam(int $a, string $b, ?float $c = null): bool { return true; }
2518        ";
2519        let codebase = create_test_codebase(code);
2520
2521        let id = FunctionLikeIdentifier::Function(ascii_lowercase_atom("multiparam"));
2522
2523        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2524        assert!(sig.is_some());
2525
2526        let sig = sig.unwrap();
2527        assert_eq!(sig.get_parameters().len(), 3);
2528
2529        let third_param = &sig.get_parameters()[2];
2530        assert!(third_param.has_default());
2531    }
2532
2533    #[test]
2534    fn test_expand_preserves_by_reference_flag() {
2535        let code = "<?php class Foo {}";
2536        let codebase = create_test_codebase(code);
2537
2538        let mut input = make_self_object();
2539        input.flags.insert(UnionFlags::BY_REFERENCE);
2540
2541        let options = options_with_self("Foo");
2542        let mut actual = input.clone();
2543        expand_union(&codebase, &mut actual, &options);
2544
2545        assert!(actual.flags.contains(UnionFlags::BY_REFERENCE));
2546    }
2547
2548    #[test]
2549    fn test_expand_preserves_possibly_undefined_flag() {
2550        let code = "<?php class Foo {}";
2551        let codebase = create_test_codebase(code);
2552
2553        let mut input = make_self_object();
2554        input.flags.insert(UnionFlags::POSSIBLY_UNDEFINED);
2555
2556        let options = options_with_self("Foo");
2557        let mut actual = input.clone();
2558        expand_union(&codebase, &mut actual, &options);
2559
2560        assert!(actual.flags.contains(UnionFlags::POSSIBLY_UNDEFINED));
2561    }
2562
2563    #[test]
2564    fn test_expand_multiple_self_in_union() {
2565        let code = "<?php class Foo {}";
2566        let codebase = create_test_codebase(code);
2567
2568        let input = TUnion::from_vec(vec![
2569            TAtomic::Object(TObject::Named(TNamedObject::new(atom("self")))),
2570            TAtomic::Object(TObject::Named(TNamedObject::new(atom("self")))),
2571        ]);
2572
2573        let options = options_with_self("Foo");
2574        let mut actual = input;
2575        expand_union(&codebase, &mut actual, &options);
2576
2577        assert!(actual.types.len() <= 2);
2578    }
2579
2580    #[test]
2581    fn test_expand_deeply_nested_types() {
2582        let code = "<?php class Foo {}";
2583        let codebase = create_test_codebase(code);
2584
2585        let inner = TList::new(Arc::new(make_self_object()));
2586        let middle = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(inner)))));
2587        let outer = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(middle)))));
2588        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(outer)));
2589
2590        let options = options_with_self("Foo");
2591        let mut actual = input;
2592        expand_union(&codebase, &mut actual, &options);
2593
2594        if let TAtomic::Array(TArray::List(outer)) = &actual.types[0]
2595            && let TAtomic::Array(TArray::List(middle)) = &outer.element_type.types[0]
2596            && let TAtomic::Array(TArray::List(inner)) = &middle.element_type.types[0]
2597        {
2598            assert!(inner.element_type.types.iter().any(|t| {
2599                if let TAtomic::Object(TObject::Named(named)) = t {
2600                    named.name == ascii_lowercase_atom("foo")
2601                } else {
2602                    false
2603                }
2604            }));
2605        }
2606    }
2607
2608    #[test]
2609    fn test_expand_with_all_options_disabled() {
2610        let code = "<?php class Foo {}";
2611        let codebase = create_test_codebase(code);
2612
2613        let input = make_self_object();
2614        let options = TypeExpansionOptions {
2615            self_class: None,
2616            static_class_type: StaticClassType::None,
2617            parent_class: None,
2618            evaluate_class_constants: false,
2619            evaluate_conditional_types: false,
2620            function_is_final: false,
2621            expand_generic: false,
2622            expand_templates: false,
2623        };
2624
2625        let mut actual = input;
2626        expand_union(&codebase, &mut actual, &options);
2627
2628        assert!(actual.types.iter().any(|t| {
2629            if let TAtomic::Object(TObject::Named(named)) = t { named.name == atom("self") } else { false }
2630        }));
2631    }
2632
2633    #[test]
2634    fn test_expand_already_expanded_type() {
2635        let code = "<?php class Foo {}";
2636        let codebase = create_test_codebase(code);
2637
2638        let input = make_named_object("Foo");
2639        let options = options_with_self("Foo");
2640
2641        let mut actual = input;
2642        expand_union(&codebase, &mut actual, &options);
2643
2644        let mut actual2 = actual.clone();
2645        expand_union(&codebase, &mut actual2, &options);
2646
2647        assert_eq!(actual.types.as_ref(), actual2.types.as_ref());
2648    }
2649
2650    #[test]
2651    fn test_expand_complex_generic_class() {
2652        let code = "<?php
2653            /**
2654             * @template T
2655             * @template U
2656             */
2657            class Container {}
2658        ";
2659        let codebase = create_test_codebase(code);
2660
2661        let named = TNamedObject::new_with_type_parameters(
2662            ascii_lowercase_atom("container"),
2663            Some(vec![make_self_object(), make_static_object()]),
2664        );
2665        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
2666
2667        let options = TypeExpansionOptions {
2668            self_class: Some(ascii_lowercase_atom("foo")),
2669            static_class_type: StaticClassType::Name(ascii_lowercase_atom("bar")),
2670            ..Default::default()
2671        };
2672
2673        let mut actual = input;
2674        expand_union(&codebase, &mut actual, &options);
2675
2676        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
2677            && let Some(params) = &named.type_parameters
2678        {
2679            assert!(params[0].types.iter().any(|t| {
2680                if let TAtomic::Object(TObject::Named(named)) = t {
2681                    named.name == ascii_lowercase_atom("foo")
2682                } else {
2683                    false
2684                }
2685            }));
2686            assert!(params[1].types.iter().any(|t| {
2687                if let TAtomic::Object(TObject::Named(named)) = t {
2688                    named.name == ascii_lowercase_atom("bar")
2689                } else {
2690                    false
2691                }
2692            }));
2693        }
2694    }
2695}