mir-analyzer 0.1.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
/// Type narrowing — refines variable types based on conditional expressions.
///
/// Given a condition expression and a branch direction (true/false), this
/// module updates the `Context` to narrow variable types accordingly.
use php_ast::ast::{BinaryOp, ExprKind, UnaryPrefixOp};

use mir_codebase::Codebase;
use mir_types::{Atomic, Union};

use crate::context::Context;

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Narrow the types in `ctx` as if `expr` evaluates to `is_true`.
pub fn narrow_from_condition<'arena, 'src>(
    expr: &php_ast::ast::Expr<'arena, 'src>,
    ctx: &mut Context,
    is_true: bool,
    codebase: &Codebase,
    file: &str,
) {
    match &expr.kind {
        // Parenthesized — unwrap and narrow the inner expression
        ExprKind::Parenthesized(inner) => {
            narrow_from_condition(inner, ctx, is_true, codebase, file);
        }

        // !expr  →  narrow as if expr is !is_true
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
            narrow_from_condition(u.operand, ctx, !is_true, codebase, file);
        }

        // $a && $b  →  if true: narrow both; if false: no constraint
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanAnd || b.op == BinaryOp::LogicalAnd => {
            if is_true {
                narrow_from_condition(b.left, ctx, true, codebase, file);
                narrow_from_condition(b.right, ctx, true, codebase, file);
            }
        }

        // $a || $b  →  if false: narrow both; if true: try to narrow same-var instanceof union
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
            if !is_true {
                narrow_from_condition(b.left, ctx, false, codebase, file);
                narrow_from_condition(b.right, ctx, false, codebase, file);
            } else {
                // For `$x instanceof A || $x instanceof B` in true-branch: narrow $x to A|B
                narrow_or_instanceof_true(b.left, b.right, ctx, codebase, file);
            }
        }

        // $x === null / $x !== null
        ExprKind::Binary(b)
            if b.op == BinaryOp::Identical || b.op == BinaryOp::NotIdentical =>
        {
            let is_identical = b.op == BinaryOp::Identical;
            let effective_true = if is_identical { is_true } else { !is_true };

            // `$x === null`
            if matches!(b.right.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            } else if matches!(b.left.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(b.right) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            }
            // `$x === true` / `$x === false`
            else if matches!(b.right.kind, ExprKind::Bool(true)) {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_bool(ctx, &name, true, effective_true);
                }
            } else if matches!(b.right.kind, ExprKind::Bool(false)) {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_bool(ctx, &name, false, effective_true);
                }
            }
            // `$x === 'literal'`
            else if let ExprKind::String(s) = &b.right.kind {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_literal_string(ctx, &name, s.as_ref(), effective_true);
                }
            } else if let ExprKind::String(s) = &b.left.kind {
                if let Some(name) = extract_var_name(b.right) {
                    narrow_var_literal_string(ctx, &name, s.as_ref(), effective_true);
                }
            }
            // `$x === 42`
            else if let ExprKind::Int(n) = &b.right.kind {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_literal_int(ctx, &name, *n, effective_true);
                }
            } else if let ExprKind::Int(n) = &b.left.kind {
                if let Some(name) = extract_var_name(b.right) {
                    narrow_var_literal_int(ctx, &name, *n, effective_true);
                }
            }
        }

        // $x == null  (loose equality)
        ExprKind::Binary(b) if b.op == BinaryOp::Equal || b.op == BinaryOp::NotEqual => {
            let is_equal = b.op == BinaryOp::Equal;
            let effective_true = if is_equal { is_true } else { !is_true };
            if matches!(b.right.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(b.left) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            } else if matches!(b.left.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(b.right) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            }
        }

        // $x instanceof ClassName
        // Also handles `!$x instanceof ClassName` which the parser produces as
        // `(!$x) instanceof ClassName` due to PHP operator precedence. The developer
        // intent is always `!($x instanceof ClassName)`, so we flip is_true.
        ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
            // Unwrap `(!$x)` on the left side — treat as negated instanceof
            let (lhs, extra_negation) = match &b.left.kind {
                ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
                    (u.operand, true)
                }
                ExprKind::Parenthesized(inner) => match &inner.kind {
                    ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
                        (u.operand, true)
                    }
                    _ => (&*b.left, false),
                },
                _ => (&*b.left, false),
            };
            let effective_is_true = if extra_negation { !is_true } else { is_true };
            if let Some(var_name) = extract_var_name(lhs) {
                if let Some(raw_name) = extract_class_name(b.right) {
                    // Resolve the short name to its FQCN using file imports
                    let class_name = codebase.resolve_class_name(file, &raw_name);
                    let current = ctx.get_var(&var_name);
                    let narrowed = if effective_is_true {
                        current.narrow_instanceof(&class_name)
                    } else {
                        // remove that specific named object type
                        current.filter_out_named_object(&class_name)
                    };
                    ctx.set_var(&var_name, narrowed);
                }
            }
        }

        // is_string($x), is_int($x), is_null($x), is_array($x), etc.
        // Also handles assert($x instanceof Y) — narrows like a bare condition.
        ExprKind::FunctionCall(call) => {
            if let ExprKind::Identifier(fn_name) | ExprKind::Variable(fn_name) = &call.name.kind {
                if fn_name.as_ref().eq_ignore_ascii_case("assert") {
                    // assert($condition) — narrow as if the condition is is_true
                    if let Some(arg_expr) = call.args.first() {
                        narrow_from_condition(&arg_expr.value, ctx, is_true, codebase, file);
                    }
                } else if let Some(arg_expr) = call.args.first() {
                    if let Some(var_name) = extract_var_name(&arg_expr.value) {
                        narrow_from_type_fn(ctx, fn_name, &var_name, is_true);
                    }
                }
            }
        }

        // isset($x)
        ExprKind::Isset(vars) => {
            for var_expr in vars.iter() {
                if let Some(var_name) = extract_var_name(var_expr) {
                    if is_true {
                        // remove null; mark as definitely assigned
                        let current = ctx.get_var(&var_name);
                        ctx.set_var(&var_name, current.remove_null());
                        ctx.assigned_vars.insert(var_name);
                    }
                }
            }
        }

        // if ($x)  — truthy/falsy narrowing
        _ => {
            if let Some(var_name) = extract_var_name(expr) {
                let current = ctx.get_var(&var_name);
                let narrowed = if is_true {
                    current.narrow_to_truthy()
                } else {
                    current.narrow_to_falsy()
                };
                if !narrowed.is_empty() {
                    ctx.set_var(&var_name, narrowed);
                } else if !current.is_empty() && !current.is_mixed() {
                    // The variable's type can never satisfy this truthiness
                    // constraint → this branch is statically unreachable.
                    ctx.diverges = true;
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// For `$x instanceof A || $x instanceof B` (true branch): narrow $x to A|B.
/// Handles OR chains recursively, e.g. `$x instanceof A || $x instanceof B || $x instanceof C`.
fn narrow_or_instanceof_true<'arena, 'src>(
    left: &php_ast::ast::Expr<'arena, 'src>,
    right: &php_ast::ast::Expr<'arena, 'src>,
    ctx: &mut Context,
    codebase: &Codebase,
    file: &str,
) {
    // Collect all class names from instanceof checks on the same variable.
    let mut var_name: Option<String> = None;
    let mut class_names: Vec<String> = vec![];

    fn collect_instanceof<'a, 's>(
        expr: &php_ast::ast::Expr<'a, 's>,
        var_name: &mut Option<String>,
        class_names: &mut Vec<String>,
        codebase: &Codebase,
        file: &str,
    ) -> bool {
        match &expr.kind {
            ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
                if let (Some(vn), Some(cn)) = (extract_var_name(b.left), extract_class_name(b.right)) {
                    let resolved = codebase.resolve_class_name(file, &cn);
                    match var_name {
                        None => { *var_name = Some(vn); class_names.push(resolved); true }
                        Some(existing) if existing == &vn => { class_names.push(resolved); true }
                        _ => false, // different variable — bail out
                    }
                } else {
                    false
                }
            }
            ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
                collect_instanceof(b.left, var_name, class_names, codebase, file)
                    && collect_instanceof(b.right, var_name, class_names, codebase, file)
            }
            ExprKind::Parenthesized(inner) => {
                collect_instanceof(inner, var_name, class_names, codebase, file)
            }
            _ => false,
        }
    }

    // Wrap left and right into a fake OR so we can reuse the collector
    let left_ok = collect_instanceof(left, &mut var_name, &mut class_names, codebase, file);
    let right_ok = collect_instanceof(right, &mut var_name, &mut class_names, codebase, file);

    if left_ok && right_ok {
        if let Some(vn) = var_name {
            if !class_names.is_empty() {
                let current = ctx.get_var(&vn);
                // Narrow to the union of all instanceof types: take union of narrow_instanceof results
                let mut narrowed = Union::empty();
                for cn in &class_names {
                    let n = current.narrow_instanceof(cn);
                    narrowed = Union::merge(&narrowed, &n);
                }
                // Fall back to current if narrowed is empty (e.g. mixed)
                let result = if narrowed.is_empty() { current.clone() } else { narrowed };
                if !result.is_empty() {
                    ctx.set_var(&vn, result);
                }
            }
        }
    }
}

fn narrow_var_null(ctx: &mut Context, name: &str, is_null: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_null {
        current.narrow_to_null()
    } else {
        current.remove_null()
    };
    if !narrowed.is_empty() {
        ctx.set_var(name, narrowed);
    } else if !current.is_empty() && !current.is_mixed() {
        // The type cannot satisfy this nullness constraint → dead branch.
        ctx.diverges = true;
    }
}

fn narrow_var_bool(ctx: &mut Context, name: &str, value: bool, is_value: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_value {
        if value {
            current.filter(|t| matches!(t, Atomic::TTrue | Atomic::TBool | Atomic::TMixed))
        } else {
            current.filter(|t| matches!(t, Atomic::TFalse | Atomic::TBool | Atomic::TMixed))
        }
    } else if value {
        current.filter(|t| !matches!(t, Atomic::TTrue))
    } else {
        current.filter(|t| !matches!(t, Atomic::TFalse))
    };
    if !narrowed.is_empty() {
        ctx.set_var(name, narrowed);
    }
}

fn narrow_from_type_fn(ctx: &mut Context, fn_name: &str, var_name: &str, is_true: bool) {
    let current = ctx.get_var(var_name);
    let narrowed = match fn_name.to_lowercase().as_str() {
        "is_string" => {
            if is_true { current.narrow_to_string() } else { current.filter(|t| !t.is_string()) }
        }
        "is_int" | "is_integer" | "is_long" => {
            if is_true { current.narrow_to_int() } else { current.filter(|t| !t.is_int()) }
        }
        "is_float" | "is_double" | "is_real" => {
            if is_true { current.narrow_to_float() } else { current.filter(|t| !matches!(t, Atomic::TFloat | Atomic::TLiteralFloat(..))) }
        }
        "is_bool" => {
            if is_true { current.narrow_to_bool() } else { current.filter(|t| !matches!(t, Atomic::TBool | Atomic::TTrue | Atomic::TFalse)) }
        }
        "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()) }
        }
        "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_numeric" => {
            if is_true {
                current.filter(|t| matches!(t, Atomic::TInt | Atomic::TFloat | Atomic::TNumeric | Atomic::TNumericString | Atomic::TLiteralInt(_) | Atomic::TMixed))
            } else {
                current.filter(|t| !matches!(t, Atomic::TInt | Atomic::TFloat | Atomic::TNumeric | Atomic::TNumericString | Atomic::TLiteralInt(_)))
            }
        }
        // method_exists($obj, 'method') — if true, narrow to TObject (suppresses
        // UndefinedMethod; the concrete type is unresolvable without knowing the method arg)
        "method_exists" | "property_exists" => {
            if is_true {
                Union::single(Atomic::TObject)
            } else {
                current.clone()
            }
        }
        _ => return,
    };
    if !narrowed.is_empty() {
        ctx.set_var(var_name, narrowed);
    }
}

