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
use mago_atom::Atom;
use mago_atom::AtomSet;
use mago_reporting::Annotation;
use mago_reporting::Issue;

use crate::identifier::method::MethodIdentifier;
use crate::metadata::CodebaseMetadata;
use crate::metadata::class_like::ClassLikeMetadata;
use crate::metadata::flags::MetadataFlags;
use crate::metadata::ttype::TypeMetadata;
use crate::reference::ReferenceSource;
use crate::reference::SymbolReferences;
use crate::ttype::TType;
use crate::ttype::TypeRef;
use crate::ttype::atomic::TAtomic;
use crate::ttype::atomic::alias::TAlias;
use crate::ttype::atomic::populate_atomic_type;
use crate::ttype::atomic::reference::TReference;
use crate::ttype::union::TUnion;
use crate::ttype::union::populate_union_type;

use super::merge::merge_interface_metadata_from_parent_interface;
use super::merge::merge_metadata_from_parent_class_like;
use super::merge::merge_metadata_from_required_class_like;
use super::merge::merge_metadata_from_trait;

#[inline]
fn sorted_atoms(iter: impl Iterator<Item = Atom>) -> Vec<Atom> {
    let mut values: Vec<_> = iter.collect();
    if values.len() > 1 {
        values.sort_unstable();
    }

    values
}

/// Detects circular references in a type definition by walking its dependencies.
///
/// Returns `Some(chain)` if a cycle is detected, where chain is the path of type names forming the cycle.
/// Returns `None` if no cycle is found.
fn detect_circular_type_reference(
    type_name: Atom,
    type_metadata: &TypeMetadata,
    all_aliases: &mago_atom::AtomMap<TypeMetadata>,
    visiting: &mut AtomSet,
    path: &mut Vec<String>,
) -> Option<Vec<String>> {
    // If we're already visiting this type, we found a cycle
    if visiting.contains(&type_name) {
        let mut cycle_chain = path.clone();
        cycle_chain.push(type_name.to_string());
        return Some(cycle_chain);
    }

    // Mark as visiting
    visiting.insert(type_name);
    path.push(type_name.to_string());

    // Walk through the type union looking for type alias references
    if let Some(cycle) = check_union_for_circular_refs(&type_metadata.type_union, all_aliases, visiting, path) {
        return Some(cycle);
    }

    // Done visiting this type
    visiting.remove(&type_name);
    path.pop();
    None
}

/// Recursively checks a `TUnion` for circular type alias references.
fn check_union_for_circular_refs(
    type_union: &TUnion,
    all_aliases: &mago_atom::AtomMap<TypeMetadata>,
    visiting: &mut AtomSet,
    path: &mut Vec<String>,
) -> Option<Vec<String>> {
    let nodes = type_union.get_all_child_nodes();
    for node in nodes {
        if let TypeRef::Atomic(TAtomic::Reference(TReference::Symbol { name, .. })) = node {
            if let Some(referenced_type) = all_aliases.get(name)
                && let Some(cycle) = detect_circular_type_reference(*name, referenced_type, all_aliases, visiting, path)
            {
                return Some(cycle);
            }
        } else {
            // Other types are not relevant for circular reference detection
        }
    }

    None
}

