mago-codex 1.15.2

PHP type system representation, comparison logic, and codebase metadata for static analysis.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use foldhash::HashMap;
use foldhash::fast::RandomState;
use indexmap::IndexMap;
use serde::Deserialize;
use serde::Serialize;

use mago_atom::Atom;
use mago_atom::AtomMap;
use mago_atom::AtomSet;
use mago_reporting::Issue;
use mago_span::Span;

use crate::flags::attribute::AttributeFlags;
use crate::identifier::method::MethodIdentifier;
use crate::metadata::attribute::AttributeMetadata;
use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
use crate::metadata::enum_case::EnumCaseMetadata;
use crate::metadata::flags::MetadataFlags;
use crate::metadata::property::PropertyMetadata;
use crate::metadata::ttype::TypeMetadata;
use crate::symbol::SymbolKind;
use crate::ttype::atomic::TAtomic;
use crate::ttype::template::GenericTemplate;
use crate::ttype::template::variance::Variance;
use crate::ttype::union::TUnion;
use crate::visibility::Visibility;

/// Type alias for template types stored in metadata.
/// Maps template parameter names to their defining entity and constraint type.
pub type TemplateTypes = IndexMap<Atom, GenericTemplate, RandomState>;

/// Contains comprehensive metadata for a PHP class-like structure (class, interface, trait, enum).
///
/// Aggregates information about inheritance, traits, generics, methods, properties, constants,
/// attributes, docblock tags, analysis flags, and more.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ClassLikeMetadata {
    pub name: Atom,
    pub original_name: Atom,
    pub span: Span,
    pub direct_parent_interfaces: AtomSet,
    pub all_parent_interfaces: AtomSet,
    pub direct_parent_class: Option<Atom>,
    pub require_extends: AtomSet,
    pub require_implements: AtomSet,
    pub all_parent_classes: AtomSet,
    pub used_traits: AtomSet,
    pub trait_alias_map: AtomMap<Atom>,
    pub trait_visibility_map: AtomMap<Visibility>,
    pub trait_final_map: AtomSet,
    pub child_class_likes: Option<AtomSet>,
    pub name_span: Option<Span>,
    pub kind: SymbolKind,
    pub template_types: TemplateTypes,
    pub template_readonly: AtomSet,
    pub template_variance: HashMap<usize, Variance>,
    pub template_extended_offsets: AtomMap<Vec<TUnion>>,
    pub template_extended_parameters: AtomMap<IndexMap<Atom, TUnion, RandomState>>,
    pub template_type_extends_count: AtomMap<usize>,
    pub template_type_implements_count: AtomMap<usize>,
    pub template_type_uses_count: AtomMap<usize>,
    pub methods: AtomSet,
    pub pseudo_methods: AtomSet,
    pub static_pseudo_methods: AtomSet,
    pub declaring_method_ids: AtomMap<MethodIdentifier>,
    pub appearing_method_ids: AtomMap<MethodIdentifier>,
    pub inheritable_method_ids: AtomMap<MethodIdentifier>,
    pub overridden_method_ids: AtomMap<IndexMap<Atom, MethodIdentifier, RandomState>>,
    pub properties: AtomMap<PropertyMetadata>,
    pub appearing_property_ids: AtomMap<Atom>,
    pub declaring_property_ids: AtomMap<Atom>,
    pub inheritable_property_ids: AtomMap<Atom>,
    pub overridden_property_ids: AtomMap<AtomSet>,
    pub initialized_properties: AtomSet,
    pub constants: AtomMap<ClassLikeConstantMetadata>,
    pub trait_constant_ids: AtomMap<Atom>,
    pub enum_cases: AtomMap<EnumCaseMetadata>,
    pub invalid_dependencies: AtomSet,
    pub attributes: Vec<AttributeMetadata>,
    pub enum_type: Option<TAtomic>,
    pub has_sealed_methods: Option<bool>,
    pub has_sealed_properties: Option<bool>,
    pub permitted_inheritors: Option<AtomSet>,
    pub issues: Vec<Issue>,
    pub attribute_flags: Option<AttributeFlags>,
    pub flags: MetadataFlags,
    pub type_aliases: AtomMap<TypeMetadata>,
    /// Imported type aliases in the form of (`from_fqcn`, `type_name`, span)
    pub imported_type_aliases: AtomMap<(Atom, Atom, Span)>,
    /// Mixin types from @mixin annotations - these types' methods/properties
    /// can be accessed via magic methods (__call, __get, __set, __callStatic)
    pub mixins: Vec<TUnion>,
}

