mir-analyzer 0.65.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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! `@psalm-assert-if-true`/`@psalm-assert-if-false` docblock-assertion
//! narrowing: applies a callee's declared assertions to the calling flow
//! state for free functions, methods, and static methods.
use php_ast::owned::ExprKind;

use mir_codebase::definitions::AssertionKind;
use mir_types::{Atomic, Type};

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

use super::arrays::{
    get_shape_path_type, resolve_shape_base_current_type, set_shape_base_narrowed, set_shape_path,
    ShapeBase,
};
use super::core::{
    extract_any_prop_access, extract_chained_prop_access, extract_class_fqcn_from_expr,
    extract_prop_access, extract_static_prop_access, extract_var_name,
    narrow_receiver_non_null_on_prop_match, resolve_prop_current_type,
    resolve_static_prop_current_type,
};
use super::instanceof_core::{filter_out_instanceof_match, filter_out_intersection_match};

pub(super) fn apply_docblock_assertions(
    call: &php_ast::owned::FunctionCallExpr,
    ctx: &mut FlowState,
    is_true: bool,
    db: &dyn MirDatabase,
    file: &str,
    fn_name: &str,
) -> bool {
    let fn_name = fn_name
        .strip_prefix('\\')
        .map(|s| s.to_string())
        .unwrap_or_else(|| fn_name.to_string());
    let fn_active = |name: &str| -> bool {
        let here = crate::db::Fqcn::from_str(db, name);
        crate::db::find_function(db, here).is_some()
    };
    let resolved_fn_name = {
        let qualified = crate::db::resolve_name(db, file, &fn_name);
        if fn_active(qualified.as_str()) {
            qualified
        } else if fn_active(fn_name.as_str()) {
            fn_name.clone()
        } else {
            qualified
        }
    };

    let here = crate::db::Fqcn::from_str(db, resolved_fn_name.as_str());
    let Some(f) = crate::db::find_function(db, here) else {
        return false;
    };
    apply_assertions(
        &f.assertions,
        &f.params,
        &f.template_params,
        &call.args,
        // A free function has no receiver — `$this` in one of its
        // assertions can never resolve to anything real.
        None,
        ctx,
        is_true,
        db,
        file,
    )
}

/// Method-call counterpart of `apply_docblock_assertions` — the callee is
/// already resolved (via `resolve_method_from_db`, shared with both instance
/// and static method-call resolution) instead of looked up by free-function
/// name here. `receiver` is the call's own object/class expression — what
/// `$this` refers to from the assertion's perspective.
pub(super) fn apply_method_docblock_assertions(
    call_args: &[php_ast::owned::Arg],
    receiver: &php_ast::owned::Expr,
    resolved: &crate::call::method::ResolvedMethod,
    ctx: &mut FlowState,
    is_true: bool,
    db: &dyn MirDatabase,
    file: &str,
) -> bool {
    if resolved.assertions.is_empty() {
        return false;
    }
    apply_assertions(
        &resolved.assertions,
        &resolved.params,
        &resolved.template_params,
        call_args,
        Some(receiver),
        ctx,
        is_true,
        db,
        file,
    )
}

/// Shared assertion-application logic for both `@psalm-assert-if-true`/
/// `-if-false` docblock forms, used by both free functions
/// (`apply_docblock_assertions`) and methods/static methods
/// (`apply_method_docblock_assertions`) — narrows whichever argument each
/// matching assertion names to var/prop/static-prop.
#[allow(clippy::too_many_arguments)]
fn apply_assertions(
    assertions: &[mir_codebase::definitions::Assertion],
    params: &[mir_codebase::definitions::DeclaredParam],
    template_params: &[mir_codebase::definitions::TemplateParam],
    call_args: &[php_ast::owned::Arg],
    receiver: Option<&php_ast::owned::Expr>,
    ctx: &mut FlowState,
    is_true: bool,
    db: &dyn MirDatabase,
    file: &str,
) -> bool {
    let expected_kind = if is_true {
        AssertionKind::AssertIfTrue
    } else {
        AssertionKind::AssertIfFalse
    };

    // An assertion type written in terms of the callee's own `@template`s
    // (e.g. `@psalm-assert-if-true T $value` alongside `@param
    // class-string<T> $class`) must resolve T from this call's actual
    // arguments before narrowing — otherwise the variable narrows to the
    // bare, unresolved template atom instead of the concrete type.
    let template_bindings =
        compute_assertion_template_bindings(template_params, params, call_args, ctx, db, file);

    let mut applied = false;
    for assertion in assertions
        .iter()
        .filter(|a| a.kind == expected_kind || (is_true && a.kind == AssertionKind::Assert))
    {
        if apply_one_assertion(
            assertion,
            params,
            call_args,
            receiver,
            ctx,
            template_bindings.as_ref(),
            db,
            file,
        ) {
            applied = true;
        }
    }

    applied
}