/// Populates the metadata for a single class-like iteratively (non-recursive).
///
/// This version assumes all dependencies have already been processed (via topological ordering).
/// It uses the remove/insert pattern to handle mutable borrowing, but no recursion.
///
/// # Safety
/// This function assumes the topological ordering guarantees that all dependencies
/// (parent classes, interfaces, traits) have already been populated.
/// Populates the metadata for a single class-like iteratively (non-recursive).
pub fn populate_class_like_metadata_iterative(
    classlike_name: Atom,
    codebase: &mut CodebaseMetadata,
    symbol_references: &mut SymbolReferences,
) {
    if let Some(metadata) = codebase.class_likes.get(&classlike_name)
        && metadata.flags.is_populated()
    {
        return; // Already done, exit early
    }

    let Some(mut metadata) = codebase.class_likes.remove(&classlike_name) else {
        return;
    };

    for attribute_metadata in &metadata.attributes {
        symbol_references.add_symbol_reference_to_symbol(metadata.name, attribute_metadata.name, true);
    }

    for property_name in metadata.get_property_names() {
        metadata.add_declaring_property_id(property_name, classlike_name);
    }

    for method_name in &metadata.methods {
        let method_id = MethodIdentifier::new(classlike_name, *method_name);
        metadata.appearing_method_ids.insert(*method_name, method_id);
        metadata.declaring_method_ids.insert(*method_name, method_id);
    }

    for trait_name in sorted_atoms(metadata.used_traits.iter().copied()) {
        merge_metadata_from_trait(&mut metadata, codebase, trait_name, symbol_references);
    }

    if let Some(parent_classname) = metadata.direct_parent_class {
        merge_metadata_from_parent_class_like(&mut metadata, codebase, parent_classname, symbol_references);
    }

    let direct_parent_interfaces = sorted_atoms(metadata.direct_parent_interfaces.iter().copied());
    for direct_parent_interface in direct_parent_interfaces {
        merge_interface_metadata_from_parent_interface(
            &mut metadata,
            codebase,
            direct_parent_interface,
            symbol_references,
        );
    }

    for required_class in sorted_atoms(metadata.require_extends.iter().copied()) {
        merge_metadata_from_required_class_like(&mut metadata, codebase, required_class, symbol_references);
    }

    for required_interface in sorted_atoms(metadata.require_implements.iter().copied()) {
        merge_interface_metadata_from_parent_interface(&mut metadata, codebase, required_interface, symbol_references);
    }

    if metadata.flags.is_readonly() {
        for property_metadata in metadata.properties.values_mut() {
            if !property_metadata.flags.is_static() {
                property_metadata.flags |= MetadataFlags::READONLY;
            }
        }
    }

    let pending_imports = std::mem::take(&mut metadata.imported_type_aliases);
    for (local_name, (source_class_name, imported_type, import_span)) in pending_imports {
        if let Some(source_class) = codebase.class_likes.get(&source_class_name) {
            if source_class.type_aliases.contains_key(&imported_type) {
                let alias_metadata = TypeMetadata {
                    span: import_span,
                    type_union: TUnion::from_atomic(TAtomic::Alias(TAlias::new(source_class_name, imported_type))),
                    from_docblock: true,
                    inferred: false,
                };

                metadata.type_aliases.insert(local_name, alias_metadata);
            } else {
                metadata.issues.push(
                    Issue::error(format!("Type alias `{imported_type}` not found in class `{source_class_name}`"))
                        .with_code("invalid-import-type")
                        .with_annotation(Annotation::primary(import_span))
                        .with_help(format!(
                            "Ensure that class `{source_class_name}` defines a `@type {imported_type}` alias"
                        )),
                );
            }
        } else if !codebase.symbols.contains(source_class_name) {
            metadata.issues.push(
                Issue::error(format!("Class `{source_class_name}` not found for type import"))
                    .with_code("unknown-class-in-import-type")
                    .with_annotation(Annotation::primary(import_span))
                    .with_help(format!("Ensure that class `{source_class_name}` is defined and scanned")),
            );
        }
    }

    for (type_name, type_metadata) in &metadata.type_aliases {
        let mut visiting = AtomSet::default();
        let mut path = Vec::new();

        if let Some(cycle) =
            detect_circular_type_reference(*type_name, type_metadata, &metadata.type_aliases, &mut visiting, &mut path)
        {
            metadata.issues.push(
                Issue::error(format!("Circular type reference detected: {}", cycle.join(" → ")))
                    .with_code(crate::issue::ScanningIssueKind::CircularTypeImport)
                    .with_annotation(
                        Annotation::primary(type_metadata.span)
                            .with_message("This type is part of a circular reference chain"),
                    )
                    .with_note(format!("The type reference chain creates a cycle: {}", cycle.join(" references ")))
                    .with_help("Reorganize your type definitions to avoid circular dependencies"),
            );
        }
    }

    if !metadata.type_aliases.is_empty() {
        for method_name in &metadata.methods {
            let method_id = (classlike_name, *method_name);
            if let Some(method_metadata) = codebase.function_likes.get_mut(&method_id) {
                let mut updated_context = method_metadata.type_resolution_context.clone().unwrap_or_default();
                for alias_name in metadata.type_aliases.keys() {
                    updated_context = updated_context.with_type_alias(*alias_name);
                }

                method_metadata.type_resolution_context = Some(updated_context);
            }
        }
    }

    metadata.mark_as_populated();
    codebase.class_likes.insert(classlike_name, metadata);
}

