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
use crate::db::MirDatabase;
use mir_types::{ArrayKey, Atomic, Name, Type};
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Loop execution guarantees
// ---------------------------------------------------------------------------

/// Returns true if a foreach loop over `arr_ty` is guaranteed to execute at least once.
/// A loop is guaranteed to execute only when EVERY atom in the (possibly union)
/// type is known to be non-empty — a single possibly-empty alternative means the
/// loop might not execute at all for that alternative.
pub(super) fn loop_guaranteed_to_execute(arr_ty: &Type) -> bool {
    !arr_ty.types.is_empty()
        && arr_ty.types.iter().all(|atomic| {
            matches!(
                atomic,
                Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. }
            ) || matches!(
                atomic,
                Atomic::TKeyedArray { properties, .. } if properties.values().any(|property| !property.optional)
            )
        })
}

/// After a loop body proven to always execute at least once, variables first
/// assigned inside the body are definitely defined afterward — strip any
/// `possibly_undefined` flag and promote `possibly_assigned_vars` → `assigned_vars`
/// for names new since `pre`. Shared by do-while (always executes) and a
/// foreach proven non-empty (`loop_guaranteed_to_execute`).
pub(super) fn promote_new_loop_vars_when_guaranteed(
    pre: &crate::flow_state::FlowState,
    post: &mut crate::flow_state::FlowState,
) {
    let new_names: Vec<Name> = post
        .vars
        .keys()
        .filter(|n| !pre.vars.contains_key(*n))
        .copied()
        .collect();
    let post_vars = Arc::make_mut(&mut post.vars);
    for name in &new_names {
        if let Some(ty) = post_vars.get_mut(name) {
            if ty.possibly_undefined {
                let mut stripped = (**ty).clone();
                stripped.possibly_undefined = false;
                *ty = mir_codebase::definitions::wrap_var_type(stripped);
            }
        }
    }
    let assigned = Arc::make_mut(&mut post.assigned_vars);
    let possibly = Arc::make_mut(&mut post.possibly_assigned_vars);
    for name in &new_names {
        if possibly.contains(name) {
            possibly.remove(name);
            assigned.insert(*name);
        }
    }
}

/// Narrows `iter` (the back-edge state) by `narrow`, then re-adds the initial
/// type of every variable the narrowing changed: the first iteration enters
/// the body without the condition having been checked.
pub(super) fn narrow_back_edge_keeping_initial(
    iter: &mut crate::flow_state::FlowState,
    initial: &crate::flow_state::FlowState,
    narrow: impl FnOnce(&mut crate::flow_state::FlowState),
) {
    let before = iter.vars.clone();
    narrow(iter);
    if iter.diverges {
        return;
    }
    let vars = Arc::make_mut(&mut iter.vars);
    for (name, init_ty) in initial.vars.iter() {
        let (Some(old), Some(narrowed)) = (before.get(name), vars.get_mut(name)) else {
            continue;
        };
        if old != narrowed {
            *narrowed = mir_codebase::definitions::wrap_var_type(Type::merge(narrowed, init_ty));
        }
    }
}

// ---------------------------------------------------------------------------
// Loop widening helpers
// ---------------------------------------------------------------------------

/// Returns true when every variable present in `prev` has the same type in
/// `next`, indicating the fixed-point has been reached.
pub(super) fn vars_stabilized(
    prev: &rustc_hash::FxHashMap<Name, Arc<Type>>,
    next: &rustc_hash::FxHashMap<Name, Arc<Type>>,
) -> bool {
    if prev.len() != next.len() {
        return false;
    }
    prev.iter().all(|(k, v)| {
        next.get(k)
            .map(|u| Arc::ptr_eq(u, v) || **u == **v)
            .unwrap_or(false)
    })
}

