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;
8
9use mago_word::Word;
10use mago_word::empty_word;
11
12use crate::identifier::function_like::FunctionLikeIdentifier;
13use crate::identifier::method::MethodIdentifier;
14use crate::metadata::CodebaseMetadata;
15use crate::metadata::class_like::ClassLikeMetadata;
16use crate::metadata::function_like::FunctionLikeMetadata;
17use crate::ttype::TType;
18use crate::ttype::TypeRef;
19use crate::ttype::atomic::TAtomic;
20use crate::ttype::atomic::alias::TAlias;
21use crate::ttype::atomic::array::TArray;
22use crate::ttype::atomic::array::key::ArrayKey;
23use crate::ttype::atomic::callable::TCallable;
24use crate::ttype::atomic::callable::TCallableSignature;
25use crate::ttype::atomic::callable::parameter::TCallableParameter;
26use crate::ttype::atomic::derived::TDerived;
27use crate::ttype::atomic::derived::index_access::TIndexAccess;
28use crate::ttype::atomic::derived::int_mask::TIntMask;
29use crate::ttype::atomic::derived::int_mask_of::TIntMaskOf;
30use crate::ttype::atomic::derived::intersection::TDerivedIntersection;
31use crate::ttype::atomic::derived::key_of::TKeyOf;
32use crate::ttype::atomic::derived::new::TNew;
33use crate::ttype::atomic::derived::properties_of::TPropertiesOf;
34use crate::ttype::atomic::derived::template_type::TTemplateType;
35use crate::ttype::atomic::derived::value_of::TValueOf;
36use crate::ttype::atomic::generic::TGenericParameter;
37use crate::ttype::atomic::mixed::TMixed;
38use crate::ttype::atomic::object::TObject;
39use crate::ttype::atomic::object::named::TNamedObject;
40use crate::ttype::atomic::reference::TGlobalReferenceSelector;
41use crate::ttype::atomic::reference::TReference;
42use crate::ttype::atomic::reference::TReferenceMemberSelector;
43use crate::ttype::atomic::scalar::TScalar;
44use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
45use crate::ttype::atomic::scalar::int::TInteger;
46use crate::ttype::atomic::scalar::string::TString;
47use crate::ttype::atomic::scalar::string::TStringLiteral;
48use crate::ttype::combiner;
49use crate::ttype::union::TUnion;
50
51thread_local! {
52    /// Thread-local set for tracking currently expanding aliases (cycle detection).
53    /// Uses a HashSet for accurate tracking without false positives from hash collisions.
54    pub(crate) static EXPANDING_ALIASES: RefCell<HashSet<(Word, Word), FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
55
56    /// Thread-local set for tracking objects whose type parameters are being expanded (cycle detection).
57    static EXPANDING_OBJECT_PARAMS: RefCell<HashSet<Word, FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
58
59    /// Thread-local set for tracking class constants whose inferred initializer is currently
60    /// being expanded. Used to break cycles like `const int b = self::b;` where the inferred
61    /// type of a constant is a reference to itself.
62    static EXPANDING_CONSTANTS: RefCell<HashSet<(Word, Word), FixedState>> = const { RefCell::new(HashSet::with_hasher(FixedState::with_seed(0))) };
63}
64
65/// RAII guard to ensure alias expansion state is properly cleaned up.
66/// This guarantees the alias is removed from the set even if the expansion panics.
67pub(crate) struct AliasExpansionGuard {
68    class_name: Word,
69    alias_name: Word,
70}
71
72impl AliasExpansionGuard {
73    #[must_use]
74    pub(crate) fn new(class_name: Word, alias_name: Word) -> Self {
75        EXPANDING_ALIASES.with(|set| set.borrow_mut().insert((class_name, alias_name)));
76        Self { class_name, alias_name }
77    }
78}
79
80impl Drop for AliasExpansionGuard {
81    fn drop(&mut self) {
82        EXPANDING_ALIASES.with(|set| set.borrow_mut().remove(&(self.class_name, self.alias_name)));
83    }
84}
85
86/// RAII guard for object type parameter expansion cycle detection.
87struct ObjectParamsExpansionGuard {
88    object_name: Word,
89}
90
91impl ObjectParamsExpansionGuard {
92    #[must_use]
93    fn try_new(object_name: Word) -> Option<Self> {
94        EXPANDING_OBJECT_PARAMS.with(|set| {
95            let mut set = set.borrow_mut();
96            if set.contains(&object_name) {
97                None
98            } else {
99                set.insert(object_name);
100                Some(Self { object_name })
101            }
102        })
103    }
104}
105
106impl Drop for ObjectParamsExpansionGuard {
107    fn drop(&mut self) {
108        EXPANDING_OBJECT_PARAMS.with(|set| set.borrow_mut().remove(&self.object_name));
109    }
110}
111
112/// RAII guard for class constant inferred-initializer expansion cycle detection.
113///
114/// A constant whose initializer references itself (directly via `self::FOO` or
115/// transitively via another constant) would otherwise drive `expand_member_reference`
116/// into infinite recursion. The guard tracks `(class_name, constant_name)` pairs that
117/// are currently being expanded and refuses re-entry.
118struct ConstantExpansionGuard {
119    class_name: Word,
120    constant_name: Word,
121}
122
123impl ConstantExpansionGuard {
124    #[must_use]
125    fn try_new(class_name: Word, constant_name: Word) -> Option<Self> {
126        EXPANDING_CONSTANTS.with(|set| {
127            let mut set = set.borrow_mut();
128            if set.contains(&(class_name, constant_name)) {
129                None
130            } else {
131                set.insert((class_name, constant_name));
132                Some(Self { class_name, constant_name })
133            }
134        })
135    }
136}
137
138impl Drop for ConstantExpansionGuard {
139    fn drop(&mut self) {
140        EXPANDING_CONSTANTS.with(|set| set.borrow_mut().remove(&(self.class_name, self.constant_name)));
141    }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
145pub enum StaticClassType {
146    #[default]
147    None,
148    /// The late-static type is bound to this exact class at the call site.
149    Exact(Word),
150    /// The class is known, but late-static identity must be preserved.
151    Name(Word),
152    /// The late-static type is bound to a potentially specialized object.
153    Object(TObject),
154    Generic(TGenericParameter),
155}
156
157#[derive(Debug, Clone, Default)]
158pub struct TypeExpansionOptions {
159    pub self_class: Option<Word>,
160    pub static_class_type: StaticClassType,
161    pub function_is_final: bool,
162    /// True when expanding the return type of a method resolved through `@mixin`:
163    /// a pre-bound `static` that reaches the receiver through mixin tags rebinds
164    /// to the receiver. Elsewhere the mixin relationship between two class names
165    /// says nothing about how a value was obtained, so no rebinding happens.
166    pub allow_mixin_static_rebind: bool,
167    /// Keep operators that depend on call arguments while binding their class-relative types.
168    pub preserve_parameter_dependencies: bool,
169}
170
171/// Expands a type union, resolving special types like `self`, `static`, `parent`,
172/// type aliases, class constants, and generic type parameters.
173pub fn expand_union(codebase: &CodebaseMetadata, return_type: &mut TUnion, options: &TypeExpansionOptions) {
174    if !return_type.is_expandable() {
175        return;
176    }
177
178    expand_union_inner(codebase, return_type, options);
179}
180
181fn expand_shared_union(codebase: &CodebaseMetadata, return_type: &mut Arc<TUnion>, options: &TypeExpansionOptions) {
182    if return_type.is_expandable() {
183        expand_union_inner(codebase, Arc::make_mut(return_type), options);
184    }
185}
186
187fn expand_union_inner(codebase: &CodebaseMetadata, return_type: &mut TUnion, options: &TypeExpansionOptions) {
188    let mut types = std::mem::take(&mut return_type.types).into_owned();
189    let mut new_return_type_parts: Vec<TAtomic> = Vec::new();
190    let mut has_skipped = false;
191
192    types.retain_mut(|return_type_part| {
193        let mut skip_key = false;
194        expand_atomic(return_type_part, codebase, options, &mut skip_key, &mut new_return_type_parts);
195
196        if skip_key {
197            has_skipped = true;
198            false
199        } else {
200            true
201        }
202    });
203
204    if has_skipped {
205        new_return_type_parts.append(&mut types);
206
207        if new_return_type_parts.is_empty() {
208            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
209        }
210
211        types = if new_return_type_parts.len() > 1 {
212            combiner::combine(new_return_type_parts, codebase, combiner::CombinerOptions::default())
213        } else {
214            new_return_type_parts
215        };
216    } else if types.len() > 1 {
217        types = combiner::combine(types, codebase, combiner::CombinerOptions::default());
218    }
219
220    return_type.types = Cow::Owned(types);
221}
222
223pub(crate) fn expand_atomic(
224    return_type_part: &mut TAtomic,
225    codebase: &CodebaseMetadata,
226    options: &TypeExpansionOptions,
227    skip_key: &mut bool,
228    new_return_type_parts: &mut Vec<TAtomic>,
229) {
230    match return_type_part {
231        TAtomic::Array(array_type) => match array_type {
232            TArray::Keyed(keyed_data) => {
233                if let Some((key_parameter, value_parameter)) = &mut keyed_data.parameters {
234                    expand_shared_union(codebase, key_parameter, options);
235                    expand_shared_union(codebase, value_parameter, options);
236                }
237
238                if let Some(known_items) = keyed_data.known_items.as_mut().map(Arc::make_mut) {
239                    // Check if any keys need resolution
240                    let needs_key_resolution = known_items.keys().any(|k| k.is_class_like_constant());
241
242                    if needs_key_resolution {
243                        let old_items = std::mem::take(known_items);
244                        for (key, (is_optional, mut value_type)) in old_items {
245                            expand_union(codebase, &mut value_type, options);
246                            let resolved_key = resolve_array_key(key, codebase, options);
247                            known_items.insert(resolved_key, (is_optional, value_type));
248                        }
249                    } else {
250                        for (_, item_type) in known_items.values_mut() {
251                            expand_union(codebase, item_type, options);
252                        }
253                    }
254                }
255            }
256            TArray::List(list_data) => {
257                expand_shared_union(codebase, &mut list_data.element_type, options);
258
259                if let Some(known_elements) = list_data.known_elements.as_mut().map(Arc::make_mut) {
260                    for (_, element_type) in known_elements.values_mut() {
261                        expand_union(codebase, element_type, options);
262                    }
263                }
264            }
265        },
266        TAtomic::Object(object) => {
267            if let Some(parameter) = resolve_generic_static_type(object, codebase, options) {
268                *skip_key = true;
269                new_return_type_parts.push(TAtomic::GenericParameter(parameter));
270            } else {
271                expand_object(object, codebase, options);
272            }
273        }
274        TAtomic::Callable(TCallable::Signature(signature)) => {
275            if let Some(return_type) = &mut signature.return_type {
276                expand_shared_union(codebase, return_type, options);
277            }
278
279            for param in signature.get_parameters_mut() {
280                if param.get_type_signature().is_some_and(TType::is_expandable)
281                    && let Some(param_type) = param.get_type_signature_mut()
282                {
283                    expand_union_inner(codebase, param_type, options);
284                }
285
286                if let Some(out_type) = param.get_out_type_mut() {
287                    expand_union(codebase, out_type, options);
288                }
289
290                if let Some(closure_this_type) = param.get_closure_this_type_mut() {
291                    expand_union(codebase, closure_this_type, options);
292                }
293            }
294
295            for constraint in Arc::make_mut(&mut signature.constraints).iter_mut() {
296                expand_shared_union(codebase, &mut constraint.input_type, options);
297                if options.preserve_parameter_dependencies
298                    || !contains_parameter_variable(constraint.parameter_type.as_ref())
299                {
300                    expand_shared_union(codebase, &mut constraint.parameter_type, options);
301                }
302            }
303        }
304        TAtomic::GenericParameter(parameter) => {
305            expand_shared_union(codebase, &mut parameter.constraint, options);
306        }
307        TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) => {
308            let mut atomic_return_type_parts = vec![];
309            expand_atomic(Arc::make_mut(constraint), codebase, options, &mut false, &mut atomic_return_type_parts);
310
311            if !atomic_return_type_parts.is_empty() {
312                *Arc::make_mut(constraint) = atomic_return_type_parts.remove(0);
313            }
314        }
315        TAtomic::Reference(TReference::Member { class_like_name, member_selector }) => {
316            *skip_key = true;
317            expand_member_reference(*class_like_name, member_selector, codebase, options, new_return_type_parts);
318        }
319        TAtomic::Reference(TReference::Global { selector }) => {
320            *skip_key = true;
321            expand_global_reference(selector, codebase, options, new_return_type_parts);
322        }
323        TAtomic::Callable(TCallable::Alias(id)) => {
324            if let Some(value) = get_atomic_of_function_like_identifier(id, codebase) {
325                *skip_key = true;
326                new_return_type_parts.push(value);
327            }
328        }
329        TAtomic::Conditional(conditional) => {
330            if options.preserve_parameter_dependencies && contains_parameter_variable(conditional) {
331                expand_shared_union(codebase, &mut conditional.subject, options);
332                expand_shared_union(codebase, &mut conditional.target, options);
333                expand_shared_union(codebase, &mut conditional.then, options);
334                expand_shared_union(codebase, &mut conditional.otherwise, options);
335                return;
336            }
337
338            *skip_key = true;
339
340            let mut then = (*conditional.then).clone();
341            let mut otherwise = (*conditional.otherwise).clone();
342
343            expand_union(codebase, &mut then, options);
344            expand_union(codebase, &mut otherwise, options);
345
346            new_return_type_parts.extend(then.types.into_owned());
347            new_return_type_parts.extend(otherwise.types.into_owned());
348        }
349        TAtomic::Alias(alias) => {
350            *skip_key = true;
351            new_return_type_parts.extend(expand_alias(alias, codebase, options));
352        }
353        TAtomic::Derived(derived) => {
354            if options.preserve_parameter_dependencies && contains_parameter_variable(derived) {
355                expand_deferred_derived(derived, codebase, options);
356                return;
357            }
358
359            *skip_key = true;
360            new_return_type_parts.extend(match derived {
361                TDerived::KeyOf(key_of) => expand_key_of(key_of, codebase, options),
362                TDerived::ValueOf(value_of) => expand_value_of(value_of, codebase, options),
363                TDerived::IndexAccess(index_access) => expand_index_access(index_access, codebase, options),
364                TDerived::IntMask(int_mask) => expand_int_mask(int_mask, codebase, options),
365                TDerived::IntMaskOf(int_mask_of) => expand_int_mask_of(int_mask_of, codebase, options),
366                TDerived::PropertiesOf(properties_of) => expand_properties_of(properties_of, codebase, options),
367                TDerived::New(new_type) => expand_new(new_type, codebase, options),
368                TDerived::TemplateType(template_type) => expand_template_type(template_type, codebase, options),
369                TDerived::Intersection(intersection) => expand_derived_intersection(intersection, codebase, options),
370            });
371        }
372        TAtomic::Iterable(iterable) => {
373            expand_shared_union(codebase, &mut iterable.key_type, options);
374            expand_shared_union(codebase, &mut iterable.value_type, options);
375        }
376        _ => {}
377    }
378}
379
380fn expand_deferred_derived(derived: &mut TDerived, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) {
381    if let Some(target) = derived.get_target_type_mut() {
382        expand_union(codebase, target, options);
383    }
384
385    match derived {
386        TDerived::IndexAccess(access) => expand_union(codebase, access.get_index_type_mut(), options),
387        TDerived::IntMask(mask) => {
388            for value in mask.get_values_mut() {
389                expand_union(codebase, value, options);
390            }
391        }
392        TDerived::TemplateType(template) => {
393            expand_union(codebase, template.get_object_mut(), options);
394            expand_union(codebase, template.get_class_name_mut(), options);
395            expand_union(codebase, template.get_template_name_mut(), options);
396        }
397        TDerived::Intersection(intersection) => {
398            if let Some(types) = intersection.get_intersection_types_mut() {
399                for ty in types {
400                    let mut expanded = TUnion::from_atomic(ty.clone());
401                    expand_union(codebase, &mut expanded, options);
402                    if expanded.types.len() == 1 {
403                        *ty = expanded.types.into_owned().remove(0);
404                    }
405                }
406            }
407        }
408        _ => {}
409    }
410}
411
412fn expand_derived_intersection(
413    intersection: &TDerivedIntersection,
414    codebase: &CodebaseMetadata,
415    options: &TypeExpansionOptions,
416) -> Vec<TAtomic> {
417    let mut base_type = intersection.get_base_type().clone();
418    expand_union(codebase, &mut base_type, options);
419    let mut results = base_type.types.into_owned();
420
421    for intersection_type in intersection.get_intersection_types().unwrap_or_default() {
422        let mut expanded_intersection = TUnion::from_atomic(intersection_type.clone());
423        expand_union(codebase, &mut expanded_intersection, options);
424
425        let mut next_results = Vec::with_capacity(results.len() * expanded_intersection.types.len());
426        for base in results {
427            for additional in expanded_intersection.types.as_ref() {
428                if let Some(string) = base.intersect_strings(additional) {
429                    next_results.push(string);
430                    continue;
431                }
432
433                let mut result = base.clone();
434                if !result.add_intersection_type(additional.clone()) {
435                    return vec![TAtomic::Derived(TDerived::Intersection(intersection.clone()))];
436                }
437                next_results.push(result);
438            }
439        }
440        results = next_results;
441    }
442
443    results
444}
445
446/// Resolves a `ClassLikeConstant` array key to its concrete `Integer` or `String` value.
447///
448/// Looks up the class constant or enum case in the codebase metadata and returns:
449/// - `ArrayKey::Integer(value)` if the constant resolves to a literal integer
450/// - `ArrayKey::String(value)` if the constant resolves to a literal string
451/// - The original key unchanged if it cannot be resolved
452fn resolve_array_key(key: ArrayKey, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> ArrayKey {
453    let ArrayKey::ClassLikeConstant { class_like_name, constant_name } = key else {
454        return key;
455    };
456
457    // Resolve self/static/this/parent to the actual class name
458    let resolved_class_name = {
459        let name_lc = class_like_name.to_ascii_lowercase();
460        match name_lc.as_bytes() {
461            b"self" => options.self_class.unwrap_or(class_like_name),
462            b"static" | b"$this" => {
463                if let StaticClassType::Exact(name) | StaticClassType::Name(name) = &options.static_class_type {
464                    *name
465                } else {
466                    options.self_class.unwrap_or(class_like_name)
467                }
468            }
469            b"parent" => {
470                if let Some(self_class) = options.self_class
471                    && let Some(class_metadata) = codebase.get_class_like_by_name(self_class)
472                    && let Some(parent) = class_metadata.direct_parent_class
473                {
474                    parent
475                } else {
476                    class_like_name
477                }
478            }
479            _ => class_like_name,
480        }
481    };
482
483    let Some(class_like) = codebase.get_class_like_by_name(resolved_class_name) else {
484        return ArrayKey::ClassLikeConstant { class_like_name, constant_name };
485    };
486
487    // Try class constants first
488    if let Some(constant) = class_like.constants.get(&constant_name)
489        && let Some(inferred) = &constant.inferred_type
490    {
491        match inferred {
492            TAtomic::Scalar(TScalar::Integer(TInteger::Literal(i))) => {
493                return ArrayKey::Integer(*i);
494            }
495            TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(s)), .. })) => {
496                return ArrayKey::from_string(*s);
497            }
498            _ => {}
499        }
500    }
501
502    // Try enum cases
503    if let Some(enum_case) = class_like.enum_cases.get(&constant_name)
504        && let Some(value_type) = &enum_case.value_type
505    {
506        match value_type {
507            TAtomic::Scalar(TScalar::Integer(TInteger::Literal(i))) => {
508                return ArrayKey::Integer(*i);
509            }
510            TAtomic::Scalar(TScalar::String(TString { literal: Some(TStringLiteral::Value(s)), .. })) => {
511                return ArrayKey::from_string(*s);
512            }
513            _ => {}
514        }
515    }
516
517    // Cannot resolve - keep as-is
518    ArrayKey::ClassLikeConstant { class_like_name, constant_name }
519}
520
521#[cold]
522fn expand_member_reference(
523    class_like_name: Word,
524    member_selector: &TReferenceMemberSelector,
525    codebase: &CodebaseMetadata,
526    options: &TypeExpansionOptions,
527    new_return_type_parts: &mut Vec<TAtomic>,
528) {
529    let class_like_name = if class_like_name.as_bytes().eq_ignore_ascii_case(b"parent") {
530        options
531            .self_class
532            .and_then(|name| codebase.get_class_like_by_name(name))
533            .and_then(|metadata| metadata.direct_parent_class)
534            .unwrap_or(class_like_name)
535    } else {
536        class_like_name
537    };
538
539    if let TReferenceMemberSelector::Identifier(member_name) = member_selector
540        && member_name.as_bytes().eq_ignore_ascii_case(b"class")
541    {
542        new_return_type_parts.push(TAtomic::Scalar(TScalar::literal_class_string(class_like_name)));
543        return;
544    }
545
546    let Some(class_like) = codebase.get_class_like_by_name(class_like_name) else {
547        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
548        return;
549    };
550
551    let (constant, constants) = match member_selector {
552        TReferenceMemberSelector::Identifier(name) => (class_like.constants.get_key_value(name), None),
553        _ => (None, Some(&class_like.constants)),
554    };
555
556    for (constant_name, constant) in
557        constant.into_iter().chain(constants.into_iter().flat_map(|constants| constants.iter()))
558    {
559        if !member_selector.matches(*constant_name) {
560            continue;
561        }
562
563        if let Some(inferred_type) = constant.inferred_type.as_ref() {
564            let Some(_guard) = ConstantExpansionGuard::try_new(class_like_name, *constant_name) else {
565                new_return_type_parts.push(TAtomic::Never);
566                continue;
567            };
568
569            let mut inferred_type = inferred_type.clone();
570            let mut skip_inferred_type = false;
571            expand_atomic(&mut inferred_type, codebase, options, &mut skip_inferred_type, new_return_type_parts);
572
573            if !skip_inferred_type {
574                new_return_type_parts.push(inferred_type);
575            }
576        } else if let Some(type_metadata) = constant.type_metadata.as_ref() {
577            let mut constant_type = type_metadata.type_union.clone();
578            expand_union(codebase, &mut constant_type, options);
579            new_return_type_parts.extend(constant_type.types.into_owned());
580        } else {
581            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
582        }
583    }
584
585    if let TReferenceMemberSelector::Identifier(name) = member_selector {
586        if class_like.enum_cases.contains_key(name) {
587            new_return_type_parts.push(TAtomic::Object(TObject::new_enum_case(class_like.original_name, *name)));
588        }
589    } else if matches!(member_selector, TReferenceMemberSelector::Wildcard) && !class_like.enum_cases.is_empty() {
590        new_return_type_parts.push(TAtomic::Object(TObject::new_enum(class_like.original_name)));
591    } else {
592        for enum_case_name in class_like.enum_cases.keys() {
593            if !member_selector.matches(*enum_case_name) {
594                continue;
595            }
596            new_return_type_parts
597                .push(TAtomic::Object(TObject::new_enum_case(class_like.original_name, *enum_case_name)));
598        }
599    }
600
601    if let TReferenceMemberSelector::Identifier(member_name) = member_selector
602        && let Some(type_alias) = class_like.type_aliases.get(member_name)
603    {
604        let mut alias_type = type_alias.type_union.clone();
605        expand_union(codebase, &mut alias_type, options);
606        new_return_type_parts.extend(alias_type.types.into_owned());
607    }
608
609    if new_return_type_parts.is_empty() {
610        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
611    }
612}
613
614fn expand_global_reference(
615    selector: &TGlobalReferenceSelector,
616    codebase: &CodebaseMetadata,
617    options: &TypeExpansionOptions,
618    new_return_type_parts: &mut Vec<TAtomic>,
619) {
620    let (constant, constants) = match selector {
621        TGlobalReferenceSelector::Identifier(name) => (codebase.constants.get_key_value(name), None),
622        TGlobalReferenceSelector::Fallback { name, fallback } => {
623            (codebase.constants.get_key_value(name).or_else(|| codebase.constants.get_key_value(fallback)), None)
624        }
625        _ => (None, Some(&codebase.constants)),
626    };
627
628    for (constant_name, constant) in
629        constant.into_iter().chain(constants.into_iter().flat_map(|constants| constants.iter()))
630    {
631        if !selector.matches(*constant_name) {
632            continue;
633        }
634
635        let Some(_guard) = ConstantExpansionGuard::try_new(empty_word(), *constant_name) else {
636            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
637            continue;
638        };
639
640        if let Some(inferred_type) = constant.inferred_type.as_ref() {
641            let mut inferred_type = inferred_type.clone();
642            expand_union(codebase, &mut inferred_type, options);
643            new_return_type_parts.extend(inferred_type.types.into_owned());
644        } else if let Some(type_metadata) = constant.type_metadata.as_ref() {
645            let mut constant_type = type_metadata.type_union.clone();
646            expand_union(codebase, &mut constant_type, options);
647            new_return_type_parts.extend(constant_type.types.into_owned());
648        } else {
649            new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
650        }
651    }
652
653    if new_return_type_parts.is_empty() {
654        new_return_type_parts.push(TAtomic::Mixed(TMixed::new()));
655    }
656}
657
658fn expand_object(object: &mut TObject, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) {
659    resolve_special_class_names(object, codebase, options);
660
661    let TObject::Named(named) = object else {
662        return;
663    };
664
665    let class_metadata = codebase.get_class_like_by_name(named.name);
666    if named.intersection_types.is_none()
667        && let Some(class_metadata) = class_metadata
668        && class_metadata.kind.is_enum()
669    {
670        *object = TObject::new_enum(class_metadata.original_name);
671        return;
672    }
673
674    let has_params = named.type_parameters.as_ref().is_some_and(|p| !p.is_empty());
675    let has_required_intersections =
676        class_metadata.map(|m| !m.require_extends.is_empty() || !m.require_implements.is_empty()).unwrap_or(false);
677    let needs_default_params = !has_params && class_metadata.map(|m| !m.template_types.is_empty()).unwrap_or(false);
678
679    if !has_params && !has_required_intersections && !needs_default_params {
680        return;
681    }
682
683    let Some(_guard) = ObjectParamsExpansionGuard::try_new(named.name) else {
684        return;
685    };
686
687    if has_required_intersections && let Some(class_metadata) = class_metadata {
688        for &required in class_metadata.require_extends.iter().chain(&class_metadata.require_implements) {
689            named.add_intersection_type(TAtomic::Object(TObject::Named(TNamedObject::new(required))));
690        }
691    }
692
693    expand_or_fill_type_parameters(named, class_metadata, codebase, options);
694}
695
696fn resolve_generic_static_type(
697    object: &TObject,
698    codebase: &CodebaseMetadata,
699    options: &TypeExpansionOptions,
700) -> Option<TGenericParameter> {
701    let StaticClassType::Generic(parameter) = &options.static_class_type else {
702        return None;
703    };
704    let TObject::Named(named) = object else {
705        return None;
706    };
707
708    let special = classify_special_class_name(named.name.as_bytes());
709    if matches!(special, SpecialClassName::None) && !named.is_static && !named.is_this {
710        return None;
711    }
712
713    if matches!(special, SpecialClassName::None)
714        && !generic_parameter_can_resolve_static(parameter, named.name, codebase)
715    {
716        return None;
717    }
718
719    let mut parameter = parameter.clone();
720    for intersection in named.intersection_types.iter().flat_map(|types| types.iter()) {
721        parameter.add_intersection_type(intersection.clone());
722    }
723
724    Some(parameter)
725}
726
727fn generic_parameter_can_resolve_static(
728    parameter: &TGenericParameter,
729    expected_class: Word,
730    codebase: &CodebaseMetadata,
731) -> bool {
732    parameter.constraint.types.iter().any(|atomic| match atomic {
733        TAtomic::Object(TObject::Named(object)) => {
734            codebase.is_instance_of(object.name.as_bytes(), expected_class.as_bytes())
735        }
736        TAtomic::Object(TObject::Enum(object)) => {
737            codebase.is_instance_of(object.name.as_bytes(), expected_class.as_bytes())
738        }
739        TAtomic::GenericParameter(parameter) => {
740            generic_parameter_can_resolve_static(parameter, expected_class, codebase)
741        }
742        _ => false,
743    })
744}
745
746/// Classifies a class-like name as one of the PHP "special" tokens that require
747/// resolution against the expansion options. The check is case-insensitive but
748/// avoids the (relatively expensive) `ascii_lowercase_word` interning step on
749/// the common path where the input is not a special name at all.
750#[derive(Copy, Clone, Eq, PartialEq)]
751enum SpecialClassName {
752    None,
753    SelfType,
754    Static,
755    Parent,
756    This,
757}
758
759#[inline]
760fn classify_special_class_name(name: &[u8]) -> SpecialClassName {
761    match name.len() {
762        4 => {
763            if name.eq_ignore_ascii_case(b"self") {
764                SpecialClassName::SelfType
765            } else {
766                SpecialClassName::None
767            }
768        }
769        5 => {
770            if name == b"$this" || name.eq_ignore_ascii_case(b"$this") {
771                SpecialClassName::This
772            } else {
773                SpecialClassName::None
774            }
775        }
776        6 => {
777            if name.eq_ignore_ascii_case(b"static") {
778                SpecialClassName::Static
779            } else if name.eq_ignore_ascii_case(b"parent") {
780                SpecialClassName::Parent
781            } else {
782                SpecialClassName::None
783            }
784        }
785        _ => SpecialClassName::None,
786    }
787}
788
789/// Resolves `static`, `$this`, `self`, and `parent` to their concrete class names.
790fn resolve_special_class_names(object: &mut TObject, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) {
791    let TObject::Named(named) = object else {
792        return;
793    };
794
795    let special = classify_special_class_name(named.name.as_bytes());
796    if matches!(special, SpecialClassName::None) && !named.is_static && !named.is_this {
797        return;
798    }
799
800    let needs_static_resolution = matches!(special, SpecialClassName::Static | SpecialClassName::This) || named.is_this;
801
802    if needs_static_resolution && let StaticClassType::Object(TObject::Enum(static_enum)) = &options.static_class_type {
803        *object = TObject::Enum(static_enum.clone());
804        return;
805    }
806
807    // A pre-bound `static` type also rebinds to an enum receiver, but only when
808    // the receiver is compatible: an instance of the named class, or reaching it
809    // through `@mixin` tags.
810    if matches!(special, SpecialClassName::None)
811        && named.is_static
812        && let StaticClassType::Object(TObject::Enum(static_enum)) = &options.static_class_type
813        && (codebase.is_instance_of(static_enum.name.as_bytes(), named.name.as_bytes())
814            || (options.allow_mixin_static_rebind && reaches_through_mixins(static_enum.name, named.name, codebase)))
815    {
816        *object = TObject::Enum(static_enum.clone());
817        return;
818    }
819
820    let TObject::Named(named) = object else {
821        return;
822    };
823
824    let was_this = named.is_this;
825    match special {
826        SpecialClassName::Static | SpecialClassName::This => {
827            resolve_static_type(named, was_this, false, codebase, options)
828        }
829        SpecialClassName::SelfType => {
830            if let Some(self_class) = options.self_class {
831                named.name = self_class;
832            }
833        }
834        SpecialClassName::Parent => {
835            if let Some(self_class) = options.self_class
836                && let Some(class_metadata) = codebase.get_class_like_by_name(self_class)
837                && let Some(parent) = class_metadata.direct_parent_class
838            {
839                named.name = parent;
840            }
841        }
842        SpecialClassName::None if named.is_static => resolve_static_type(named, was_this, true, codebase, options),
843        SpecialClassName::None => {}
844    }
845}
846
847/// Resolves a `static` or `$this` type to a named object using the static class type from options.
848///
849/// `is_this_type`: true when the original type was `$this` (same instance), false for `static`.
850/// `check_compatibility`: when true, verifies the static type is compatible before resolving.
851fn resolve_static_type(
852    named: &mut TNamedObject,
853    is_this_type: bool,
854    check_compatibility: bool,
855    codebase: &CodebaseMetadata,
856    options: &TypeExpansionOptions,
857) {
858    match &options.static_class_type {
859        StaticClassType::Exact(static_class)
860            if !check_compatibility || codebase.is_instance_of(static_class.as_bytes(), named.name.as_bytes()) =>
861        {
862            named.name = *static_class;
863            named.is_static = false;
864            named.is_this = false;
865        }
866        StaticClassType::Object(TObject::Named(static_obj)) => {
867            // When `check_compatibility` is false, `named.name` is the literal
868            // `static`/`$this` keyword rather than a class name, so no
869            // compatibility or mixin-reachability question arises.
870            let mut crosses_mixin = false;
871            if check_compatibility
872                && !codebase.is_instance_of(static_obj.name.as_bytes(), named.name.as_bytes())
873                && !intersection_object_names(static_obj)
874                    .any(|name| codebase.is_instance_of(name.as_bytes(), named.name.as_bytes()))
875            {
876                crosses_mixin = options.allow_mixin_static_rebind
877                    && (reaches_through_mixins(static_obj.name, named.name, codebase)
878                        || intersection_object_names(static_obj)
879                            .any(|name| reaches_through_mixins(name, named.name, codebase)));
880
881                if !crosses_mixin {
882                    return;
883                }
884            }
885
886            if let Some(intersections) = &static_obj.intersection_types {
887                named.intersection_types.get_or_insert_with(Box::default).extend(intersections.iter().cloned());
888            }
889
890            // When the receiver reaches the declaring class through `@mixin`, the
891            // declaring class's type parameters do not apply to it; the receiver's
892            // own parameters (if any) are the correct ones.
893            if crosses_mixin
894                || (static_obj.type_parameters.is_some() && should_use_static_type_params(named, static_obj, codebase))
895            {
896                named.type_parameters.clone_from(&static_obj.type_parameters);
897            }
898
899            named.name = static_obj.name;
900            let effectively_final = is_effectively_final(&static_obj.name, codebase, options);
901            named.is_static = !effectively_final;
902            named.is_this = !effectively_final && is_this_type;
903        }
904        StaticClassType::Name(static_class)
905            if (!check_compatibility || codebase.is_instance_of(static_class.as_bytes(), named.name.as_bytes())) =>
906        {
907            named.name = *static_class;
908            let effectively_final = is_effectively_final(static_class, codebase, options);
909            named.is_static = !effectively_final;
910            named.is_this = !effectively_final && is_this_type;
911        }
912        _ => {}
913    }
914}
915
916/// Checks whether a class is effectively final for the purpose of `$this`/`static` resolution.
917///
918/// A class is effectively final when it cannot be extended, meaning `static` === `self`:
919///
920/// - The class is declared `final`
921/// - The class is anonymous
922/// - The method is declared `final`
923fn is_effectively_final(class_name: &Word, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> bool {
924    if options.function_is_final {
925        return true;
926    }
927
928    codebase.get_class_like_by_name(*class_name).is_some_and(|meta| meta.name_span.is_none() || meta.flags.is_final())
929}
930
931/// Iterates the class names of an object's intersection types.
932fn intersection_object_names(obj: &TNamedObject) -> impl Iterator<Item = Word> {
933    obj.intersection_types
934        .iter()
935        .flat_map(|types| types.iter())
936        .filter_map(|t| if let TAtomic::Object(obj) = t { obj.get_name() } else { None })
937}
938
939/// Checks whether `class_name` reaches `target_name` through a chain of `@mixin`
940/// tags. Methods pulled in via `@mixin` have their `static` return types pre-bound
941/// to the mixin class, so rebinding them to the class carrying the tag must treat
942/// that class as compatible.
943fn reaches_through_mixins(class_name: Word, target_name: Word, codebase: &CodebaseMetadata) -> bool {
944    let Some(metadata) = codebase.get_class_like_by_name(class_name) else {
945        return false;
946    };
947
948    // Direct mixins cover the overwhelmingly common case; the walk only
949    // descends into (and only allocates for) mixins that are chained.
950    let mut visited = HashSet::with_hasher(FixedState::with_seed(0));
951    let mut stack = Vec::new();
952    let mut current = metadata;
953    loop {
954        for (mixin_name, mixin_metadata) in direct_mixins(current, codebase) {
955            if codebase.is_instance_of(mixin_name.as_bytes(), target_name.as_bytes()) {
956                return true;
957            }
958
959            if let Some(mixin_metadata) = mixin_metadata
960                && !mixin_metadata.mixins.is_empty()
961                && visited.insert(mixin_name)
962            {
963                stack.push(mixin_metadata);
964            }
965        }
966
967        let Some(next) = stack.pop() else {
968            return false;
969        };
970        current = next;
971    }
972}
973
974/// Iterates the classes directly named by a class's `@mixin` tags, along with
975/// their metadata if known. A generic-parameter mixin (`@mixin T`) names its
976/// classes through the template constraint.
977fn direct_mixins<'ctx>(
978    metadata: &'ctx ClassLikeMetadata,
979    codebase: &'ctx CodebaseMetadata,
980) -> impl Iterator<Item = (Word, Option<&'ctx ClassLikeMetadata>)> {
981    metadata.mixins.iter().flat_map(|mixin| mixin.type_union.types.as_ref().iter()).flat_map(move |mixin_type| {
982        let atomics = match mixin_type {
983            TAtomic::GenericParameter(TGenericParameter { constraint, .. }) => constraint.types.as_ref(),
984            other => std::slice::from_ref(other),
985        };
986
987        atomics.iter().filter_map(move |atomic| {
988            let mixin_name = atomic.get_object_or_enum_name()?;
989            Some((mixin_name, codebase.get_class_like_by_name(mixin_name)))
990        })
991    })
992}
993
994/// Returns true if we should use the static object's type parameters instead of the current ones.
995/// This is true when current params are None or came from omitted/defaulted template arguments.
996fn should_use_static_type_params(named: &TNamedObject, static_obj: &TNamedObject, codebase: &CodebaseMetadata) -> bool {
997    let Some(current_params) = &named.type_parameters else {
998        return true;
999    };
1000
1001    let Some(class_metadata) = codebase.get_class_like_by_name(static_obj.name) else {
1002        return false;
1003    };
1004
1005    let templates = &class_metadata.template_types;
1006
1007    current_params.len() == templates.len()
1008        && current_params.iter().zip(templates.values()).all(|(current, template)| {
1009            current.from_template_fallback()
1010                || current == &template.constraint
1011                || template.default.as_ref().is_some_and(|default| current == default)
1012        })
1013}
1014
1015/// Expands existing type parameters and fills omitted arguments.
1016fn expand_or_fill_type_parameters(
1017    named: &mut TNamedObject,
1018    class_metadata: Option<&ClassLikeMetadata>,
1019    codebase: &CodebaseMetadata,
1020    options: &TypeExpansionOptions,
1021) {
1022    if let Some(class_metadata) = class_metadata {
1023        let template_count = class_metadata.template_types.len();
1024        let supplied_count = named.type_parameters.as_ref().map_or(0, |parameters| parameters.len());
1025
1026        if supplied_count < template_count {
1027            let mut params = named.type_parameters.take().unwrap_or_default().into_vec();
1028            params.extend(class_metadata.template_types.values().skip(supplied_count).map(|template| {
1029                if let Some(default) = &template.default {
1030                    let mut default = default.clone();
1031                    default.set_from_template_default(true);
1032                    default
1033                } else {
1034                    let mut constraint = template.constraint.clone();
1035                    constraint.set_from_unspecified_template(true);
1036                    constraint
1037                }
1038            }));
1039            named.type_parameters = Some(params.into_boxed_slice());
1040        }
1041    }
1042
1043    if let Some(params) = &mut named.type_parameters {
1044        for param in params.iter_mut() {
1045            expand_union(codebase, param, options);
1046        }
1047    }
1048}
1049
1050#[must_use]
1051pub fn get_signature_of_function_like_identifier(
1052    function_like_identifier: &FunctionLikeIdentifier,
1053    codebase: &CodebaseMetadata,
1054) -> Option<TCallableSignature> {
1055    get_signature_of_function_like_identifier_with_options(function_like_identifier, codebase, false)
1056}
1057
1058/// Builds a callable signature without eagerly expanding types that depend on one of its
1059/// parameters.
1060///
1061/// This is used for first-class and partial callables, where the concrete argument is only
1062/// available when the resulting callable is invoked.
1063#[must_use]
1064pub fn get_parameter_dependent_signature_of_function_like_identifier(
1065    function_like_identifier: &FunctionLikeIdentifier,
1066    codebase: &CodebaseMetadata,
1067) -> Option<TCallableSignature> {
1068    get_signature_of_function_like_identifier_with_options(function_like_identifier, codebase, true)
1069}
1070
1071fn get_signature_of_function_like_identifier_with_options(
1072    function_like_identifier: &FunctionLikeIdentifier,
1073    codebase: &CodebaseMetadata,
1074    preserve_parameter_dependencies: bool,
1075) -> Option<TCallableSignature> {
1076    let (function_like_metadata, options) = match function_like_identifier {
1077        FunctionLikeIdentifier::Function(_) => {
1078            (codebase.get_function_like(function_like_identifier)?, TypeExpansionOptions::default())
1079        }
1080        FunctionLikeIdentifier::Closure(name) => (codebase.get_closure(name)?, TypeExpansionOptions::default()),
1081        FunctionLikeIdentifier::Method(classlike_name, method_name) => (
1082            codebase.get_declaring_method_by_id(&MethodIdentifier::new(*classlike_name, *method_name))?,
1083            TypeExpansionOptions {
1084                self_class: Some(*classlike_name),
1085                static_class_type: StaticClassType::Name(*classlike_name),
1086                ..Default::default()
1087            },
1088        ),
1089    };
1090
1091    Some(get_signature_of_function_like_metadata_with_options(
1092        function_like_identifier,
1093        function_like_metadata,
1094        codebase,
1095        &options,
1096        preserve_parameter_dependencies,
1097    ))
1098}
1099
1100#[must_use]
1101pub fn get_atomic_of_function_like_identifier(
1102    function_like_identifier: &FunctionLikeIdentifier,
1103    codebase: &CodebaseMetadata,
1104) -> Option<TAtomic> {
1105    let signature = get_signature_of_function_like_identifier(function_like_identifier, codebase)?;
1106
1107    Some(TAtomic::Callable(TCallable::Signature(signature)))
1108}
1109
1110#[must_use]
1111pub fn get_signature_of_function_like_metadata(
1112    function_like_identifier: &FunctionLikeIdentifier,
1113    function_like_metadata: &FunctionLikeMetadata,
1114    codebase: &CodebaseMetadata,
1115    options: &TypeExpansionOptions,
1116) -> TCallableSignature {
1117    get_signature_of_function_like_metadata_with_options(
1118        function_like_identifier,
1119        function_like_metadata,
1120        codebase,
1121        options,
1122        function_like_identifier.is_closure(),
1123    )
1124}
1125
1126fn get_signature_of_function_like_metadata_with_options(
1127    function_like_identifier: &FunctionLikeIdentifier,
1128    function_like_metadata: &FunctionLikeMetadata,
1129    codebase: &CodebaseMetadata,
1130    options: &TypeExpansionOptions,
1131    preserve_parameter_dependencies: bool,
1132) -> TCallableSignature {
1133    let options = &TypeExpansionOptions { preserve_parameter_dependencies, ..options.clone() };
1134    let parameters: Vec<_> = function_like_metadata
1135        .parameters
1136        .iter()
1137        .map(|parameter_metadata| {
1138            let type_signature = if let Some(t) = parameter_metadata.get_type_metadata() {
1139                let mut t = t.type_union.clone();
1140                expand_union(codebase, &mut t, options);
1141                Some(Arc::new(t))
1142            } else {
1143                None
1144            };
1145
1146            TCallableParameter::new(
1147                type_signature,
1148                parameter_metadata.flags.is_by_reference(),
1149                parameter_metadata.flags.is_variadic(),
1150                parameter_metadata.flags.has_default(),
1151            )
1152            .with_name(Some(*parameter_metadata.get_name()))
1153            .with_out_type(parameter_metadata.out_type.as_ref().map(|ty| {
1154                let mut ty = ty.type_union.clone();
1155                expand_union(codebase, &mut ty, options);
1156                Arc::new(ty)
1157            }))
1158            .with_closure_this_type(parameter_metadata.closure_this_type.as_ref().map(|ty| {
1159                let mut ty = ty.type_union.clone();
1160                expand_union(codebase, &mut ty, options);
1161                Arc::new(ty)
1162            }))
1163        })
1164        .collect();
1165
1166    let return_type = if let Some(type_metadata) = function_like_metadata.return_type_metadata.as_ref() {
1167        let mut return_type = type_metadata.type_union.clone();
1168        expand_union(codebase, &mut return_type, options);
1169        Some(Arc::new(return_type))
1170    } else {
1171        None
1172    };
1173
1174    let is_closure = matches!(function_like_identifier, FunctionLikeIdentifier::Closure(_));
1175    TCallableSignature::new(function_like_metadata.flags.is_pure(), is_closure)
1176        .with_parameters(parameters)
1177        .with_return_type(return_type)
1178        .with_source(Some(*function_like_identifier))
1179}
1180
1181#[must_use]
1182pub fn contains_parameter_variable(ttype: &impl TType) -> bool {
1183    ttype.any_child_node(|node| {
1184        matches!(
1185            node,
1186            TypeRef::Atomic(TAtomic::Variable(variable))
1187                if !variable.as_bytes().eq_ignore_ascii_case(b"$this")
1188        )
1189    })
1190}
1191
1192#[cold]
1193fn expand_key_of(
1194    return_type_key_of: &TKeyOf,
1195    codebase: &CodebaseMetadata,
1196    options: &TypeExpansionOptions,
1197) -> Vec<TAtomic> {
1198    let mut target_type = return_type_key_of.get_target_type().clone();
1199    expand_union(codebase, &mut target_type, options);
1200
1201    let Some(new_return_types) = TKeyOf::get_key_of_targets(&target_type.types, codebase, false) else {
1202        return vec![TAtomic::Derived(TDerived::KeyOf(return_type_key_of.clone()))];
1203    };
1204
1205    new_return_types.types.into_owned()
1206}
1207
1208#[cold]
1209fn expand_value_of(
1210    return_type_value_of: &TValueOf,
1211    codebase: &CodebaseMetadata,
1212    options: &TypeExpansionOptions,
1213) -> Vec<TAtomic> {
1214    let mut target_type = return_type_value_of.get_target_type().clone();
1215    expand_union(codebase, &mut target_type, options);
1216
1217    let Some(new_return_types) = TValueOf::get_value_of_targets(&target_type.types, codebase, false) else {
1218        return vec![TAtomic::Derived(TDerived::ValueOf(return_type_value_of.clone()))];
1219    };
1220
1221    new_return_types.types.into_owned()
1222}
1223
1224#[cold]
1225fn expand_index_access(
1226    return_type_index_access: &TIndexAccess,
1227    codebase: &CodebaseMetadata,
1228    options: &TypeExpansionOptions,
1229) -> Vec<TAtomic> {
1230    let mut target_type = return_type_index_access.get_target_type().clone();
1231    expand_union(codebase, &mut target_type, options);
1232
1233    let mut index_type = return_type_index_access.get_index_type().clone();
1234    expand_union(codebase, &mut index_type, options);
1235
1236    let Some(new_return_types) =
1237        TIndexAccess::get_indexed_access_result(&target_type.types, &index_type.types, codebase, false)
1238    else {
1239        return vec![TAtomic::Derived(TDerived::IndexAccess(return_type_index_access.clone()))];
1240    };
1241
1242    new_return_types.types.into_owned()
1243}
1244
1245#[cold]
1246fn expand_new(new_type: &TNew, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
1247    let mut target_type = new_type.get_target_type().clone();
1248    expand_union(codebase, &mut target_type, options);
1249
1250    let Some(new_return_types) = TNew::get_new_targets(&target_type.types, codebase) else {
1251        return vec![TAtomic::Derived(TDerived::New(new_type.clone()))];
1252    };
1253
1254    new_return_types.types.into_owned()
1255}
1256
1257#[cold]
1258fn expand_template_type(
1259    template_type: &TTemplateType,
1260    codebase: &CodebaseMetadata,
1261    options: &TypeExpansionOptions,
1262) -> Vec<TAtomic> {
1263    let mut expanded = template_type.clone();
1264    expand_union(codebase, expanded.get_object_mut(), options);
1265    expand_union(codebase, expanded.get_class_name_mut(), options);
1266    expand_union(codebase, expanded.get_template_name_mut(), options);
1267
1268    let Some(resolved) = expanded.resolve(codebase) else {
1269        return vec![TAtomic::Mixed(TMixed::new())];
1270    };
1271
1272    resolved.types.into_owned()
1273}
1274
1275#[cold]
1276fn expand_int_mask(int_mask: &TIntMask, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
1277    let mut literal_values = Vec::new();
1278
1279    for value in int_mask.get_values() {
1280        let mut expanded = value.clone();
1281        expand_union(codebase, &mut expanded, options);
1282
1283        if let Some(int_val) = expanded.get_single_literal_int_value() {
1284            literal_values.push(int_val);
1285        }
1286    }
1287
1288    if literal_values.is_empty() {
1289        return vec![TAtomic::Scalar(TScalar::int())];
1290    }
1291
1292    mask_combinations(&literal_values)
1293}
1294
1295#[cold]
1296fn expand_int_mask_of(
1297    int_mask_of: &TIntMaskOf,
1298    codebase: &CodebaseMetadata,
1299    options: &TypeExpansionOptions,
1300) -> Vec<TAtomic> {
1301    let mut target = int_mask_of.get_target_type().clone();
1302    expand_union(codebase, &mut target, options);
1303
1304    let mut literal_values = Vec::new();
1305    for atomic in target.types.iter() {
1306        if let Some(int_val) = atomic.get_literal_int_value() {
1307            literal_values.push(int_val);
1308        }
1309    }
1310
1311    if literal_values.is_empty() {
1312        return vec![TAtomic::Scalar(TScalar::int())];
1313    }
1314
1315    mask_combinations(&literal_values)
1316}
1317
1318fn mask_combinations(literal_values: &[i64]) -> Vec<TAtomic> {
1319    let generalization_limit = usize::from(combiner::CombinerOptions::default().integer_combination_threshold) + 1;
1320    let mut combinations = TIntMask::calculate_smallest_mask_combinations(literal_values, generalization_limit);
1321    if !combinations.contains(&0) {
1322        combinations.push(0);
1323    }
1324
1325    combinations.into_iter().map(|v| TAtomic::Scalar(TScalar::literal_int(v))).collect()
1326}
1327
1328#[cold]
1329fn expand_properties_of(
1330    properties_of: &TPropertiesOf,
1331    codebase: &CodebaseMetadata,
1332    options: &TypeExpansionOptions,
1333) -> Vec<TAtomic> {
1334    let mut target_type = properties_of.get_target_type().clone();
1335    expand_union(codebase, &mut target_type, options);
1336
1337    let Some(mut keyed_array) =
1338        TPropertiesOf::get_properties_of_targets(&target_type.types, codebase, properties_of.visibility(), false)
1339    else {
1340        return vec![TAtomic::Derived(TDerived::PropertiesOf(properties_of.clone()))];
1341    };
1342
1343    let mut skip_keyed_array = false;
1344    let mut expanded_parts = vec![];
1345    expand_atomic(&mut keyed_array, codebase, options, &mut skip_keyed_array, &mut expanded_parts);
1346    if skip_keyed_array {
1347        expanded_parts
1348    } else {
1349        expanded_parts.push(keyed_array);
1350        expanded_parts
1351    }
1352}
1353
1354#[cold]
1355fn expand_alias(alias: &TAlias, codebase: &CodebaseMetadata, options: &TypeExpansionOptions) -> Vec<TAtomic> {
1356    let class_name = alias.get_class_name();
1357    let alias_name = alias.get_alias_name();
1358
1359    // Check for cycle using the HashSet
1360    let is_cycle = EXPANDING_ALIASES.with(|set| set.borrow().contains(&(class_name, alias_name)));
1361
1362    if is_cycle {
1363        return vec![TAtomic::Alias(alias.clone())];
1364    }
1365
1366    let Some(mut expanded_union) = alias.resolve(codebase).cloned() else {
1367        return vec![TAtomic::Alias(alias.clone())];
1368    };
1369
1370    let _guard = AliasExpansionGuard::new(class_name, alias_name);
1371
1372    expand_union(codebase, &mut expanded_union, options);
1373
1374    expanded_union.types.into_owned()
1375}
1376
1377#[cfg(test)]
1378#[allow(clippy::unwrap_used, clippy::expect_used)]
1379mod tests {
1380    use super::*;
1381    use mago_allocator::LocalArena;
1382
1383    use std::borrow::Cow;
1384    use std::collections::HashSet;
1385    use std::sync::Arc;
1386
1387    use mago_database::Database;
1388    use mago_database::DatabaseReader;
1389    use mago_database::file::File;
1390
1391    use mago_names::resolver::NameResolver;
1392
1393    use mago_syntax::parser::parse_file;
1394    use mago_word::WordSet;
1395    use mago_word::ascii_lowercase_word;
1396    use mago_word::word;
1397
1398    use crate::metadata::CodebaseMetadata;
1399    use crate::misc::GenericParent;
1400    use crate::populator::populate_codebase;
1401    use crate::reference::SymbolReferences;
1402    use crate::scanner::scan_program;
1403    use crate::ttype::atomic::array::TArray;
1404    use crate::ttype::atomic::array::keyed::TKeyedArray;
1405    use crate::ttype::atomic::array::list::TList;
1406    use crate::ttype::atomic::callable::TCallable;
1407    use crate::ttype::atomic::callable::TCallableSignature;
1408    use crate::ttype::atomic::callable::parameter::TCallableParameter;
1409    use crate::ttype::atomic::conditional::TConditional;
1410    use crate::ttype::atomic::derived::TDerived;
1411    use crate::ttype::atomic::derived::index_access::TIndexAccess;
1412    use crate::ttype::atomic::derived::key_of::TKeyOf;
1413    use crate::ttype::atomic::derived::value_of::TValueOf;
1414    use crate::ttype::atomic::generic::TGenericParameter;
1415    use crate::ttype::atomic::iterable::TIterable;
1416    use crate::ttype::atomic::object::r#enum::TEnum;
1417    use crate::ttype::atomic::object::named::TNamedObject;
1418    use crate::ttype::atomic::reference::TReference;
1419    use crate::ttype::atomic::reference::TReferenceMemberSelector;
1420    use crate::ttype::atomic::scalar::TScalar;
1421    use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
1422    use crate::ttype::atomic::scalar::class_like_string::TClassLikeStringKind;
1423    use crate::ttype::flags::UnionFlags;
1424    use crate::ttype::get_int;
1425    use crate::ttype::get_mixed;
1426    use crate::ttype::get_never;
1427    use crate::ttype::get_null;
1428    use crate::ttype::get_string;
1429    use crate::ttype::get_void;
1430
1431    fn create_test_codebase(code: &'static str) -> CodebaseMetadata {
1432        let file = File::ephemeral(Cow::Borrowed(b"code.php"), Cow::Borrowed(code.as_bytes()));
1433        let config =
1434            mago_database::DatabaseConfiguration::new(std::path::Path::new("/"), vec![], vec![], vec![], vec![])
1435                .into_static();
1436        let database = Database::single(file, config);
1437
1438        let mut codebase = CodebaseMetadata::new();
1439        let arena = LocalArena::new();
1440        for file in database.files() {
1441            let program = parse_file(&arena, &file);
1442            assert!(!program.has_errors(), "Parse failed: {:?}", program.errors);
1443            let resolved_names = NameResolver::new(&arena).resolve(program);
1444            let program_codebase =
1445                scan_program(&arena, &file, program, &resolved_names, mago_php_version::PHPVersion::LATEST);
1446
1447            codebase.extend(program_codebase);
1448        }
1449
1450        populate_codebase(&mut codebase, &mut SymbolReferences::new(), WordSet::default(), HashSet::default());
1451
1452        codebase
1453    }
1454
1455    fn options_with_self(self_class: &str) -> TypeExpansionOptions {
1456        TypeExpansionOptions { self_class: Some(ascii_lowercase_word(self_class.as_bytes())), ..Default::default() }
1457    }
1458
1459    fn options_with_static(static_class: &str) -> TypeExpansionOptions {
1460        TypeExpansionOptions {
1461            self_class: Some(ascii_lowercase_word(static_class.as_bytes())),
1462            static_class_type: StaticClassType::Name(ascii_lowercase_word(static_class.as_bytes())),
1463            ..Default::default()
1464        }
1465    }
1466
1467    fn options_with_static_object(object: TObject) -> TypeExpansionOptions {
1468        TypeExpansionOptions {
1469            self_class: object.get_name(),
1470            static_class_type: StaticClassType::Object(object),
1471            ..Default::default()
1472        }
1473    }
1474
1475    macro_rules! assert_expands_to {
1476        ($codebase:expr, $input:expr, $expected:expr) => {
1477            assert_expands_to!($codebase, $input, $expected, &TypeExpansionOptions::default())
1478        };
1479        ($codebase:expr, $input:expr, $expected:expr, $options:expr) => {{
1480            let mut actual = $input.clone();
1481            expand_union($codebase, &mut actual, $options);
1482            assert_eq!(
1483                actual.types.as_ref(),
1484                $expected.types.as_ref(),
1485                "Type expansion mismatch.\nInput: {:?}\nExpected: {:?}\nActual: {:?}",
1486                $input,
1487                $expected,
1488                actual
1489            );
1490        }};
1491    }
1492
1493    fn make_self_object() -> TUnion {
1494        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))))
1495    }
1496
1497    fn make_static_object() -> TUnion {
1498        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("static")))))
1499    }
1500
1501    fn make_parent_object() -> TUnion {
1502        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("parent")))))
1503    }
1504
1505    fn make_named_object(name: &str) -> TUnion {
1506        TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_word(name.as_bytes())))))
1507    }
1508
1509    #[test]
1510    fn test_expand_null_type() {
1511        let codebase = CodebaseMetadata::new();
1512        let null_type = get_null();
1513        assert_expands_to!(&codebase, null_type, get_null());
1514    }
1515
1516    #[test]
1517    fn test_expand_void_type() {
1518        let codebase = CodebaseMetadata::new();
1519        let void_type = get_void();
1520        assert_expands_to!(&codebase, void_type, get_void());
1521    }
1522
1523    #[test]
1524    fn test_expand_never_type() {
1525        let codebase = CodebaseMetadata::new();
1526        let never_type = get_never();
1527        assert_expands_to!(&codebase, never_type, get_never());
1528    }
1529
1530    #[test]
1531    fn test_expand_int_type() {
1532        let codebase = CodebaseMetadata::new();
1533        let int_type = get_int();
1534        assert_expands_to!(&codebase, int_type, get_int());
1535    }
1536
1537    #[test]
1538    fn test_expand_mixed_type() {
1539        let codebase = CodebaseMetadata::new();
1540        let mixed_type = get_mixed();
1541        assert_expands_to!(&codebase, mixed_type, get_mixed());
1542    }
1543
1544    #[test]
1545    fn test_expand_keyed_array_with_self_key() {
1546        let code = "<?php class Foo {}";
1547        let codebase = create_test_codebase(code);
1548
1549        let mut keyed = TKeyedArray::new();
1550        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
1551        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1552
1553        let options = options_with_self("Foo");
1554        let mut actual = input;
1555        expand_union(&codebase, &mut actual, &options);
1556
1557        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1558            && let Some((key, _)) = &keyed.parameters
1559        {
1560            assert!(key.types.iter().any(|t| {
1561                if let TAtomic::Object(TObject::Named(named)) = t {
1562                    named.name == ascii_lowercase_word(b"foo")
1563                } else {
1564                    false
1565                }
1566            }));
1567        }
1568    }
1569
1570    #[test]
1571    fn test_expand_keyed_array_with_self_value() {
1572        let code = "<?php class Foo {}";
1573        let codebase = create_test_codebase(code);
1574
1575        let mut keyed = TKeyedArray::new();
1576        keyed.parameters = Some((Arc::new(get_string()), Arc::new(make_self_object())));
1577        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1578
1579        let options = options_with_self("Foo");
1580        let mut actual = input;
1581        expand_union(&codebase, &mut actual, &options);
1582
1583        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1584            && let Some((_, value)) = &keyed.parameters
1585        {
1586            assert!(value.types.iter().any(|t| {
1587                if let TAtomic::Object(TObject::Named(named)) = t {
1588                    named.name == ascii_lowercase_word(b"foo")
1589                } else {
1590                    false
1591                }
1592            }));
1593        }
1594    }
1595
1596    #[test]
1597    fn test_expand_keyed_array_known_items() {
1598        let code = "<?php class Foo {}";
1599        let codebase = create_test_codebase(code);
1600
1601        use crate::ttype::atomic::array::key::ArrayKey;
1602        use std::collections::BTreeMap;
1603
1604        let mut keyed = TKeyedArray::new();
1605        let mut known_items = BTreeMap::new();
1606        known_items.insert(ArrayKey::String(word("key")), (false, make_self_object()));
1607        keyed.known_items = Some(known_items.into());
1608        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1609
1610        let options = options_with_self("Foo");
1611        let mut actual = input;
1612        expand_union(&codebase, &mut actual, &options);
1613
1614        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1615            && let Some(items) = &keyed.known_items
1616        {
1617            let (_, item_type) = items.get(&ArrayKey::String(word("key"))).unwrap();
1618            assert!(item_type.types.iter().any(|t| {
1619                if let TAtomic::Object(TObject::Named(named)) = t {
1620                    named.name == ascii_lowercase_word(b"foo")
1621                } else {
1622                    false
1623                }
1624            }));
1625        }
1626    }
1627
1628    #[test]
1629    fn test_expand_list_with_self_element() {
1630        let code = "<?php class Foo {}";
1631        let codebase = create_test_codebase(code);
1632
1633        let list = TList::new(Arc::new(make_self_object()));
1634        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1635
1636        let options = options_with_self("Foo");
1637        let mut actual = input;
1638        expand_union(&codebase, &mut actual, &options);
1639
1640        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1641            assert!(list.element_type.types.iter().any(|t| {
1642                if let TAtomic::Object(TObject::Named(named)) = t {
1643                    named.name == ascii_lowercase_word(b"foo")
1644                } else {
1645                    false
1646                }
1647            }));
1648        }
1649    }
1650
1651    #[test]
1652    fn test_expand_list_known_elements() {
1653        let code = "<?php class Foo {}";
1654        let codebase = create_test_codebase(code);
1655
1656        use std::collections::BTreeMap;
1657
1658        let mut list = TList::new(Arc::new(get_mixed()));
1659        let mut known_elements = BTreeMap::new();
1660        known_elements.insert(0, (false, make_self_object()));
1661        list.known_elements = Some(known_elements.into());
1662        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1663
1664        let options = options_with_self("Foo");
1665        let mut actual = input;
1666        expand_union(&codebase, &mut actual, &options);
1667
1668        if let TAtomic::Array(TArray::List(list)) = &actual.types[0]
1669            && let Some(elements) = &list.known_elements
1670        {
1671            let (_, element_type) = elements.get(&0).unwrap();
1672            assert!(element_type.types.iter().any(|t| {
1673                if let TAtomic::Object(TObject::Named(named)) = t {
1674                    named.name == ascii_lowercase_word(b"foo")
1675                } else {
1676                    false
1677                }
1678            }));
1679        }
1680    }
1681
1682    #[test]
1683    fn test_expand_nested_array() {
1684        let code = "<?php class Foo {}";
1685        let codebase = create_test_codebase(code);
1686
1687        let inner_list = TList::new(Arc::new(make_self_object()));
1688        let inner_array = TUnion::from_atomic(TAtomic::Array(TArray::List(inner_list)));
1689
1690        let mut outer = TKeyedArray::new();
1691        outer.parameters = Some((Arc::new(make_self_object()), Arc::new(inner_array)));
1692        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(outer)));
1693
1694        let options = options_with_self("Foo");
1695        let mut actual = input;
1696        expand_union(&codebase, &mut actual, &options);
1697
1698        if let TAtomic::Array(TArray::Keyed(keyed)) = &actual.types[0]
1699            && let Some((key, value)) = &keyed.parameters
1700        {
1701            assert!(key.types.iter().any(|t| {
1702                if let TAtomic::Object(TObject::Named(named)) = t {
1703                    named.name == ascii_lowercase_word(b"foo")
1704                } else {
1705                    false
1706                }
1707            }));
1708            if let TAtomic::Array(TArray::List(inner)) = &value.types[0] {
1709                assert!(inner.element_type.types.iter().any(|t| {
1710                    if let TAtomic::Object(TObject::Named(named)) = t {
1711                        named.name == ascii_lowercase_word(b"foo")
1712                    } else {
1713                        false
1714                    }
1715                }));
1716            }
1717        }
1718    }
1719
1720    #[test]
1721    fn test_expand_empty_array() {
1722        let codebase = CodebaseMetadata::new();
1723        let keyed = TKeyedArray::new();
1724        let input = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed.clone())));
1725        let expected = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
1726        assert_expands_to!(&codebase, input, expected);
1727    }
1728
1729    #[test]
1730    fn test_expand_non_empty_list() {
1731        let code = "<?php class Foo {}";
1732        let codebase = create_test_codebase(code);
1733
1734        let mut list = TList::new(Arc::new(make_self_object()));
1735        list.non_empty = true;
1736        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(list)));
1737
1738        let options = options_with_self("Foo");
1739        let mut actual = input;
1740        expand_union(&codebase, &mut actual, &options);
1741
1742        if let TAtomic::Array(TArray::List(list)) = &actual.types[0] {
1743            assert!(list.non_empty);
1744            assert!(list.element_type.types.iter().any(|t| {
1745                if let TAtomic::Object(TObject::Named(named)) = t {
1746                    named.name == ascii_lowercase_word(b"foo")
1747                } else {
1748                    false
1749                }
1750            }));
1751        }
1752    }
1753
1754    #[test]
1755    fn test_expand_self_to_class_name() {
1756        let code = "<?php class Foo {}";
1757        let codebase = create_test_codebase(code);
1758
1759        let input = make_self_object();
1760        let options = options_with_self("Foo");
1761        let mut actual = input;
1762        expand_union(&codebase, &mut actual, &options);
1763
1764        assert!(actual.types.iter().any(|t| {
1765            if let TAtomic::Object(TObject::Named(named)) = t {
1766                named.name == ascii_lowercase_word(b"foo")
1767            } else {
1768                false
1769            }
1770        }));
1771    }
1772
1773    #[test]
1774    fn test_expand_static_to_class_name() {
1775        let code = "<?php class Foo {}";
1776        let codebase = create_test_codebase(code);
1777
1778        let input = make_static_object();
1779        let options = options_with_static("Foo");
1780        let mut actual = input;
1781        expand_union(&codebase, &mut actual, &options);
1782
1783        assert!(actual.types.iter().any(|t| {
1784            if let TAtomic::Object(TObject::Named(named)) = t {
1785                named.name == ascii_lowercase_word(b"foo")
1786            } else {
1787                false
1788            }
1789        }));
1790    }
1791
1792    #[test]
1793    fn test_expand_static_with_object_type() {
1794        let code = "<?php class Foo {}";
1795        let codebase = create_test_codebase(code);
1796
1797        let input = make_static_object();
1798        let static_obj = TObject::Named(TNamedObject::new(ascii_lowercase_word(b"foo")));
1799        let options = options_with_static_object(static_obj);
1800        let mut actual = input;
1801        expand_union(&codebase, &mut actual, &options);
1802
1803        assert!(actual.types.iter().any(|t| {
1804            if let TAtomic::Object(TObject::Named(named)) = t {
1805                named.name == ascii_lowercase_word(b"foo") && named.is_static && !named.is_this
1806            } else {
1807                false
1808            }
1809        }));
1810    }
1811
1812    #[test]
1813    fn test_expand_static_replaces_defaulted_type_parameters_with_receiver_parameters() {
1814        let code = "<?php
1815            /**
1816             * @template TKey of array-key
1817             * @template TValue
1818             */
1819            final class Collection {}
1820        ";
1821        let codebase = create_test_codebase(code);
1822
1823        let mut input = TNamedObject::new_static(ascii_lowercase_word(b"collection"));
1824        let mut default_key = crate::ttype::get_arraykey();
1825        default_key.set_from_template_default(true);
1826        let mut default_value = crate::ttype::get_mixed();
1827        default_value.set_from_template_default(true);
1828        input.type_parameters = Some(Box::new([default_key, default_value]));
1829
1830        let receiver = TNamedObject::new_with_type_parameters(
1831            ascii_lowercase_word(b"collection"),
1832            Some(vec![crate::ttype::get_int(), crate::ttype::get_string()]),
1833        );
1834        let options = options_with_static_object(TObject::Named(receiver));
1835        let mut actual = TUnion::from_atomic(TAtomic::Object(TObject::Named(input)));
1836        expand_union(&codebase, &mut actual, &options);
1837
1838        let TAtomic::Object(TObject::Named(actual)) = &actual.types[0] else {
1839            panic!("expected a named object");
1840        };
1841        let parameters = actual.type_parameters.as_ref().expect("expected type parameters");
1842        assert_eq!(parameters.as_ref(), &[crate::ttype::get_int(), crate::ttype::get_string()]);
1843    }
1844
1845    #[test]
1846    fn test_expand_static_with_enum_type() {
1847        let code = "<?php enum Status { case Active; case Inactive; }";
1848        let codebase = create_test_codebase(code);
1849
1850        let input = make_static_object();
1851        let static_enum = TObject::Enum(TEnum::new(ascii_lowercase_word(b"status")));
1852        let options = options_with_static_object(static_enum);
1853        let mut actual = input;
1854        expand_union(&codebase, &mut actual, &options);
1855
1856        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Object(TObject::Enum(_)))));
1857    }
1858
1859    #[test]
1860    fn test_expand_parent_to_parent_class() {
1861        let code = "<?php
1862            class BaseClass {}
1863            class ChildClass extends BaseClass {}
1864        ";
1865        let codebase = create_test_codebase(code);
1866
1867        let input = make_parent_object();
1868        let options = options_with_self("ChildClass");
1869        let mut actual = input;
1870        expand_union(&codebase, &mut actual, &options);
1871
1872        assert!(actual.types.iter().any(|t| {
1873            if let TAtomic::Object(TObject::Named(named)) = t {
1874                named.name == ascii_lowercase_word(b"baseclass")
1875            } else {
1876                false
1877            }
1878        }));
1879    }
1880
1881    #[test]
1882    fn test_expand_parent_without_parent_class() {
1883        let code = "<?php class Foo {}";
1884        let codebase = create_test_codebase(code);
1885
1886        let input = make_parent_object();
1887        let options = options_with_self("Foo");
1888        let mut actual = input;
1889        expand_union(&codebase, &mut actual, &options);
1890
1891        assert!(actual.types.iter().any(|t| {
1892            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("parent") } else { false }
1893        }));
1894    }
1895
1896    #[test]
1897    fn test_expand_this_variable() {
1898        let code = "<?php class Foo {}";
1899        let codebase = create_test_codebase(code);
1900
1901        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new_this(word("$this")))));
1902        let options = options_with_static("Foo");
1903        let mut actual = input;
1904        expand_union(&codebase, &mut actual, &options);
1905
1906        assert!(actual.types.iter().any(|t| {
1907            if let TAtomic::Object(TObject::Named(named)) = t {
1908                named.name == ascii_lowercase_word(b"foo")
1909            } else {
1910                false
1911            }
1912        }));
1913    }
1914
1915    #[test]
1916    fn test_expand_this_with_final_function() {
1917        let code = "<?php class Foo {}";
1918        let codebase = create_test_codebase(code);
1919
1920        let input = make_static_object();
1921        let options = TypeExpansionOptions {
1922            self_class: Some(ascii_lowercase_word(b"foo")),
1923            static_class_type: StaticClassType::Name(ascii_lowercase_word(b"foo")),
1924            function_is_final: true,
1925            ..Default::default()
1926        };
1927        let mut actual = input;
1928        expand_union(&codebase, &mut actual, &options);
1929
1930        assert!(actual.types.iter().any(|t| {
1931            if let TAtomic::Object(TObject::Named(named)) = t {
1932                named.name == ascii_lowercase_word(b"foo") && !named.is_this
1933            } else {
1934                false
1935            }
1936        }));
1937    }
1938
1939    #[test]
1940    fn test_expand_static_to_generic_receiver() {
1941        let codebase = create_test_codebase("<?php class Base {}");
1942        let base = ascii_lowercase_word(b"base");
1943        let parameter = TGenericParameter::new(
1944            word("T"),
1945            Arc::new(TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(base))))),
1946            GenericParent::ClassLike(word("Consumer")),
1947        );
1948        let mut actual = TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new_static(base))));
1949
1950        expand_union(
1951            &codebase,
1952            &mut actual,
1953            &TypeExpansionOptions {
1954                self_class: Some(base),
1955                static_class_type: StaticClassType::Generic(parameter.clone()),
1956                ..Default::default()
1957            },
1958        );
1959
1960        assert_eq!(actual, TUnion::from_atomic(TAtomic::GenericParameter(parameter)));
1961    }
1962
1963    #[test]
1964    fn test_expand_object_with_type_parameters() {
1965        let code = "<?php class Container {}";
1966        let codebase = create_test_codebase(code);
1967
1968        let named =
1969            TNamedObject::new_with_type_parameters(ascii_lowercase_word(b"container"), Some(vec![make_self_object()]));
1970        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
1971
1972        let options = options_with_self("Foo");
1973        let mut actual = input;
1974        expand_union(&codebase, &mut actual, &options);
1975
1976        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
1977            && let Some(params) = &named.type_parameters
1978        {
1979            assert_eq!(params.len(), 1);
1980            assert!(params[0].types.iter().any(|t| {
1981                if let TAtomic::Object(TObject::Named(named)) = t {
1982                    named.name == ascii_lowercase_word(b"foo")
1983                } else {
1984                    false
1985                }
1986            }));
1987        }
1988    }
1989
1990    #[test]
1991    fn test_expand_object_marks_omitted_type_params_as_unspecified() {
1992        let code = "<?php
1993            /** @template T */
1994            class Container {}
1995        ";
1996        let codebase = create_test_codebase(code);
1997
1998        let named = TNamedObject::new(ascii_lowercase_word(b"container"));
1999        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
2000
2001        let mut actual = input;
2002        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2003
2004        let TAtomic::Object(TObject::Named(named)) = &actual.types[0] else {
2005            panic!("Expected a named object");
2006        };
2007        let parameter = &named.type_parameters.as_ref().expect("Expected a filled type parameter")[0];
2008
2009        assert!(parameter.is_mixed());
2010        assert!(parameter.from_unspecified_template());
2011        assert!(!parameter.from_template_default());
2012    }
2013
2014    #[test]
2015    fn test_expand_object_keeps_declared_template_defaults_concrete() {
2016        let code = "<?php
2017            /** @template T = string */
2018            class Container {}
2019        ";
2020        let codebase = create_test_codebase(code);
2021
2022        let named = TNamedObject::new(ascii_lowercase_word(b"container"));
2023        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
2024
2025        let mut actual = input;
2026        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2027
2028        let TAtomic::Object(TObject::Named(named)) = &actual.types[0] else {
2029            panic!("Expected a named object");
2030        };
2031        let parameter = &named.type_parameters.as_ref().expect("Expected a filled type parameter")[0];
2032
2033        assert!(parameter.is_string());
2034        assert!(parameter.from_template_default());
2035        assert!(!parameter.from_unspecified_template());
2036    }
2037
2038    #[test]
2039    fn test_expand_object_intersection_from_static() {
2040        let code = "<?php
2041            interface Stringable {}
2042            class Foo implements Stringable {}
2043        ";
2044        let codebase = create_test_codebase(code);
2045
2046        let input = make_static_object();
2047
2048        let mut static_named = TNamedObject::new(ascii_lowercase_word(b"foo"));
2049        static_named.intersection_types = Some(Box::new(vec![TAtomic::Object(TObject::Named(TNamedObject::new(
2050            ascii_lowercase_word(b"stringable"),
2051        )))]));
2052        let static_obj = TObject::Named(static_named);
2053        let options = options_with_static_object(static_obj);
2054
2055        let mut actual = input;
2056        expand_union(&codebase, &mut actual, &options);
2057
2058        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0] {
2059            assert!(named.intersection_types.is_some());
2060        }
2061    }
2062
2063    #[test]
2064    fn test_expand_self_without_self_class_option() {
2065        let codebase = CodebaseMetadata::new();
2066
2067        let input = make_self_object();
2068        let mut actual = input;
2069        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2070
2071        assert!(actual.types.iter().any(|t| {
2072            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("self") } else { false }
2073        }));
2074    }
2075
2076    #[test]
2077    fn test_expand_callable_return_type() {
2078        let code = "<?php class Foo {}";
2079        let codebase = create_test_codebase(code);
2080
2081        let sig = TCallableSignature::new(false, false).with_return_type(Some(Arc::new(make_self_object())));
2082        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
2083
2084        let options = options_with_self("Foo");
2085        let mut actual = input;
2086        expand_union(&codebase, &mut actual, &options);
2087
2088        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
2089            && let Some(ret) = sig.get_return_type()
2090        {
2091            assert!(ret.types.iter().any(|t| {
2092                if let TAtomic::Object(TObject::Named(named)) = t {
2093                    named.name == ascii_lowercase_word(b"foo")
2094                } else {
2095                    false
2096                }
2097            }));
2098        }
2099    }
2100
2101    #[test]
2102    fn test_expand_callable_parameter_types() {
2103        let code = "<?php class Foo {}";
2104        let codebase = create_test_codebase(code);
2105
2106        let param = TCallableParameter::new(Some(Arc::new(make_self_object())), false, false, false);
2107        let sig = TCallableSignature::new(false, false).with_parameters(vec![param]);
2108        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
2109
2110        let options = options_with_self("Foo");
2111        let mut actual = input;
2112        expand_union(&codebase, &mut actual, &options);
2113
2114        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
2115            && let Some(param) = sig.get_parameters().first()
2116            && let Some(param_type) = param.get_type_signature()
2117        {
2118            assert!(param_type.types.iter().any(|t| {
2119                if let TAtomic::Object(TObject::Named(named)) = t {
2120                    named.name == ascii_lowercase_word(b"foo")
2121                } else {
2122                    false
2123                }
2124            }));
2125        }
2126    }
2127
2128    #[test]
2129    fn closure_effects_bind_to_each_trait_consumer() {
2130        let codebase = create_test_codebase(
2131            "<?php
2132            class FirstBase {}
2133            class SecondBase {}
2134            trait Factory {
2135                public function make(): void {
2136                    $write = /**
2137                     * @param-out parent $value
2138                     * @param-closure-this parent $callback
2139                     */
2140                    static function (&$value, callable $callback): void {};
2141                }
2142            }
2143            class First extends FirstBase { use Factory; }
2144            class Second extends SecondBase { use Factory; }
2145        ",
2146        );
2147        let metadata = codebase.function_likes.values().find(|metadata| metadata.kind.is_closure()).unwrap();
2148        let identifier = FunctionLikeIdentifier::Closure(metadata.name);
2149        for (class, parent) in [("First", "FirstBase"), ("Second", "SecondBase")] {
2150            let signature =
2151                get_signature_of_function_like_metadata(&identifier, metadata, &codebase, &options_with_self(class));
2152            let expected = codebase.get_class_like_by_name(word(parent)).unwrap().name;
2153            assert_eq!(signature.get_parameters()[0].get_out_type().unwrap().get_id(), expected);
2154            assert_eq!(signature.get_parameters()[1].get_closure_this_type().unwrap().get_id(), expected);
2155        }
2156        assert_eq!(metadata.parameters[0].out_type.as_ref().unwrap().type_union.get_id(), word("parent"));
2157    }
2158
2159    #[test]
2160    fn test_expand_callable_alias_to_function() {
2161        let code = "<?php
2162            function myFunc(): int { return 1; }
2163        ";
2164        let codebase = create_test_codebase(code);
2165
2166        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc")));
2167        let input = TUnion::from_atomic(TAtomic::Callable(alias));
2168
2169        let mut actual = input;
2170        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2171
2172        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
2173    }
2174
2175    #[test]
2176    fn test_expand_callable_alias_to_method() {
2177        let code = "<?php
2178            class Foo {
2179                public function bar(): int { return 1; }
2180            }
2181        ";
2182        let codebase = create_test_codebase(code);
2183
2184        let alias = TCallable::Alias(FunctionLikeIdentifier::Method(
2185            ascii_lowercase_word(b"foo"),
2186            ascii_lowercase_word(b"bar"),
2187        ));
2188        let input = TUnion::from_atomic(TAtomic::Callable(alias));
2189
2190        let mut actual = input;
2191        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2192
2193        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Signature(_)))));
2194    }
2195
2196    #[test]
2197    fn test_expand_callable_alias_unknown() {
2198        let codebase = CodebaseMetadata::new();
2199
2200        let alias = TCallable::Alias(FunctionLikeIdentifier::Function(word("nonexistent")));
2201        let input = TUnion::from_atomic(TAtomic::Callable(alias));
2202
2203        let mut actual = input;
2204        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2205
2206        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Callable(TCallable::Alias(_)))));
2207    }
2208
2209    #[test]
2210    fn test_expand_closure_signature() {
2211        let code = "<?php class Foo {}";
2212        let codebase = create_test_codebase(code);
2213
2214        let sig = TCallableSignature::new(false, true).with_return_type(Some(Arc::new(make_self_object())));
2215        let input = TUnion::from_atomic(TAtomic::Callable(TCallable::Signature(sig)));
2216
2217        let options = options_with_self("Foo");
2218        let mut actual = input;
2219        expand_union(&codebase, &mut actual, &options);
2220
2221        if let TAtomic::Callable(TCallable::Signature(sig)) = &actual.types[0]
2222            && let Some(ret) = sig.get_return_type()
2223        {
2224            assert!(ret.types.iter().any(|t| {
2225                if let TAtomic::Object(TObject::Named(named)) = t {
2226                    named.name == ascii_lowercase_word(b"foo")
2227                } else {
2228                    false
2229                }
2230            }));
2231        }
2232    }
2233
2234    #[test]
2235    fn test_expand_generic_parameter_constraint() {
2236        let code = "<?php class Foo {}";
2237        let codebase = create_test_codebase(code);
2238
2239        let generic = TGenericParameter::new(
2240            word("T"),
2241            Arc::new(make_self_object()),
2242            GenericParent::ClassLike(ascii_lowercase_word(b"foo")),
2243        );
2244        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
2245
2246        let options = options_with_self("Foo");
2247        let mut actual = input;
2248        expand_union(&codebase, &mut actual, &options);
2249
2250        if let TAtomic::GenericParameter(param) = &actual.types[0] {
2251            assert!(param.constraint.types.iter().any(|t| {
2252                if let TAtomic::Object(TObject::Named(named)) = t {
2253                    named.name == ascii_lowercase_word(b"foo")
2254                } else {
2255                    false
2256                }
2257            }));
2258        }
2259    }
2260
2261    #[test]
2262    fn test_expand_nested_generic_constraint() {
2263        let code = "<?php class Foo {} class Bar {}";
2264        let codebase = create_test_codebase(code);
2265
2266        let container =
2267            TNamedObject::new_with_type_parameters(ascii_lowercase_word(b"container"), Some(vec![make_self_object()]));
2268        let constraint = TUnion::from_atomic(TAtomic::Object(TObject::Named(container)));
2269
2270        let generic = TGenericParameter::new(
2271            word("T"),
2272            Arc::new(constraint),
2273            GenericParent::ClassLike(ascii_lowercase_word(b"bar")),
2274        );
2275        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
2276
2277        let options = options_with_self("Foo");
2278        let mut actual = input;
2279        expand_union(&codebase, &mut actual, &options);
2280
2281        if let TAtomic::GenericParameter(param) = &actual.types[0]
2282            && let TAtomic::Object(TObject::Named(named)) = &param.constraint.types[0]
2283            && let Some(params) = &named.type_parameters
2284        {
2285            assert_eq!(params.len(), 1);
2286            assert!(params[0].types.iter().any(|t| {
2287                if let TAtomic::Object(TObject::Named(named)) = t {
2288                    named.name == ascii_lowercase_word(b"foo")
2289                } else {
2290                    false
2291                }
2292            }));
2293        }
2294    }
2295
2296    #[test]
2297    fn test_expand_generic_with_intersection() {
2298        let code = "<?php
2299            interface Stringable {}
2300            class Foo {}
2301        ";
2302        let codebase = create_test_codebase(code);
2303
2304        let mut generic = TGenericParameter::new(
2305            word("T"),
2306            Arc::new(make_self_object()),
2307            GenericParent::ClassLike(ascii_lowercase_word(b"foo")),
2308        );
2309        generic.intersection_types =
2310            Some(vec![TAtomic::Object(TObject::Named(TNamedObject::new(ascii_lowercase_word(b"stringable"))))]);
2311        let input = TUnion::from_atomic(TAtomic::GenericParameter(generic));
2312
2313        let options = options_with_self("Foo");
2314        let mut actual = input;
2315        expand_union(&codebase, &mut actual, &options);
2316
2317        if let TAtomic::GenericParameter(param) = &actual.types[0] {
2318            assert!(param.intersection_types.is_some());
2319            assert!(param.constraint.types.iter().any(|t| {
2320                if let TAtomic::Object(TObject::Named(named)) = t {
2321                    named.name == ascii_lowercase_word(b"foo")
2322                } else {
2323                    false
2324                }
2325            }));
2326        }
2327    }
2328
2329    #[test]
2330    fn test_expand_class_string_of_self() {
2331        let code = "<?php class Foo {}";
2332        let codebase = create_test_codebase(code);
2333
2334        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))));
2335        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
2336        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
2337
2338        let options = options_with_self("Foo");
2339        let mut actual = input;
2340        expand_union(&codebase, &mut actual, &options);
2341
2342        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
2343            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
2344        {
2345            assert_eq!(named.name, ascii_lowercase_word(b"foo"));
2346        }
2347    }
2348
2349    #[test]
2350    fn test_expand_class_string_of_static() {
2351        let code = "<?php class Foo {}";
2352        let codebase = create_test_codebase(code);
2353
2354        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("static")))));
2355        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Class, constraint };
2356        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
2357
2358        let options = options_with_static("Foo");
2359        let mut actual = input;
2360        expand_union(&codebase, &mut actual, &options);
2361
2362        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { constraint, .. })) = &actual.types[0]
2363            && let TAtomic::Object(TObject::Named(named)) = constraint.as_ref()
2364        {
2365            assert_eq!(named.name, ascii_lowercase_word(b"foo"));
2366        }
2367    }
2368
2369    #[test]
2370    fn test_expand_interface_string_of_type() {
2371        let code = "<?php interface MyInterface {}";
2372        let codebase = create_test_codebase(code);
2373
2374        let constraint = Arc::new(TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))));
2375        let class_string = TClassLikeString::OfType { kind: TClassLikeStringKind::Interface, constraint };
2376        let input = TUnion::from_atomic(TAtomic::Scalar(TScalar::ClassLikeString(class_string)));
2377
2378        let options = options_with_self("MyInterface");
2379        let mut actual = input;
2380        expand_union(&codebase, &mut actual, &options);
2381
2382        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::OfType { kind, constraint })) =
2383            &actual.types[0]
2384        {
2385            assert!(matches!(kind, TClassLikeStringKind::Interface));
2386            if let TAtomic::Object(TObject::Named(named)) = constraint.as_ref() {
2387                assert_eq!(named.name, ascii_lowercase_word(b"myinterface"));
2388            }
2389        }
2390    }
2391
2392    #[test]
2393    fn test_expand_member_reference_wildcard_constants() {
2394        let code = "<?php
2395            class Foo {
2396                public const A = 1;
2397                public const B = 2;
2398            }
2399        ";
2400        let codebase = create_test_codebase(code);
2401
2402        let reference = TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Wildcard);
2403        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2404
2405        let mut actual = input;
2406        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2407
2408        assert!(!actual.types.is_empty());
2409    }
2410
2411    #[test]
2412    fn test_expand_member_reference_wildcard_enum_cases() {
2413        let code = "<?php
2414            enum Status {
2415                case Active;
2416                case Inactive;
2417            }
2418        ";
2419        let codebase = create_test_codebase(code);
2420
2421        let reference = TReference::new_member(ascii_lowercase_word(b"status"), TReferenceMemberSelector::Wildcard);
2422        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2423
2424        let mut actual = input;
2425        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2426
2427        assert_eq!(actual.types.len(), 1);
2428        assert!(matches!(
2429            &actual.types[0],
2430            TAtomic::Object(TObject::Enum(TEnum { name, case: None })) if name.as_bytes().eq_ignore_ascii_case(b"Status")
2431        ));
2432    }
2433
2434    #[test]
2435    fn test_expand_member_reference_wildcard_enum_cases_and_constants() {
2436        let code = "<?php
2437            enum Status {
2438                case Active;
2439                case Inactive;
2440                public const VALUE = 1;
2441            }
2442        ";
2443        let codebase = create_test_codebase(code);
2444
2445        let reference = TReference::new_member(ascii_lowercase_word(b"status"), TReferenceMemberSelector::Wildcard);
2446        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2447
2448        let mut actual = input;
2449        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2450
2451        assert_eq!(actual.types.len(), 2);
2452        assert!(actual.types.iter().any(|t| matches!(
2453            t,
2454            TAtomic::Object(TObject::Enum(TEnum { name, case: None })) if name.as_bytes().eq_ignore_ascii_case(b"Status")
2455        )));
2456        assert!(actual.types.iter().any(|t| t.get_literal_int_value() == Some(1)));
2457    }
2458
2459    #[test]
2460    fn test_expand_member_reference_starts_with() {
2461        let code = "<?php
2462            class Foo {
2463                public const STATUS_ACTIVE = 1;
2464                public const STATUS_INACTIVE = 2;
2465                public const OTHER = 3;
2466            }
2467        ";
2468        let codebase = create_test_codebase(code);
2469
2470        let reference =
2471            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::StartsWith(word("STATUS_")));
2472        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2473
2474        let mut actual = input;
2475        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2476
2477        assert!(!actual.types.is_empty());
2478    }
2479
2480    #[test]
2481    fn test_expand_member_reference_ends_with() {
2482        let code = "<?php
2483            class Foo {
2484                public const READ_ERROR = 1;
2485                public const WRITE_ERROR = 2;
2486                public const SUCCESS = 0;
2487            }
2488        ";
2489        let codebase = create_test_codebase(code);
2490
2491        let reference =
2492            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::EndsWith(word("_ERROR")));
2493        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2494
2495        let mut actual = input;
2496        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2497
2498        assert!(!actual.types.is_empty());
2499    }
2500
2501    #[test]
2502    fn test_expand_member_reference_identifier_constant() {
2503        let code = "<?php
2504            class Foo {
2505                public const BAR = 42;
2506            }
2507        ";
2508        let codebase = create_test_codebase(code);
2509
2510        let reference =
2511            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("BAR")));
2512        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2513
2514        let mut actual = input;
2515        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2516
2517        assert_eq!(actual.types.len(), 1);
2518    }
2519
2520    #[test]
2521    fn test_expand_member_reference_identifier_enum_case() {
2522        let code = "<?php
2523            enum Status {
2524                case Active;
2525            }
2526        ";
2527        let codebase = create_test_codebase(code);
2528
2529        let reference = TReference::new_member(
2530            ascii_lowercase_word(b"status"),
2531            TReferenceMemberSelector::Identifier(word("Active")),
2532        );
2533        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2534
2535        let mut actual = input;
2536        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2537
2538        assert_eq!(actual.types.len(), 1);
2539        assert!(matches!(&actual.types[0], TAtomic::Object(TObject::Enum(_))));
2540    }
2541
2542    #[test]
2543    fn test_expand_member_identifier_is_case_sensitive_and_keeps_aliases() {
2544        let mut codebase =
2545            create_test_codebase("<?php enum Status { case Active; public const VALUE = 42; public const value = 7; }");
2546        let metadata = codebase.class_likes.get_mut(&word("status")).unwrap();
2547        metadata.type_aliases.insert(
2548            word("VALUE"),
2549            crate::metadata::ttype::TypeMetadata {
2550                span: metadata.span,
2551                type_union: get_string(),
2552                from_docblock: true,
2553                inferred: false,
2554            },
2555        );
2556
2557        for (name, expected) in [
2558            (
2559                "VALUE",
2560                TUnion::from_vec(vec![TAtomic::Scalar(TScalar::literal_int(42)), TAtomic::Scalar(TScalar::string())]),
2561            ),
2562            ("value", crate::ttype::get_literal_int(7)),
2563            ("Value", get_mixed()),
2564            ("Active", TUnion::from_atomic(TAtomic::Object(TObject::new_enum_case(word("Status"), word("Active"))))),
2565            ("active", get_mixed()),
2566        ] {
2567            let mut actual = TUnion::from_atomic(TAtomic::Reference(TReference::new_member(
2568                word("Status"),
2569                TReferenceMemberSelector::Identifier(word(name)),
2570            )));
2571            expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2572            assert_eq!(actual, expected, "member {name}");
2573        }
2574    }
2575
2576    #[test]
2577    fn test_expand_member_reference_unknown_class() {
2578        let codebase = CodebaseMetadata::new();
2579
2580        let reference = TReference::new_member(word("NonExistent"), TReferenceMemberSelector::Identifier(word("FOO")));
2581        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2582
2583        let mut actual = input;
2584        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2585
2586        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2587    }
2588
2589    #[test]
2590    fn test_expand_member_reference_unknown_member() {
2591        let code = "<?php class Foo {}";
2592        let codebase = create_test_codebase(code);
2593
2594        let reference = TReference::new_member(
2595            ascii_lowercase_word(b"foo"),
2596            TReferenceMemberSelector::Identifier(word("NONEXISTENT")),
2597        );
2598        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2599
2600        let mut actual = input;
2601        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2602
2603        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Mixed(_))));
2604    }
2605
2606    #[test]
2607    fn test_expand_member_reference_constant_with_inferred_type() {
2608        let code = r#"<?php
2609            class Foo {
2610                public const VALUE = "hello";
2611            }
2612        "#;
2613        let codebase = create_test_codebase(code);
2614
2615        let reference =
2616            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("VALUE")));
2617        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2618
2619        let mut actual = input;
2620        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2621
2622        assert_eq!(actual.types.len(), 1);
2623    }
2624
2625    #[test]
2626    fn test_expand_member_reference_constant_with_type_metadata() {
2627        let code = "<?php
2628            class Foo {
2629                /** @var int */
2630                public const VALUE = 42;
2631            }
2632        ";
2633        let codebase = create_test_codebase(code);
2634
2635        let reference =
2636            TReference::new_member(ascii_lowercase_word(b"foo"), TReferenceMemberSelector::Identifier(word("VALUE")));
2637        let input = TUnion::from_atomic(TAtomic::Reference(reference));
2638
2639        let mut actual = input;
2640        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2641
2642        assert_eq!(actual.types.len(), 1);
2643    }
2644
2645    #[test]
2646    fn test_expand_conditional_both_branches() {
2647        let code = "<?php class Foo {} class Bar {}";
2648        let codebase = create_test_codebase(code);
2649
2650        let conditional = TConditional::new(
2651            Arc::new(get_mixed()),
2652            Arc::new(get_string()),
2653            Arc::new(make_self_object()),
2654            Arc::new(make_self_object()),
2655            false,
2656        );
2657        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2658
2659        let options = options_with_self("Foo");
2660        let mut actual = input;
2661        expand_union(&codebase, &mut actual, &options);
2662
2663        assert!(actual.types.iter().any(|t| {
2664            if let TAtomic::Object(TObject::Named(named)) = t {
2665                named.name == ascii_lowercase_word(b"foo")
2666            } else {
2667                false
2668            }
2669        }));
2670    }
2671
2672    #[test]
2673    fn test_expand_conditional_with_self_in_then() {
2674        let code = "<?php class Foo {}";
2675        let codebase = create_test_codebase(code);
2676
2677        let conditional = TConditional::new(
2678            Arc::new(get_mixed()),
2679            Arc::new(get_string()),
2680            Arc::new(make_self_object()),
2681            Arc::new(get_int()),
2682            false,
2683        );
2684        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2685
2686        let options = options_with_self("Foo");
2687        let mut actual = input;
2688        expand_union(&codebase, &mut actual, &options);
2689
2690        assert!(!actual.types.is_empty());
2691    }
2692
2693    #[test]
2694    fn test_expand_conditional_with_self_in_otherwise() {
2695        let code = "<?php class Foo {}";
2696        let codebase = create_test_codebase(code);
2697
2698        let conditional = TConditional::new(
2699            Arc::new(get_mixed()),
2700            Arc::new(get_string()),
2701            Arc::new(get_int()),
2702            Arc::new(make_self_object()),
2703            false,
2704        );
2705        let input = TUnion::from_atomic(TAtomic::Conditional(conditional));
2706
2707        let options = options_with_self("Foo");
2708        let mut actual = input;
2709        expand_union(&codebase, &mut actual, &options);
2710
2711        assert!(!actual.types.is_empty());
2712    }
2713
2714    #[test]
2715    fn test_expand_simple_alias() {
2716        let code = "<?php
2717            class Foo {
2718                /** @phpstan-type MyInt = int */
2719            }
2720        ";
2721        let codebase = create_test_codebase(code);
2722
2723        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("MyInt"));
2724        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2725
2726        let mut actual = input;
2727        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2728
2729        assert!(!actual.types.is_empty());
2730    }
2731
2732    #[test]
2733    fn test_expand_nested_alias() {
2734        let code = "<?php
2735            class Foo {
2736                /** @phpstan-type Inner = int */
2737                /** @phpstan-type Outer = Inner */
2738            }
2739        ";
2740        let codebase = create_test_codebase(code);
2741
2742        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("Outer"));
2743        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2744
2745        let mut actual = input;
2746        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2747
2748        assert!(!actual.types.is_empty());
2749    }
2750
2751    #[test]
2752    fn test_expand_alias_cycle_detection() {
2753        let code = "<?php
2754            /** @phpstan-type SelfRef = int|array<int, SelfRef> */
2755            class Foo {}
2756        ";
2757        let codebase = create_test_codebase(code);
2758
2759        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("SelfRef"));
2760        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2761
2762        let mut actual = input;
2763        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2764
2765        assert!(!actual.types.is_empty());
2766    }
2767
2768    #[test]
2769    fn test_expand_alias_unknown() {
2770        let codebase = CodebaseMetadata::new();
2771
2772        let alias = TAlias::new(word("NonExistent"), word("Unknown"));
2773        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2774
2775        let mut actual = input;
2776        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2777
2778        assert!(actual.types.iter().any(|t| matches!(t, TAtomic::Alias(_))));
2779    }
2780
2781    #[test]
2782    fn test_expand_alias_direct_self_reference() {
2783        let code = "<?php
2784            /** @psalm-type SelfAlias = SelfAlias */
2785            class Foo {}
2786        ";
2787        let codebase = create_test_codebase(code);
2788
2789        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("SelfAlias"));
2790        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2791
2792        let options = TypeExpansionOptions::default();
2793        let mut actual = input;
2794        expand_union(&codebase, &mut actual, &options);
2795
2796        assert!(!actual.types.is_empty());
2797    }
2798
2799    #[test]
2800    fn test_expand_alias_with_self_inside() {
2801        let code = "<?php
2802            class Foo {
2803                /** @phpstan-type MySelf = self */
2804            }
2805        ";
2806        let codebase = create_test_codebase(code);
2807
2808        let alias = TAlias::new(ascii_lowercase_word(b"foo"), word("MySelf"));
2809        let input = TUnion::from_atomic(TAtomic::Alias(alias));
2810
2811        let options = options_with_self("Foo");
2812        let mut actual = input;
2813        expand_union(&codebase, &mut actual, &options);
2814
2815        assert!(!actual.types.is_empty());
2816    }
2817
2818    #[test]
2819    fn test_expand_key_of_array() {
2820        let codebase = CodebaseMetadata::new();
2821
2822        let mut keyed = TKeyedArray::new();
2823        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2824        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2825
2826        let key_of = TKeyOf::new(Arc::new(array_type));
2827        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2828
2829        let mut actual = input;
2830        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2831
2832        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_string));
2833    }
2834
2835    #[test]
2836    fn test_expand_key_of_with_self() {
2837        let code = "<?php class Foo {}";
2838        let codebase = create_test_codebase(code);
2839
2840        let mut keyed = TKeyedArray::new();
2841        keyed.parameters = Some((Arc::new(make_self_object()), Arc::new(get_int())));
2842        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2843
2844        let key_of = TKeyOf::new(Arc::new(array_type));
2845        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::KeyOf(key_of)));
2846
2847        let options = options_with_self("Foo");
2848        let mut actual = input;
2849        expand_union(&codebase, &mut actual, &options);
2850
2851        assert!(!actual.types.is_empty());
2852    }
2853
2854    #[test]
2855    fn test_expand_value_of_array() {
2856        let codebase = CodebaseMetadata::new();
2857
2858        let mut keyed = TKeyedArray::new();
2859        keyed.parameters = Some((Arc::new(get_string()), Arc::new(get_int())));
2860        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2861
2862        let value_of = TValueOf::new(Arc::new(array_type));
2863        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2864
2865        let mut actual = input;
2866        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2867
2868        assert!(actual.types.iter().any(super::super::atomic::TAtomic::is_int));
2869    }
2870
2871    #[test]
2872    fn test_expand_value_of_enum() {
2873        let code = "<?php
2874            enum Status: string {
2875                case Active = 'active';
2876                case Inactive = 'inactive';
2877            }
2878        ";
2879        let codebase = create_test_codebase(code);
2880
2881        let enum_type =
2882            TUnion::from_atomic(TAtomic::Object(TObject::Enum(TEnum::new(ascii_lowercase_word(b"status")))));
2883
2884        let value_of = TValueOf::new(Arc::new(enum_type));
2885        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::ValueOf(value_of)));
2886
2887        let mut actual = input;
2888        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2889
2890        assert!(!actual.types.is_empty());
2891    }
2892
2893    #[test]
2894    fn test_expand_index_access() {
2895        let codebase = CodebaseMetadata::new();
2896
2897        use crate::ttype::atomic::array::key::ArrayKey;
2898        use std::collections::BTreeMap;
2899
2900        let mut keyed = TKeyedArray::new();
2901        let mut known_items = BTreeMap::new();
2902        known_items.insert(ArrayKey::String(word("key")), (false, get_int()));
2903        keyed.known_items = Some(known_items.into());
2904        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2905
2906        use crate::ttype::get_literal_string;
2907        let index_type = get_literal_string(word("key"));
2908
2909        let index_access = TIndexAccess::new(array_type, index_type);
2910        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2911
2912        let mut actual = input;
2913        expand_union(&codebase, &mut actual, &TypeExpansionOptions::default());
2914
2915        assert!(!actual.types.is_empty());
2916    }
2917
2918    #[test]
2919    fn test_expand_index_access_with_self() {
2920        let code = "<?php class Foo {}";
2921        let codebase = create_test_codebase(code);
2922
2923        use crate::ttype::atomic::array::key::ArrayKey;
2924        use std::collections::BTreeMap;
2925
2926        let mut keyed = TKeyedArray::new();
2927        let mut known_items = BTreeMap::new();
2928        known_items.insert(ArrayKey::String(word("key")), (false, make_self_object()));
2929        keyed.known_items = Some(known_items.into());
2930        let array_type = TUnion::from_atomic(TAtomic::Array(TArray::Keyed(keyed)));
2931
2932        use crate::ttype::get_literal_string;
2933        let index_type = get_literal_string(word("key"));
2934
2935        let index_access = TIndexAccess::new(array_type, index_type);
2936        let input = TUnion::from_atomic(TAtomic::Derived(TDerived::IndexAccess(index_access)));
2937
2938        let options = options_with_self("Foo");
2939        let mut actual = input;
2940        expand_union(&codebase, &mut actual, &options);
2941
2942        assert!(!actual.types.is_empty());
2943    }
2944
2945    #[test]
2946    fn test_expand_iterable_key_type() {
2947        let code = "<?php class Foo {}";
2948        let codebase = create_test_codebase(code);
2949
2950        let iterable = TIterable::new(Arc::new(make_self_object()), Arc::new(get_int()));
2951        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2952
2953        let options = options_with_self("Foo");
2954        let mut actual = input;
2955        expand_union(&codebase, &mut actual, &options);
2956
2957        if let TAtomic::Iterable(iter) = &actual.types[0] {
2958            assert!(iter.get_key_type().types.iter().any(|t| {
2959                if let TAtomic::Object(TObject::Named(named)) = t {
2960                    named.name == ascii_lowercase_word(b"foo")
2961                } else {
2962                    false
2963                }
2964            }));
2965        }
2966    }
2967
2968    #[test]
2969    fn test_expand_iterable_value_type() {
2970        let code = "<?php class Foo {}";
2971        let codebase = create_test_codebase(code);
2972
2973        let iterable = TIterable::new(Arc::new(get_int()), Arc::new(make_self_object()));
2974        let input = TUnion::from_atomic(TAtomic::Iterable(iterable));
2975
2976        let options = options_with_self("Foo");
2977        let mut actual = input;
2978        expand_union(&codebase, &mut actual, &options);
2979
2980        if let TAtomic::Iterable(iter) = &actual.types[0] {
2981            assert!(iter.get_value_type().types.iter().any(|t| {
2982                if let TAtomic::Object(TObject::Named(named)) = t {
2983                    named.name == ascii_lowercase_word(b"foo")
2984                } else {
2985                    false
2986                }
2987            }));
2988        }
2989    }
2990
2991    #[test]
2992    fn test_expand_shared_iterable_leaves_other_owners_unchanged() {
2993        let codebase = create_test_codebase("<?php class Foo {}");
2994        let key = Arc::new(get_int());
2995        let value = Arc::new(make_self_object());
2996        let mut actual = TUnion::from_atomic(TAtomic::Iterable(TIterable::new(Arc::clone(&key), Arc::clone(&value))));
2997
2998        expand_union(&codebase, &mut actual, &options_with_self("Foo"));
2999
3000        let TAtomic::Iterable(iterable) = actual.get_single() else {
3001            panic!("expected an iterable");
3002        };
3003        assert!(Arc::ptr_eq(&iterable.key_type, &key));
3004        assert!(!Arc::ptr_eq(&iterable.value_type, &value));
3005        assert_eq!(*value, make_self_object());
3006        assert_eq!(iterable.value_type.get_id(), word("foo"));
3007    }
3008
3009    #[test]
3010    fn test_get_signature_of_function() {
3011        let code = r#"<?php
3012            function myFunc(int $a): string { return ""; }
3013        "#;
3014        let codebase = create_test_codebase(code);
3015
3016        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc"));
3017
3018        let sig = get_signature_of_function_like_identifier(&id, &codebase);
3019        assert!(sig.is_some());
3020
3021        let sig = sig.unwrap();
3022        assert_eq!(sig.get_parameters().len(), 1);
3023        assert!(sig.get_return_type().is_some());
3024    }
3025
3026    #[test]
3027    fn test_get_signature_of_method() {
3028        let code = "<?php
3029            class Foo {
3030                public function bar(string $s): int { return 0; }
3031            }
3032        ";
3033        let codebase = create_test_codebase(code);
3034
3035        let id = FunctionLikeIdentifier::Method(ascii_lowercase_word(b"foo"), ascii_lowercase_word(b"bar"));
3036
3037        let sig = get_signature_of_function_like_identifier(&id, &codebase);
3038        assert!(sig.is_some());
3039
3040        let sig = sig.unwrap();
3041        assert_eq!(sig.get_parameters().len(), 1);
3042    }
3043
3044    #[test]
3045    fn test_get_signature_of_closure() {
3046        let codebase = CodebaseMetadata::new();
3047
3048        let id = FunctionLikeIdentifier::Closure(word(b"{closure:test.php:1:1}"));
3049        let sig = get_signature_of_function_like_identifier(&id, &codebase);
3050
3051        assert!(sig.is_none());
3052    }
3053
3054    #[test]
3055    fn test_get_atomic_of_function() {
3056        let code = "<?php
3057            function myFunc(): void {}
3058        ";
3059        let codebase = create_test_codebase(code);
3060
3061        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"myfunc"));
3062
3063        let atomic = get_atomic_of_function_like_identifier(&id, &codebase);
3064        assert!(atomic.is_some());
3065        assert!(matches!(atomic.unwrap(), TAtomic::Callable(TCallable::Signature(_))));
3066    }
3067
3068    #[test]
3069    fn test_get_signature_with_parameters() {
3070        let code = "<?php
3071            function multiParam(int $a, string $b, ?float $c = null): bool { return true; }
3072        ";
3073        let codebase = create_test_codebase(code);
3074
3075        let id = FunctionLikeIdentifier::Function(ascii_lowercase_word(b"multiparam"));
3076
3077        let sig = get_signature_of_function_like_identifier(&id, &codebase);
3078        assert!(sig.is_some());
3079
3080        let sig = sig.unwrap();
3081        assert_eq!(sig.get_parameters().len(), 3);
3082
3083        let third_param = &sig.get_parameters()[2];
3084        assert!(third_param.has_default());
3085    }
3086
3087    #[test]
3088    fn test_expand_preserves_by_reference_flag() {
3089        let code = "<?php class Foo {}";
3090        let codebase = create_test_codebase(code);
3091
3092        let mut input = make_self_object();
3093        input.flags.insert(UnionFlags::BY_REFERENCE);
3094
3095        let options = options_with_self("Foo");
3096        let mut actual = input.clone();
3097        expand_union(&codebase, &mut actual, &options);
3098
3099        assert!(actual.flags.contains(UnionFlags::BY_REFERENCE));
3100    }
3101
3102    #[test]
3103    fn test_expand_preserves_possibly_undefined_flag() {
3104        let code = "<?php class Foo {}";
3105        let codebase = create_test_codebase(code);
3106
3107        let mut input = make_self_object();
3108        input.flags.insert(UnionFlags::POSSIBLY_UNDEFINED);
3109
3110        let options = options_with_self("Foo");
3111        let mut actual = input.clone();
3112        expand_union(&codebase, &mut actual, &options);
3113
3114        assert!(actual.flags.contains(UnionFlags::POSSIBLY_UNDEFINED));
3115    }
3116
3117    #[test]
3118    fn test_expand_multiple_self_in_union() {
3119        let code = "<?php class Foo {}";
3120        let codebase = create_test_codebase(code);
3121
3122        let input = TUnion::from_vec(vec![
3123            TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))),
3124            TAtomic::Object(TObject::Named(TNamedObject::new(word("self")))),
3125        ]);
3126
3127        let options = options_with_self("Foo");
3128        let mut actual = input;
3129        expand_union(&codebase, &mut actual, &options);
3130
3131        assert!(actual.types.len() <= 2);
3132    }
3133
3134    #[test]
3135    fn test_expand_deeply_nested_types() {
3136        let code = "<?php class Foo {}";
3137        let codebase = create_test_codebase(code);
3138
3139        let inner = TList::new(Arc::new(make_self_object()));
3140        let middle = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(inner)))));
3141        let outer = TList::new(Arc::new(TUnion::from_atomic(TAtomic::Array(TArray::List(middle)))));
3142        let input = TUnion::from_atomic(TAtomic::Array(TArray::List(outer)));
3143
3144        let options = options_with_self("Foo");
3145        let mut actual = input;
3146        expand_union(&codebase, &mut actual, &options);
3147
3148        if let TAtomic::Array(TArray::List(outer)) = &actual.types[0]
3149            && let TAtomic::Array(TArray::List(middle)) = &outer.element_type.types[0]
3150            && let TAtomic::Array(TArray::List(inner)) = &middle.element_type.types[0]
3151        {
3152            assert!(inner.element_type.types.iter().any(|t| {
3153                if let TAtomic::Object(TObject::Named(named)) = t {
3154                    named.name == ascii_lowercase_word(b"foo")
3155                } else {
3156                    false
3157                }
3158            }));
3159        }
3160    }
3161
3162    #[test]
3163    fn test_expand_with_all_options_disabled() {
3164        let code = "<?php class Foo {}";
3165        let codebase = create_test_codebase(code);
3166
3167        let input = make_self_object();
3168        let options = TypeExpansionOptions {
3169            self_class: None,
3170            static_class_type: StaticClassType::None,
3171            function_is_final: false,
3172            allow_mixin_static_rebind: false,
3173            preserve_parameter_dependencies: false,
3174        };
3175
3176        let mut actual = input;
3177        expand_union(&codebase, &mut actual, &options);
3178
3179        assert!(actual.types.iter().any(|t| {
3180            if let TAtomic::Object(TObject::Named(named)) = t { named.name == word("self") } else { false }
3181        }));
3182    }
3183
3184    #[test]
3185    fn test_expand_already_expanded_type() {
3186        let code = "<?php class Foo {}";
3187        let codebase = create_test_codebase(code);
3188
3189        let input = make_named_object("Foo");
3190        let options = options_with_self("Foo");
3191
3192        let mut actual = input;
3193        expand_union(&codebase, &mut actual, &options);
3194
3195        let mut actual2 = actual.clone();
3196        expand_union(&codebase, &mut actual2, &options);
3197
3198        assert_eq!(actual.types.as_ref(), actual2.types.as_ref());
3199    }
3200
3201    #[test]
3202    fn test_expand_complex_generic_class() {
3203        let code = "<?php
3204            /**
3205             * @template T
3206             * @template U
3207             */
3208            class Container {}
3209        ";
3210        let codebase = create_test_codebase(code);
3211
3212        let named = TNamedObject::new_with_type_parameters(
3213            ascii_lowercase_word(b"container"),
3214            Some(vec![make_self_object(), make_static_object()]),
3215        );
3216        let input = TUnion::from_atomic(TAtomic::Object(TObject::Named(named)));
3217
3218        let options = TypeExpansionOptions {
3219            self_class: Some(ascii_lowercase_word(b"foo")),
3220            static_class_type: StaticClassType::Name(ascii_lowercase_word(b"bar")),
3221            ..Default::default()
3222        };
3223
3224        let mut actual = input;
3225        expand_union(&codebase, &mut actual, &options);
3226
3227        if let TAtomic::Object(TObject::Named(named)) = &actual.types[0]
3228            && let Some(params) = &named.type_parameters
3229        {
3230            assert_eq!(params.len(), 2);
3231            assert!(params[0].types.iter().any(|t| {
3232                if let TAtomic::Object(TObject::Named(named)) = t {
3233                    named.name == ascii_lowercase_word(b"foo")
3234                } else {
3235                    false
3236                }
3237            }));
3238            assert!(params[1].types.iter().any(|t| {
3239                if let TAtomic::Object(TObject::Named(named)) = t {
3240                    named.name == ascii_lowercase_word(b"bar")
3241                } else {
3242                    false
3243                }
3244            }));
3245        }
3246    }
3247
3248    #[test]
3249    fn bounded_mask_combinations_combine_like_all_combinations() {
3250        use crate::ttype::atomic::mixed::truthiness::TMixedTruthiness;
3251
3252        let codebase = CodebaseMetadata::default();
3253        let literal = |value| TAtomic::Scalar(TScalar::literal_int(value));
3254        let neighbours: Vec<Vec<TAtomic>> = vec![
3255            vec![],
3256            vec![TAtomic::Mixed(TMixed::new())],
3257            vec![TAtomic::Mixed(TMixed::truthy())],
3258            vec![TAtomic::Mixed(TMixed::new().with_truthiness(TMixedTruthiness::Falsy))],
3259            vec![TAtomic::Mixed(TMixed::new().with_is_non_null(true))],
3260            vec![TAtomic::Mixed(TMixed::isset_from_loop())],
3261            vec![TAtomic::Scalar(TScalar::int())],
3262            vec![TAtomic::Scalar(TScalar::Integer(TInteger::positive()))],
3263            vec![literal(3), literal(-7)],
3264            (0..200)
3265                .map(|value| TAtomic::Scalar(TScalar::Integer(TInteger::from_bounds(Some(value), Some(value + 10)))))
3266                .collect(),
3267            vec![TAtomic::Scalar(TScalar::string())],
3268            vec![TAtomic::Scalar(TScalar::literal_string(word("a")))],
3269            vec![TAtomic::Scalar(TScalar::ArrayKey)],
3270            vec![TAtomic::Scalar(TScalar::Numeric)],
3271            vec![TAtomic::Scalar(TScalar::Generic)],
3272            vec![TAtomic::Scalar(TScalar::bool())],
3273            vec![TAtomic::Null],
3274            vec![TAtomic::Never],
3275        ];
3276
3277        for values in [&[1, 2, 4, 8, 16, 32, 64, 128, 256][..], &[-1024, -512, 1, 2, 4, 8, 16, 32, 64, 128]] {
3278            let all: Vec<TAtomic> = TIntMask::calculate_mask_combinations(values).into_iter().map(literal).collect();
3279            let bounded = mask_combinations(values);
3280            assert!(bounded.len() < all.len());
3281
3282            for before in &neighbours {
3283                for after in &neighbours {
3284                    let combine = |mask: &[TAtomic]| {
3285                        let types = before.iter().chain(mask).chain(after).cloned().collect();
3286                        combiner::combine(types, &codebase, combiner::CombinerOptions::default())
3287                    };
3288
3289                    assert_eq!(combine(&bounded), combine(&all), "{values:?} {before:?} {after:?}");
3290                }
3291            }
3292        }
3293    }
3294}