mago-analyzer 1.10.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use std::borrow::Cow;

use mago_codex::ttype::TType;
use mago_codex::ttype::comparator::ComparisonResult;
use mago_codex::ttype::comparator::union_comparator;
use mago_codex::ttype::get_mixed;
use mago_codex::ttype::union::TUnion;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::ArgumentList;
use mago_syntax::ast::Expression;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstructInput<'ast, 'arena> {
    ArgumentList(Option<&'ast ArgumentList<'arena>>),
    Expression(&'ast Expression<'arena>),
    ExpressionList(&'ast [&'arena Expression<'arena>]),
}

/// Analyzes inputs for a language construct (e.g., `echo`, `exit`, `return`).
///
/// This function is generalized to handle inputs from various syntaxes by matching
/// on the `ConstructInput` enum. It dispatches to the type verifier for each
/// provided value and correctly sets the `is_argument` flag to ensure error
/// messages use the appropriate terminology ("argument" vs. "value").
pub fn analyze_construct_inputs<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    construct_kind: &'static str,
    construct_keyword: Span,
    inputs: ConstructInput<'_, 'arena>,
    expected_type: &TUnion,
    is_variadic: bool,
    has_default: bool,
    has_side_effects: bool,
) -> Result<(), AnalysisError> {
    if has_side_effects && block_context.scope.is_pure() {
        context.collector.report_with_code(
            IssueCode::ImpureConstruct,
            Issue::error(format!(
                "Impure use of `{construct_kind}` in a pure context."
            ))
                .with_annotation(Annotation::primary(construct_keyword).with_message("This operation has side effects"))
                .with_note(format!(
                    "Constructs like `{construct_kind}` can cause side effects (e.g., producing output, changing state, or terminating the script), which are disallowed in contexts marked as `@pure` or `@mutation-free`."
                ))
                .with_help(format!(
                    "To resolve this, either remove the call to `{construct_kind}` from this function, or if the side effects are intended, remove the `@pure` or `@mutation-free` annotation from the surrounding scope."
                )),
        );
    }

    match inputs {
        ConstructInput::ArgumentList(list_option) => {
            let Some(argument_list) = list_option.filter(|l| !l.arguments.is_empty()) else {
                if !has_default {
                    report_missing_input(context, construct_kind, &construct_keyword, true);
                }

                return Ok(());
            };

            argument_list.analyze(context, block_context, artifacts)?;

            for (index, argument) in argument_list.arguments.iter().enumerate() {
                if index > 0 && !is_variadic {
                    report_too_many_inputs(context, construct_kind, &construct_keyword, argument.span(), index, true);
                    continue;
                }

                let input_type =
                    artifacts.get_expression_type(argument).map_or_else(|| Cow::Owned(get_mixed()), Cow::Borrowed);

                verify_construct_input_type(
                    context,
                    &input_type,
                    expected_type,
                    index,
                    argument.value(),
                    construct_kind,
                    &construct_keyword,
                    true,
                );
            }
        }
        ConstructInput::Expression(expression) => {
            expression.analyze(context, block_context, artifacts)?;

            let input_type =
                artifacts.get_expression_type(expression).map_or_else(|| Cow::Owned(get_mixed()), Cow::Borrowed);

            verify_construct_input_type(
                context,
                &input_type,
                expected_type,
                0,
                expression,
                construct_kind,
                &construct_keyword,
                false,
            );
        }
        ConstructInput::ExpressionList(expressions) => {
            if expressions.is_empty() {
                if !has_default {
                    report_missing_input(context, construct_kind, &construct_keyword, false);
                }
                return Ok(());
            }

            for (index, expression) in expressions.iter().enumerate() {
                if index > 0 && !is_variadic {
                    report_too_many_inputs(
                        context,
                        construct_kind,
                        &construct_keyword,
                        expression.span(),
                        index,
                        false,
                    );

                    continue;
                }

                expression.analyze(context, block_context, artifacts)?;

                let input_type =
                    artifacts.get_expression_type(expression).map_or_else(|| Cow::Owned(get_mixed()), Cow::Borrowed);

                verify_construct_input_type(
                    context,
                    &input_type,
                    expected_type,
                    index,
                    expression,
                    construct_kind,
                    &construct_keyword,
                    false, // Not in a formal argument list
                );
            }
        }
    }

    Ok(())
}