/// For any variable whose type changed relative to `pre_vars`, widen to
/// the union of both types.  Called after MAX_ITERS to avoid non-termination.
///
/// If `loop_guaranteed` is true (loop is guaranteed to execute at least once),
/// variables that are new in the loop (only in current, not in pre) won't be
/// merged with null/undefined, since the loop will definitely assign them.
pub(super) fn widen_unstable(
    pre_vars: &rustc_hash::FxHashMap<Name, Arc<Type>>,
    current_vars: &mut rustc_hash::FxHashMap<Name, Arc<Type>>,
    loop_guaranteed: bool,
) {
    for (name, ty) in current_vars.iter_mut() {
        if let Some(pre_ty) = pre_vars.get(name) {
            if !Arc::ptr_eq(ty, pre_ty) && **ty != **pre_ty {
                let mut merged = (**ty).clone();
                merged.merge_with(pre_ty);
                *ty = mir_codebase::definitions::wrap_var_type(merged);
            }
        } else if loop_guaranteed {
            // Variable is new in loop and loop is guaranteed to execute.
            // Don't merge with pre-type (which would be null/undefined).
            // The variable type is just its assigned value.
        } else {
            // Loop might not execute; variable might be undefined.
            // Leave as-is since it's already set in the entry context.
        }
    }
}

// ---------------------------------------------------------------------------
// foreach key/value type inference
// ---------------------------------------------------------------------------

pub(crate) fn infer_foreach_types(arr_ty: &Type) -> (Type, Type) {
    if arr_ty.is_mixed() {
        return (Type::mixed(), Type::mixed());
    }
    // Merge key/value across every array-like atom in the union instead of
    // returning on the first match — a union like `non-empty-list<string> |
    // array{0: string}` (e.g. a preg_split()===false fallback) must widen the
    // key to plain `int`, not collapse to the first alternative's shape-only
    // literal key.
    let mut keys = Type::empty();
    let mut values = Type::empty();
    let mut matched = false;
    for atomic in &arr_ty.types {
        match atomic {
            Atomic::TTemplateParam { as_type, .. } => {
                let iterable_bound = as_type.types.iter().any(|bound_atomic| {
                    matches!(
                        bound_atomic,
                        Atomic::TArray { .. }
                            | Atomic::TNonEmptyArray { .. }
                            | Atomic::TList { .. }
                            | Atomic::TNonEmptyList { .. }
                            | Atomic::TKeyedArray { .. }
                    )
                });
                if iterable_bound {
                    matched = true;
                    let target = Type::single(atomic.clone());
                    keys.merge_with(&Type::single(Atomic::TKeyOf {
                        target: Box::new(target.clone()),
                    }));
                    values.merge_with(&Type::single(Atomic::TValueOf {
                        target: Box::new(target),
                    }));
                }
            }
            Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
                matched = true;
                keys.merge_with(key);
                values.merge_with(value);
            }
            Atomic::TList { value } | Atomic::TNonEmptyList { value } => {
                matched = true;
                keys.merge_with(&Type::single(Atomic::TInt));
                values.merge_with(value);
            }
            Atomic::TKeyedArray { properties, .. } => {
                matched = true;
                for (k, prop) in properties.iter() {
                    let key_atomic = match k {
                        ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
                        ArrayKey::Int(i) => Atomic::TLiteralInt(*i),
                    };
                    keys.merge_with(&Type::single(key_atomic));
                    values.merge_with(&prop.ty);
                }
            }
            Atomic::TString => {
                matched = true;
                keys.merge_with(&Type::single(Atomic::TInt));
                values.merge_with(&Type::single(Atomic::TString));
            }
            _ => {}
        }
    }
    if !matched {
        return (Type::mixed(), Type::mixed());
    }
    // Empty keyed array (e.g. `$arr = []` before push) — treat both as
    // mixed to avoid propagating Type::empty() as a variable type.
    let keys = if keys.is_empty() { Type::mixed() } else { keys };
    let values = if values.is_empty() {
        Type::mixed()
    } else {
        values
    };
    (keys, values)
}

