mir-analyzer 0.85.0

Analysis engine for the mir PHP static analyzer
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
//! `is_*`/`ctype_*`/`array_is_list`/`method_exists`/`property_exists` type-check
//! narrowing, for variable, property, and static-property receivers.
use std::borrow::Cow;

use php_ast::ast::{BinaryOp, UnaryPrefixOp};
use php_ast::owned::{Expr, ExprKind};

use mir_types::{Atomic, Type};

use crate::db::MirDatabase;
use crate::flow_state::FlowState;

use super::core::{
    apply_prop_narrowed, is_numeric_string, narrow_receiver_non_null_on_prop_match,
    resolve_prop_current_type, resolve_static_prop_current_type, set_narrowed, UnionNarrowExt,
};
use super::literals::narrow_string_to_non_empty;

pub(super) fn narrow_from_type_fn(
    ctx: &mut FlowState,
    fn_name: &str,
    var_name: &str,
    db: &dyn MirDatabase,
    is_true: bool,
) {
    let current = ctx.get_var(var_name);
    let Some(narrowed) = type_fn_narrowed(&current, fn_name, db, is_true) else {
        return;
    };
    set_narrowed(ctx, var_name, &current, narrowed, true);
}

/// Property-access counterpart of `narrow_from_type_fn`, for
/// `is_string($this->prop)`, `is_array($this->prop)`, `array_is_list($this->prop)`,
/// `ctype_digit($this->prop)`, `method_exists($this->prop, ...)`, etc. — the
/// property-access fallback for the `is_*`/`ctype_*`/type-check family, as the
/// `instanceof`/null/literal-match arms elsewhere in this file have.
pub(super) fn narrow_prop_from_type_fn(
    ctx: &mut FlowState,
    fn_name: &str,
    obj_var: &str,
    prop: &str,
    db: &dyn MirDatabase,
    file: &str,
    is_true: bool,
) {
    let current = resolve_prop_current_type(ctx, obj_var, prop, db, file);
    let Some(narrowed) = type_fn_narrowed(&current, fn_name, db, is_true) else {
        return;
    };
    // A nullable receiver makes `$obj->prop` itself evaluate to `null` (PHP 8
    // warning, not fatal), which is an extra value the property's own declared
    // type doesn't account for. That extra `null` only satisfies `is_null()`'s
    // true branch — every other `is_*`/`ctype_*` check returns false on null,
    // so it's their false branch that gains a reachable-despite-empty case
    // (same reasoning as `narrow_prop_instanceof`'s false-branch gate).
    let is_null_check = crate::util::php_ident_lowercase(fn_name) == "is_null";
    let receiver_nullable = ctx.get_var(obj_var).is_nullable();
    // Proves the property's own value isn't null (`is_true != is_null_check`,
    // same condition as mark_diverges above) — which, on a nullable receiver,
    // also proves the receiver itself wasn't null (see the comment above).
    let proved_prop_non_null = is_true != is_null_check;
    let mark_diverges = !receiver_nullable || proved_prop_non_null;
    apply_prop_narrowed(ctx, obj_var, prop, current, narrowed, mark_diverges);
    narrow_receiver_non_null_on_prop_match(ctx, obj_var, proved_prop_non_null);
}

/// Static-property counterpart of `narrow_prop_from_type_fn`, for
/// `is_string(self::$prop)`, `ctype_digit(static::$prop)`, etc. Unlike the
/// instance-property case, a static property has no separate "receiver
/// variable" whose own nullability could add an extra unaccounted-for
/// `null` — `self::`/`static::` is never itself null — so mark_diverges is
/// unconditional, matching the plain-variable case.
pub(super) fn narrow_static_prop_from_type_fn(
    ctx: &mut FlowState,
    fn_name: &str,
    fqcn: &str,
    prop: &str,
    db: &dyn MirDatabase,
    is_true: bool,
) {
    let current = resolve_static_prop_current_type(ctx, fqcn, prop, db);
    let Some(narrowed) = type_fn_narrowed(&current, fn_name, db, is_true) else {
        return;
    };
    apply_prop_narrowed(ctx, fqcn, prop, current, narrowed, true);
}