impl ClassLikeMetadata {
    #[must_use]
    pub fn new(
        name: Atom,
        original_name: Atom,
        span: Span,
        name_span: Option<Span>,
        flags: MetadataFlags,
    ) -> ClassLikeMetadata {
        ClassLikeMetadata {
            constants: AtomMap::default(),
            trait_constant_ids: AtomMap::default(),
            enum_cases: AtomMap::default(),
            flags,
            kind: SymbolKind::Class,
            direct_parent_interfaces: AtomSet::default(),
            all_parent_classes: AtomSet::default(),
            appearing_method_ids: AtomMap::default(),
            attributes: Vec::new(),
            all_parent_interfaces: AtomSet::default(),
            declaring_method_ids: AtomMap::default(),
            appearing_property_ids: AtomMap::default(),
            declaring_property_ids: AtomMap::default(),
            direct_parent_class: None,
            require_extends: AtomSet::default(),
            require_implements: AtomSet::default(),
            inheritable_method_ids: AtomMap::default(),
            enum_type: None,
            inheritable_property_ids: AtomMap::default(),
            initialized_properties: AtomSet::default(),
            invalid_dependencies: AtomSet::default(),
            span,
            name_span,
            methods: AtomSet::default(),
            pseudo_methods: AtomSet::default(),
            static_pseudo_methods: AtomSet::default(),
            overridden_method_ids: AtomMap::default(),
            overridden_property_ids: AtomMap::default(),
            properties: AtomMap::default(),
            template_variance: HashMap::default(),
            template_type_extends_count: AtomMap::default(),
            template_extended_parameters: AtomMap::default(),
            template_extended_offsets: AtomMap::default(),
            template_type_implements_count: AtomMap::default(),
            template_type_uses_count: AtomMap::default(),
            template_types: TemplateTypes::default(),
            used_traits: AtomSet::default(),
            trait_alias_map: AtomMap::default(),
            trait_visibility_map: AtomMap::default(),
            trait_final_map: AtomSet::default(),
            name,
            original_name,
            child_class_likes: None,
            template_readonly: AtomSet::default(),
            has_sealed_methods: None,
            has_sealed_properties: None,
            permitted_inheritors: None,
            issues: vec![],
            attribute_flags: None,
            type_aliases: AtomMap::default(),
            imported_type_aliases: AtomMap::default(),
            mixins: Vec::default(),
        }
    }

    /// Returns a reference to the map of trait method aliases.
    #[inline]
    #[must_use]
    pub fn get_trait_alias_map(&self) -> &AtomMap<Atom> {
        &self.trait_alias_map
    }

    /// Returns a vector of the generic type parameter names.
    #[inline]
    #[must_use]
    pub fn get_template_type_names(&self) -> Vec<Atom> {
        self.template_types.keys().copied().collect()
    }

    /// Returns type parameters for a specific generic parameter name.
    #[inline]
    #[must_use]
    pub fn get_template_type(&self, name: Atom) -> Option<&GenericTemplate> {
        self.template_types.get(&name)
    }

    /// Returns type parameters for a specific generic parameter name with its index.
    #[inline]
    #[must_use]
    pub fn get_template_type_with_index(&self, name: Atom) -> Option<(usize, &GenericTemplate)> {
        self.template_types.get_full(&name).map(|(index, _, types)| (index, types))
    }

    #[must_use]
    pub fn get_template_for_index(&self, index: usize) -> Option<(Atom, &GenericTemplate)> {
        self.template_types.get_index(index).map(|(name, types)| (*name, types))
    }

    #[must_use]
    pub fn get_template_name_for_index(&self, index: usize) -> Option<Atom> {
        self.template_types.get_index(index).map(|(name, _)| *name)
    }

    #[must_use]
    pub fn get_template_index_for_name(&self, name: Atom) -> Option<usize> {
        self.template_types.get_index_of(&name)
    }

    /// Checks if a specific parent is either a parent class or interface.
    #[inline]
    #[must_use]
    pub fn has_parent(&self, parent: Atom) -> bool {
        self.all_parent_classes.contains(&parent) || self.all_parent_interfaces.contains(&parent)
    }

    /// Checks if a specific parent has template extended parameters.
    #[inline]
    #[must_use]
    pub fn has_template_extended_parameter(&self, parent: Atom) -> bool {
        self.template_extended_parameters.contains_key(&parent)
    }

    /// Checks if a specific method appears in this class-like.
    #[inline]
    #[must_use]
    pub fn has_appearing_method(&self, method: Atom) -> bool {
        self.appearing_method_ids.contains_key(&method)
    }