/// Apply a single already-selected assertion to its matching argument(s) —
/// the per-assertion body shared between `apply_assertions`'s conditional
/// if-true/if-false narrowing (pre-filtered by kind + branch) and a bare,
/// unconditional `@psalm-assert` statement call (which always applies,
/// regardless of any condition, and must never fall through to the generic
/// per-call-site `AssertionKind::Assert` handling that used to be
/// hand-duplicated in `call/function.rs`, `call/method.rs`, and
/// `call/static_call.rs` — none of which ever read `assertion.param_key`,
/// handled a variadic param, or resolved a named argument, unlike this
/// shared body).
#[allow(clippy::too_many_arguments)]
pub(crate) fn apply_one_assertion(
    assertion: &mir_codebase::definitions::Assertion,
    params: &[mir_codebase::definitions::DeclaredParam],
    call_args: &[php_ast::owned::Arg],
    receiver: Option<&php_ast::owned::Expr>,
    ctx: &mut FlowState,
    template_bindings: Option<&rustc_hash::FxHashMap<mir_types::Name, Type>>,
    db: &dyn MirDatabase,
    file: &str,
) -> bool {
    // `@psalm-assert Type $this->prop` targets the CALL'S OWN RECEIVER —
    // `$this` in the docblock is written from the method's own
    // perspective, not a declared parameter, so it can never match the
    // by-name lookup below. Scoped to a bare-variable receiver only (the
    // reported shape, `$this->connect()` or `$obj->connect()`) — a
    // receiver that's itself a property chain (`$this->service->connect()`)
    // would need a synthetic 2-hop key, which collides with unrelated
    // unused-variable tracking for that same key; not attempted here.
    if assertion.param_key.is_empty() {
        if let Some(prop_name) = assertion.param.strip_prefix("this->") {
            if !prop_name.contains("->") && !prop_name.contains('[') {
                let Some(obj_key) = receiver.and_then(extract_var_name) else {
                    return false;
                };
                let ty = match template_bindings {
                    Some(b) => assertion.ty.substitute_templates(b),
                    None => assertion.ty.clone(),
                };
                let ty = if assertion.negated {
                    let current = resolve_prop_current_type(ctx, &obj_key, prop_name, db, file);
                    negate_assertion_type(&current, &ty, db)
                } else {
                    ty
                };
                let proved_prop_non_null = !ty.is_nullable();
                ctx.set_prop_refined(&obj_key, prop_name, ty);
                narrow_receiver_non_null_on_prop_match(ctx, &obj_key, proved_prop_non_null);
                return true;
            }
        }
    }

    let Some(index) = params.iter().position(|p| p.name == assertion.param) else {
        return false;
    };
    // A literal spread call (`f(...[$x, Foo::class])`) is a single `Arg`
    // whose value is the whole array literal — resolving "the argument for
    // param N" by nth-positional index (`arg_for_param_index`) then picks
    // that WHOLE spread arg for every N, not the individual element
    // expression, so the narrowing target itself is wrong regardless of
    // which param the assertion names. Expand it into one synthetic `Arg`
    // per literal element first, mirroring the same expansion
    // `call/method.rs`/`call/static_call.rs`/`call/function.rs` already do
    // for real argument-type checking.
    let expanded_args: Vec<php_ast::owned::Arg>;
    let call_args: &[php_ast::owned::Arg] =
        if let Some(v) = expand_literal_spread_call_args(call_args) {
            expanded_args = v;
            &expanded_args
        } else {
            call_args
        };
    let mut applied = false;
    // A variadic param's assertion applies to every trailing positional
    // arg it swallows (`assertVariadic(...$values)` asserted over each
    // of `assertVariadic($a, $b, $c)`), not just the first one —
    // `arg_for_param_index` only ever resolves a single positional arg.
    let variadic_args: Vec<&php_ast::owned::Arg>;
    let args_to_check: &[&php_ast::owned::Arg] = if params[index].is_variadic {
        // A spread argument (`f(...$list)`) is a single `Arg` whose value is
        // the WHOLE array, not one of the variadic's scalar elements —
        // narrowing it here as if it were a per-element target would
        // overwrite the array variable's own type with the assertion's
        // per-element type. No per-element narrowing is possible without
        // knowing the spread array's contents, so skip it entirely (safe:
        // this just means the assertion doesn't narrow through a spread
        // call, not a false positive).
        variadic_args = call_args
            .iter()
            .filter(|a| a.name.is_none() && !a.unpack)
            .skip(index)
            .collect();
        &variadic_args
    } else {
        variadic_args = arg_for_param_index(params, call_args, index)
            .into_iter()
            .collect();
        &variadic_args
    };
    for arg in args_to_check {
        // `@psalm-assert-if-true Type $arr['key']` — the assertion
        // targets a specific key of this parameter, not the whole
        // argument. Build a shape-path target from the argument
        // expression + the asserted key (rather than narrowing the
        // argument's own whole value) and SET that key's type,
        // adding it to the shape if not already present — the
        // array-key-refinement machinery `isset()`/`empty()` already
        // use for NARROWING an existing key, applied here as an
        // ASSIGN instead.
        if !assertion.param_key.is_empty() {
            let path = &assertion.param_key;
            let base = if let Some(name) = extract_var_name(&arg.value) {
                Some(ShapeBase::Var(name))
            } else if let Some((obj, prop)) = extract_chained_prop_access(&arg.value) {
                // `extract_chained_prop_access` subsumes the bare 1-hop case
                // (identical `(obj, prop)` for `$x->prop`) and additionally
                // covers a 2-hop chain (`$this->a->b`) via a synthetic
                // `"this->a"` key — see its own doc comment.
                Some(ShapeBase::Prop(obj, prop))
            } else {
                extract_static_prop_access(&arg.value, ctx, db, file)
                    .map(|(fqcn, prop)| ShapeBase::Static(fqcn, prop))
            };
            if let Some(base) = base {
                let current = resolve_shape_base_current_type(ctx, &base, db, file);
                let ty = match template_bindings {
                    Some(b) => assertion.ty.substitute_templates(b),
                    None => assertion.ty.clone(),
                };
                let ty = if assertion.negated {
                    let current_leaf = get_shape_path_type(&current, path);
                    negate_assertion_type(&current_leaf, &ty, db)
                } else {
                    ty
                };
                let narrowed = set_shape_path(&current, path, &ty);
                set_shape_base_narrowed(ctx, &base, current, narrowed);
                applied = true;
            }
            continue;
        }
        if let Some(var_name) = extract_var_name(&arg.value) {
            let ty = match template_bindings {
                Some(b) => assertion.ty.substitute_templates(b),
                None => assertion.ty.clone(),
            };
            let ty = if assertion.negated {
                negate_assertion_type(&ctx.get_var(&var_name), &ty, db)
            } else {
                ty
            };
            ctx.set_var(&var_name, ty);
            applied = true;
        } else if let Some((obj, prop)) = extract_chained_prop_access(&arg.value) {
            let ty = match template_bindings {
                Some(b) => assertion.ty.substitute_templates(b),
                None => assertion.ty.clone(),
            };
            let ty = if assertion.negated {
                let current = resolve_prop_current_type(ctx, &obj, &prop, db, file);
                negate_assertion_type(&current, &ty, db)
            } else {
                ty
            };
            // `$obj->prop` on a null `$obj` reads as null, so proving
            // the property itself is non-nullable also proves `$obj`
            // wasn't null.
            let proved_prop_non_null = !ty.is_nullable();
            ctx.set_prop_refined(&obj, &prop, ty);
            narrow_receiver_non_null_on_prop_match(ctx, &obj, proved_prop_non_null);
            applied = true;
        } else if let Some((fqcn, prop)) = extract_static_prop_access(&arg.value, ctx, db, file) {
            let ty = match template_bindings {
                Some(b) => assertion.ty.substitute_templates(b),
                None => assertion.ty.clone(),
            };
            let ty = if assertion.negated {
                let current = resolve_static_prop_current_type(ctx, &fqcn, &prop, db);
                negate_assertion_type(&current, &ty, db)
            } else {
                ty
            };
            ctx.set_prop_refined(&fqcn, &prop, ty);
            applied = true;
        }
    }
    applied
}

