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