mago-analyzer 1.21.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
use std::rc::Rc;

use mago_atom::atom;
use mago_codex::ttype::TType;
use mago_codex::ttype::get_bool;
use mago_codex::ttype::get_false;
use mago_codex::ttype::get_mixed;
use mago_codex::ttype::get_true;
use mago_codex::ttype::union::TUnion;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_syntax::ast::Binary;
use mago_syntax::ast::BinaryOperator;
use mago_syntax::ast::Expression;
use mago_syntax::ast::Literal;
use mago_syntax::ast::Parenthesized;
use mago_syntax::ast::Variable;
use mago_text_edit::TextEdit;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::artifacts::get_expression_range;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;
use crate::expression::binary::utils::are_definitely_not_identical;
use crate::expression::binary::utils::are_definitely_not_loosely_equal;
use crate::expression::binary::utils::is_always_greater_than;
use crate::expression::binary::utils::is_always_greater_than_or_equal;
use crate::expression::binary::utils::is_always_identical_to;
use crate::expression::binary::utils::is_always_less_than;
use crate::expression::binary::utils::is_always_less_than_or_equal;
use crate::utils::misc::unwrap_expression;

/// Analyzes standard comparison operations (e.g., `==`, `===`, `<`, `<=`, `>`, `>=`).
///
/// All these operations result in a boolean. This function:
/// 1. Analyzes both left and right operands.
/// 2. Calls `check_comparison_operand` to validate each operand's type for comparison.
/// 3. Sets the result type of the binary expression to `bool`.
/// 4. Reports warnings for potentially problematic comparisons (e.g., array with int).
/// 5. Reports errors for invalid comparisons (e.g., involving `mixed`).
/// 6. Reports hints for redundant comparisons where the outcome is statically known.
/// 7. Establishes data flow from operands to the expression node.
pub fn analyze_comparison_operation<'ctx, 'arena>(
    binary: &Binary<'arena>,
    context: &mut Context<'ctx, 'arena>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
) -> Result<(), AnalysisError> {
    let was_inside_general_use = block_context.flags.inside_general_use();
    block_context.flags.set_inside_general_use(true);
    binary.lhs.analyze(context, block_context, artifacts)?;
    binary.rhs.analyze(context, block_context, artifacts)?;
    block_context.flags.set_inside_general_use(was_inside_general_use);

    let fallback_type = Rc::new(get_mixed());
    let lhs_type = artifacts.get_rc_expression_type(&binary.lhs).unwrap_or(&fallback_type);
    let rhs_type = artifacts.get_rc_expression_type(&binary.rhs).unwrap_or(&fallback_type);

    check_comparison_operand(context, binary.lhs, lhs_type, "Left", &binary.operator);
    check_comparison_operand(context, binary.rhs, rhs_type, "Right", &binary.operator);

    if context.settings.no_boolean_literal_comparison
        // Only consider equality/inequality operators.
        && binary.operator.is_equality()
        // Identify if one side is a boolean literal and the other side's type is `bool`.
        && let Some((variable_expr, literal_expr, literal_value)) =
            if let Some(literal_value) = get_boolean_literal(binary.rhs) {
                if lhs_type.is_bool() { Some((binary.lhs, binary.rhs, literal_value)) } else { None }
            } else if let Some(literal_value) = get_boolean_literal(binary.lhs) {
                if rhs_type.is_bool() { Some((binary.rhs, binary.lhs, literal_value)) } else { None }
            } else {
                None
            }
    {
        // Determine if the simplified expression should be negated.
        let should_negate = if binary.operator.is_negated_equality() && literal_value {
            // `!= true`, `!== true`, or `<> true` becomes `!`
            true
        } else if !binary.operator.is_negated_equality() && !literal_value {
            // `== false` or `=== false` becomes `!`
            true
        } else {
            // `== true`, `=== true`, `!= false`, `!== false`, `<> false` are non-negated
            false
        };

        let issue = Issue::warning("Avoid direct comparison with boolean literals.")
            .with_annotation(Annotation::primary(binary.span()).with_message(format!(
                "This comparison with `{}` is redundant",
                if literal_value { "true" } else { "false" }
            )))
            .with_note("Comparing a value directly to `true` or `false` is verbose and can be simplified.")
            .with_help(if should_negate {
                "This can be simplified to `!<expression>`."
            } else {
                "This can be simplified to just `<expression>`."
            });

        context.collector.propose_with_code(IssueCode::RedundantComparison, issue, |edits| {
            // Determine which part of the expression to remove (the operator and the literal).
            let redundant_range = if variable_expr.start_position() < literal_expr.start_position() {
                // Case: `$variable op $literal`
                binary.operator.span().join(literal_expr.span())
            } else {
                // Case: `$literal op $variable`
                literal_expr.span().join(binary.operator.span())
            };

            edits.push(TextEdit::delete(redundant_range));

            if should_negate {
                edits.push(TextEdit::insert(variable_expr.start_offset(), "!"));
            }
        });
    }

    let mut reported_general_invalid_operand = false;

    if !lhs_type.is_mixed() && !rhs_type.is_mixed() {
        let lhs_is_array = lhs_type.is_array();
        let rhs_is_array = rhs_type.is_array();

        if lhs_is_array && !rhs_type.has_array() && !rhs_type.has_iterable() && !rhs_type.is_null() {
            context.collector.report_with_code(
                IssueCode::InvalidOperand,
                Issue::warning(format!(
                    "Comparing an `array` with a non-array type `{}` using `{}`.",
                    rhs_type.get_id(),
                    binary.operator.as_str()
                ))
                .with_annotation(Annotation::primary(binary.lhs.span()).with_message("This is an array"))
                .with_annotation(Annotation::secondary(binary.rhs.span()).with_message(format!("This has type `{}`", rhs_type.get_id())))
                .with_note("PHP's comparison rules for arrays against other types can be non-obvious (e.g., an array is usually considered 'greater' than non-null scalars).")
                .with_help("Ensure both operands are of comparable types or explicitly cast/convert them before comparison if this behavior is not intended."),
            );

            reported_general_invalid_operand = true;
        } else if !lhs_type.has_array() && !lhs_type.has_iterable() && rhs_is_array && !lhs_type.is_null() {
            context.collector.report_with_code(
                IssueCode::InvalidOperand,
                Issue::warning(format!(
                    "Comparing a non-array type `{}` with an `array` using `{}`.",
                    lhs_type.get_id(),
                    binary.operator.as_str()
                ))
                .with_annotation(Annotation::primary(binary.lhs.span()).with_message(format!("This has type `{}`", lhs_type.get_id())))
                .with_annotation(Annotation::secondary(binary.rhs.span()).with_message("This is an array"))
                .with_note("PHP's comparison rules for arrays against other types can be non-obvious.")
                .with_help("Ensure both operands are of comparable types or explicitly cast/convert them before comparison if this behavior is not intended."),
            );

            reported_general_invalid_operand = true;
        }
    }

    let result_type = if reported_general_invalid_operand {
        get_bool()
    } else {
        match binary.operator {
            BinaryOperator::LessThan(_) => {
                if is_always_less_than(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "always less than", "`true`");
                    }

                    get_true()
                } else if is_always_greater_than_or_equal(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "never less than", "`false`");
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::LessThanOrEqual(_) => {
                if is_always_less_than_or_equal(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "always less than or equal to",
                            "`true`",
                        );
                    }

                    get_true()
                } else if is_always_greater_than(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "never less than or equal to",
                            "`false`",
                        );
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::GreaterThan(_) => {
                if is_always_greater_than(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "always greater than", "`true`");
                    }

                    get_true()
                } else if is_always_less_than_or_equal(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "never greater than", "`false`");
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::GreaterThanOrEqual(_) => {
                if is_always_greater_than_or_equal(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "always greater than or equal to",
                            "`true`",
                        );
                    }

                    get_true()
                } else if is_always_less_than(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "never greater than or equal to",
                            "`false`",
                        );
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::Equal(_) => {
                let should_be_specific =
                    should_use_specific_equality_inference(block_context, binary.lhs, binary.rhs, false);

                if !should_be_specific {
                    get_bool()
                } else if is_always_identical_to(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "always equal to", "`true`");
                    }

                    get_true()
                } else if are_definitely_not_loosely_equal(context.codebase, lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "never equal to", "`false`");
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::NotEqual(_) | BinaryOperator::AngledNotEqual(_) => {
                let should_be_specific =
                    should_use_specific_equality_inference(block_context, binary.lhs, binary.rhs, false);

                if !should_be_specific {
                    get_bool()
                } else if is_always_identical_to(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "never equal to (always false for !=)",
                            "`false`",
                        );
                    }

                    get_false()
                } else if are_definitely_not_loosely_equal(context.codebase, lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "always not equal to (always true for !=)",
                            "`true`",
                        );
                    }

                    get_true()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::Identical(_) => {
                let should_be_specific =
                    should_use_specific_equality_inference(block_context, binary.lhs, binary.rhs, true);

                if !should_be_specific {
                    get_bool()
                } else if is_always_identical_to(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "always identical to", "`true`");
                    }

                    get_true()
                } else if are_definitely_not_identical(context.codebase, lhs_type, rhs_type, false) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "never identical to", "`false`");
                    }

                    get_false()
                } else {
                    get_bool()
                }
            }
            BinaryOperator::NotIdentical(_) => {
                let should_be_specific =
                    should_use_specific_equality_inference(block_context, binary.lhs, binary.rhs, true);

                if !should_be_specific {
                    get_bool()
                } else if is_always_identical_to(lhs_type, rhs_type) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(
                            context,
                            artifacts,
                            binary,
                            "never identical to (always false for !==)",
                            "`false`",
                        );
                    }

                    get_false()
                } else if are_definitely_not_identical(context.codebase, lhs_type, rhs_type, false) {
                    if !block_context.flags.inside_loop_expressions() {
                        report_redundant_comparison(context, artifacts, binary, "always not identical to", "`true`");
                    }

                    get_true()
                } else {
                    get_bool()
                }
            }
            _ => get_bool(),
        }
    };

    artifacts.expression_types.insert(get_expression_range(binary), Rc::new(result_type));

    Ok(())
}