    /// Returns a vector of property names.
    #[inline]
    #[must_use]
    pub fn get_property_names(&self) -> AtomSet {
        self.properties.keys().copied().collect()
    }

    /// Checks if a specific property appears in this class-like.
    #[inline]
    #[must_use]
    pub fn has_appearing_property(&self, name: Atom) -> bool {
        self.appearing_property_ids.contains_key(&name)
    }

    /// Checks if a specific property is declared in this class-like.
    #[inline]
    #[must_use]
    pub fn has_declaring_property(&self, name: Atom) -> bool {
        self.declaring_property_ids.contains_key(&name)
    }

    /// Takes ownership of the issues found for this class-like structure.
    #[inline]
    pub fn take_issues(&mut self) -> Vec<Issue> {
        std::mem::take(&mut self.issues)
    }

    /// Adds a single direct parent interface.
    #[inline]
    pub fn add_direct_parent_interface(&mut self, interface: Atom) {
        self.direct_parent_interfaces.insert(interface);
        self.all_parent_interfaces.insert(interface);
    }

    /// Adds a single interface to the list of all parent interfaces. Use with caution, normally derived.
    #[inline]
    pub fn add_all_parent_interface(&mut self, interface: Atom) {
        self.all_parent_interfaces.insert(interface);
    }

    /// Adds multiple interfaces to the list of all parent interfaces. Use with caution.
    #[inline]
    pub fn add_all_parent_interfaces(&mut self, interfaces: impl IntoIterator<Item = Atom>) {
        self.all_parent_interfaces.extend(interfaces);
    }

    /// Adds multiple ancestor classes. Use with caution.
    #[inline]
    pub fn add_all_parent_classes(&mut self, classes: impl IntoIterator<Item = Atom>) {
        self.all_parent_classes.extend(classes);
    }

    /// Adds a single used trait. Returns `true` if the trait was not already present.
    #[inline]
    pub fn add_used_trait(&mut self, trait_name: Atom) -> bool {
        self.used_traits.insert(trait_name)
    }

    /// Adds multiple used traits.
    #[inline]
    pub fn add_used_traits(&mut self, traits: impl IntoIterator<Item = Atom>) {
        self.used_traits.extend(traits);
    }

    /// Adds or updates a single trait alias. Returns the previous original name if one existed for the alias.
    #[inline]
    pub fn add_trait_alias(&mut self, method: Atom, alias: Atom) -> Option<Atom> {
        self.trait_alias_map.insert(method, alias)
    }

    /// Adds or updates a single trait visibility override. Returns the previous visibility if one existed.
    #[inline]
    pub fn add_trait_visibility(&mut self, method: Atom, visibility: Visibility) -> Option<Visibility> {
        self.trait_visibility_map.insert(method, visibility)
    }

    /// Adds a single template type definition.
    #[inline]
    pub fn add_template_type(&mut self, name: Atom, constraint: GenericTemplate) {
        self.template_types.insert(name, constraint);
    }

    /// Adds or updates the variance for a specific parameter index. Returns the previous variance if one existed.
    #[inline]
    pub fn add_template_variance_parameter(&mut self, index: usize, variance: Variance) -> Option<Variance> {
        self.template_variance.insert(index, variance)
    }

    /// Adds or replaces the offset types for a specific template parameter name.
    #[inline]
    pub fn add_template_extended_offset(&mut self, name: Atom, types: Vec<TUnion>) -> Option<Vec<TUnion>> {
        self.template_extended_offsets.insert(name, types)
    }

    /// Adds or replaces the resolved parameters for a specific parent FQCN.
    #[inline]
    pub fn extend_template_extended_parameters(
        &mut self,
        template_extended_parameters: AtomMap<IndexMap<Atom, TUnion, RandomState>>,
    ) {
        self.template_extended_parameters.extend(template_extended_parameters);
    }

    /// Adds or replaces a single resolved parameter for the parent FQCN.
    #[inline]
    pub fn add_template_extended_parameter(
        &mut self,
        parent_fqcn: Atom,
        parameter_name: Atom,
        parameter_type: TUnion,
    ) -> Option<TUnion> {
        self.template_extended_parameters.entry(parent_fqcn).or_default().insert(parameter_name, parameter_type)
    }

    /// Adds or updates the declaring method identifier for a method name.
    #[inline]
    pub fn add_declaring_method_id(
        &mut self,
        method: Atom,
        declaring_method_id: MethodIdentifier,
    ) -> Option<MethodIdentifier> {
        self.add_appearing_method_id(method, declaring_method_id);
        self.declaring_method_ids.insert(method, declaring_method_id)
    }

