mago-analyzer 1.24.0

A PHP static analyzer that can detect type errors in PHP code, and provide suggestions for fixing them.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::rc::Rc;

use mago_atom::Atom;
use mago_codex::ttype::TType;
use mago_codex::ttype::TypeRef;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::reference::TReference;
use mago_codex::ttype::builder::get_type_from_string;
use mago_codex::ttype::comparator::ComparisonResult;
use mago_codex::ttype::comparator::union_comparator::can_expression_types_be_identical;
use mago_codex::ttype::comparator::union_comparator::is_contained_by;
use mago_codex::ttype::expander;
use mago_codex::ttype::expander::TypeExpansionOptions;
use mago_codex::ttype::union::TUnion;
use mago_codex::ttype::union::populate_union_type;
use mago_docblock::document::Element;
use mago_docblock::document::TagKind;
use mago_docblock::tag::parse_var_tag;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::Expression;

use crate::artifacts::AnalysisArtifacts;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;

/// Populates the context with variable types defined in the docblock.
///
/// This function retrieves all `@var`, `@psalm-var`, and `@phpstan-var` tags from the docblock
/// of the current statement in the context, parses their variable types, and inserts them
/// into the current block context.
///
/// # Arguments
///
/// * `context`: The main analysis context, providing access to the docblock parser and error collector.
/// * `block_context`: The current block context, which holds local variables and their types.
/// * `artifacts`: The analysis artifacts, which may be used to store or retrieve additional information.
/// * `override_existing`: A boolean indicating whether to override existing variable types in the block context.
pub fn populate_docblock_variables<'ctx>(
    context: &mut Context<'ctx, '_>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    override_existing: bool,
) {
    populate_docblock_variables_excluding(context, block_context, artifacts, override_existing, None);
}

/// Same as `populate_docblock_variables`, but allows excluding a specific variable.
///
/// This is useful for assignment statements where we want to populate all @var annotations
/// except the one for the assignment target (which is handled by the assignment analyzer).
pub fn populate_docblock_variables_excluding<'ctx>(
    context: &mut Context<'ctx, '_>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    override_existing: bool,
    exclude_variable: Option<Atom>,
) {
    for (name, variable_type, variable_type_span) in get_docblock_variables(context, block_context, artifacts, true) {
        // Check for undefined type references in ALL @var types, regardless of variable name.
        for type_ref in variable_type.get_all_child_nodes() {
            let TypeRef::Atomic(TAtomic::Reference(TReference::Symbol { name: ref_name, .. })) = type_ref else {
                continue;
            };

            context.collector.report_with_code(
                IssueCode::NonExistentClassLike,
                Issue::error(format!("Cannot find class, interface, enum, or type alias `{ref_name}`."))
                    .with_annotation(
                        Annotation::primary(variable_type_span)
                            .with_message(format!("`{ref_name}` is not defined in the current codebase")),
                    )
                    .with_note("This error occurs when a type is referenced but not found in any analyzed source files or stubs.")
                    .with_note("If this type comes from an optional dependency or extension, you can safely suppress this issue using `@mago-ignore` or `@mago-expect`.")
                    .with_help("Verify the type name is spelled correctly, the file containing it is included in analysis, and any required `use` statements are present."),
            );
        }

        let Some(variable_name) = name else {
            continue;
        };

        // Skip if this variable should be excluded (handled by assignment analyzer)
        if exclude_variable.is_some_and(|excluded| variable_name.as_str() == excluded) {
            continue;
        }

        insert_variable_from_docblock(
            context,
            block_context,
            variable_name,
            variable_type,
            variable_type_span,
            override_existing,
        );
    }
}