/// Attempts to extract a boolean literal from an expression, looking through parentheses.
fn get_boolean_literal(expr: &Expression<'_>) -> Option<bool> {
    match expr {
        Expression::Literal(Literal::True(_)) => Some(true),
        Expression::Literal(Literal::False(_)) => Some(false),
        Expression::Parenthesized(Parenthesized { expression, .. }) => get_boolean_literal(expression),
        _ => None,
    }
}

fn should_use_specific_equality_inference(
    block_context: &BlockContext<'_>,
    lhs: &Expression<'_>,
    rhs: &Expression<'_>,
    identity: bool,
) -> bool {
    if identity {
        !involves_external_reference(lhs, block_context)
            && !involves_external_reference(rhs, block_context)
            && !involves_static_variable(lhs, block_context)
            && !involves_static_variable(rhs, block_context)
    } else {
        !block_context.flags.inside_loop()
            && !involves_external_reference(lhs, block_context)
            && !involves_external_reference(rhs, block_context)
            && !involves_static_variable(lhs, block_context)
            && !involves_static_variable(rhs, block_context)
    }
}

/// Checks if an expression involves a static variable.
fn involves_static_variable(expr: &Expression<'_>, block_context: &BlockContext<'_>) -> bool {
    matches!(unwrap_expression(expr), Expression::Variable(Variable::Direct(var)) if block_context.static_locals.contains(&atom(var.name)))
}