/// Verifies the type of a single input passed to a language construct.
///
/// This function checks for a variety of type mismatches, such as `null` or `false`
/// being passed to parameters that don't accept them, and general type
/// incompatibilities. It uses a set of helper functions to report clear,
/// specific errors to the user.
///
/// # Arguments
///
/// * `context` - The shared analysis context.
/// * `input_type` - The type of the value being passed.
/// * `parameter_type` - The type expected by the language construct.
/// * `argument_offset` - The 0-based index of the input, used for error messages.
/// * `input_expression` - The AST node of the input expression for highlighting.
/// * `construct_kind` - A string name of the construct (e.g., "echo", "exit").
/// * `construct_keyword` - The span of the construct's keyword for highlighting.
/// * `is_argument` - Controls terminology in errors. `true` uses "argument", `false` uses "value".
fn verify_construct_input_type<'arena>(
    context: &mut Context<'_, 'arena>,
    input_type: &TUnion,
    parameter_type: &TUnion,
    argument_offset: usize,
    input_expression: &Expression<'arena>,
    construct_kind: &'static str,
    construct_keyword: &Span,
    is_argument: bool,
) {
    if input_type.is_never() {
        return report_never_input(
            context,
            construct_kind,
            input_expression,
            argument_offset,
            construct_keyword,
            is_argument,
        );
    }

    let input_type_str = input_type.get_id();
    let parameter_type_str = parameter_type.get_id();

    if !parameter_type.accepts_null() {
        if input_type.is_null() {
            return report_null_input(
                context,
                construct_kind,
                input_expression,
                argument_offset,
                &parameter_type_str,
                construct_keyword,
                is_argument,
            );
        }
        if input_type.is_nullable() && !input_type.ignore_nullable_issues() {
            report_possibly_null_input(
                context,
                construct_kind,
                input_expression,
                argument_offset,
                &input_type_str,
                &parameter_type_str,
                construct_keyword,
                is_argument,
            );
        }
    }

    if !parameter_type.accepts_false() {
        if input_type.is_false() {
            return report_false_input(
                context,
                construct_kind,
                input_expression,
                argument_offset,
                &parameter_type_str,
                construct_keyword,
                is_argument,
            );
        }
        if input_type.is_falsable() && !input_type.ignore_falsable_issues() {
            report_possibly_false_input(
                context,
                construct_kind,
                input_expression,
                argument_offset,
                &input_type_str,
                &parameter_type_str,
                construct_keyword,
                is_argument,
            );
        }
    }

    let mut comparison = ComparisonResult::new();
    if union_comparator::is_contained_by(
        context.codebase,
        input_type,
        parameter_type,
        true,
        true,
        false,
        &mut comparison,
    ) {
        return;
    }

    if input_type.is_mixed() {
        return report_mixed_input(
            context,
            construct_kind,
            input_expression,
            argument_offset,
            &input_type_str,
            &parameter_type_str,
            construct_keyword,
            is_argument,
        );
    }

    if comparison.type_coerced.unwrap_or(false) {
        report_less_specific_input(
            context,
            &comparison,
            construct_kind,
            input_expression,
            argument_offset,
            &input_type_str,
            &parameter_type_str,
            construct_keyword,
            is_argument,
        );
    } else {
        report_invalid_or_possibly_invalid_input(
            context,
            input_type,
            parameter_type,
            construct_kind,
            input_expression,
            argument_offset,
            &input_type_str,
            &parameter_type_str,
            construct_keyword,
            is_argument,
        );
    }
}

fn get_ordinal(index: usize) -> Cow<'static, str> {
    match index {
        0 => "first".into(),
        1 => "second".into(),
        2 => "third".into(),
        n => format!("{}th", n + 1).into(),
    }
}

fn report_missing_input(context: &mut Context<'_, '_>, kind: &str, keyword: &Span, is_argument: bool) {
    let term = if is_argument { "argument" } else { "value" };
    context.collector.report_with_code(
        IssueCode::TooFewArguments,
        Issue::error(format!("`{kind}` expects at least one {term}."))
            .with_annotation(Annotation::primary(keyword.span()).with_message(format!("{term} is missing here"))),
    );
}