/// Retrieves all `@var`, `@psalm-var`, and `@phpstan-var` tags from the docblocks preceding the
/// current statement in the context, parsing their variable types.
///
/// This function scans the docblocks associated with the current statement in the context,
/// extracting all variable type declarations. It returns a vector of tuples, each containing:
///
/// - An optional variable name (if specified in the tag)
/// - The parsed type as a `TUnion`
/// - The span of the tag in the source code.
///
/// # Arguments
///
/// * `context`: The main analysis context, providing access to the docblock parser and error collector.
/// * `block_context`: The current block context, which may influence the parsing of docblocks.
/// * `artifacts`: The analysis artifacts, which may be used to store or retrieve additional information.
///
/// # Returns
///
/// A vector of tuples, where each tuple contains:
///
/// - `Option<String>`: The variable name if specified, or `None` if the tag is unnamed.
/// - `TUnion`: The parsed type from the tag.
/// - `Span`: The span of the tag in the source code.
pub fn get_docblock_variables<'ctx>(
    context: &mut Context<'ctx, '_>,
    block_context: &BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    allow_tracing: bool,
) -> Vec<(Option<mago_atom::Atom>, TUnion, Span)> {
    context.get_parsed_docblocks()
        .into_iter()
        // Filter out non-tag elements
        .filter_map(|element| match element {
            Element::Tag(tag) => Some(tag),
            _ => None,
        })
        .filter_map(|tag| {
            if allow_tracing && let TagKind::PsalmTrace = tag.kind {
                let variable_name = tag.description.trim();
                let variable_atom = mago_atom::atom(variable_name);
                match block_context.locals.get(&variable_atom) {
                    Some(variable_type) => {
                        let variable_type_str = variable_type.get_id();


                        context.collector.report_with_code(
                            IssueCode::PsalmTrace,
                            Issue::note(format!(
                                "Trace: Type of `{variable_name}` is `{variable_type_str}`"
                            ))
                            .with_annotation(
                                Annotation::primary(tag.description_span)
                                    .with_message(format!("Type is: `{variable_type_str}`")),
                            )
                            .with_note(
                                "Spotted a `@psalm-trace` tag! While this works for compatibility, Mago has a more powerful way to inspect types.",
                            )
                            .with_help(
                                "For more flexible debugging, try using `Mago\\inspect()` directly in your code. It can inspect any expression, not just variables (e.g., `Mago\\inspect($foo->bar());`)."
                            ),
                        );
                    }
                    None => {
                        context.collector.report_with_code(
                            IssueCode::InvalidDocblock,
                            Issue::error(format!(
                                "Invalid `@psalm-trace`: Variable `{variable_name}` not found in this scope."
                            ))
                            .with_annotation(Annotation::primary(tag.description_span).with_message(
                                "This variable is not defined or is out of scope here",
                            ))
                            .with_help(
                                "Check for typos or ensure the variable is defined on a path that reaches this docblock.",
                            ),
                        );
                    }
                }

                return None;
            }

            if !matches!(tag.kind, TagKind::Var | TagKind::PsalmVar | TagKind::PhpstanVar) {
                return None;
            }

            let tag_content = tag.description;

            let var_tag = parse_var_tag(tag_content, tag.description_span).ok()?;
            let variable_name = var_tag.variable.map(|v| mago_atom::Atom::from(&v.name));
            let type_string = var_tag.type_string;

            match get_type_from_string(
                &type_string.value,
                type_string.span,
                &context.scope,
                &context.type_resolution_context,
                block_context.scope.get_class_like_name(),
            ) {
                Ok(mut variable_type) => {
                    populate_union_type(
                        &mut variable_type,
                        &context.codebase.symbols,
                        block_context.scope.get_reference_source().as_ref(),
                        &mut artifacts.symbol_references,
                        true,
                    );

                    expander::expand_union(
                        context.codebase,
                        &mut variable_type,
                        &TypeExpansionOptions {
                            self_class: block_context.scope.get_class_like_name(),
                            ..Default::default()
                        },
                    );

                    Some((variable_name, variable_type, type_string.span))
                }
                Err(type_error) => {
                    context.collector.report_with_code(
                        IssueCode::InvalidDocblock,
                        Issue::error(format!(
                            "Invalid type in `@var` tag for variable `{}`.",
                            variable_name.as_deref().unwrap_or("expression")
                        ))
                        .with_annotation(Annotation::primary(type_error.span()).with_message(type_error.to_string()))
                        .with_note(type_error.note())
                        .with_help(type_error.help()),
                    );

                    None
                }
            }
        })
        .collect::<Vec<_>>()
}

