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