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_word::Word;
9use mago_word::ascii_lowercase_word;
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<(Word, Word), 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<Word, 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<(Word, Word), 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: Word,
74    alias_name: Word,
75}
76
77impl AliasExpansionGuard {
78    #[must_use]
79    fn new(class_name: Word, alias_name: Word) -> 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: Word,
94}
95
96impl ObjectParamsExpansionGuard {
97    #[must_use]
98    fn try_new(object_name: Word) -> 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: Word,
125    constant_name: Word,
126}
127
128impl ConstantExpansionGuard {
129    #[must_use]
130    fn try_new(class_name: Word, constant_name: Word) -> 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(Word),
154    Object(TObject),
155}
156
157#[derive(Debug)]
158pub struct TypeExpansionOptions {
159    pub self_class: Option<Word>,
160    pub static_class_type: StaticClassType,
161    pub parent_class: Option<Word>,
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_word(class_like_name.as_bytes());
384        match name_lc.as_bytes() {
385            b"self" => options.self_class.unwrap_or(class_like_name),
386            b"static" | b"$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            b"parent" => {
394                if let Some(self_class) = options.self_class
395                    && let Some(class_metadata) = codebase.get_class_like(self_class.as_bytes())
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.as_bytes()) 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: Word,
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.as_bytes().eq_ignore_ascii_case(b"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.as_bytes()) 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.as_bytes());
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_word` 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: &[u8]) -> SpecialClassName {
586    match name.len() {
587        4 => {
588            if name.eq_ignore_ascii_case(b"self") {
589                SpecialClassName::SelfType
590            } else {
591                SpecialClassName::None
592            }
593        }
594        5 => {
595            if name == b"$this" || name.eq_ignore_ascii_case(b"$this") {
596                SpecialClassName::This
597            } else {
598                SpecialClassName::None
599            }
600        }
601        6 => {
602            if name.eq_ignore_ascii_case(b"static") {
603                SpecialClassName::Static
604            } else if name.eq_ignore_ascii_case(b"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_bytes());
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.as_bytes())
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.as_bytes(), named.name.as_bytes())) =>
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: &Word, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> bool {
709    if options.function_is_final {
710        return true;
711    }
712
713    codebase.get_class_like(class_name.as_bytes()).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.as_bytes(), named.name.as_bytes())
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.as_bytes(), named.name.as_bytes()))
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.as_bytes()) 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.as_bytes()) {
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.as_bytes())?;
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(name) => {
791            let function_like_metadata = codebase.get_closure(name)?;
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 =
802                codebase.get_declaring_method(classlike_name.as_bytes(), method_name.as_bytes())?;
803
804            get_signature_of_function_like_metadata(
805                function_like_identifier,
806                function_like_metadata,
807                codebase,
808                &TypeExpansionOptions {
809                    self_class: Some(*classlike_name),
810                    static_class_type: StaticClassType::Name(*classlike_name),
811                    ..Default::default()
812                },
813            )
814        }
815    })
816}
817
818#[must_use]
819pub fn get_atomic_of_function_like_identifier(
820    function_like_identifier: &FunctionLikeIdentifier,
821    codebase: &CodebaseMetadata,
822) -> Option<TAtomic> {
823    let signature = get_signature_of_function_like_identifier(function_like_identifier, codebase)?;
824
825    Some(TAtomic::Callable(TCallable::Signature(signature)))
826}
827
828#[must_use]
829pub fn get_signature_of_function_like_metadata(
830    function_like_identifier: &FunctionLikeIdentifier,
831    function_like_metadata: &FunctionLikeMetadata,
832    codebase: &CodebaseMetadata,
833    options: &TypeExpansionOptions,
834) -> TCallableSignature {
835    let parameters: Vec<_> = function_like_metadata
836        .parameters
837        .iter()
838        .map(|parameter_metadata| {
839            let type_signature = if let Some(t) = parameter_metadata.get_type_metadata() {
840                let mut t = t.type_union.clone();
841                expand_union(codebase, &mut t, options);
842                Some(Arc::new(t))
843            } else {
844                None
845            };
846
847            TCallableParameter::new(
848                type_signature,
849                parameter_metadata.flags.is_by_reference(),
850                parameter_metadata.flags.is_variadic(),
851                parameter_metadata.flags.has_default(),
852            )
853        })
854        .collect();
855
856    let return_type = if let Some(type_metadata) = function_like_metadata.return_type_metadata.as_ref() {
857        let mut return_type = type_metadata.type_union.clone();
858        expand_union(codebase, &mut return_type, options);
859        Some(Arc::new(return_type))
860    } else {
861        None
862    };
863
864    let is_closure = matches!(function_like_identifier, FunctionLikeIdentifier::Closure(_));
865    TCallableSignature::new(function_like_metadata.flags.is_pure(), is_closure)
866        .with_parameters(parameters)
867        .with_return_type(return_type)
868        .with_source(Some(*function_like_identifier))
869}
870
871#[cold]
872fn expand_key_of(
873    return_type_key_of: &TKeyOf,
874    codebase: &CodebaseMetadata,
875    options: &TypeExpansionOptions,
876) -> Vec<TAtomic> {
877    let mut target_type = return_type_key_of.get_target_type().clone();
878    expand_union(codebase, &mut target_type, options);
879
880    let Some(new_return_types) = TKeyOf::get_key_of_targets(&target_type.types, codebase, false) else {
881        return vec![TAtomic::Derived(TDerived::KeyOf(return_type_key_of.clone()))];
882    };
883
884    new_return_types.types.into_owned()
885}
886
887#[cold]
888fn expand_value_of(
889    return_type_value_of: &TValueOf,
890    codebase: &CodebaseMetadata,
891    options: &TypeExpansionOptions,
892) -> Vec<TAtomic> {
893    let mut target_type = return_type_value_of.get_target_type().clone();
894    expand_union(codebase, &mut target_type, options);
895
896    let Some(new_return_types) = TValueOf::get_value_of_targets(&target_type.types, codebase, false) else {
897        return vec![TAtomic::Derived(TDerived::ValueOf(return_type_value_of.clone()))];
898    };
899
900    new_return_types.types.into_owned()
901}
902
903#[cold]
904fn expand_index_access(
905    return_type_index_access: &TIndexAccess,
906    codebase: &CodebaseMetadata,
907    options: &TypeExpansionOptions,
908) -> Vec<TAtomic> {
909    let mut target_type = return_type_index_access.get_target_type().clone();
910    expand_union(codebase, &mut target_type, options);
911
912    let mut index_type = return_type_index_access.get_index_type().clone();
913    expand_union(codebase, &mut index_type, options);
914
915    let Some(new_return_types) = TIndexAccess::get_indexed_access_result(&target_type.types, &index_type.types, false)
916    else {
917        return vec![TAtomic::Derived(TDerived::IndexAccess(return_type_index_access.clone()))];
918    };
919
920    new_return_types.types.into_owned()
921}
922
923#[cold]
924fn expand_new(new_type: &TNew, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
925    let mut target_type = new_type.get_target_type().clone();
926    expand_union(codebase, &mut target_type, options);
927
928    let Some(new_return_types) = TNew::get_new_targets(&target_type.types, codebase) else {
929        return vec![TAtomic::Derived(TDerived::New(new_type.clone()))];
930    };
931
932    new_return_types.types.into_owned()
933}
934
935#[cold]
936fn expand_template_type(
937    template_type: &TTemplateType,
938    codebase: &CodebaseMetadata,
939    options: &TypeExpansionOptions,
940) -> Vec<TAtomic> {
941    let mut expanded = template_type.clone();
942    expand_union(codebase, expanded.get_object_mut(), options);
943    expand_union(codebase, expanded.get_class_name_mut(), options);
944    expand_union(codebase, expanded.get_template_name_mut(), options);
945
946    let Some(resolved) = expanded.resolve(codebase) else {
947        return vec![TAtomic::Mixed(TMixed::new())];
948    };
949
950    resolved.types.into_owned()
951}
952
953#[cold]
954fn expand_int_mask(int_mask: &TIntMask, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
955    let mut literal_values = Vec::new();
956
957    for value in int_mask.get_values() {
958        let mut expanded = value.clone();
959        expand_union(codebase, &mut expanded, options);
960
961        if let Some(int_val) = expanded.get_single_literal_int_value() {
962            literal_values.push(int_val);
963        }
964    }
965
966    if literal_values.is_empty() {
967        return vec![TAtomic::Scalar(TScalar::int())];
968    }
969
970    let combinations = TIntMask::calculate_mask_combinations(&literal_values);
971    combinations.into_iter().map(|v| TAtomic::Scalar(TScalar::literal_int(v))).collect()
972}
973
974#[cold]
975fn expand_int_mask_of(
976    int_mask_of: &TIntMaskOf,
977    codebase: &CodebaseMetadata,
978    options: &TypeExpansionOptions,
979) -> Vec<TAtomic> {
980    let mut target = int_mask_of.get_target_type().clone();
981    expand_union(codebase, &mut target, options);
982
983    let mut literal_values = Vec::new();
984    for atomic in target.types.iter() {
985        if let Some(int_val) = atomic.get_literal_int_value() {
986            literal_values.push(int_val);
987        }
988    }
989
990    if literal_values.is_empty() {
991        return vec![TAtomic::Scalar(TScalar::int())];
992    }
993
994    let combinations = TIntMask::calculate_mask_combinations(&literal_values);
995    combinations.into_iter().map(|v| TAtomic::Scalar(TScalar::literal_int(v))).collect()
996}
997
998#[cold]
999fn expand_properties_of(
1000    properties_of: &TPropertiesOf,
1001    codebase: &CodebaseMetadata,
1002    options: &TypeExpansionOptions,
1003) -> Vec<TAtomic> {
1004    let mut target_type = properties_of.get_target_type().clone();
1005    expand_union(codebase, &mut target_type, options);
1006
1007    let Some(mut keyed_array) =
1008        TPropertiesOf::get_properties_of_targets(&target_type.types, codebase, properties_of.visibility(), false)
1009    else {
1010        return vec![TAtomic::Derived(TDerived::PropertiesOf(properties_of.clone()))];
1011    };
1012
1013    let mut skip_keyed_array = false;
1014    let mut expanded_parts = vec![];
1015    expand_atomic(&mut keyed_array, codebase, options, &mut skip_keyed_array, &mut expanded_parts);
1016    if skip_keyed_array {
1017        expanded_parts
1018    } else {
1019        expanded_parts.push(keyed_array);
1020        expanded_parts
1021    }
1022}
1023
1024#[cold]
1025fn expand_alias(alias: &TAlias, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
1026    let class_name = alias.get_class_name();
1027    let alias_name = alias.get_alias_name();
1028
1029    // Check for cycle using the HashSet
1030    let is_cycle = EXPANDING_ALIASES.with(|set| set.borrow().contains(&(class_name, alias_name)));
1031
1032    if is_cycle {
1033        return vec![TAtomic::Alias(alias.clone())];
1034    }
1035
1036    let Some(mut expanded_union) = alias.resolve(codebase).cloned() else {
1037        return vec![TAtomic::Alias(alias.clone())];
1038    };
1039
1040    let _guard = AliasExpansionGuard::new(class_name, alias_name);
1041
1042    expand_union(codebase, &mut expanded_union, options);
1043
1044    expanded_union.types.into_owned()
1045}
1046
1047#[cfg(test)]
1048#[allow(clippy::unwrap_used, clippy::expect_used)]
1049mod tests {
1050    use super::*;
1051
1052    use std::borrow::Cow;
1053    use std::collections::HashSet;
1054    use std::sync::Arc;
1055
1056    use bumpalo::Bump;
1057
1058    use mago_database::Database;
1059    use mago_database::DatabaseReader;
1060    use mago_database::file::File;
1061
1062    use mago_names::resolver::NameResolver;
1063
1064    use mago_syntax::parser::parse_file;
1065    use mago_word::WordSet;
1066    use mago_word::word;
1067
1068    use crate::metadata::CodebaseMetadata;
1069    use crate::misc::GenericParent;
1070    use crate::populator::populate_codebase;
1071    use crate::reference::SymbolReferences;
1072    use crate::scanner::scan_program;
1073    use crate::ttype::atomic::array::TArray;
1074    use crate::ttype::atomic::array::keyed::TKeyedArray;
1075    use crate::ttype::atomic::array::list::TList;
1076    use crate::ttype::atomic::callable::TCallable;
1077    use crate::ttype::atomic::callable::TCallableSignature;
1078    use crate::ttype::atomic::callable::parameter::TCallableParameter;
1079    use crate::ttype::atomic::conditional::TConditional;
1080    use crate::ttype::atomic::derived::TDerived;
1081    use crate::ttype::atomic::derived::index_access::TIndexAccess;
1082    use crate::ttype::atomic::derived::key_of::TKeyOf;
1083    use crate::ttype::atomic::derived::value_of::TValueOf;
1084    use crate::ttype::atomic::generic::TGenericParameter;
1085    use crate::ttype::atomic::iterable::TIterable;
1086    use crate::ttype::atomic::object::r#enum::TEnum;
1087    use crate::ttype::atomic::object::named::TNamedObject;
1088    use crate::ttype::atomic::reference::TReference;
1089    use crate::ttype::atomic::reference::TReferenceMemberSelector;
1090    use crate::ttype::atomic::scalar::TScalar;
1091    use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
1092    use crate::ttype::atomic::scalar::class_like_string::TClassLikeStringKind;
1093    use crate::ttype::flags::UnionFlags;
1094    use crate::ttype::get_int;
1095    use crate::ttype::get_mixed;
1096    use crate::ttype::get_never;
1097    use crate::ttype::get_null;
1098    use crate::ttype::get_string;
1099    use crate::ttype::get_void;
1100
1101    fn create_test_codebase(code: &'static str) -> CodebaseMetadata {
1102        let file = File::ephemeral(Cow::Borrowed(b"code.php"), Cow::Borrowed(code.as_bytes()));
1103        let config =
1104            mago_database::DatabaseConfiguration::new(std::path::Path::new("/"), vec![], vec![], vec![], vec![])
1105                .into_static();
1106        let database = Database::single(file, config);
1107
1108        let mut codebase = CodebaseMetadata::new();
1109        let arena = Bump::new();
1110        for file in database.files() {
1111            let program = parse_file(&arena, &file);
1112            assert!(!program.has_errors(), "Parse failed: {:?}", program.errors);
1113            let resolved_names = NameResolver::new(&arena).resolve(program);
1114            let program_codebase =
1115                scan_program(&arena, &file, program, &resolved_names, mago_php_version::PHPVersion::LATEST);
1116
1117            codebase.extend(program_codebase);
1118        }
1119
1120        populate_codebase(&mut codebase, &mut SymbolReferences::new(), WordSet::default(), HashSet::default());
1121
1122        codebase
1123    }
1124
1125    fn options_with_self(self_class: &str) -> TypeExpansionOptions {
1126        TypeExpansionOptions { self_class: Some(ascii_lowercase_word(self_class.as_bytes())), ..Default::default() }
1127    }
1128
1129    fn options_with_static(static_class: &str) -> TypeExpansionOptions {
1130        TypeExpansionOptions {
1131            self_class: Some(ascii_lowercase_word(static_class.as_bytes())),
1132            static_class_type: StaticClassType::Name(ascii_lowercase_word(static_class.as_bytes())),
1133            ..Default::default()
1134        }
1135    }
1136
1137    fn options_with_static_object(object: TObject) -> TypeExpansionOptions {
1138        TypeExpansionOptions {
1139            self_class: object.get_name(),
1140            static_class_type: StaticClassType::Object(object),
1141            ..Default::default()
1142        }
1143    }
1144
1145    macro_rules! assert_expands_to {
1146        ($codebase:expr, $input:expr, $expected:expr) => {
1147            assert_expands_to!($codebase, $input, $expected, &TypeExpansionOptions::default())
1148        };
1149        ($codebase:expr, $input:expr, $expected:expr, $options:expr) => {{
1150            let mut actual = $input.clone();
1151            expand_union($codebase, &mut actual, $options);
1152            assert_eq!(
1153                actual.types.as_ref(),
1154                $expected.types.as_ref(),
1155                "Type expansion mismatch.\nInput: {:?}\nExpected: {:?}\nActual: {:?}",
1156                $input,
1157                $expected,
1158                actual
1159            );
1160        }};
1161    }
1162
1163    fn make_self_object() -> TUnion {
1164        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))))
1165    }
1166
1167    fn make_static_object() -> TUnion {
1168        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("static")))))
1169    }
1170
1171    fn make_parent_object() -> TUnion {
1172        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("parent")))))
1173    }
1174
1175    fn make_named_object(name: &str) -> TUnion {
1176        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_word(name.as_bytes())))))
1177    }
1178
1179    #[test]
1180    fn test_expand_null_type() {
1181        let codebase = CodebaseMetadata::new();
1182        let null_type = get_null();
1183        assert_expands_to!(&codebase, null_type, get_null());
1184    }
1185
1186    #[test]
1187    fn test_expand_void_type() {
1188        let codebase = CodebaseMetadata::new();
1189        let void_type = get_void();
1190        assert_expands_to!(&codebase, void_type, get_void());
1191    }
1192
1193    #[test]
1194    fn test_expand_never_type() {
1195        let codebase = CodebaseMetadata::new();
1196        let never_type = get_never();
1197        assert_expands_to!(&codebase, never_type, get_never());
1198    }
1199
1200    #[test]
1201    fn test_expand_int_type() {
1202        let codebase = CodebaseMetadata::new();
1203        let int_type = get_int();
1204        assert_expands_to!(&codebase, int_type, get_int());
1205    }
1206
1207    #[test]
1208    fn test_expand_mixed_type() {
1209        let codebase = CodebaseMetadata::new();
1210        let mixed_type = get_mixed();
1211        assert_expands_to!(&codebase, mixed_type, get_mixed());
1212    }
1213
1214    #[test]
1215    fn test_expand_keyed_array_with_self_key() {
1216        let code = "<?php class Foo {}";
1217        let codebase = create_test_codebase(code);
1218
1219        let mut keyed = TKeyedArray::new();
1220        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
1221        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1222
1223        let options = options_with_self("Foo");
1224        let mut actual = input;
1225        expand_union(&codebase, &mut actual, &options);
1226
1227        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1228            && let Some((key, _)) = &keyed.parameters
1229        {
1230            assert!(key.types.iter().any(|t| {
1231                if let TAtomic::Object(TObject::Named(named)) = t {
1232                    named.name == ascii_lowercase_word(b"foo")
1233                } else {
1234                    false
1235                }
1236            }));
1237        }
1238    }
1239
1240    #[test]
1241    fn test_expand_keyed_array_with_self_value() {
1242        let code = "<?php class Foo {}";
1243        let codebase = create_test_codebase(code);
1244
1245        let mut keyed = TKeyedArray::new();
1246        keyed.parameters = Some((Arc::new(get_string()), Arc::new(make_self_object())));
1247        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1248
1249        let options = options_with_self("Foo");
1250        let mut actual = input;
1251        expand_union(&codebase, &mut actual, &options);
1252
1253        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1254            && let Some((_, value)) = &keyed.parameters
1255        {
1256            assert!(value.types.iter().any(|t| {
1257                if let TAtomic::Object(TObject::Named(named)) = t {
1258                    named.name == ascii_lowercase_word(b"foo")
1259                } else {
1260                    false
1261                }
1262            }));
1263        }
1264    }
1265
1266    #[test]
1267    fn test_expand_keyed_array_known_items() {
1268        let code = "<?php class Foo {}";
1269        let codebase = create_test_codebase(code);
1270
1271        use crate::ttype::atomic::array::key::ArrayKey;
1272        use std::collections::BTreeMap;
1273
1274        let mut keyed = TKeyedArray::new();
1275        let mut known_items = BTreeMap::new();
1276        known_items.insert(ArrayKey::String(word("key")), (false, make_self_object()));
1277        keyed.known_items = Some(known_items);
1278        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1279
1280        let options = options_with_self("Foo");
1281        let mut actual = input;
1282        expand_union(&codebase, &mut actual, &options);
1283
1284        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1285            && let Some(items) = &keyed.known_items
1286        {
1287            let (_, item_type) = items.get(&ArrayKey::String(word("key"))).unwrap();
1288            assert!(item_type.types.iter().any(|t| {
1289                if let TAtomic::Object(TObject::Named(named)) = t {
1290                    named.name == ascii_lowercase_word(b"foo")
1291                } else {
1292                    false
1293                }
1294            }));
1295        }
1296    }
1297
1298    #[test]
1299    fn test_expand_list_with_self_element() {
1300        let code = "<?php class Foo {}";
1301        let codebase = create_test_codebase(code);
1302
1303        let list = TList::new(Arc::new(make_self_object()));
1304        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1305
1306        let options = options_with_self("Foo");
1307        let mut actual = input;
1308        expand_union(&codebase, &mut actual, &options);
1309
1310        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1311            assert!(list.element_type.types.iter().any(|t| {
1312                if let TAtomic::Object(TObject::Named(named)) = t {
1313                    named.name == ascii_lowercase_word(b"foo")
1314                } else {
1315                    false
1316                }
1317            }));
1318        }
1319    }
1320
1321    #[test]
1322    fn test_expand_list_known_elements() {
1323        let code = "<?php class Foo {}";
1324        let codebase = create_test_codebase(code);
1325
1326        use std::collections::BTreeMap;
1327
1328        let mut list = TList::new(Arc::new(get_mixed()));
1329        let mut known_elements = BTreeMap::new();
1330        known_elements.insert(0, (false, make_self_object()));
1331        list.known_elements = Some(known_elements);
1332        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1333
1334        let options = options_with_self("Foo");
1335        let mut actual = input;
1336        expand_union(&codebase, &mut actual, &options);
1337
1338        if let TAtomic::Array(TArray::List(list)) = &actual.types[0]
1339            && let Some(elements) = &list.known_elements
1340        {
1341            let (_, element_type) = elements.get(&0).unwrap();
1342            assert!(element_type.types.iter().any(|t| {
1343                if let TAtomic::Object(TObject::Named(named)) = t {
1344                    named.name == ascii_lowercase_word(b"foo")
1345                } else {
1346                    false
1347                }
1348            }));
1349        }
1350    }
1351
1352    #[test]
1353    fn test_expand_nested_array() {
1354        let code = "<?php class Foo {}";
1355        let codebase = create_test_codebase(code);
1356
1357        let inner_list = TList::new(Arc::new(make_self_object()));
1358        let inner_array = TUnion::from_atomic(TAtomic::Array(TArray::List(inner_list)));
1359
1360        let mut outer = TKeyedArray::new();
1361        outer.parameters = Some((Arc::new(make_self_object()), Arc::new(inner_array)));
1362        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(outer)));
1363
1364        let options = options_with_self("Foo");
1365        let mut actual = input;
1366        expand_union(&codebase, &mut actual, &options);
1367
1368        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1369            && let Some((key, value)) = &keyed.parameters
1370        {
1371            assert!(key.types.iter().any(|t| {
1372                if let TAtomic::Object(TObject::Named(named)) = t {
1373                    named.name == ascii_lowercase_word(b"foo")
1374                } else {
1375                    false
1376                }
1377            }));
1378            if let TAtomic::Array(TArray::List(inner)) = &value.types[0] {
1379                assert!(inner.element_type.types.iter().any(|t| {
1380                    if let TAtomic::Object(TObject::Named(named)) = t {
1381                        named.name == ascii_lowercase_word(b"foo")
1382                    } else {
1383                        false
1384                    }
1385                }));
1386            }
1387        }
1388    }
1389
1390    #[test]
1391    fn test_expand_empty_array() {
1392        let codebase = CodebaseMetadata::new();
1393        let keyed = TKeyedArray::new();
1394        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed.clone())));
1395        let expected = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1396        assert_expands_to!(&codebase, input, expected);
1397    }
1398
1399    #[test]
1400    fn test_expand_non_empty_list() {
1401        let code = "<?php class Foo {}";
1402        let codebase = create_test_codebase(code);
1403
1404        let mut list = TList::new(Arc::new(make_self_object()));
1405        list.non_empty = true;
1406        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1407
1408        let options = options_with_self("Foo");
1409        let mut actual = input;
1410        expand_union(&codebase, &mut actual, &options);
1411
1412        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1413            assert!(list.non_empty);
1414            assert!(list.element_type.types.iter().any(|t| {
1415                if let TAtomic::Object(TObject::Named(named)) = t {
1416                    named.name == ascii_lowercase_word(b"foo")
1417                } else {
1418                    false
1419                }
1420            }));
1421        }
1422    }
1423
1424    #[test]
1425    fn test_expand_self_to_class_name() {
1426        let code = "<?php class Foo {}";
1427        let codebase = create_test_codebase(code);
1428
1429        let input = make_self_object();
1430        let options = options_with_self("Foo");
1431        let mut actual = input;
1432        expand_union(&codebase, &mut actual, &options);
1433
1434        assert!(actual.types.iter().any(|t| {
1435            if let TAtomic::Object(TObject::Named(named)) = t {
1436                named.name == ascii_lowercase_word(b"foo")
1437            } else {
1438                false
1439            }
1440        }));
1441    }
1442
1443    #[test]
1444    fn test_expand_static_to_class_name() {
1445        let code = "<?php class Foo {}";
1446        let codebase = create_test_codebase(code);
1447
1448        let input = make_static_object();
1449        let options = options_with_static("Foo");
1450        let mut actual = input;
1451        expand_union(&codebase, &mut actual, &options);
1452
1453        assert!(actual.types.iter().any(|t| {
1454            if let TAtomic::Object(TObject::Named(named)) = t {
1455                named.name == ascii_lowercase_word(b"foo")
1456            } else {
1457                false
1458            }
1459        }));
1460    }
1461
1462    #[test]
1463    fn test_expand_static_with_object_type() {
1464        let code = "<?php class Foo {}";
1465        let codebase = create_test_codebase(code);
1466
1467        let input = make_static_object();
1468        let static_obj = TObject::Named(TNamedObject::new(ascii_lowercase_word(b"foo")));
1469        let options = options_with_static_object(static_obj);
1470        let mut actual = input;
1471        expand_union(&codebase, &mut actual, &options);
1472
1473        assert!(actual.types.iter().any(|t| {
1474            if let TAtomic::Object(TObject::Named(named)) = t {
1475                named.name == ascii_lowercase_word(b"foo") && named.is_static && !named.is_this
1476            } else {
1477                false
1478            }
1479        }));
1480    }
1481
1482    #[test]
1483    fn test_expand_static_with_enum_type() {
1484        let code = "<?php enum Status { case Active; case Inactive; }";
1485        let codebase = create_test_codebase(code);
1486
1487        let input = make_static_object();
1488        let static_enum = TObject::Enum(TEnum::new(ascii_lowercase_word(b"status")));
1489        let options = options_with_static_object(static_enum);
1490        let mut actual = input;
1491        expand_union(&codebase, &mut actual, &options);
1492
1493        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Object(TObject::Enum(_)))));
1494    }
1495
1496    #[test]
1497    fn test_expand_parent_to_parent_class() {
1498        let code = "<?php
1499            class BaseClass {}
1500            class ChildClass extends BaseClass {}
1501        ";
1502        let codebase = create_test_codebase(code);
1503
1504        let input = make_parent_object();
1505        let options = options_with_self("ChildClass");
1506        let mut actual = input;
1507        expand_union(&codebase, &mut actual, &options);
1508
1509        assert!(actual.types.iter().any(|t| {
1510            if let TAtomic::Object(TObject::Named(named)) = t {
1511                named.name == ascii_lowercase_word(b"baseclass")
1512            } else {
1513                false
1514            }
1515        }));
1516    }
1517
1518    #[test]
1519    fn test_expand_parent_without_parent_class() {
1520        let code = "<?php class Foo {}";
1521        let codebase = create_test_codebase(code);
1522
1523        let input = make_parent_object();
1524        let options = options_with_self("Foo");
1525        let mut actual = input;
1526        expand_union(&codebase, &mut actual, &options);
1527
1528        assert!(actual.types.iter().any(|t| {
1529            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("parent") } else { false }
1530        }));
1531    }
1532
1533    #[test]
1534    fn test_expand_this_variable() {
1535        let code = "<?php class Foo {}";
1536        let codebase = create_test_codebase(code);
1537
1538        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new_this(word("$this")))));
1539        let options = options_with_static("Foo");
1540        let mut actual = input;
1541        expand_union(&codebase, &mut actual, &options);
1542
1543        assert!(actual.types.iter().any(|t| {
1544            if let TAtomic::Object(TObject::Named(named)) = t {
1545                named.name == ascii_lowercase_word(b"foo")
1546            } else {
1547                false
1548            }
1549        }));
1550    }
1551
1552    #[test]
1553    fn test_expand_this_with_final_function() {
1554        let code = "<?php class Foo {}";
1555        let codebase = create_test_codebase(code);
1556
1557        let input = make_static_object();
1558        let options = TypeExpansionOptions {
1559            self_class: Some(ascii_lowercase_word(b"foo")),
1560            static_class_type: StaticClassType::Name(ascii_lowercase_word(b"foo")),
1561            function_is_final: true,
1562            ..Default::default()
1563        };
1564        let mut actual = input;
1565        expand_union(&codebase, &mut actual, &options);
1566
1567        assert!(actual.types.iter().any(|t| {
1568            if let TAtomic::Object(TObject::Named(named)) = t {
1569                named.name == ascii_lowercase_word(b"foo") && !named.is_this
1570            } else {
1571                false
1572            }
1573        }));
1574    }
1575
1576    #[test]
1577    fn test_expand_object_with_type_parameters() {
1578        let code = "<?php class Container {}";
1579        let codebase = create_test_codebase(code);
1580
1581        let named =
1582            TNamedObject::new_with_type_parameters(ascii_lowercase_word(b"container"), Some(vec![make_self_object()]));
1583        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
1584
1585        let options = options_with_self("Foo");
1586        let mut actual = input;
1587        expand_union(&codebase, &mut actual, &options);
1588
1589        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
1590            && let Some(params) = &named.type_parameters
1591        {
1592            assert!(params[0].types.iter().any(|t| {
1593                if let TAtomic::Object(TObject::Named(named)) = t {
1594                    named.name == ascii_lowercase_word(b"foo")
1595                } else {
1596                    false
1597                }
1598            }));
1599        }
1600    }
1601
1602    #[test]
1603    fn test_expand_object_gets_default_type_params() {
1604        let code = "<?php
1605            /** @template T */
1606            class Container {}
1607        ";
1608        let codebase = create_test_codebase(code);
1609
1610        let named = TNamedObject::new(ascii_lowercase_word(b"container"));
1611        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
1612
1613        let mut actual = input;
1614        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1615
1616        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0] {
1617            assert!(named.type_parameters.is_some());
1618        }
1619    }
1620
1621    #[test]
1622    fn test_expand_object_intersection_from_static() {
1623        let code = "<?php
1624            interface Stringable {}
1625            class Foo implements Stringable {}
1626        ";
1627        let codebase = create_test_codebase(code);
1628
1629        let input = make_static_object();
1630
1631        let mut static_named = TNamedObject::new(ascii_lowercase_word(b"foo"));
1632        static_named.intersection_types =
1633            Some(vec![TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_word(b"stringable"))))]);
1634        let static_obj = TObject::Named(static_named);
1635        let options = options_with_static_object(static_obj);
1636
1637        let mut actual = input;
1638        expand_union(&codebase, &mut actual, &options);
1639
1640        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0] {
1641            assert!(named.intersection_types.is_some());
1642        }
1643    }
1644
1645    #[test]
1646    fn test_expand_self_without_self_class_option() {
1647        let codebase = CodebaseMetadata::new();
1648
1649        let input = make_self_object();
1650        let mut actual = input;
1651        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1652
1653        assert!(actual.types.iter().any(|t| {
1654            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("self") } else { false }
1655        }));
1656    }
1657
1658    #[test]
1659    fn test_expand_callable_return_type() {
1660        let code = "<?php class Foo {}";
1661        let codebase = create_test_codebase(code);
1662
1663        let sig = TCallableSignature::new(false, false).with_return_type(Some(Arc::new(make_self_object())));
1664        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1665
1666        let options = options_with_self("Foo");
1667        let mut actual = input;
1668        expand_union(&codebase, &mut actual, &options);
1669
1670        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1671            && let Some(ret) = sig.get_return_type()
1672        {
1673            assert!(ret.types.iter().any(|t| {
1674                if let TAtomic::Object(TObject::Named(named)) = t {
1675                    named.name == ascii_lowercase_word(b"foo")
1676                } else {
1677                    false
1678                }
1679            }));
1680        }
1681    }
1682
1683    #[test]
1684    fn test_expand_callable_parameter_types() {
1685        let code = "<?php class Foo {}";
1686        let codebase = create_test_codebase(code);
1687
1688        let param = TCallableParameter::new(Some(Arc::new(make_self_object())), false, false, false);
1689        let sig = TCallableSignature::new(false, false).with_parameters(vec![param]);
1690        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1691
1692        let options = options_with_self("Foo");
1693        let mut actual = input;
1694        expand_union(&codebase, &mut actual, &options);
1695
1696        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1697            && let Some(param) = sig.get_parameters().first()
1698            && let Some(param_type) = param.get_type_signature()
1699        {
1700            assert!(param_type.types.iter().any(|t| {
1701                if let TAtomic::Object(TObject::Named(named)) = t {
1702                    named.name == ascii_lowercase_word(b"foo")
1703                } else {
1704                    false
1705                }
1706            }));
1707        }
1708    }
1709
1710    #[test]
1711    fn test_expand_callable_alias_to_function() {
1712        let code = "<?php
1713            function myFunc(): int { return 1; }
1714        ";
1715        let codebase = create_test_codebase(code);
1716
1717        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc")));
1718        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1719
1720        let mut actual = input;
1721        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1722
1723        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
1724    }
1725
1726    #[test]
1727    fn test_expand_callable_alias_to_method() {
1728        let code = "<?php
1729            class Foo {
1730                public function bar(): int { return 1; }
1731            }
1732        ";
1733        let codebase = create_test_codebase(code);
1734
1735        let alias = TCallable::Alias(FunctionLikeIdentifier::Method(
1736            ascii_lowercase_word(b"foo"),
1737            ascii_lowercase_word(b"bar"),
1738        ));
1739        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1740
1741        let mut actual = input;
1742        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1743
1744        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
1745    }
1746
1747    #[test]
1748    fn test_expand_callable_alias_unknown() {
1749        let codebase = CodebaseMetadata::new();
1750
1751        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(word("nonexistent")));
1752        let input = TUnion::from_atomic(TAtomic::Callable(alias));
1753
1754        let mut actual = input;
1755        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1756
1757        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Alias(_)))));
1758    }
1759
1760    #[test]
1761    fn test_expand_closure_signature() {
1762        let code = "<?php class Foo {}";
1763        let codebase = create_test_codebase(code);
1764
1765        let sig = TCallableSignature::new(false, true).with_return_type(Some(Arc::new(make_self_object())));
1766        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
1767
1768        let options = options_with_self("Foo");
1769        let mut actual = input;
1770        expand_union(&codebase, &mut actual, &options);
1771
1772        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
1773            && let Some(ret) = sig.get_return_type()
1774        {
1775            assert!(ret.types.iter().any(|t| {
1776                if let TAtomic::Object(TObject::Named(named)) = t {
1777                    named.name == ascii_lowercase_word(b"foo")
1778                } else {
1779                    false
1780                }
1781            }));
1782        }
1783    }
1784
1785    #[test]
1786    fn test_expand_generic_parameter_constraint() {
1787        let code = "<?php class Foo {}";
1788        let codebase = create_test_codebase(code);
1789
1790        let generic = TGenericParameter::new(
1791            word("T"),
1792            Arc::new(make_self_object()),
1793            GenericParent::ClassLike(ascii_lowercase_word(b"foo")),
1794        );
1795        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1796
1797        let options = options_with_self("Foo");
1798        let mut actual = input;
1799        expand_union(&codebase, &mut actual, &options);
1800
1801        if let TAtomic::GenericParameter(param) = &actual.types[0] {
1802            assert!(param.constraint.types.iter().any(|t| {
1803                if let TAtomic::Object(TObject::Named(named)) = t {
1804                    named.name == ascii_lowercase_word(b"foo")
1805                } else {
1806                    false
1807                }
1808            }));
1809        }
1810    }
1811
1812    #[test]
1813    fn test_expand_nested_generic_constraint() {
1814        let code = "<?php class Foo {} class Bar {}";
1815        let codebase = create_test_codebase(code);
1816
1817        let container =
1818            TNamedObject::new_with_type_parameters(ascii_lowercase_word(b"container"), Some(vec![make_self_object()]));
1819        let constraint = TUnion::from_atomic(TAtomic::Object(TObject::Named(container)));
1820
1821        let generic = TGenericParameter::new(
1822            word("T"),
1823            Arc::new(constraint),
1824            GenericParent::ClassLike(ascii_lowercase_word(b"bar")),
1825        );
1826        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1827
1828        let options = options_with_self("Foo");
1829        let mut actual = input;
1830        expand_union(&codebase, &mut actual, &options);
1831
1832        if let TAtomic::GenericParameter(param) = &actual.types[0]
1833            && let TAtomic::Object(TObject::Named(named)) = &param.constraint.types[0]
1834            && let Some(params) = &named.type_parameters
1835        {
1836            assert!(params[0].types.iter().any(|t| {
1837                if let TAtomic::Object(TObject::Named(named)) = t {
1838                    named.name == ascii_lowercase_word(b"foo")
1839                } else {
1840                    false
1841                }
1842            }));
1843        }
1844    }
1845
1846    #[test]
1847    fn test_expand_generic_with_intersection() {
1848        let code = "<?php
1849            interface Stringable {}
1850            class Foo {}
1851        ";
1852        let codebase = create_test_codebase(code);
1853
1854        let mut generic = TGenericParameter::new(
1855            word("T"),
1856            Arc::new(make_self_object()),
1857            GenericParent::ClassLike(ascii_lowercase_word(b"foo")),
1858        );
1859        generic.intersection_types =
1860            Some(vec![TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_word(b"stringable"))))]);
1861        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
1862
1863        let options = options_with_self("Foo");
1864        let mut actual = input;
1865        expand_union(&codebase, &mut actual, &options);
1866
1867        if let TAtomic::GenericParameter(param) = &actual.types[0] {
1868            assert!(param.intersection_types.is_some());
1869            assert!(param.constraint.types.iter().any(|t| {
1870                if let TAtomic::Object(TObject::Named(named)) = t {
1871                    named.name == ascii_lowercase_word(b"foo")
1872                } else {
1873                    false
1874                }
1875            }));
1876        }
1877    }
1878
1879    #[test]
1880    fn test_expand_class_string_of_self() {
1881        let code = "<?php class Foo {}";
1882        let codebase = create_test_codebase(code);
1883
1884        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))));
1885        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
1886        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1887
1888        let options = options_with_self("Foo");
1889        let mut actual = input;
1890        expand_union(&codebase, &mut actual, &options);
1891
1892        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
1893            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
1894        {
1895            assert_eq!(named.name, ascii_lowercase_word(b"foo"));
1896        }
1897    }
1898
1899    #[test]
1900    fn test_expand_class_string_of_static() {
1901        let code = "<?php class Foo {}";
1902        let codebase = create_test_codebase(code);
1903
1904        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("static")))));
1905        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
1906        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1907
1908        let options = options_with_static("Foo");
1909        let mut actual = input;
1910        expand_union(&codebase, &mut actual, &options);
1911
1912        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
1913            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
1914        {
1915            assert_eq!(named.name, ascii_lowercase_word(b"foo"));
1916        }
1917    }
1918
1919    #[test]
1920    fn test_expand_interface_string_of_type() {
1921        let code = "<?php interface MyInterface {}";
1922        let codebase = create_test_codebase(code);
1923
1924        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))));
1925        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Interface, constraint };
1926        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
1927
1928        let options = options_with_self("MyInterface");
1929        let mut actual = input;
1930        expand_union(&codebase, &mut actual, &options);
1931
1932        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { kind, constraint })) =
1933            &actual.types[0]
1934        {
1935            assert!(matches!(kind, TClassLikeStringKind::Interface));
1936            if let TAtomic::Object(TObject::Named(named)) = constraint.as_ref() {
1937                assert_eq!(named.name, ascii_lowercase_word(b"myinterface"));
1938            }
1939        }
1940    }
1941
1942    #[test]
1943    fn test_expand_member_reference_wildcard_constants() {
1944        let code = "<?php
1945            class Foo {
1946                public const A = 1;
1947                public const B = 2;
1948            }
1949        ";
1950        let codebase = create_test_codebase(code);
1951
1952        let reference = TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Wildcard);
1953        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1954
1955        let mut actual = input;
1956        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1957
1958        assert!(!actual.types.is_empty());
1959    }
1960
1961    #[test]
1962    fn test_expand_member_reference_wildcard_enum_cases() {
1963        let code = "<?php
1964            enum Status {
1965                case Active;
1966                case Inactive;
1967            }
1968        ";
1969        let codebase = create_test_codebase(code);
1970
1971        let reference = TReference::new_member(ascii_lowercase_word(b"status"), TReferenceMemberSelector::Wildcard);
1972        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1973
1974        let mut actual = input;
1975        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1976
1977        assert_eq!(actual.types.len(), 2);
1978        assert!(actual.types.iter().all(|t| matches!(t, TAtomic::Object(TObject::Enum(_)))));
1979    }
1980
1981    #[test]
1982    fn test_expand_member_reference_starts_with() {
1983        let code = "<?php
1984            class Foo {
1985                public const STATUS_ACTIVE = 1;
1986                public const STATUS_INACTIVE = 2;
1987                public const OTHER = 3;
1988            }
1989        ";
1990        let codebase = create_test_codebase(code);
1991
1992        let reference =
1993            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::StartsWith(word("STATUS_")));
1994        let input = TUnion::from_atomic(TAtomic::Reference(reference));
1995
1996        let mut actual = input;
1997        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
1998
1999        assert!(!actual.types.is_empty());
2000    }
2001
2002    #[test]
2003    fn test_expand_member_reference_ends_with() {
2004        let code = "<?php
2005            class Foo {
2006                public const READ_ERROR = 1;
2007                public const WRITE_ERROR = 2;
2008                public const SUCCESS = 0;
2009            }
2010        ";
2011        let codebase = create_test_codebase(code);
2012
2013        let reference =
2014            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::EndsWith(word("_ERROR")));
2015        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2016
2017        let mut actual = input;
2018        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2019
2020        assert!(!actual.types.is_empty());
2021    }
2022
2023    #[test]
2024    fn test_expand_member_reference_identifier_constant() {
2025        let code = "<?php
2026            class Foo {
2027                public const BAR = 42;
2028            }
2029        ";
2030        let codebase = create_test_codebase(code);
2031
2032        let reference =
2033            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("BAR")));
2034        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2035
2036        let mut actual = input;
2037        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2038
2039        assert_eq!(actual.types.len(), 1);
2040    }
2041
2042    #[test]
2043    fn test_expand_member_reference_identifier_enum_case() {
2044        let code = "<?php
2045            enum Status {
2046                case Active;
2047            }
2048        ";
2049        let codebase = create_test_codebase(code);
2050
2051        let reference = TReference::new_member(
2052            ascii_lowercase_word(b"status"),
2053            TReferenceMemberSelector::Identifier(word("Active")),
2054        );
2055        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2056
2057        let mut actual = input;
2058        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2059
2060        assert_eq!(actual.types.len(), 1);
2061        assert!(matches!(&actual.types[0], TAtomic::Object(TObject::Enum(_))));
2062    }
2063
2064    #[test]
2065    fn test_expand_member_reference_unknown_class() {
2066        let codebase = CodebaseMetadata::new();
2067
2068        let reference = TReference::new_member(word("NonExistent"), TReferenceMemberSelector::Identifier(word("FOO")));
2069        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2070
2071        let mut actual = input;
2072        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2073
2074        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2075    }
2076
2077    #[test]
2078    fn test_expand_member_reference_unknown_member() {
2079        let code = "<?php class Foo {}";
2080        let codebase = create_test_codebase(code);
2081
2082        let reference = TReference::new_member(
2083            ascii_lowercase_word(b"foo"),
2084            TReferenceMemberSelector::Identifier(word("NONEXISTENT")),
2085        );
2086        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2087
2088        let mut actual = input;
2089        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2090
2091        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2092    }
2093
2094    #[test]
2095    fn test_expand_member_reference_constant_with_inferred_type() {
2096        let code = r#"<?php
2097            class Foo {
2098                public const VALUE = "hello";
2099            }
2100        "#;
2101        let codebase = create_test_codebase(code);
2102
2103        let reference =
2104            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("VALUE")));
2105        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2106
2107        let mut actual = input;
2108        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2109
2110        assert_eq!(actual.types.len(), 1);
2111    }
2112
2113    #[test]
2114    fn test_expand_member_reference_constant_with_type_metadata() {
2115        let code = "<?php
2116            class Foo {
2117                /** @var int */
2118                public const VALUE = 42;
2119            }
2120        ";
2121        let codebase = create_test_codebase(code);
2122
2123        let reference =
2124            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("VALUE")));
2125        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2126
2127        let mut actual = input;
2128        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2129
2130        assert_eq!(actual.types.len(), 1);
2131    }
2132
2133    #[test]
2134    fn test_expand_conditional_both_branches() {
2135        let code = "<?php class Foo {} class Bar {}";
2136        let codebase = create_test_codebase(code);
2137
2138        let conditional = TConditional::new(
2139            Arc::new(get_mixed()),
2140            Arc::new(get_string()),
2141            Arc::new(make_self_object()),
2142            Arc::new(make_self_object()),
2143            false,
2144        );
2145        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2146
2147        let options = options_with_self("Foo");
2148        let mut actual = input;
2149        expand_union(&codebase, &mut actual, &options);
2150
2151        assert!(actual.types.iter().any(|t| {
2152            if let TAtomic::Object(TObject::Named(named)) = t {
2153                named.name == ascii_lowercase_word(b"foo")
2154            } else {
2155                false
2156            }
2157        }));
2158    }
2159
2160    #[test]
2161    fn test_expand_conditional_with_self_in_then() {
2162        let code = "<?php class Foo {}";
2163        let codebase = create_test_codebase(code);
2164
2165        let conditional = TConditional::new(
2166            Arc::new(get_mixed()),
2167            Arc::new(get_string()),
2168            Arc::new(make_self_object()),
2169            Arc::new(get_int()),
2170            false,
2171        );
2172        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2173
2174        let options = options_with_self("Foo");
2175        let mut actual = input;
2176        expand_union(&codebase, &mut actual, &options);
2177
2178        assert!(!actual.types.is_empty());
2179    }
2180
2181    #[test]
2182    fn test_expand_conditional_with_self_in_otherwise() {
2183        let code = "<?php class Foo {}";
2184        let codebase = create_test_codebase(code);
2185
2186        let conditional = TConditional::new(
2187            Arc::new(get_mixed()),
2188            Arc::new(get_string()),
2189            Arc::new(get_int()),
2190            Arc::new(make_self_object()),
2191            false,
2192        );
2193        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2194
2195        let options = options_with_self("Foo");
2196        let mut actual = input;
2197        expand_union(&codebase, &mut actual, &options);
2198
2199        assert!(!actual.types.is_empty());
2200    }
2201
2202    #[test]
2203    fn test_expand_simple_alias() {
2204        let code = "<?php
2205            class Foo {
2206                /** @phpstan-type MyInt = int */
2207            }
2208        ";
2209        let codebase = create_test_codebase(code);
2210
2211        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("MyInt"));
2212        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2213
2214        let mut actual = input;
2215        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2216
2217        assert!(!actual.types.is_empty());
2218    }
2219
2220    #[test]
2221    fn test_expand_nested_alias() {
2222        let code = "<?php
2223            class Foo {
2224                /** @phpstan-type Inner = int */
2225                /** @phpstan-type Outer = Inner */
2226            }
2227        ";
2228        let codebase = create_test_codebase(code);
2229
2230        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("Outer"));
2231        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2232
2233        let mut actual = input;
2234        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2235
2236        assert!(!actual.types.is_empty());
2237    }
2238
2239    #[test]
2240    fn test_expand_alias_cycle_detection() {
2241        let code = "<?php
2242            /** @phpstan-type SelfRef = int|array<int, SelfRef> */
2243            class Foo {}
2244        ";
2245        let codebase = create_test_codebase(code);
2246
2247        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("SelfRef"));
2248        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2249
2250        let mut actual = input;
2251        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2252
2253        assert!(!actual.types.is_empty());
2254    }
2255
2256    #[test]
2257    fn test_expand_alias_unknown() {
2258        let codebase = CodebaseMetadata::new();
2259
2260        let alias = TAlias::new(word("NonExistent"), word("Unknown"));
2261        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2262
2263        let mut actual = input;
2264        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2265
2266        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Alias(_))));
2267    }
2268
2269    #[test]
2270    fn test_expand_alias_with_self_inside() {
2271        let code = "<?php
2272            class Foo {
2273                /** @phpstan-type MySelf = self */
2274            }
2275        ";
2276        let codebase = create_test_codebase(code);
2277
2278        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("MySelf"));
2279        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2280
2281        let options = options_with_self("Foo");
2282        let mut actual = input;
2283        expand_union(&codebase, &mut actual, &options);
2284
2285        assert!(!actual.types.is_empty());
2286    }
2287
2288    #[test]
2289    fn test_expand_key_of_array() {
2290        let codebase = CodebaseMetadata::new();
2291
2292        let mut keyed = TKeyedArray::new();
2293        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2294        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2295
2296        let key_of = TKeyOf::new(Arc::new(array_type));
2297        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2298
2299        let mut actual = input;
2300        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2301
2302        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_string));
2303    }
2304
2305    #[test]
2306    fn test_expand_key_of_with_self() {
2307        let code = "<?php class Foo {}";
2308        let codebase = create_test_codebase(code);
2309
2310        let mut keyed = TKeyedArray::new();
2311        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
2312        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2313
2314        let key_of = TKeyOf::new(Arc::new(array_type));
2315        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2316
2317        let options = options_with_self("Foo");
2318        let mut actual = input;
2319        expand_union(&codebase, &mut actual, &options);
2320
2321        assert!(!actual.types.is_empty());
2322    }
2323
2324    #[test]
2325    fn test_expand_value_of_array() {
2326        let codebase = CodebaseMetadata::new();
2327
2328        let mut keyed = TKeyedArray::new();
2329        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2330        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2331
2332        let value_of = TValueOf::new(Arc::new(array_type));
2333        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2334
2335        let mut actual = input;
2336        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2337
2338        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_int));
2339    }
2340
2341    #[test]
2342    fn test_expand_value_of_enum() {
2343        let code = "<?php
2344            enum Status: string {
2345                case Active = 'active';
2346                case Inactive = 'inactive';
2347            }
2348        ";
2349        let codebase = create_test_codebase(code);
2350
2351        let enum_type =
2352            TUnion::from_atomic(TAtomic::Object(TObject::Enum(TEnum::new(ascii_lowercase_word(b"status")))));
2353
2354        let value_of = TValueOf::new(Arc::new(enum_type));
2355        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2356
2357        let mut actual = input;
2358        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2359
2360        assert!(!actual.types.is_empty());
2361    }
2362
2363    #[test]
2364    fn test_expand_index_access() {
2365        let codebase = CodebaseMetadata::new();
2366
2367        use crate::ttype::atomic::array::key::ArrayKey;
2368        use std::collections::BTreeMap;
2369
2370        let mut keyed = TKeyedArray::new();
2371        let mut known_items = BTreeMap::new();
2372        known_items.insert(ArrayKey::String(word("key")), (false, get_int()));
2373        keyed.known_items = Some(known_items);
2374        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2375
2376        use crate::ttype::get_literal_string;
2377        let index_type = get_literal_string(word("key"));
2378
2379        let index_access = TIndexAccess::new(array_type, index_type);
2380        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2381
2382        let mut actual = input;
2383        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2384
2385        assert!(!actual.types.is_empty());
2386    }
2387
2388    #[test]
2389    fn test_expand_index_access_with_self() {
2390        let code = "<?php class Foo {}";
2391        let codebase = create_test_codebase(code);
2392
2393        use crate::ttype::atomic::array::key::ArrayKey;
2394        use std::collections::BTreeMap;
2395
2396        let mut keyed = TKeyedArray::new();
2397        let mut known_items = BTreeMap::new();
2398        known_items.insert(ArrayKey::String(word("key")), (false, make_self_object()));
2399        keyed.known_items = Some(known_items);
2400        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2401
2402        use crate::ttype::get_literal_string;
2403        let index_type = get_literal_string(word("key"));
2404
2405        let index_access = TIndexAccess::new(array_type, index_type);
2406        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2407
2408        let options = options_with_self("Foo");
2409        let mut actual = input;
2410        expand_union(&codebase, &mut actual, &options);
2411
2412        assert!(!actual.types.is_empty());
2413    }
2414
2415    #[test]
2416    fn test_expand_iterable_key_type() {
2417        let code = "<?php class Foo {}";
2418        let codebase = create_test_codebase(code);
2419
2420        let iterable = TIterable::new(Arc::new(make_self_object()), Arc::new(get_int()));
2421        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2422
2423        let options = options_with_self("Foo");
2424        let mut actual = input;
2425        expand_union(&codebase, &mut actual, &options);
2426
2427        if let TAtomic::Iterable(iter) = &actual.types[0] {
2428            assert!(iter.get_key_type().types.iter().any(|t| {
2429                if let TAtomic::Object(TObject::Named(named)) = t {
2430                    named.name == ascii_lowercase_word(b"foo")
2431                } else {
2432                    false
2433                }
2434            }));
2435        }
2436    }
2437
2438    #[test]
2439    fn test_expand_iterable_value_type() {
2440        let code = "<?php class Foo {}";
2441        let codebase = create_test_codebase(code);
2442
2443        let iterable = TIterable::new(Arc::new(get_int()), Arc::new(make_self_object()));
2444        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2445
2446        let options = options_with_self("Foo");
2447        let mut actual = input;
2448        expand_union(&codebase, &mut actual, &options);
2449
2450        if let TAtomic::Iterable(iter) = &actual.types[0] {
2451            assert!(iter.get_value_type().types.iter().any(|t| {
2452                if let TAtomic::Object(TObject::Named(named)) = t {
2453                    named.name == ascii_lowercase_word(b"foo")
2454                } else {
2455                    false
2456                }
2457            }));
2458        }
2459    }
2460
2461    #[test]
2462    fn test_get_signature_of_function() {
2463        let code = r#"<?php
2464            function myFunc(int $a): string { return ""; }
2465        "#;
2466        let codebase = create_test_codebase(code);
2467
2468        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc"));
2469
2470        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2471        assert!(sig.is_some());
2472
2473        let sig = sig.unwrap();
2474        assert_eq!(sig.get_parameters().len(), 1);
2475        assert!(sig.get_return_type().is_some());
2476    }
2477
2478    #[test]
2479    fn test_get_signature_of_method() {
2480        let code = "<?php
2481            class Foo {
2482                public function bar(string $s): int { return 0; }
2483            }
2484        ";
2485        let codebase = create_test_codebase(code);
2486
2487        let id = FunctionLikeIdentifier::Method(ascii_lowercase_word(b"foo"), ascii_lowercase_word(b"bar"));
2488
2489        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2490        assert!(sig.is_some());
2491
2492        let sig = sig.unwrap();
2493        assert_eq!(sig.get_parameters().len(), 1);
2494    }
2495
2496    #[test]
2497    fn test_get_signature_of_closure() {
2498        let codebase = CodebaseMetadata::new();
2499
2500        let id = FunctionLikeIdentifier::Closure(word(b"{closure:test.php:1:1}"));
2501        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2502
2503        assert!(sig.is_none());
2504    }
2505
2506    #[test]
2507    fn test_get_atomic_of_function() {
2508        let code = "<?php
2509            function myFunc(): void {}
2510        ";
2511        let codebase = create_test_codebase(code);
2512
2513        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc"));
2514
2515        let atomic = get_atomic_of_function_like_identifier(&id, &codebase);
2516        assert!(atomic.is_some());
2517        assert!(matches!(atomic.unwrap(), TAtomic::Callable(TCallable::Signature(_))));
2518    }
2519
2520    #[test]
2521    fn test_get_signature_with_parameters() {
2522        let code = "<?php
2523            function multiParam(int $a, string $b, ?float $c = null): bool { return true; }
2524        ";
2525        let codebase = create_test_codebase(code);
2526
2527        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"multiparam"));
2528
2529        let sig = get_signature_of_function_like_identifier(&id, &codebase);
2530        assert!(sig.is_some());
2531
2532        let sig = sig.unwrap();
2533        assert_eq!(sig.get_parameters().len(), 3);
2534
2535        let third_param = &sig.get_parameters()[2];
2536        assert!(third_param.has_default());
2537    }
2538
2539    #[test]
2540    fn test_expand_preserves_by_reference_flag() {
2541        let code = "<?php class Foo {}";
2542        let codebase = create_test_codebase(code);
2543
2544        let mut input = make_self_object();
2545        input.flags.insert(UnionFlags::BY_REFERENCE);
2546
2547        let options = options_with_self("Foo");
2548        let mut actual = input.clone();
2549        expand_union(&codebase, &mut actual, &options);
2550
2551        assert!(actual.flags.contains(UnionFlags::BY_REFERENCE));
2552    }
2553
2554    #[test]
2555    fn test_expand_preserves_possibly_undefined_flag() {
2556        let code = "<?php class Foo {}";
2557        let codebase = create_test_codebase(code);
2558
2559        let mut input = make_self_object();
2560        input.flags.insert(UnionFlags::POSSIBLY_UNDEFINED);
2561
2562        let options = options_with_self("Foo");
2563        let mut actual = input.clone();
2564        expand_union(&codebase, &mut actual, &options);
2565
2566        assert!(actual.flags.contains(UnionFlags::POSSIBLY_UNDEFINED));
2567    }
2568
2569    #[test]
2570    fn test_expand_multiple_self_in_union() {
2571        let code = "<?php class Foo {}";
2572        let codebase = create_test_codebase(code);
2573
2574        let input = TUnion::from_vec(vec![
2575            TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))),
2576            TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))),
2577        ]);
2578
2579        let options = options_with_self("Foo");
2580        let mut actual = input;
2581        expand_union(&codebase, &mut actual, &options);
2582
2583        assert!(actual.types.len() <= 2);
2584    }
2585
2586    #[test]
2587    fn test_expand_deeply_nested_types() {
2588        let code = "<?php class Foo {}";
2589        let codebase = create_test_codebase(code);
2590
2591        let inner = TList::new(Arc::new(make_self_object()));
2592        let middle = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(inner)))));
2593        let outer = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(middle)))));
2594        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(outer)));
2595
2596        let options = options_with_self("Foo");
2597        let mut actual = input;
2598        expand_union(&codebase, &mut actual, &options);
2599
2600        if let TAtomic::Array(TArray::List(outer)) = &actual.types[0]
2601            && let TAtomic::Array(TArray::List(middle)) = &outer.element_type.types[0]
2602            && let TAtomic::Array(TArray::List(inner)) = &middle.element_type.types[0]
2603        {
2604            assert!(inner.element_type.types.iter().any(|t| {
2605                if let TAtomic::Object(TObject::Named(named)) = t {
2606                    named.name == ascii_lowercase_word(b"foo")
2607                } else {
2608                    false
2609                }
2610            }));
2611        }
2612    }
2613
2614    #[test]
2615    fn test_expand_with_all_options_disabled() {
2616        let code = "<?php class Foo {}";
2617        let codebase = create_test_codebase(code);
2618
2619        let input = make_self_object();
2620        let options = TypeExpansionOptions {
2621            self_class: None,
2622            static_class_type: StaticClassType::None,
2623            parent_class: None,
2624            evaluate_class_constants: false,
2625            evaluate_conditional_types: false,
2626            function_is_final: false,
2627            expand_generic: false,
2628            expand_templates: false,
2629        };
2630
2631        let mut actual = input;
2632        expand_union(&codebase, &mut actual, &options);
2633
2634        assert!(actual.types.iter().any(|t| {
2635            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("self") } else { false }
2636        }));
2637    }
2638
2639    #[test]
2640    fn test_expand_already_expanded_type() {
2641        let code = "<?php class Foo {}";
2642        let codebase = create_test_codebase(code);
2643
2644        let input = make_named_object("Foo");
2645        let options = options_with_self("Foo");
2646
2647        let mut actual = input;
2648        expand_union(&codebase, &mut actual, &options);
2649
2650        let mut actual2 = actual.clone();
2651        expand_union(&codebase, &mut actual2, &options);
2652
2653        assert_eq!(actual.types.as_ref(), actual2.types.as_ref());
2654    }
2655
2656    #[test]
2657    fn test_expand_complex_generic_class() {
2658        let code = "<?php
2659            /**
2660             * @template T
2661             * @template U
2662             */
2663            class Container {}
2664        ";
2665        let codebase = create_test_codebase(code);
2666
2667        let named = TNamedObject::new_with_type_parameters(
2668            ascii_lowercase_word(b"container"),
2669            Some(vec![make_self_object(), make_static_object()]),
2670        );
2671        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
2672
2673        let options = TypeExpansionOptions {
2674            self_class: Some(ascii_lowercase_word(b"foo")),
2675            static_class_type: StaticClassType::Name(ascii_lowercase_word(b"bar")),
2676            ..Default::default()
2677        };
2678
2679        let mut actual = input;
2680        expand_union(&codebase, &mut actual, &options);
2681
2682        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
2683            && let Some(params) = &named.type_parameters
2684        {
2685            assert!(params[0].types.iter().any(|t| {
2686                if let TAtomic::Object(TObject::Named(named)) = t {
2687                    named.name == ascii_lowercase_word(b"foo")
2688                } else {
2689                    false
2690                }
2691            }));
2692            assert!(params[1].types.iter().any(|t| {
2693                if let TAtomic::Object(TObject::Named(named)) = t {
2694                    named.name == ascii_lowercase_word(b"bar")
2695                } else {
2696                    false
2697                }
2698            }));
2699        }
2700    }
2701}