/// Compute the `@template`-resolved bindings for an assertion's callee, the
/// same "resolve T from this call's actual arguments" logic
/// `apply_assertions` needs internally — exposed so a bare, unconditional
/// `@psalm-assert` statement call (which never goes through
/// `apply_assertions` at all, since that dispatch only ever runs for a call
/// used as a boolean CONDITION) can compute the identical bindings before
/// calling `apply_one_assertion` per matching assertion.
pub(crate) fn compute_assertion_template_bindings(
    template_params: &[mir_codebase::definitions::TemplateParam],
    params: &[mir_codebase::definitions::DeclaredParam],
    call_args: &[php_ast::owned::Arg],
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<rustc_hash::FxHashMap<mir_types::Name, Type>> {
    if template_params.is_empty() {
        return None;
    }
    let expanded_args: Vec<php_ast::owned::Arg>;
    let call_args: &[php_ast::owned::Arg] =
        if let Some(v) = expand_literal_spread_call_args(call_args) {
            expanded_args = v;
            &expanded_args
        } else {
            call_args
        };
    let arg_types: Vec<Type> = call_args
        .iter()
        .map(|arg| assertion_arg_type(&arg.value, ctx, db, file))
        .collect();
    let arg_names: Vec<Option<String>> = call_args
        .iter()
        .map(|arg| arg.name.as_ref().map(crate::parser::name_to_string_owned))
        .collect();
    Some(
        crate::generic::infer_template_bindings(
            db,
            template_params,
            params,
            &arg_types,
            &arg_names,
        )
        .0,
    )
}

/// Resolve a method-call receiver's exact class FQCN for dispatching a
/// `@psalm-assert-if-true`/`-if-false` docblock assertion — only handles a
/// receiver resolved to a single concrete class atom, or a `TIntersection`
/// whose parts unambiguously agree on which one declares `method_name`
/// (mirroring `narrow_nullsafe_method_call_null`'s same conservative scope;
/// a union of multiple UNRELATED classes could resolve the same method name
/// to different signatures, so that case still falls through). Handles a
/// bare-variable receiver (`$v->isInt($p)`), a 1-hop property receiver
/// (`$this->validator->isInt($p)`, a very common real-world shape), a
/// static-property receiver, and — via `resolve_chained_receiver_type` — a
/// deeper property chain, an array-index hop, or a method-call hop
/// (`$h->getValidator()->isInt($p)`), all of which previously fell through
/// unresolved, silently no-oping the whole assertion.
pub(super) fn method_call_receiver_fqcn(
    object: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
    method_name: &str,
) -> Option<std::sync::Arc<str>> {
    let obj_ty = if let Some(obj_var) = extract_var_name(object) {
        ctx.get_var(&obj_var)
    } else if let Some((obj_var, prop)) = extract_any_prop_access(object) {
        // `extract_any_prop_access` also matches a nullsafe (`?->`) receiver,
        // unlike the plain-`->`-only `extract_prop_access` this used to
        // call — mirrors the same fix already applied to the self-out
        // write-back's receiver resolution in `call/method.rs`. Deliberately
        // 1-hop-only here (not `extract_chained_prop_access`): a 2+-hop
        // receiver must fall through to the `resolve_chained_receiver_type`
        // arm below instead, which resolves its DECLARED type rather than
        // an unpopulated `prop_refined` synthetic-key lookup.
        resolve_prop_current_type(ctx, &obj_var, &prop, db, file)
    } else if let Some((fqcn, prop)) = extract_static_prop_access(object, ctx, db, file) {
        // `self::$validator->isValid($x)` — a static-property receiver is a
        // first-class shape everywhere else in this file (the assertion
        // TARGET side already resolves one), but this receiver-resolution
        // helper only ever tried a bare variable or an instance-property
        // chain, silently no-oping assert-if-true/-false narrowing for it.
        resolve_static_prop_current_type(ctx, &fqcn, &prop, db)
    } else {
        // A 2+-hop property chain (`$this->service->validator->isInt($p)`),
        // an array-index hop, or a method-call hop — none has a
        // `prop_refined` narrowing history keyed the way the 1-hop arm
        // above needs, but the DECLARED type through the chain (the same
        // resolver purity/taint checks already chain-walk with) is enough
        // to resolve which class's method this assertion targets.
        crate::expr::assignment::resolve_chained_receiver_type(object, ctx, db, file)?
    };
    let non_null_atoms: Vec<&Atomic> = obj_ty
        .types
        .iter()
        .filter(|t| !matches!(t, Atomic::TNull))
        .collect();
    match non_null_atoms.as_slice() {
        [Atomic::TNamedObject { fqcn, .. }]
        | [Atomic::TSelf { fqcn }]
        | [Atomic::TStaticObject { fqcn }]
        | [Atomic::TParent { fqcn }] => Some(std::sync::Arc::from(fqcn.as_ref())),
        // `Foo&Bar` — ordinary method-call resolution (`call/method.rs`'s
        // own `TIntersection` arm) already dispatches to whichever part
        // declares the method, so assertion-tag narrowing riding along the
        // same call must resolve the identical FQCN instead of silently
        // no-oping just because no single member atom matched above.
        [Atomic::TIntersection { parts }] => {
            parts
                .iter()
                .flat_map(|p| p.types.iter())
                .find_map(|atomic| match atomic {
                    Atomic::TNamedObject { fqcn, .. } => {
                        let resolved = crate::db::resolve_name(db, file, fqcn.as_ref());
                        let resolved: std::sync::Arc<str> = std::sync::Arc::from(resolved.as_str());
                        crate::db::has_method_in_chain(db, &resolved, method_name)
                            .then_some(resolved)
                    }
                    _ => None,
                })
        }
        _ => None,
    }
}

/// Resolve a static-method call's class-name expression (`Foo::bar()`,
/// `self::bar()`, `static::bar()`, `parent::bar()`) to a FQCN — the bare-
/// identifier counterpart of `extract_static_prop_access_parts`'s class
/// resolution (that one matches a `StaticPropertyAccess`'s `.class` field;
/// this one matches a `StaticMethodCall`'s). `extract_class_fqcn_from_expr`
/// is the wrong tool here: it resolves `Foo::class`/a string literal, not a
/// bare class-name identifier used directly as a call target.
pub(super) fn resolve_static_call_class_fqcn(
    class_expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<std::sync::Arc<str>> {
    let ExprKind::Identifier(id) = &class_expr.kind else {
        return None;
    };
    let resolved = crate::db::resolve_name(db, file, id.as_ref());
    match resolved.as_str() {
        "self" | "static" => Some(std::sync::Arc::from(
            ctx.self_fqcn.as_deref().or(ctx.static_fqcn.as_deref())?,
        )),
        "parent" => Some(std::sync::Arc::from(ctx.parent_fqcn.as_deref()?)),
        s => Some(std::sync::Arc::from(s)),
    }
}

/// Compute the narrowed type for a negated assertion (`@psalm-assert !Type
/// $x` — "$x is asserted NOT to be this type"): `current` minus `asserted`
/// for the shapes that can be precisely subtracted — `null`, `false`, and a
/// named class/interface (via the same subclass-aware exclusion a
/// `!($x instanceof C)` guard already uses). A union/intersection target
/// (`!A|B`) subtracts each atom in turn — "$x is not A|B" means neither A
/// nor B — instead of bailing out entirely just because the target has more
/// than one atom. Any atom kind not recognized is left unchanged rather than
/// risk excluding too much.
pub(crate) fn negate_assertion_type(current: &Type, asserted: &Type, db: &dyn MirDatabase) -> Type {
    if current.is_mixed_not_template() {
        return current.clone();
    }
    let mut result = current.clone();
    for atomic in &asserted.types {
        result = match atomic {
            Atomic::TNull => result.remove_null(),
            Atomic::TFalse => result.remove_false(),
            Atomic::TTrue => result.remove_true(),
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn } => filter_out_instanceof_match(&result, fqcn, db),
            Atomic::TIntersection { parts } => filter_out_intersection_match(&result, parts, db),
            _ => result,
        };
    }
    result
}

/// Resolve the call argument that actually feeds `params[param_index]`,
/// honoring named-argument reordering: a named argument binds by name
/// wherever it sits textually, so `call_args[param_index]` is only correct
/// when every argument is positional.
fn arg_for_param_index<'a>(
    params: &[mir_codebase::definitions::DeclaredParam],
    call_args: &'a [php_ast::owned::Arg],
    param_index: usize,
) -> Option<&'a php_ast::owned::Arg> {
    let param_name = params.get(param_index)?.name.as_ref();
    if let Some(arg) = call_args.iter().find(|a| {
        a.name
            .as_ref()
            .is_some_and(|n| crate::parser::name_to_string_owned(n) == param_name)
    }) {
        return Some(arg);
    }
    call_args
        .iter()
        .filter(|a| a.name.is_none())
        .nth(param_index)
}