fn report_too_many_inputs(
    context: &mut Context<'_, '_>,
    kind: &str,
    keyword: &Span,
    input_span: Span,
    index: usize,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(index);
    context.collector.report_with_code(
        IssueCode::TooManyArguments,
        Issue::error(format!("Unexpected {position} {term} provided to `{kind}`."))
            .with_annotation(Annotation::primary(input_span).with_message(format!("Unexpected {term}")))
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` defined here"))),
    );
}

fn report_never_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);
    context.collector.report_with_code(
        IssueCode::NoValue,
        Issue::error(format!("The {position} {term} for `{kind}` cannot produce a value."))
            .with_annotation(Annotation::primary(expr.span()).with_message("This expression has type `never`"))
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_note("An expression of type `never` cannot complete, often because it throws or exits."),
    );
}

fn report_null_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);
    context.collector.report_with_code(
        IssueCode::NullArgument,
        Issue::error(format!("The {position} {term} for `{kind}` is `null`."))
            .with_annotation(
                Annotation::primary(expr.span()).with_message(format!("Expected `{param_type}`, but got `null`")),
            )
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_help("Provide a non-null value."),
    );
}

fn report_possibly_null_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    in_type: &str,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);
    context.collector.report_with_code(
        IssueCode::PossiblyNullArgument,
        Issue::error(format!("The {position} {term} for `{kind}` might be `null`."))
            .with_annotation(
                Annotation::primary(expr.span()).with_message(format!("This is type `{in_type}` which can be `null`")),
            )
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_note(format!("The expected type `{param_type}` does not accept `null`."))
            .with_help("Add a `null` check to guard this input."),
    );
}

fn report_false_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);

    context.collector.report_with_code(
        IssueCode::FalseArgument,
        Issue::error(format!("The {position} {term} for `{kind}` is `false`."))
            .with_annotation(
                Annotation::primary(expr.span()).with_message(format!("Expected `{param_type}`, but got `false`")),
            )
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_help("Provide a non-false value."),
    );
}

fn report_possibly_false_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    in_type: &str,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);

    context.collector.report_with_code(
        IssueCode::PossiblyFalseArgument,
        Issue::error(format!("The {position} {term} for `{kind}` might be `false`."))
            .with_annotation(
                Annotation::primary(expr.span()).with_message(format!("This is type `{in_type}` which can be `false`")),
            )
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_note(format!("The expected type `{param_type}` does not accept `false`."))
            .with_help("Add a `false` check to guard this input."),
    );
}

fn report_mixed_input<'arena>(
    context: &mut Context<'_, 'arena>,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    in_type: &str,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);

    context.collector.report_with_code(
        IssueCode::MixedArgument,
        Issue::error(format!("The {position} {term} for `{kind}` is too general."))
            .with_annotation(Annotation::primary(expr.span()).with_message(format!("Type `{in_type}` is too broad")))
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_note(format!("The expected type `{param_type}` is more specific."))
            .with_help("Add a specific type hint or assertion for this value."),
    );
}

fn report_less_specific_input<'arena>(
    context: &mut Context<'_, 'arena>,
    comparison: &ComparisonResult,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    in_type: &str,
    param_type: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);
    let (code, reason) = if comparison.type_coerced_from_nested_mixed.unwrap_or(false) {
        (IssueCode::LessSpecificNestedArgumentType, "due to nested `mixed`")
    } else {
        (IssueCode::LessSpecificArgument, "it is a wider type")
    };

    context.collector.report_with_code(
        code,
        Issue::error(format!("The {position} {term} type `{in_type}` is less specific than expected `{param_type}`."))
            .with_annotation(
                Annotation::primary(expr.span()).with_message(format!("This type is too general {reason}")),
            )
            .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
            .with_help("Provide a more specific type."),
    );
}

fn report_invalid_or_possibly_invalid_input<'arena>(
    context: &mut Context<'_, 'arena>,
    in_type: &TUnion,
    param_type: &TUnion,
    kind: &str,
    expr: &Expression<'arena>,
    offset: usize,
    in_type_str: &str,
    param_type_str: &str,
    keyword: &Span,
    is_argument: bool,
) {
    let term = if is_argument { "argument" } else { "value" };
    let position = get_ordinal(offset);

    let issue =
        if union_comparator::can_expression_types_be_identical(context.codebase, in_type, param_type, false, false) {
            Issue::error(format!("The {position} {term} for `{kind}` might have the wrong type."))
                .with_code(IssueCode::PossiblyInvalidArgument)
                .with_annotation(Annotation::primary(expr.span()).with_message(format!(
                    "This is `{in_type_str}`, which only sometimes overlaps with `{param_type_str}`"
                )))
                .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
                .with_help("Add a type check to ensure the value is what you expect.")
        } else {
            Issue::error(format!("Invalid type for the {position} {term}."))
                .with_code(IssueCode::InvalidArgument)
                .with_annotation(
                    Annotation::primary(expr.span())
                        .with_message(format!("This is type `{in_type_str}`, but expected `{param_type_str}`")),
                )
                .with_annotation(Annotation::secondary(keyword.span()).with_message(format!("`{kind}` called here")))
                .with_help("Adjust the value to match the expected type.")
        };

    context.collector.report(issue);
}