/// Checks if an expression involves a variable captured by reference from an outer scope.
fn involves_external_reference(expr: &Expression<'_>, block_context: &BlockContext<'_>) -> bool {
    matches!(unwrap_expression(expr), Expression::Variable(Variable::Direct(var)) if block_context.references_to_external_scope.contains(&atom(var.name)))
}

/// Checks a single operand of a comparison operation for problematic types.
fn check_comparison_operand<'ast, 'arena>(
    context: &mut Context<'_, 'arena>,
    operand: &'ast Expression<'arena>,
    operand_type: &TUnion,
    side: &'static str,
    operator: &'ast BinaryOperator<'arena>,
) {
    if operator.is_identity() {
        return;
    }

    let op_str = operator.as_str();

    if operand_type.is_null() {
        context.collector.report_with_code(
            IssueCode::NullOperand,
            Issue::error(format!(
                "{side} operand in `{op_str}` comparison is `null`."
            ))
            .with_annotation(Annotation::primary(operand.span()).with_message("This is `null`"))
            .with_note(format!("Comparing `null` with `{op_str}` can lead to unexpected results due to PHP's type coercion rules (e.g., `null == 0` is true)."))
            .with_help("Ensure this operand is non-null and has a comparable type. Explicitly check for `null` if it's an expected state."),
        );
    } else if operand_type.can_be_null() && !operand_type.is_mixed() {
        context.collector.report_with_code(
            IssueCode::PossiblyNullOperand,
            Issue::warning(format!(
                "{} operand in `{}` comparison might be `null` (type `{}`).",
                side, op_str, operand_type.get_id()
            ))
            .with_annotation(Annotation::primary(operand.span()).with_message("This might be `null`"))
            .with_note(format!("If this operand is `null` at runtime, PHP's specific comparison rules for `null` with `{op_str}` will apply."))
            .with_help("Ensure this operand is non-null or that comparison with `null` is intended and handled safely."),
        );
    } else if operand_type.is_mixed() {
        context.collector.report_with_code(
            IssueCode::MixedOperand,
            Issue::error(format!("{side} operand in `{op_str}` comparison has `mixed` type."))
                .with_annotation(Annotation::primary(operand.span()).with_message("This has type `mixed`"))
                .with_note(format!(
                    "The result of comparing `mixed` types with `{op_str}` is unpredictable and can hide bugs."
                ))
                .with_help("Ensure this operand has a known, comparable type before using this comparison operator."),
        );
    } else if operand_type.is_false() {
        context.collector.report_with_code(
            IssueCode::FalseOperand,
            Issue::error(format!(
               "{side} operand in `{op_str}` comparison is `false`."
            ))
            .with_annotation(Annotation::primary(operand.span()).with_message("This is `false`"))
            .with_note(format!("PHP compares `false` with other types according to specific rules (e.g., `false == 0` is true using `{op_str}`). This can hide bugs."))
            .with_help("Ensure this operand is not `false` or explicitly handle the `false` case if it represents a distinct state (e.g., an error from a function)."),
        );
    } else if operand_type.is_falsable() && !operand_type.ignore_falsable_issues() {
        context.collector.report_with_code(
            IssueCode::PossiblyFalseOperand,
            Issue::warning(format!(
                "{} operand in `{}` comparison might be `false` (type `{}`).",
                side, op_str, operand_type.get_id()
            ))
            .with_annotation(Annotation::primary(operand.span()).with_message("This might be `false`"))
            .with_note(format!("If this operand is `false` at runtime, PHP's specific comparison rules for `false` with `{op_str}` will apply."))
            .with_help("Ensure this operand is non-false or that comparison with `false` is intended and handled safely."),
        );
    }
}