    /// Adds or updates the appearing method identifier for a method name.
    #[inline]
    pub fn add_appearing_method_id(
        &mut self,
        method: Atom,
        appearing_method_id: MethodIdentifier,
    ) -> Option<MethodIdentifier> {
        self.appearing_method_ids.insert(method, appearing_method_id)
    }

    /// Adds a parent method identifier to the map for an overridden method. Initializes map if needed. Returns the previous value if one existed.
    #[inline]
    pub fn add_overridden_method_parent(
        &mut self,
        method: Atom,
        parent_method_id: MethodIdentifier,
    ) -> Option<MethodIdentifier> {
        self.overridden_method_ids
            .entry(method)
            .or_default()
            .insert(parent_method_id.get_class_name(), parent_method_id)
    }

    /// Adds or updates a property's metadata. Returns the previous metadata if the property existed.
    #[inline]
    pub fn add_property(&mut self, name: Atom, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
        let class_name = self.name;

        self.add_declaring_property_id(name, class_name);
        if property_metadata.flags.has_default() {
            self.initialized_properties.insert(name);
        }

        if !property_metadata.is_final() {
            self.inheritable_property_ids.insert(name, class_name);
        }

        self.properties.insert(name, property_metadata)
    }

    /// Adds or updates a property's metadata using just the property metadata. Returns the previous metadata if the property existed.
    #[inline]
    pub fn add_property_metadata(&mut self, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
        let name = property_metadata.get_name().0;

        self.add_property(name, property_metadata)
    }

    /// Adds or updates the declaring class FQCN for a property name.
    #[inline]
    pub fn add_declaring_property_id(&mut self, prop: Atom, declaring_fqcn: Atom) -> Option<Atom> {
        self.appearing_property_ids.insert(prop, declaring_fqcn);
        self.declaring_property_ids.insert(prop, declaring_fqcn)
    }

    #[must_use]
    pub fn get_missing_required_interface<'a>(&self, other: &'a ClassLikeMetadata) -> Option<&'a Atom> {
        for required_interface in &other.require_implements {
            if self.all_parent_interfaces.contains(required_interface) {
                continue;
            }

            if (self.flags.is_abstract() || self.kind.is_trait())
                && self.require_implements.contains(required_interface)
            {
                continue; // Abstract classes and traits can require interfaces they implement
            }

            return Some(required_interface);
        }

        None
    }

    #[must_use]
    pub fn get_missing_required_extends<'a>(&self, other: &'a ClassLikeMetadata) -> Option<&'a Atom> {
        for required_extend in &other.require_extends {
            if self.all_parent_classes.contains(required_extend) {
                continue;
            }

            if self.kind.is_interface() && self.all_parent_interfaces.contains(required_extend) {
                continue;
            }

            if (self.flags.is_abstract() || self.kind.is_trait()) && self.require_extends.contains(required_extend) {
                continue; // Abstract classes and traits can require classes they extend
            }

            return Some(required_extend);
        }

        None
    }

    #[must_use]
    pub fn is_permitted_to_inherit(&self, other: &ClassLikeMetadata) -> bool {
        if self.kind.is_trait() || self.flags.is_abstract() {
            return true; // Traits and abstract classes can always inherit
        }

        let Some(permitted_inheritors) = &other.permitted_inheritors else {
            return true; // No restrictions, inheriting is allowed
        };

        if permitted_inheritors.contains(&self.name) {
            return true; // This class-like is explicitly permitted to inherit
        }

        self.all_parent_interfaces.iter().any(|parent_interface| permitted_inheritors.contains(parent_interface))
            || self.all_parent_classes.iter().any(|parent_class| permitted_inheritors.contains(parent_class))
            || self.used_traits.iter().any(|used_trait| permitted_inheritors.contains(used_trait))
    }

    #[inline]
    pub fn mark_as_populated(&mut self) {
        self.flags |= MetadataFlags::POPULATED;
        self.shrink_to_fit();
    }

    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.properties.shrink_to_fit();
        self.initialized_properties.shrink_to_fit();
        self.appearing_property_ids.shrink_to_fit();
        self.declaring_property_ids.shrink_to_fit();
        self.inheritable_property_ids.shrink_to_fit();
        self.overridden_property_ids.shrink_to_fit();
        self.appearing_method_ids.shrink_to_fit();
        self.declaring_method_ids.shrink_to_fit();
        self.inheritable_method_ids.shrink_to_fit();
        self.overridden_method_ids.shrink_to_fit();
        self.attributes.shrink_to_fit();
        self.constants.shrink_to_fit();
        self.enum_cases.shrink_to_fit();
        self.type_aliases.shrink_to_fit();
    }
}