/// Core `is_*`/`ctype_*`/`array_is_list`/`method_exists`/`property_exists`
/// narrowing logic, shared between the variable-receiver
/// (`narrow_from_type_fn`) and property-receiver (`narrow_prop_from_type_fn`)
/// entry points, and (via `classify_var_predicate`) any `FlowState`-free
/// consumer that has its own `(fn_name, is_true)` pair to narrow by — e.g. a
/// predicate-shaped callback's element-type narrowing. Returns `None` for an
/// unrecognized function name — the caller should leave the type untouched.
pub(crate) fn type_fn_narrowed(
    current: &Type,
    fn_name: &str,
    db: &dyn MirDatabase,
    is_true: bool,
) -> Option<Type> {
    Some(match crate::util::php_ident_lowercase(fn_name).as_str() {
        "is_string" => {
            if is_true {
                current.narrow_to_string()
            } else {
                // `TScalar` (the opaque atom a preceding `!is_scalar()` false-branch
                // narrows onto) is also excluded here — a scalar value that has
                // survived every OTHER `is_*` false-branch in an
                // `is_bool()||is_int()||is_float()||is_string()` disjunction can no
                // longer be a string either, same reasoning as `is_scalar`'s own
                // false-branch exclusion below.
                current.filter(|t| !t.is_string() && !matches!(t, Atomic::TScalar))
            }
        }
        "is_int" | "is_integer" | "is_long" => {
            if is_true {
                current.narrow_to_int()
            } else {
                current.filter(|t| !t.is_int() && !matches!(t, Atomic::TScalar))
            }
        }
        "is_float" | "is_double" | "is_real" => {
            if is_true {
                current.narrow_to_float()
            } else {
                current.filter(|t| {
                    !matches!(
                        t,
                        Atomic::TFloat
                            | Atomic::TIntegralFloat
                            | Atomic::TLiteralFloat(..)
                            | Atomic::TScalar
                    )
                })
            }
        }
        "is_bool" => {
            if is_true {
                current.narrow_to_bool()
            } else {
                current.filter(|t| {
                    !matches!(
                        t,
                        Atomic::TBool | Atomic::TTrue | Atomic::TFalse | Atomic::TScalar
                    )
                })
            }
        }
        "is_null" => {
            if is_true {
                current.narrow_to_null()
            } else {
                current.remove_null()
            }
        }
        "is_array" => {
            if is_true {
                current.narrow_to_array()
            } else {
                current.filter(|t| !t.is_array())
            }
        }
        "array_is_list" => {
            if is_true {
                current.narrow_to_list()
            } else {
                current.filter(|t| {
                    !matches!(
                        t,
                        Atomic::TList { .. }
                            | Atomic::TNonEmptyList { .. }
                            | Atomic::TKeyedArray { is_list: true, .. }
                    )
                })
            }
        }
        "is_object" => {
            if is_true {
                current.narrow_to_object()
            } else {
                current.filter(|t| !t.is_object())
            }
        }
        "is_callable" => {
            if is_true {
                current.narrow_to_callable()
            } else {
                current.filter(|t| !t.is_callable())
            }
        }
        "is_scalar" => {
            if is_true {
                current.narrow_to_scalar()
            } else {
                current.filter(|t| {
                    !t.is_string()
                        && !t.is_int()
                        && !matches!(
                            t,
                            Atomic::TFloat
                                | Atomic::TIntegralFloat
                                | Atomic::TLiteralFloat(..)
                                | Atomic::TBool
                                | Atomic::TTrue
                                | Atomic::TFalse
                                | Atomic::TScalar
                                | Atomic::TNumeric
                        )
                })
            }
        }
        "is_iterable" => {
            if is_true {
                current.narrow_to_iterable()
            } else {
                // Beyond the array atom (always excludable), a named-object atom
                // is only excludable when it's `final` (no subclass could add
                // `implements Traversable` later) AND its own hierarchy provably
                // doesn't already extend/implement Traversable — same
                // final-class soundness gate `narrow_var_to_specific_class` uses
                // for its false branch. A non-final or unresolvable class stays.
                current
                    .filter(|t| !atom_excluded_from_is_iterable_or_countable(t, "Traversable", db))
            }
        }
        "is_countable" => {
            if is_true {
                narrow_to_countable_with_interface(current, db)
            } else {
                current.filter(|t| !atom_excluded_from_is_iterable_or_countable(t, "Countable", db))
            }
        }
        "is_resource" => {
            if is_true {
                current.narrow_to_resource()
            } else {
                // Exclude nothing (no resource type exists); return unchanged
                current.clone()
            }
        }
        "is_numeric" => {
            if is_true {
                // In the truthy branch: keep numeric types and string types that
                // *could* be numeric. TString / TNonEmptyString narrow to TNumericString
                // (a string proven to be numeric-valued). All int and float variants are
                // always numeric. TMixed is kept as-is.
                let mut narrowed_parts = Type::empty();
                for t in &current.types {
                    match t {
                        // All int and float variants are unconditionally numeric.
                        Atomic::TInt
                        | Atomic::TIntRange { .. }
                        | Atomic::TPositiveInt
                        | Atomic::TNonNegativeInt
                        | Atomic::TNegativeInt
                        | Atomic::TLiteralInt(_)
                        | Atomic::TFloat
                        | Atomic::TIntegralFloat
                        | Atomic::TLiteralFloat(..)
                        | Atomic::TNumeric
                        | Atomic::TNumericString => {
                            narrowed_parts.add_type(t.clone());
                        }
                        // A generic string could be numeric; narrow to numeric-string.
                        Atomic::TString | Atomic::TNonEmptyString => {
                            narrowed_parts.add_type(Atomic::TNumericString);
                        }
                        // A literal string is numeric only if it parses as a number.
                        Atomic::TLiteralString(s) if is_numeric_string(s) => {
                            narrowed_parts.add_type(t.clone());
                        }
                        // mixed/scalar could be anything; a truthy is_numeric()
                        // proves it's specifically int|float|numeric-string, so
                        // replace it rather than leaving it as mixed/scalar (matching
                        // how is_string/is_int/etc. narrow these two atoms).
                        Atomic::TScalar | Atomic::TMixed => {
                            narrowed_parts.add_type(Atomic::TInt);
                            narrowed_parts.add_type(Atomic::TFloat);
                            narrowed_parts.add_type(Atomic::TNumericString);
                        }
                        _ => {} // non-numeric types are excluded
                    }
                }
                narrowed_parts
            } else {
                current.filter(|t| {
                    !matches!(
                        t,
                        Atomic::TInt
                            | Atomic::TIntRange { .. }
                            | Atomic::TPositiveInt
                            | Atomic::TNonNegativeInt
                            | Atomic::TNegativeInt
                            | Atomic::TFloat
                            | Atomic::TIntegralFloat
                            | Atomic::TNumeric
                            | Atomic::TNumericString
                            | Atomic::TLiteralInt(_)
                            | Atomic::TLiteralFloat(..)
                    ) && !matches!(t, Atomic::TLiteralString(s) if is_numeric_string(s.as_ref()))
                })
            }
        }
        // ctype_*() returns false on an empty string for every variant, so a
        // truthy result proves the string argument is non-empty. It says
        // nothing when the argument isn't a string (e.g. ctype_digit(65) is
        // true because 65 is ASCII 'A', unrelated to decimal digits), so
        // only TString atoms are touched — everything else passes through.
        "ctype_alpha" | "ctype_alnum" | "ctype_digit" | "ctype_lower" | "ctype_upper"
        | "ctype_punct" | "ctype_space" | "ctype_xdigit" | "ctype_print" | "ctype_graph"
        | "ctype_cntrl" => {
            if is_true {
                narrow_string_to_non_empty(current)
            } else {
                current.clone()
            }
        }
        // method_exists($obj, 'method') / property_exists($obj, 'prop') — both accept
        // object|string, so on true keep object atoms as-is (preserving the specific
        // class instead of collapsing it to bare TObject) and keep string/class-string
        // atoms as-is; TMixed is replaced with bare TObject (a usable placeholder — the
        // string alternative isn't worth widening a plain mixed into a union for).
        // TScalar excludes object entirely though, so it can only narrow to TString,
        // never TObject (bool|int|float|string can never be an object instance).
        "method_exists" | "property_exists" => {
            // A receiver that's neither object-like, string-like, mixed, nor
            // scalar (e.g. plain int/bool/array) can never be passed to
            // method_exists()/property_exists() — PHP 8 throws a TypeError for
            // such an argument regardless of which boolean the call returns,
            // so reaching EITHER branch already proves it was object|string.
            // Let the result go empty like every sibling is_*() arm (the
            // caller's set_narrowed/apply_prop_narrowed already marks
            // divergence on empty), instead of silently reverting to the
            // unnarrowed current type.
            let mut result = Type::empty();
            result.from_docblock = current.from_docblock;
            for t in &current.types {
                if t.is_object() || t.is_string() {
                    result.add_type(t.clone());
                } else if matches!(t, Atomic::TMixed) {
                    result.add_type(Atomic::TObject);
                } else if matches!(t, Atomic::TScalar) {
                    result.add_type(Atomic::TString);
                }
            }
            result
        }
        _ => return None,
    })
}