fn narrow_var_literal_string(ctx: &mut Context, name: &str, value: &str, is_value: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_value {
        // Keep the specific literal, plus catch-all types that could contain it
        current.filter(|t| match t {
            Atomic::TLiteralString(s) => s.as_ref() == value,
            Atomic::TString | Atomic::TScalar | Atomic::TMixed => true,
            _ => false,
        })
    } else {
        // Remove only this specific literal; leave TString/TMixed intact
        current.filter(|t| !matches!(t, Atomic::TLiteralString(s) if s.as_ref() == value))
    };
    if !narrowed.is_empty() {
        ctx.set_var(name, narrowed);
    }
}

fn narrow_var_literal_int(ctx: &mut Context, name: &str, value: i64, is_value: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_value {
        current.filter(|t| match t {
            Atomic::TLiteralInt(n) => *n == value,
            Atomic::TInt | Atomic::TScalar | Atomic::TNumeric | Atomic::TMixed => true,
            _ => false,
        })
    } else {
        current.filter(|t| !matches!(t, Atomic::TLiteralInt(n) if *n == value))
    };
    if !narrowed.is_empty() {
        ctx.set_var(name, narrowed);
    }
}

fn extract_var_name<'a, 'arena, 'src>(
    expr: &'a php_ast::ast::Expr<'arena, 'src>,
) -> Option<String> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(name.as_ref().trim_start_matches('$').to_string()),
        ExprKind::Parenthesized(inner) => extract_var_name(inner),
        _ => None,
    }
}

fn extract_class_name<'arena, 'src>(
    expr: &php_ast::ast::Expr<'arena, 'src>,
) -> Option<String> {
    match &expr.kind {
        ExprKind::Identifier(name) => Some(name.to_string()),
        ExprKind::Variable(_name) => None, // dynamic class — can't narrow
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Extension methods on Union used only in narrowing
// ---------------------------------------------------------------------------

trait UnionNarrowExt {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Union;
    fn filter_out_named_object(&self, fqcn: &str) -> Union;
}

impl UnionNarrowExt for Union {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Union {
        let mut result = Union::empty();
        result.possibly_undefined = self.possibly_undefined;
        result.from_docblock = self.from_docblock;
        for atomic in &self.types {
            if f(atomic) {
                result.types.push(atomic.clone());
            }
        }
        result
    }

    fn filter_out_named_object(&self, fqcn: &str) -> Union {
        self.filter(|t| match t {
            Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() != fqcn,
            _ => true,
        })
    }
}