/// If `call_args` is a single spread argument over a literal array
/// (`f(...[$a, $b])`), rewrite it into one synthetic, non-spread `Arg` per
/// element — each wrapping the element's own real expression (so a
/// subsequent narrowing target, e.g. `extract_var_name`, still resolves to
/// the actual `$a`/`$b`, not the outer array). Returns `None` for anything
/// else (no spread, more than one arg, a non-literal spread source, or a
/// keyed/nested-spread/by-ref element), leaving the caller to fall back to
/// the original `call_args` unexpanded.
fn expand_literal_spread_call_args(
    call_args: &[php_ast::owned::Arg],
) -> Option<Vec<php_ast::owned::Arg>> {
    let [sole] = call_args else {
        return None;
    };
    if !sole.unpack {
        return None;
    }
    let ExprKind::Array(elements) = &sole.value.kind else {
        return None;
    };
    let mut expanded = Vec::with_capacity(elements.len());
    for el in elements.iter() {
        if el.key.is_some() || el.unpack || el.by_ref {
            return None;
        }
        expanded.push(php_ast::owned::Arg {
            name: None,
            value: el.value.clone(),
            unpack: false,
            by_ref: false,
            span: el.span,
        });
    }
    Some(expanded)
}

/// Best-effort type of a call argument for inferring `@template` bindings on
/// an assert-if-true/-false narrowing call — not a full expression
/// evaluator, just enough to resolve the common `class-string<T>`/`T
/// $x`-typed guard-function shapes (e.g. `isInstanceOf($value,
/// Foo::class)`). Anything else falls back to `mixed`, which leaves the
/// template unbound rather than mis-bound.
fn assertion_arg_type(
    expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Type {
    if let Some(var_name) = extract_var_name(expr) {
        return ctx.get_var(&var_name);
    }
    if let Some((obj_var, prop)) = extract_prop_access(expr) {
        return resolve_prop_current_type(ctx, &obj_var, &prop, db, file);
    }
    if let Some(fqcn) = extract_class_fqcn_from_expr(
        expr,
        ctx.self_fqcn.as_deref(),
        ctx.static_fqcn.as_deref(),
        ctx.parent_fqcn.as_deref(),
        db,
        file,
    ) {
        return Type::single(Atomic::TClassString(Some(mir_types::Name::from(
            fqcn.as_ref(),
        ))));
    }
    Type::mixed()
}