/// `is_countable()` true branch: arrays stay, and each named-object atom is
/// narrowed as `instanceof Countable` (a non-final class becomes `C&Countable`,
/// a final class that can't be Countable drops out).
fn narrow_to_countable_with_interface(current: &Type, db: &dyn MirDatabase) -> Type {
    let countable = current.narrow_to_countable();
    let no_templates = rustc_hash::FxHashSet::default();
    let mut result = Type::empty();
    result.possibly_undefined = countable.possibly_undefined;
    result.from_docblock = countable.from_docblock;
    for atom in &countable.types {
        match atom {
            Atomic::TNamedObject { .. }
            | Atomic::TSelf { .. }
            | Atomic::TStaticObject { .. }
            | Atomic::TParent { .. } => {
                if let Atomic::TNamedObject { fqcn, .. } = atom {
                    if crate::db::is_final(db, fqcn)
                        && !crate::db::extends_or_implements(db, fqcn, "Countable")
                    {
                        continue;
                    }
                }
                let narrowed = super::instanceof_core::narrow_instanceof_preserving_subtypes(
                    &Type::single(atom.clone()),
                    "Countable",
                    db,
                    &no_templates,
                );
                for t in narrowed.types {
                    result.add_type(t);
                }
            }
            _ => result.add_type(atom.clone()),
        }
    }
    result
}

