Skip to main content

mago_codex/ttype/
expander.rs

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