/// Helper to report redundant comparison issues.
fn report_redundant_comparison<'arena>(
    context: &mut Context<'_, 'arena>,
    artifacts: &mut AnalysisArtifacts,
    binary: &Binary<'arena>,
    comparison_description: &str,
    result_value_str: &str,
) {
    let operator_span = binary.operator.span();
    if operator_span.is_zero() {
        // this is a synthetic node, do not report it.
        return;
    }

    context.collector.report_with_code(
        IssueCode::RedundantComparison,
        Issue::help(format!(
            "Redundant `{}` comparison: left-hand side is {} right-hand side.",
            binary.operator.as_str(),
            comparison_description
        ))
        .with_annotation(Annotation::primary(binary.lhs.span()).with_message(
            match artifacts.get_expression_type(&binary.lhs) {
                Some(t) => format!("Left operand is `{}`", t.get_id()),
                None => "Left operand type is unknown".to_string(),
            },
        ))
        .with_annotation(Annotation::secondary(binary.rhs.span()).with_message(
            match artifacts.get_expression_type(&binary.rhs) {
                Some(t) => format!("Right operand is `{}`", t.get_id()),
                None => "Right operand type is unknown".to_string(),
            },
        ))
        .with_note(format!(
            "The `{}` operator will always return {} in this case.",
            binary.operator.as_str(),
            result_value_str
        ))
        .with_help(format!(
            "Consider simplifying or removing this comparison as it always evaluates to {result_value_str}."
        )),
    );
}