/// Populates types for properties, constants, enum cases, and type aliases within a class-like.
pub fn populate_class_like_types(
    name: Atom,
    metadata: &mut ClassLikeMetadata,
    codebase_symbols: &crate::symbol::Symbols,
    symbol_references: &mut SymbolReferences,
    force_repopulation: bool,
) {
    let class_like_reference_source = ReferenceSource::Symbol(true, name);

    for (property_name, property_metadata) in &mut metadata.properties {
        let property_reference_source = ReferenceSource::ClassLikeMember(true, name, *property_name);

        if let Some(signature) = property_metadata.type_declaration_metadata.as_mut() {
            populate_union_type(
                &mut signature.type_union,
                codebase_symbols,
                Some(&property_reference_source),
                symbol_references,
                force_repopulation,
            );
        }

        if let Some(signature) = property_metadata.type_metadata.as_mut() {
            populate_union_type(
                &mut signature.type_union,
                codebase_symbols,
                Some(&property_reference_source),
                symbol_references,
                force_repopulation,
            );
        }

        if let Some(default) = property_metadata.default_type_metadata.as_mut() {
            populate_union_type(
                &mut default.type_union,
                codebase_symbols,
                Some(&property_reference_source),
                symbol_references,
                force_repopulation,
            );
        }

        for hook in property_metadata.hooks.values_mut() {
            if let Some(hook_return_type) = &mut hook.return_type_metadata {
                populate_union_type(
                    &mut hook_return_type.type_union,
                    codebase_symbols,
                    Some(&property_reference_source),
                    symbol_references,
                    force_repopulation,
                );
            }

            let Some(hook_parameter) = hook.parameter.as_mut() else {
                continue;
            };

            if let Some(hook_parameter_type_declaration) = &mut hook_parameter.type_declaration_metadata {
                populate_union_type(
                    &mut hook_parameter_type_declaration.type_union,
                    codebase_symbols,
                    Some(&property_reference_source),
                    symbol_references,
                    force_repopulation,
                );
            }

            if let Some(hook_parameter_type) = &mut hook_parameter.type_metadata {
                populate_union_type(
                    &mut hook_parameter_type.type_union,
                    codebase_symbols,
                    Some(&property_reference_source),
                    symbol_references,
                    force_repopulation,
                );
            }

            if let Some(hook_parameter_out_type) = &mut hook_parameter.out_type {
                populate_union_type(
                    &mut hook_parameter_out_type.type_union,
                    codebase_symbols,
                    Some(&property_reference_source),
                    symbol_references,
                    force_repopulation,
                );
            }

            if let Some(hook_parameter_default_type) = &mut hook_parameter.default_type {
                populate_union_type(
                    &mut hook_parameter_default_type.type_union,
                    codebase_symbols,
                    Some(&property_reference_source),
                    symbol_references,
                    force_repopulation,
                );
            }
        }
    }

    for template in metadata.template_types.values_mut() {
        if template.constraint.needs_population() || force_repopulation {
            populate_union_type(
                &mut template.constraint,
                codebase_symbols,
                Some(&class_like_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    for template in &mut metadata.template_extended_offsets.values_mut().flatten() {
        if template.needs_population() || force_repopulation {
            populate_union_type(
                template,
                codebase_symbols,
                Some(&class_like_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    for p in metadata.template_extended_parameters.values_mut().flat_map(|m| m.values_mut()) {
        if p.needs_population() || force_repopulation {
            populate_union_type(
                p,
                codebase_symbols,
                Some(&class_like_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    for type_alias in metadata.type_aliases.values_mut() {
        populate_union_type(
            &mut type_alias.type_union,
            codebase_symbols,
            Some(&class_like_reference_source),
            symbol_references,
            force_repopulation,
        );
    }

    for mixin_type in &mut metadata.mixins {
        if mixin_type.needs_population() || force_repopulation {
            populate_union_type(
                mixin_type,
                codebase_symbols,
                Some(&class_like_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    for (constant_name, constant) in &mut metadata.constants {
        let constant_reference_source = ReferenceSource::ClassLikeMember(true, name, *constant_name);

        for attribute_metadata in &constant.attributes {
            symbol_references.add_class_member_reference_to_symbol(
                (name, *constant_name),
                attribute_metadata.name,
                true,
            );
        }

        if let Some(signature) = &mut constant.type_metadata {
            populate_union_type(
                &mut signature.type_union,
                codebase_symbols,
                Some(&constant_reference_source),
                symbol_references,
                force_repopulation,
            );
        }

        if let Some(inferred) = &mut constant.inferred_type {
            populate_atomic_type(
                inferred,
                codebase_symbols,
                Some(&constant_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    for (enum_case_name, enum_case) in &mut metadata.enum_cases {
        let enum_case_reference_source = ReferenceSource::ClassLikeMember(true, name, *enum_case_name);

        for attribute_metadata in &enum_case.attributes {
            symbol_references.add_class_member_reference_to_symbol(
                (name, *enum_case_name),
                attribute_metadata.name,
                true,
            );
        }

        if let Some(value_type) = &mut enum_case.value_type {
            populate_atomic_type(
                value_type,
                codebase_symbols,
                Some(&enum_case_reference_source),
                symbol_references,
                force_repopulation,
            );
        }
    }

    if let Some(enum_type) = &mut metadata.enum_type {
        populate_atomic_type(
            enum_type,
            codebase_symbols,
            Some(&ReferenceSource::Symbol(true, name)),
            symbol_references,
            force_repopulation,
        );
    }
}