/// Whether `t` is provably excluded from `is_iterable()`/`is_countable()`'s
/// false branch: always true for the `array` atom (the one type both
/// functions are unconditionally true for), and true for a named-object atom
/// that already provably extends/implements `$interface` — such an atom can
/// never make `is_iterable()`/`is_countable()` false, so it can't survive
/// into the false branch. A `final` class that provably does NOT
/// extend/implement `$interface` is the opposite case (guaranteed to make
/// the check false) and must be kept, not excluded. A non-final or
/// unresolvable class is kept too: stripping it risks falsely excluding a
/// legitimately Countable/Traversable subclass.
pub(super) fn atom_excluded_from_is_iterable_or_countable(
    t: &Atomic,
    interface: &str,
    db: &dyn MirDatabase,
) -> bool {
    if t.is_array() {
        return true;
    }
    if let Atomic::TNamedObject { fqcn, .. }
    | Atomic::TSelf { fqcn }
    | Atomic::TStaticObject { fqcn }
    | Atomic::TParent { fqcn } = t
    {
        return crate::db::extends_or_implements(db, fqcn, interface);
    }
    false
}

/// Pure, `FlowState`-free counterpart of the guard-condition matching that
/// drives `narrow_from_type_fn`: does `expr` test `var_name` in one of the
/// shapes `type_fn_narrowed` understands? Recognizes a bare `fn_name($var)`
/// call, its negation `!fn_name($var)`, and the `$var === null` /
/// `$var !== null` (and loose `==`/`!=`) spellings of `is_null($var)` /
/// `!is_null($var)` that PHP code favors over the function-call form.
///
/// Returns the `is_*`/`ctype_*` function name to feed into `type_fn_narrowed`
/// together with `is_true`: the truth value of `fn_name($var)` implied by
/// `expr` being true — i.e. exactly the polarity to narrow by when `expr`
/// itself is the condition being satisfied (a guard's true branch, or a
/// predicate-callback's "kept" case).
///
/// Used by callback-shaped consumers outside `narrowing`'s `FlowState`-driven
/// guard dispatch (e.g. `array_filter`'s element-type narrowing) that have
/// already isolated a single subject variable and a boolean body to test it
/// against, but have no flow-tracked variable to narrow in place.
pub(crate) fn classify_var_predicate<'a>(
    expr: &'a Expr,
    var_name: &str,
) -> Option<(Cow<'a, str>, bool)> {
    fn unwrap(e: &Expr) -> &Expr {
        match &e.kind {
            ExprKind::Parenthesized(inner) => unwrap(inner),
            _ => e,
        }
    }
    let is_var = |e: &Expr| matches!(&unwrap(e).kind, ExprKind::Variable(name) if name.trim_start_matches('$') == var_name);
    let call_fn_name = |e: &'a Expr| -> Option<&'a str> {
        let ExprKind::FunctionCall(call) = &unwrap(e).kind else {
            return None;
        };
        let ExprKind::Identifier(name) = &call.name.kind else {
            return None;
        };
        let [arg] = &*call.args else {
            return None;
        };
        arg.value.as_ref().filter(|v| is_var(v))?;
        Some(name.as_ref())
    };

    let e = unwrap(expr);
    match &e.kind {
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
            call_fn_name(&u.operand).map(|name| (Cow::Borrowed(name), false))
        }
        ExprKind::Binary(b) => {
            let is_true = match b.op {
                BinaryOp::Identical | BinaryOp::Equal => true,
                BinaryOp::NotIdentical | BinaryOp::NotEqual => false,
                _ => return None,
            };
            let matches_null = (is_var(&b.left) && matches!(unwrap(&b.right).kind, ExprKind::Null))
                || (is_var(&b.right) && matches!(unwrap(&b.left).kind, ExprKind::Null));
            matches_null.then_some((Cow::Borrowed("is_null"), is_true))
        }
        _ => call_fn_name(e).map(|name| (Cow::Borrowed(name), true)),
    }
}