/// Finds the last applicable `@var` tag for a given variable and parses its type string.
///
/// This function retrieves the docblock associated with the current statement from the
/// context. It then iterates through all `@var`, `@psalm-var`, and `@phpstan-var` tags
/// to find the last one that applies to the specified `variable_id`. If a matching
/// tag is found, it attempts to parse the type string into a `TUnion`.
///
/// If parsing fails, a detailed error is reported to the user.
///
/// # Arguments
///
/// * `context`: The main analysis context, providing access to the docblock parser and error collector.
/// * `variable_id`: The name of the variable (e.g., "$foo") for which to find a type hint.
/// * `variable_span`: The span of the variable's usage, used for error reporting context.
///
/// # Returns
///
/// An `Option<TUnion>` containing the parsed type if a valid, matching `@var` tag
/// was found and successfully parsed. Returns `None` otherwise.
pub fn get_type_from_var_docblock<'ctx>(
    context: &mut Context<'ctx, '_>,
    block_context: &BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    value_expression_variable_id: Option<&str>,
    mut allow_unnamed: bool,
) -> Option<(TUnion, Span)> {
    allow_unnamed =
        allow_unnamed && !block_context.flags.inside_return() && !block_context.flags.inside_loop_expressions();

    get_docblock_variables(context, block_context, artifacts, false)
        .into_iter()
        .rfind(|(var_name, _, _)| match var_name {
            None if allow_unnamed => true,
            Some(name) if Some(name.as_str()) == value_expression_variable_id => true,
            _ => false,
        })
        .map(|(_, variable_type, variable_type_span)| (variable_type, variable_type_span))
}

/// Inserts a variable type from a docblock into the current block context.
///
/// This function is used to handle `@var` tags in docblocks, allowing the
/// type of a variable to be defined or overridden based on the docblock's
/// annotations. It checks if the variable already exists in the block context,
/// and if so, it verifies that the new type is compatible with the existing type.
///
/// # Arguments
///
/// * `context`: The main analysis context, providing access to the error collector.
/// * `block_context`: The current block context, which holds local variables and their types.
/// * `variable_name`: The name of the variable as specified in the docblock.
/// * `variable_type`: The type of the variable as a `TUnion`, parsed from the docblock.
/// * `variable_type_span`: The span of the variable type in the source code, used for error reporting.
/// * `override_existing`: A boolean indicating whether to override an existing variable type
pub fn insert_variable_from_docblock<'ctx>(
    context: &mut Context<'ctx, '_>,
    block_context: &mut BlockContext<'ctx>,
    variable_name: mago_atom::Atom,
    variable_type: TUnion,
    variable_type_span: Span,
    override_existing: bool,
) {
    if !override_existing && block_context.locals.contains_key(&variable_name) {
        return;
    }

    if let Some(previous_type) = block_context.locals.remove(&variable_name) {
        let is_super = is_contained_by(
            context.codebase,
            &variable_type,
            &previous_type,
            false,
            false,
            false,
            &mut ComparisonResult::default(),
        );

        let is_sub = is_contained_by(
            context.codebase,
            &previous_type,
            &variable_type,
            false,
            false,
            false,
            &mut ComparisonResult::default(),
        );

        let is_redundant = is_super
            && is_sub
            && !variable_type.is_mixed()
            && !previous_type.is_mixed()
            && !variable_type.is_generic_parameter()
            && !previous_type.is_generic_parameter()
            && !previous_type.contains_placeholder();

        let is_impossible = !is_redundant
            && !is_super
            && !is_sub
            && !can_expression_types_be_identical(context.codebase, &previous_type, &variable_type, false, false);

        if is_impossible {
            let variable_type_str = variable_type.get_id();
            let previous_type_str = previous_type.get_id();

            context.collector.report_with_code(
                IssueCode::DocblockTypeMismatch,
                Issue::error(format!("Docblock type mismatch for variable `{variable_name}`."))
                    .with_annotation(
                        Annotation::primary(variable_type_span)
                            .with_message(format!("This docblock asserts the type should be `{variable_type_str}`, but it was previously defined as `{previous_type_str}`.")),
                    )
                    .with_note("The type of the variable defined in the docblock does not match the previously defined type.")
                    .with_help(format!(
                        "Change the docblock type to match `{previous_type_str}`, or update the variable definition to a compatible type `{variable_type_str}`."
                    )),
            );
        } else if is_redundant {
            context.collector.report_with_code(
                IssueCode::RedundantDocblockType,
                Issue::warning(format!("Redundant docblock type for variable `{variable_name}`."))
                    .with_annotation(Annotation::primary(variable_type_span).with_message(format!(
                        "This docblock asserts the type should be `{}`, which is identical to the previously defined type.",
                        variable_type.get_id(),
                    )))
                    .with_help("You can remove this redundant `@var` docblock tag."),
            );
        }
    }

    block_context.locals.insert(variable_name, Rc::new(variable_type));
}