/// Like [`infer_foreach_types`], but also resolves `foreach` over an object —
/// a `Generator`, or a user-defined class implementing `Iterator` /
/// `IteratorAggregate` — into its key/value item types, instead of always
/// falling back to `mixed`.
pub(crate) fn infer_foreach_types_with_db(db: &dyn MirDatabase, arr_ty: &Type) -> (Type, Type) {
    infer_foreach_types_with_db_depth(db, arr_ty, 4)
}

fn infer_foreach_types_with_db_depth(
    db: &dyn MirDatabase,
    arr_ty: &Type,
    depth: u8,
) -> (Type, Type) {
    if depth == 0 || arr_ty.is_mixed() {
        return (Type::mixed(), Type::mixed());
    }
    for atomic in &arr_ty.types {
        match atomic {
            Atomic::TNamedObject { fqcn, type_params } => {
                if let Some(kv) = resolve_iterator_item_types(db, fqcn, type_params, depth) {
                    return kv;
                }
            }
            Atomic::TIntersection { parts } => {
                for part in parts.iter() {
                    for part_atomic in &part.types {
                        if let Atomic::TNamedObject { fqcn, type_params } = part_atomic {
                            if let Some(kv) =
                                resolve_iterator_item_types(db, fqcn, type_params, depth)
                            {
                                return kv;
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    infer_foreach_types(arr_ty)
}

/// `Generator<TKey, TValue, TSend, TReturn>` (per the stdlib generic stub) —
/// a bare `Generator` or the one-arg `Generator<TValue>` shorthand fall back
/// to a mixed/inferred key.
fn generator_item_types(type_params: &[Type]) -> (Type, Type) {
    match type_params {
        [] => (Type::mixed(), Type::mixed()),
        [value] => (Type::mixed(), value.clone()),
        [key, value, ..] => (key.clone(), value.clone()),
    }
}

/// Replace a bare `static`/`self` atom in `ty` with the concrete receiver
/// class, mirroring `call::args::substitute_static_atom`'s treatment of the
/// two atoms as equivalent — needed so a `getIterator(): static` return type
/// is recognized as a `TNamedObject` (an object the caller can chase further)
/// instead of a `TStaticObject`/`TSelf` sentinel it never matches.
fn rebind_static_self(ty: Type, fqcn: &str, own_type_params: &[Type]) -> Type {
    let mut out = Type::empty();
    out.from_docblock = ty.from_docblock;
    out.possibly_undefined = ty.possibly_undefined;
    for atomic in ty.types {
        let rebound = match atomic {
            Atomic::TStaticObject { .. } | Atomic::TSelf { .. } => Atomic::TNamedObject {
                fqcn: Name::from(fqcn),
                type_params: mir_types::union::vec_to_type_params(own_type_params.to_vec()),
            },
            other => other,
        };
        out.add_type(rebound);
    }
    out
}

/// Resolve the key/value item types `foreach` produces for an instance of
/// `fqcn<type_params>`. Returns `None` when `fqcn` isn't `Generator` and
/// doesn't implement `Iterator`/`IteratorAggregate` (or the info needed to
/// resolve it further just isn't available) — the caller then falls back to
/// treating the object as non-iterable-typed (`mixed`/`mixed`).
pub(crate) fn resolve_iterator_item_types(
    db: &dyn MirDatabase,
    fqcn: &Name,
    type_params: &[Type],
    depth: u8,
) -> Option<(Type, Type)> {
    let bare = fqcn.as_ref().trim_start_matches('\\');
    if bare.eq_ignore_ascii_case("Generator") {
        return Some(generator_item_types(type_params));
    }
    // The receiver's static type may itself be one of the built-in iteration
    // interfaces used generically — e.g. `@param Iterator<int, string> $x` —
    // rather than a concrete class implementing it. There's no `current()`/
    // `getIterator()` to chase in that case; the annotation's own type args
    // (if supplied) directly are the key/value types.
    if (bare.eq_ignore_ascii_case("Iterator")
        || bare.eq_ignore_ascii_case("IteratorAggregate")
        || bare.eq_ignore_ascii_case("Traversable"))
        && !type_params.is_empty()
    {
        return Some(generator_item_types(type_params));
    }

    let class = crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, bare))?;
    let class_tps = crate::db::class_template_params(db, bare).unwrap_or_default();
    let own_bindings = crate::generic::build_class_bindings(&class_tps, type_params);
    let mut annotation_bindings = own_bindings.clone();
    for (k, v) in crate::db::inherited_template_bindings(db, bare, &annotation_bindings) {
        annotation_bindings.entry(k).or_insert(v);
    }

    // Prefer an explicit `@implements Iterator<TKey, TValue>` (or
    // `IteratorAggregate<TKey, TValue>`) annotation: it directly states the
    // item types without needing to chase `current()`/`getIterator()`. This
    // annotation is always declared directly on `bare` itself (own-declared,
    // not inherited — `class.implements_type_args()`), so own-bindings-wins
    // is always correct here.
    let annotated = class
        .implements_type_args()
        .iter()
        .find_map(|(iface, args)| {
            let iface_bare = iface.trim_start_matches('\\');
            (iface_bare.eq_ignore_ascii_case("Iterator")
                || iface_bare.eq_ignore_ascii_case("IteratorAggregate"))
            .then_some(args)
        });
    if let Some(args) = annotated {
        if args.len() >= 2 {
            let key = args[0].substitute_templates(&annotation_bindings);
            let value = args[1].substitute_templates(&annotation_bindings);
            return Some((key, value));
        }
    }

    // Hierarchy-aware, not `class.interfaces()` (own-declared-only): a bare
    // subclass (`class IntBag extends Bag {}`) inherits `Bag implements
    // Iterator` without redeclaring it, but still iterates as one.
    let implements = |name: &str| crate::db::extends_or_implements(db, bare, name);
    // `current()`/`key()`/`getIterator()` may be declared directly on `bare`
    // or inherited from an ancestor — each is resolved independently, so the
    // own-vs-inherited merge direction is decided per method using its own
    // owner, not once for the whole function (a same-named template letter
    // reused by both `bare` and a `@extends`-fixed ancestor must resolve
    // differently depending on which of them actually declares the method).
    let method_return_ty = |method: &str| -> Option<Type> {
        let (owner, def) =
            crate::db::find_method_in_chain(db, crate::db::Fqcn::from_str(db, bare), method)?;
        let ty = def.return_type.as_deref().cloned()?;
        let mut bindings = own_bindings.clone();
        let inherited = crate::db::inherited_template_bindings(db, bare, &own_bindings);
        if owner.as_ref() == bare {
            for (k, v) in inherited {
                bindings.entry(k).or_insert(v);
            }
        } else {
            bindings.extend(inherited);
        }
        Some(ty.substitute_templates(&bindings))
    };

    if implements("IteratorAggregate") {
        let ret_ty = method_return_ty("getiterator")?;
        // `getIterator(): static { return $this; }` is a common self-iterating
        // pattern — `static`/`self` is a `TStaticObject`/`TSelf` atom, not a
        // `TNamedObject`, so the recursive call below would never match it and
        // fall back to `mixed`. Go straight to the class's own `Iterator`
        // implementation (the standard idiom this pattern is written for)
        // instead of rebinding and recursing, which would just rediscover the
        // same `getIterator(): static` and loop until `depth` bottoms out.
        let returns_self_or_static = ret_ty
            .types
            .iter()
            .any(|a| matches!(a, Atomic::TStaticObject { .. } | Atomic::TSelf { .. }));
        if returns_self_or_static && implements("Iterator") {
            let value = method_return_ty("current").unwrap_or_else(Type::mixed);
            let key = method_return_ty("key").unwrap_or_else(Type::mixed);
            return Some((key, value));
        }
        let ret_ty = rebind_static_self(ret_ty, bare, type_params);
        return Some(infer_foreach_types_with_db_depth(db, &ret_ty, depth - 1));
    }
    if implements("Iterator") {
        let value = method_return_ty("current").unwrap_or_else(Type::mixed);
        let key = method_return_ty("key").unwrap_or_else(Type::mixed);
        return Some((key, value));
    }
    None
}