pub fn check_docblock_type_incompatibility(
    context: &mut Context<'_, '_>,
    value_expression_variable_id: Option<&str>,
    value_expression_span: Span,
    inferred_type: &TUnion,
    docblock_type: &TUnion,
    dockblock_type_span: Span,
    source_expression: Option<&Expression>,
) {
    let is_super = is_contained_by(
        context.codebase,
        docblock_type,
        inferred_type,
        false,
        false,
        false,
        &mut ComparisonResult::default(),
    );

    let is_sub = is_contained_by(
        context.codebase,
        inferred_type,
        docblock_type,
        false,
        false,
        false,
        &mut ComparisonResult::default(),
    );

    let is_redundant = is_super
        && is_sub
        && !docblock_type.is_mixed()
        && !inferred_type.is_mixed()
        && !docblock_type.is_generic_parameter()
        && !inferred_type.is_generic_parameter()
        && !inferred_type.contains_placeholder();

    let is_impossible = !is_redundant
        && !is_super
        && !is_sub
        && !can_expression_types_be_identical(context.codebase, inferred_type, docblock_type, false, true);

    if is_impossible {
        let docblock_type_str = docblock_type.get_id();
        let inferred_type_str = inferred_type.get_id();

        let mut issue = if let Some(value_expression_variable_id) = value_expression_variable_id {
            Issue::error(format!("Docblock type mismatch for variable `{value_expression_variable_id}`."))
                .with_annotation(
                    Annotation::primary(dockblock_type_span)
                        .with_message(format!("This docblock asserts the type should be `{docblock_type_str}`...")),
                )
        } else {
            Issue::error("Docblock type mismatch for expression.".to_string()).with_annotation(
                Annotation::primary(dockblock_type_span)
                    .with_message(format!("This docblock asserts the type should be `{docblock_type_str}`...")),
            )
        };

        if let Some(value_expression_variable_id) = value_expression_variable_id {
            if let Some(source_expression) = source_expression {
                issue = issue.with_annotation(Annotation::secondary(source_expression.span()).with_message(format!(
                    "...but this expression provides an incompatible type `{inferred_type_str}`."
                )));
            }

            issue = issue.with_annotation(
                Annotation::secondary(value_expression_span)
                    .with_message(format!("The assignment to `{value_expression_variable_id}` here is invalid.")),
            ) .with_note(
                "The type of the assigned value and the `@var` docblock type have no overlap, making this assignment impossible."
            )
            .with_help(format!(
                "Change the assigned value to match `{docblock_type_str}`, or update the `@var` tag to a compatible type."
            ));
        } else {
            issue = issue.with_annotation(
                Annotation::secondary(value_expression_span)
                    .with_message(format!("...but this expression provides an incompatible type `{inferred_type_str}`.")),
            )
            .with_note(
                "The type resolved from the docblock and the type of the expression have no overlap, making the docblock type invalid.",
            )
            .with_help(format!(
                "Change the expression to match `{docblock_type_str}`, or update the `@var` tag to a compatible type."
            ));
        }

        context.collector.report_with_code(IssueCode::DocblockTypeMismatch, issue);

        return;
    }

    if is_redundant {
        let docblock_type_str = docblock_type.get_id();
        let inferred_type_str = inferred_type.get_id();

        let mut issue = if let Some(value_expression_variable_id) = value_expression_variable_id {
            Issue::warning(format!("Redundant docblock type for variable `{value_expression_variable_id}`."))
                .with_annotation(Annotation::primary(dockblock_type_span).with_message(format!(
                    "This docblock asserts the type should be `{docblock_type_str}`, which is identical to the inferred type."
                )))
        } else {
            Issue::warning("Redundant docblock type for expression.".to_string()).with_annotation(
                Annotation::primary(dockblock_type_span).with_message(format!(
                    "This docblock asserts the type should be `{docblock_type_str}`, which is identical to the inferred type."
                )),
            )
        };

        if let Some(value_expression_variable_id) = value_expression_variable_id {
            issue = issue
                .with_annotation(Annotation::secondary(value_expression_span).with_message(format!(
                    "The variable `{value_expression_variable_id}` type is known to be `{inferred_type_str}` here."
                )))
                .with_note("The type defined in this docblock is identical to the inferred type of the variable.")
                .with_help("You can remove this redundant `@var` docblock tag.");
        } else {
            issue = issue
                .with_annotation(
                    Annotation::secondary(value_expression_span)
                        .with_message(format!("This expression's type is already inferred as `{inferred_type_str}`.")),
                )
                .with_note("The type defined in this docblock is identical to the inferred type of the expression.")
                .with_help("You can remove this redundant `@var` docblock tag.");
        }

        context.collector.report_with_code(IssueCode::RedundantDocblockType, issue);
    }
}