mir-analyzer 0.82.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
use std::sync::Arc;

use mir_codebase::definitions::TemplateParam;
use mir_issues::Issue;
use mir_types::{Location, Name, Type};
use rustc_hash::{FxHashMap, FxHashSet};

use super::*;
use crate::db::SourceFile;

/// Snapshot of a class's discriminator + abstractness.
#[derive(Debug, Clone, Copy)]
pub struct ClassKind {
    pub is_interface: bool,
    pub is_trait: bool,
    pub is_enum: bool,
    pub is_abstract: bool,
}

pub fn class_kind(db: &dyn MirDatabase, fqcn: &str) -> Option<ClassKind> {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    let class = crate::db::find_class_like(db, here)?;
    Some(ClassKind {
        is_interface: class.is_interface(),
        is_trait: class.is_trait(),
        is_enum: class.is_enum(),
        is_abstract: class.is_abstract(),
    })
}

pub fn class_exists(db: &dyn MirDatabase, fqcn: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    crate::db::find_class_like(db, here).is_some()
}

/// True when `fqcn` is a `final` class (or an enum, which is implicitly
/// final) — i.e. provably has no subclasses. Unknown classes are not final.
pub fn is_final(db: &dyn MirDatabase, fqcn: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    crate::db::find_class_like(db, here).is_some_and(|c| c.is_final())
}

pub fn function_exists(db: &dyn MirDatabase, fqn: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqn);
    crate::db::find_function(db, here).is_some()
}

pub fn constant_exists(db: &dyn MirDatabase, fqn: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqn);
    crate::db::find_global_constant(db, here).is_some()
}

/// Resolve a type atom's already-inferred `fqcn` (`TNamedObject`/`TSelf`/
/// `TStaticObject`/`TParent`/an intersection member) to a canonical class
/// name for member (method/property) dispatch. Such a name is normally
/// already canonical by construction — re-running `resolve_name`'s
/// raw-source-text rules on it would wrongly re-prepend the current file's
/// namespace onto an already-resolved GLOBAL (backslash-less) class name,
/// since `resolve_name` can't tell "already resolved" apart from "bare
/// unqualified source text". Trust the literal name first when it already
/// names a real class; only fall back to `resolve_name` when it doesn't
/// (e.g. a raw class-string still needing namespace-relative resolution).
pub fn resolve_receiver_fqcn(db: &dyn MirDatabase, file: &str, fqcn: &str) -> String {
    if class_exists(db, fqcn) {
        return fqcn.to_string();
    }
    resolve_name(db, file, fqcn)
}

/// Like [`resolve_name`], but for a **docblock**-derived class name: a bare
/// real global builtin (`Closure`, `Throwable`, …) is left unqualified
/// instead of being prepended with the current namespace, matching how
/// Psalm/PHPStan lenently resolve these in docblocks even with no explicit
/// `use` import — see `is_global_builtin_docblock_class`.
/// An explicit `use` import for the same bare name still wins, same
/// priority order `resolve_name` itself uses internally.
pub fn resolve_docblock_type_name(db: &dyn MirDatabase, file: &str, name: &str) -> String {
    if !name.contains('\\') && !name.starts_with('\\') {
        let imports = db.file_class_imports(file);
        let has_explicit_import = imports.get(&Name::new(name)).is_some()
            || imports
                .iter()
                .any(|(alias, _)| alias.as_str().eq_ignore_ascii_case(name));
        if !has_explicit_import && crate::util::is_global_builtin_docblock_class(name) {
            return name.to_string();
        }
    }
    resolve_name(db, file, name)
}

pub fn resolve_name(db: &dyn MirDatabase, file: &str, name: &str) -> String {
    if name.starts_with('\\') {
        return name.trim_start_matches('\\').to_string();
    }

    let lower = name.to_ascii_lowercase();
    if matches!(lower.as_str(), "self" | "static" | "parent") {
        return name.to_string();
    }

    if name.contains('\\') {
        if let Some((first, rest)) = name.split_once('\\') {
            let imports = db.file_class_imports(file);
            if let Some(base) = imports.get(&Name::new(first)) {
                return format!("{}\\{rest}", base.as_str());
            }
            // Case-insensitive fallback: PHP resolves the leading segment of a
            // qualified name against `use` imports case-insensitively, same as
            // unqualified names below.
            if let Some((_, base)) = imports
                .iter()
                .find(|(alias, _)| alias.as_str().eq_ignore_ascii_case(first))
            {
                return format!("{}\\{rest}", base.as_str());
            }
        }
        // If the name is already a known FQCN (e.g. stored in TNamedObject by a prior
        // resolution step), return it unchanged to avoid double-prepending the namespace.
        if class_exists(db, name) {
            return name.to_string();
        }
        // Qualified name not yet in the DB (PSR-4 lazy-load will fire after this call):
        // PHP always prepends the current namespace unconditionally.
        if let Some(ns) = db.file_namespace(file) {
            return format!("{}\\{}", ns, name);
        }
        return name.to_string();
    }

    let imports = db.file_class_imports(file);
    if let Some(fqcn) = imports.get(&Name::new(name)) {
        return fqcn.as_str().to_string();
    }
    // Case-insensitive fallback: PHP class names are case-insensitive for
    // resolution. Iterate as a last resort; the exact-case hit above
    // catches the common path.
    if let Some((_, fqcn)) = imports
        .iter()
        .find(|(alias, _)| alias.as_str().eq_ignore_ascii_case(name))
    {
        return fqcn.as_str().to_string();
    }
    if let Some(ns) = db.file_namespace(file) {
        return format!("{}\\{}", ns, name);
    }
    name.to_string()
}

/// The `@template` params `fqcn` itself declares in its own docblock — empty
/// (or `None`) if it declares none, even when an ancestor further up the
/// chain does. Only the handful of callers that specifically care about
/// *this type's own declaration* (e.g. comparing a subclass's declared arity
/// against an ancestor's) should reach for this; almost everyone else wants
/// [`class_template_params`], which resolves the inherited case too.
pub fn declared_template_params(db: &dyn MirDatabase, fqcn: &str) -> Option<Arc<[TemplateParam]>> {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    let class = crate::db::find_class_like(db, here)?;
    Some(Arc::from(class.template_params().to_vec()))
}

/// The `@template` params that parameterize `fqcn` — its own, or if it
/// declares none, the nearest ancestor's found by walking up its native
/// `extends` chain. A plain subclass that doesn't redeclare `@template`
/// (`class IntBox extends Box {}`) is still implicitly parameterized the
/// same way its generic ancestor is — PHP/Psalm don't require re-declaring
/// an un-narrowed inherited template. This is what almost every caller wants
/// ("does this receiver have template slots to bind" — constructor-arg
/// inference on `new`, building bindings for a method call); reach for
/// [`declared_template_params`] instead only when own-declaration-only is
/// specifically the question being asked.
pub fn class_template_params(db: &dyn MirDatabase, fqcn: &str) -> Option<Arc<[TemplateParam]>> {
    let mut visited: FxHashSet<Arc<str>> = FxHashSet::default();
    // A worklist, not a linear `current = parent` chain: a bare interface
    // (`interface DogContainer extends AnimalContainer {}`) may extend
    // several bases at once, and PHP/Psalm don't require it to redeclare an
    // un-narrowed inherited `@template` — same reasoning `declared_template_params`'s
    // doc comment gives for the class case (see `inherited_template_bindings`
    // for the analogous worklist over interfaces' multi-base `extends`).
    let mut worklist: Vec<Arc<str>> = vec![Arc::from(fqcn)];
    while let Some(current) = worklist.pop() {
        if !visited.insert(current.clone()) {
            continue;
        }
        if let Some(tps) = declared_template_params(db, current.as_ref()) {
            if !tps.is_empty() {
                return Some(tps);
            }
        }
        let here = crate::db::Fqcn::from_str(db, current.as_ref());
        match crate::db::find_class_like(db, here) {
            Some(crate::db::ClassLike::Class(cls)) => {
                if let Some(parent) = cls.parent.clone() {
                    worklist.push(parent);
                }
            }
            Some(crate::db::ClassLike::Interface(iface)) => {
                worklist.extend(iface.extends.iter().cloned());
            }
            _ => {}
        }
    }
    None
}

/// Whether `fqcn` (or any ancestor up its native `extends` chain) is
/// `@psalm-immutable`. A subclass that doesn't redeclare the tag is just as
/// immutable as its ancestor — PHP/Psalm don't require re-annotating an
/// inherited class-level contract, the same reasoning `class_template_params`
/// already documents for `@template`. Previously this was read straight off
/// `ClassDef::is_immutable` (own declaration only) at both call sites, so a
/// subclass of an immutable class allowed an external write to an inherited
/// property that the ancestor-typed receiver would have correctly rejected.
pub fn class_is_immutable(db: &dyn MirDatabase, fqcn: &str) -> bool {
    let mut visited: FxHashSet<Arc<str>> = FxHashSet::default();
    let mut current: Option<Arc<str>> = Some(Arc::from(fqcn));
    while let Some(fqcn) = current {
        if !visited.insert(fqcn.clone()) {
            break;
        }
        let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
        match crate::db::find_class_like(db, here) {
            Some(crate::db::ClassLike::Class(cls)) => {
                if cls.is_immutable {
                    return true;
                }
                current = cls.parent.clone();
            }
            _ => break,
        }
    }
    false
}

/// Whether `fqcn` (or any ancestor up its native `extends` chain) is a PHP 8.2+
/// native `readonly` class. Native readonlyness enforces at the language level
/// that no property may be reassigned after construction, so every non-constructor
/// instance method of such an owner is mutation-free by construction — even when it
/// lacks an explicit `@psalm-mutation-free`. Mirrors `class_is_immutable`'s ancestor
/// walk: a child class inherits readonly-ness from its base.
/// Public predicate: true when `fqcn` is a native-readonly class or a PHP enum, and thus every
/// non-constructor method on it is mutation-free by construction. See the private helper below.
pub fn owner_type_is_mutation_free_by_construction(db: &dyn MirDatabase, fqcn: &str) -> bool {
    matches!(
        owner_mutation_free_by_construction_kind(db, fqcn),
        Some(OwnerMutationFreeKind::NativeReadonly | OwnerMutationFreeKind::Enum)
    )
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum OwnerMutationFreeKind {
    /// Native `readonly` class — property reassignment forbidden after construction.
    NativeReadonly,
    /// PHP enum — no mutable instance properties exist by definition (enums cannot
    /// declare non-promoted/instance state), so methods are mutation-free by construction.
    Enum,
}

/// Whether `fqcn` is an owner type whose every non-constructor method is
/// mutation-free *by construction*: either a native `readonly` class or a PHP enum.
///
/// Both kinds forbid mutating instance state after the constructor runs, so even without
/// an explicit `@psalm-mutation-free`, calling such methods from immutable/pure contexts
/// cannot introduce impurity. Mirrors `class_is_immutable`'s ancestor walk for classes:
/// a non-readonly child of a readonly base is still readonly (the language rule applies),
/// but enums are resolved as their own kind.
fn owner_mutation_free_by_construction_kind(
    db: &dyn MirDatabase,
    fqcn: &str,
) -> Option<OwnerMutationFreeKind> {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    match crate::db::find_class_like(db, here)? {
        ClassLike::Enum(_) => Some(OwnerMutationFreeKind::Enum),
        // Interfaces and traits declare no instance property storage of their own.
        ClassLike::Interface(_) | ClassLike::Trait(_) => None,
        // A readonly class is mutation-free by construction; a non-readonly class may
        // still be so if it (or any base along its native `extends` spine) eventually
        // derives from a native readonly base.
        ClassLike::Class(mut cls) => {
            loop {
                if cls.is_readonly {
                    return Some(OwnerMutationFreeKind::NativeReadonly);
                }
                let Some(parent_fqcn) = cls.parent.clone() else {
                    break;
                };
                let here = crate::db::Fqcn::from_str(db, parent_fqcn.as_ref());
                match crate::db::find_class_like(db, here) {
                    Some(ClassLike::Class(pcls)) => cls = pcls,
                    _ => return None,
                }
            }
            None
        }
    }
}

pub fn inherited_template_bindings(
    db: &dyn MirDatabase,
    fqcn: &str,
    own_bindings: &FxHashMap<Name, Type>,
) -> FxHashMap<Name, Type> {
    let mut bindings: FxHashMap<Name, Type> = FxHashMap::default();
    let mut substitution: FxHashMap<Name, Type> = own_bindings.clone();
    let mut visited: FxHashSet<Arc<str>> = FxHashSet::default();
    // A worklist, not a linear `current = parent` chain: an interface's
    // native `extends A, B` clause may name several bases at once, and each
    // of THOSE may further extend other generic interfaces — walking only
    // the class/parent spine would drop any template parameterization
    // declared past the first interface hop.
    let mut worklist: Vec<Arc<str>> = vec![Arc::from(fqcn)];

    let apply_type_args = |iface: &Arc<str>,
                           args: &[Type],
                           bindings: &mut FxHashMap<Name, Type>,
                           substitution: &mut FxHashMap<Name, Type>| {
        let Some(iface_tps) = class_template_params(db, iface.as_ref()) else {
            return;
        };
        for (tp, ty) in iface_tps.iter().zip(args.iter()) {
            let resolved_ty = ty.substitute_templates(substitution);
            substitution
                .entry(tp.name)
                .or_insert_with(|| resolved_ty.clone());
            bindings.entry(tp.name).or_insert(resolved_ty);
        }
    };

    while let Some(current) = worklist.pop() {
        if !visited.insert(current.clone()) {
            continue;
        }
        let Some(class) =
            crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, current.as_ref()))
        else {
            continue;
        };

        for (iface, args) in class.implements_type_args() {
            apply_type_args(iface, args, &mut bindings, &mut substitution);
        }
        for (iface, args) in class.interface_extends_type_args() {
            apply_type_args(iface, args, &mut bindings, &mut substitution);
        }
        if let Some(parent) = class.parent() {
            let extends_type_args = class.extends_type_args();
            if !extends_type_args.is_empty() {
                apply_type_args(parent, extends_type_args, &mut bindings, &mut substitution);
            }
        }

        // A used trait's own `@template` params are bound from an explicit
        // `@use TraitName<T>` type-argument list when the using class/trait
        // supplies one, substituting any of ITS OWN templates already bound
        // above/by the caller (`@use Collection<self>`-style forwarding);
        // otherwise (or for an arg position past the supplied list) they
        // fall back to `mixed` — the same fallback un-bound templates get
        // elsewhere — rather than staying absent: an absent entry would let
        // the RECEIVER's own same-named template letter silently leak into
        // the trait's property/method types wherever this function's result
        // is merged with a caller's own bindings via `entry().or_insert()`.
        for trait_fqcn in class.class_traits() {
            if let Some(trait_tps) = declared_template_params(db, trait_fqcn.as_ref()) {
                let explicit_args = class
                    .trait_use_type_args()
                    .iter()
                    .find(|(t, _)| t == trait_fqcn)
                    .map(|(_, args)| args.as_slice());
                for (i, tp) in trait_tps.iter().enumerate() {
                    let resolved = explicit_args
                        .and_then(|args| args.get(i))
                        .map(|ty| ty.substitute_templates(&substitution))
                        .unwrap_or_else(Type::mixed);
                    substitution
                        .entry(tp.name)
                        .or_insert_with(|| resolved.clone());
                    bindings.entry(tp.name).or_insert(resolved);
                }
            }
        }

        // Keep walking every ancestor edge — typed or not — so a base
        // interface/class/trait that itself parameterizes (or uses) a
        // further generic ancestor still gets picked up even when the edge
        // leading to it carried no type args of its own.
        worklist.extend(class.interfaces().iter().cloned());
        worklist.extend(class.extends().iter().cloned());
        worklist.extend(class.class_traits().iter().cloned());
        if let Some(parent) = class.parent() {
            worklist.push(parent.clone());
        }
    }
    bindings
}

pub fn has_unknown_ancestor(db: &dyn MirDatabase, fqcn: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    if crate::db::find_class_like(db, here).is_none() {
        return false;
    }
    crate::db::class_ancestors_by_fqcn(db, here)
        .iter()
        .skip(1) // self
        .any(|ancestor| !class_exists(db, ancestor))
}

/// Declaration site of the class member `symbol` names; the lookup is kind-specific
/// because a class may declare a method and a property with the same name.
pub fn member_location(db: &dyn MirDatabase, symbol: &crate::Name) -> Option<Location> {
    match symbol {
        // Precedence-aware so trait aliases and `insteadof` winners resolve.
        crate::Name::Method { class, name } => {
            let here = crate::db::Fqcn::from_str(db, class);
            crate::db::find_method_respecting_precedence(db, here, name)?
                .1
                .location
                .clone()
        }
        crate::Name::Property { class, name } => {
            let here = crate::db::Fqcn::from_str(db, class);
            crate::db::find_property_in_chain(db, here, name)?
                .1
                .location
        }
        crate::Name::ClassConstant { class, name } => {
            let here = crate::db::Fqcn::from_str(db, class);
            crate::db::find_class_constant_in_chain(db, here, name)?
                .1
                .location
        }
        _ => None,
    }
}

pub fn class_constant_exists_in_chain(db: &dyn MirDatabase, fqcn: &str, const_name: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, fqcn);
    crate::db::find_class_constant_in_chain(db, here, const_name).is_some()
}

/// Subtype check: does `child` extend or implement `ancestor`?
///
/// Run on every assignment / arg / return / throw-catch type-compatibility
/// check — by far the hottest consumer of FQCN interning (`ustr::Ustr::from`
/// takes a global lock). The same `(child, ancestor)` pairs recur constantly,
/// so when a **pass-scoped** subtype cache is present (set on the batch body
/// pass via `freeze_workspace_index`) we hash the raw `&str` pair and return
/// **before** any interning. The cache is sound for the same reason the frozen
/// index is: the class graph is immutable for the duration of the pass, so a
/// memoized answer can't go stale. On the canonical / open-file db the cache is
/// absent (`None`) and every call recomputes — correct under mid-analysis
/// mutation, just not accelerated.
///
/// **Case semantics**: class names compare case-insensitively (PHP semantics;
/// `class Base` / `class base` are the same class). The byte-exact comparisons
/// below are kept as a zero-cost fast path; the `eq_ignore_ascii_case` fallback
/// matches the ASCII-fold case of the workspace symbol index
/// (`find_class_like`), which is the existing resolution standard. Case-variant
/// spellings produce distinct subtype-cache entries (distinct hashes) but the
/// same answer, so the cache stays sound.
pub fn extends_or_implements(db: &dyn MirDatabase, child: &str, ancestor: &str) -> bool {
    if child == ancestor || child.eq_ignore_ascii_case(ancestor) {
        return true;
    }
    let Some(cache) = db.subtype_cache() else {
        return extends_or_implements_uncached(db, child, ancestor);
    };
    use std::hash::{Hash, Hasher};
    let mut h1 = rustc_hash::FxHasher::default();
    child.hash(&mut h1);
    let mut h2 = rustc_hash::FxHasher::default();
    ancestor.hash(&mut h2);
    let key = (h1.finish(), h2.finish());
    // Collision-safe: the stored strings are verified against the lookup pair,
    // so a hash collision degrades to a recompute, never a wrong answer.
    if let Some(entry) = cache.get(&key) {
        if entry.0.as_ref() == child && entry.1.as_ref() == ancestor {
            return entry.2;
        }
    }
    let result = extends_or_implements_uncached(db, child, ancestor);
    // `or_insert_with` so a colliding entry (different pair, same hash) is left
    // intact — that pair just won't be cached.
    cache
        .entry(key)
        .or_insert_with(|| (Box::from(child), Box::from(ancestor), result));
    result
}

fn extends_or_implements_uncached(db: &dyn MirDatabase, child: &str, ancestor: &str) -> bool {
    let here = crate::db::Fqcn::from_str(db, child);
    let Some(class) = crate::db::find_class_like(db, here) else {
        return false;
    };

    // If the ancestor is namespace-qualified but doesn't exist in the symbol table,
    // fall back to the short name. This recovers global stub classes (DOMNode, etc.)
    // that were incorrectly namespace-qualified when referenced from namespaced files
    // without a leading backslash.
    let short: Option<&str> = if ancestor.contains('\\') {
        let fqcn = crate::db::Fqcn::from_str(db, ancestor);
        if crate::db::find_class_like(db, fqcn).is_none() {
            ancestor.rsplit('\\').next()
        } else {
            None
        }
    } else {
        None
    };
    let eff = short.unwrap_or(ancestor);

    if child == eff || child.eq_ignore_ascii_case(eff) {
        return true;
    }

    if class.is_enum() {
        if class
            .interfaces()
            .iter()
            .any(|i| i.as_ref() == eff || i.as_ref().eq_ignore_ascii_case(eff))
        {
            return true;
        }
        if eff.eq_ignore_ascii_case("UnitEnum") || eff.eq_ignore_ascii_case("\\UnitEnum") {
            return true;
        }
        if (eff.eq_ignore_ascii_case("BackedEnum") || eff.eq_ignore_ascii_case("\\BackedEnum"))
            && class.is_backed_enum()
        {
            return true;
        }
        return false;
    }
    crate::db::class_ancestors_by_fqcn(db, here)
        .iter()
        .any(|p| p.as_ref() == eff || p.as_ref().eq_ignore_ascii_case(eff))
}

// parse_file tracked query (S0 — owned parse, salsa-memoized)

/// Newtype so `Arc<ParseResult>` can be a salsa tracked-query return type.
///
/// Equality is pointer identity — salsa uses it to decide whether
/// downstream queries need re-running after a re-parse.
#[derive(Clone)]
pub struct TrackedParseResult(pub Arc<php_rs_parser::ParseResult>);

impl std::fmt::Debug for TrackedParseResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("TrackedParseResult").finish()
    }
}

impl PartialEq for TrackedParseResult {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for TrackedParseResult {}

/// Parse `file`'s source text into a fully-owned, lifetime-free
/// [`php_rs_parser::ParseResult`] and memoize it in Salsa.
///
/// Salsa invalidates this memo whenever `file.text(db)` changes.  All
/// downstream queries that need the AST or source-map should call this
/// instead of calling `php_rs_parser::parse` directly, so they get the
/// cached result for free on every incremental edit that doesn't touch
/// this file.
///
/// `lru = 256` caps the number of owned ASTs held in memory. Beyond that
/// cap, the least-recently-used parse is evicted; if a later query re-asks,
/// salsa re-parses on demand. For CLI cold-start the visit pattern is
/// "parse once, never re-ask," so eviction is effectively free; for LSP
/// the working set is small. Without the cap, parsing 12k files would
/// pin ~1–4 GB of owned AST for the whole session.
///
/// A cold reference pass re-asks past this cap (Phase 1 warm-up parses,
/// Phase 2 `analyze_file` re-parses whatever was evicted), but the re-parse
/// runs inside the rayon-parallel Phase 2: measured on the Laravel fixture
/// (11.6k registered files, `Illuminate\Support\Str` cold query and cold
/// CLI batch), `lru = 65536` moved neither wall time (within noise) nor
/// peak RSS. Keep the small cap — it bounds steady-state memory for free.
#[salsa::tracked(lru = 256)]
pub fn parse_file(db: &dyn MirDatabase, file: SourceFile) -> TrackedParseResult {
    let text = file.text(db);
    TrackedParseResult(Arc::new(php_rs_parser::parse(text.as_ref())))
}

// collect_file_definitions tracked query (S1)

/// Uncached version of collect_file_definitions for bulk operations like vendor
/// collection, where we don't need Salsa to cache the intermediate StubSlice
/// results. This avoids holding `Arc<StubSlice>` in Salsa's query cache after
/// ingestion.
pub fn collect_file_definitions_uncached(
    db: &dyn MirDatabase,
    file: SourceFile,
) -> FileDefinitions {
    let path = file.path(db);
    let text = file.text(db);

    let php_version = db_php_version(db);

    // Content hash needed for both in-process and disk cache lookups.
    let content_hash = crate::stub_cache::hash_source(text);

    // Fast path 1: in-process parse cache (populated by collect_and_ingest_file).
    // Avoids re-parsing files that were already processed in the same session.
    // Safe inside a tracked query: content-addressed by source hash, not mutated.
    // Definition locations embed the collecting file's path, so only a
    // same-path entry is reusable.
    if let Some(cached) = db
        .parse_cache()
        .get(&content_hash, php_version.cache_byte())
        .filter(|cached| cached.slice.file.as_deref() == Some(path))
    {
        crate::metrics::record_stub_cache_hit();
        return FileDefinitions {
            slice: cached.slice,
            issues: cached.issues,
        };
    }

    // Fast path 2: disk cache hit avoids arena alloc + parse + collection walk.
    // Safe inside a tracked query because the cache is content-addressed.
    let disk_cache_state = db.stub_cache().map(|cache| {
        let php_v = php_version.cache_byte();
        (cache, php_v)
    });
    if let Some((cache, php_v)) = &disk_cache_state {
        if let Some((mut slice, issues)) = cache.get(path, &content_hash, *php_v) {
            crate::stub_cache::prepare_for_ingest(&mut slice);
            crate::metrics::record_stub_cache_hit();
            return FileDefinitions {
                slice: Arc::new(slice),
                issues: Arc::new(issues),
            };
        }
        crate::metrics::record_stub_cache_miss();
    }

    let parsed = php_rs_parser::parse(text);

    let has_hard_parse_errors = parsed.errors.iter().any(crate::parser::is_hard_parse_error);

    let mut all_issues: Vec<Issue> = parsed
        .errors
        .iter()
        .filter(|err| !crate::parser::is_spurious_reserved_class_error(err))
        .map(|err| crate::parser::parse_error_to_issue(err, path, text, &parsed.source_map))
        .collect();

    let collector = crate::collector::DefinitionCollector::new_for_slice(
        path.clone(),
        text,
        &parsed.source_map,
    )
    .with_php_version(php_version);
    let (mut slice, collector_issues) = collector.collect_slice(&parsed.program);
    all_issues.extend(collector_issues);
    mir_codebase::definitions::deduplicate_params_in_slice(&mut slice);

    let slice_arc = Arc::new(slice);
    let issues_arc = Arc::new(all_issues);

    // Write back to both caches as long as the AST parsed cleanly.
    //
    // Collector-emitted diagnostics (malformed docblocks, unknown @psalm
    // annotations, etc.) are warnings on a fully-parsed AST — the slice is
    // complete and valid. Excluding those files from the cache forces a
    // re-parse on every subsequent session for any vendor file with so much
    // as a docblock warning. Only hard parse errors (incomplete AST) block
    // caching.
    if !has_hard_parse_errors {
        // In-process cache: prevents re-parsing in the same session, and
        // preserves these exact issues for a later hit.
        db.parse_cache().insert(
            content_hash,
            php_version.cache_byte(),
            Arc::clone(&slice_arc),
            Arc::clone(&issues_arc),
        );
        // Disk cache: prevents re-parsing in future sessions.
        if let Some((cache, php_v)) = &disk_cache_state {
            cache.put(path, &content_hash, *php_v, &slice_arc, &issues_arc);
        }
    }

    FileDefinitions {
        slice: slice_arc,
        issues: issues_arc,
    }
}

/// `lru = 65536` caps the number of `FileDefinitions` results held in Salsa's
/// memo table. Without an LRU, every vendor class file ever loaded in a
/// long-running LSP session retains its `Arc<StubSlice>` in the memo
/// indefinitely, even after the file is evicted from the session via
/// `invalidate_file`.
///
/// The cap must comfortably exceed the workspace's file count, not just the
/// simultaneous active-file count: the first subtype/defs index build and
/// the ancestor resolution behind it walk EVERY registered file through
/// this query, and a cap below the workspace size makes each walk
/// re-execute the evicted majority — at `lru = 4096`, a cold reference
/// query on a 15K-file workspace re-collected (and re-parsed past
/// `parse_file`'s own LRU) every file ~3×.
/// 65536 covers the LSP consumer's 50K-file scan ceiling with headroom
/// while still bounding transiently-loaded vendor slices in pathological
/// sessions.
#[salsa::tracked(lru = 65536)]
pub fn collect_file_definitions(db: &dyn MirDatabase, file: SourceFile) -> FileDefinitions {
    collect_file_definitions_uncached(db, file)
}

// File-level inferred-type Salsa query

type MethodInferMap = FxHashMap<(Arc<str>, Arc<str>), Arc<Type>>;
// Property names are case-sensitive in PHP (unlike method names), so unlike
// `MethodInferMap` this is keyed by the name as written, not lowercased.
type PropertyInferMap = FxHashMap<(Arc<str>, Arc<str>), Arc<Type>>;

#[derive(Clone, Debug)]
pub struct InferredFileTypes {
    pub functions: Arc<FxHashMap<Arc<str>, Arc<Type>>>,
    pub methods: Arc<MethodInferMap>,
    pub properties: Arc<PropertyInferMap>,
}

impl InferredFileTypes {
    pub fn empty() -> Self {
        Self {
            functions: Arc::new(FxHashMap::default()),
            methods: Arc::new(MethodInferMap::default()),
            properties: Arc::new(PropertyInferMap::default()),
        }
    }
}

impl PartialEq for InferredFileTypes {
    fn eq(&self, other: &Self) -> bool {
        if Arc::ptr_eq(&self.functions, &other.functions)
            && Arc::ptr_eq(&self.methods, &other.methods)
            && Arc::ptr_eq(&self.properties, &other.properties)
        {
            return true;
        }
        if self.functions.len() != other.functions.len()
            || self.methods.len() != other.methods.len()
            || self.properties.len() != other.properties.len()
        {
            return false;
        }
        for (k, v) in self.functions.iter() {
            if other.functions.get(k).is_none_or(|ov| *ov != *v) {
                return false;
            }
        }
        for (k, v) in self.methods.iter() {
            if other.methods.get(k).is_none_or(|ov| *ov != *v) {
                return false;
            }
        }
        for (k, v) in self.properties.iter() {
            if other.properties.get(k).is_none_or(|ov| *ov != *v) {
                return false;
            }
        }
        true
    }
}

fn infer_file_return_types_initial(
    _db: &dyn MirDatabase,
    _id: salsa::Id,
    _file: SourceFile,
) -> InferredFileTypes {
    InferredFileTypes::empty()
}

fn infer_file_return_types_cycle(
    _db: &dyn MirDatabase,
    cycle: &salsa::Cycle,
    last: &InferredFileTypes,
    value: InferredFileTypes,
    _file: SourceFile,
) -> InferredFileTypes {
    if !crate::db::inferred_types::should_widen(cycle) {
        return value;
    }
    InferredFileTypes {
        functions: Arc::new(widen_unstable_map(&last.functions, &value.functions)),
        methods: Arc::new(widen_unstable_map(&last.methods, &value.methods)),
        properties: Arc::new(widen_unstable_map(&last.properties, &value.properties)),
    }
}

fn widen_unstable_map<K: Eq + std::hash::Hash + Clone>(
    last: &FxHashMap<K, Arc<Type>>,
    value: &FxHashMap<K, Arc<Type>>,
) -> FxHashMap<K, Arc<Type>> {
    value
        .iter()
        .map(|(k, ty)| {
            let ty = if last.get(k) == Some(ty) {
                ty.clone()
            } else {
                mir_codebase::definitions::wrap_var_type(Type::mixed())
            };
            (k.clone(), ty)
        })
        .collect()
}

/// Memoized parse of the configured PHP version string.
///
/// Reads the `AnalyzeFileInput.php_version` salsa input so that salsa tracks
/// the dependency correctly; `from_str` is called at most once per version
/// change instead of once per file.
#[salsa::tracked(returns(copy))]
pub fn db_php_version(db: &dyn MirDatabase) -> crate::php_version::PhpVersion {
    use std::str::FromStr as _;
    crate::php_version::PhpVersion::from_str(db.analyze_config().php_version(db).as_ref())
        .unwrap_or(crate::php_version::PhpVersion::LATEST)
}

/// Shared setup for file-scoped Salsa analysis queries.
///
/// Several tracked queries open-code the same sequence:
///
/// - load `file.path(db)` / `file.text(db)`
/// - load `parse_file(db, file)`
/// - compute the configured PHP version
/// - gate on hard parse errors
///
/// Centralizing that setup keeps the query family behavior aligned and makes
/// future parse/version changes land in one place.
pub struct PreparedAnalysisFile<'a> {
    pub path: &'a Arc<str>,
    pub text: &'a Arc<str>,
    pub parsed: &'a TrackedParseResult,
    pub php_version: crate::php_version::PhpVersion,
    pub has_hard_parse_errors: bool,
}

impl PreparedAnalysisFile<'_> {
    pub fn parse_result(&self) -> &php_rs_parser::ParseResult {
        &self.parsed.0
    }
}

pub fn prepare_analysis_file(db: &dyn MirDatabase, file: SourceFile) -> PreparedAnalysisFile<'_> {
    let path = file.path(db);
    let text = file.text(db);
    let parsed = parse_file(db, file);
    PreparedAnalysisFile {
        path,
        text,
        has_hard_parse_errors: parsed
            .0
            .errors
            .iter()
            .any(crate::parser::is_hard_parse_error),
        parsed,
        php_version: db_php_version(db),
    }
}

#[salsa::tracked(cycle_fn = infer_file_return_types_cycle, cycle_initial = infer_file_return_types_initial)]
pub fn infer_file_return_types(db: &dyn MirDatabase, file: SourceFile) -> InferredFileTypes {
    let prepared = prepare_analysis_file(db, file);

    if prepared.has_hard_parse_errors {
        return InferredFileTypes::empty();
    }

    let mut functions: FxHashMap<Arc<str>, Arc<Type>> = FxHashMap::default();
    let mut methods: FxHashMap<(Arc<str>, Arc<str>), Arc<Type>> = FxHashMap::default();
    let mut properties: FxHashMap<(Arc<str>, Arc<str>), Arc<Type>> = FxHashMap::default();

    for key in crate::db::file_scopes(db, file).iter() {
        let inferred = crate::db::infer_scope(db, file, key.clone())
            .inferred_types
            .clone();
        for (fqn, ty) in inferred.functions.iter() {
            functions.insert(
                fqn.clone(),
                mir_codebase::definitions::wrap_var_type(ty.clone()),
            );
        }
        for (fqcn, name, ty) in inferred.methods.iter() {
            let name_lower: Arc<str> = if name.bytes().any(|b| b.is_ascii_uppercase()) {
                Arc::from(crate::util::php_ident_lowercase(name))
            } else {
                name.clone()
            };
            methods.insert(
                (fqcn.clone(), name_lower),
                mir_codebase::definitions::wrap_var_type(ty.clone()),
            );
        }
        for (fqcn, name, ty) in inferred.properties.iter() {
            properties
                .entry((fqcn.clone(), name.clone()))
                .and_modify(|existing: &mut Arc<Type>| {
                    let mut merged = (**existing).clone();
                    merged.merge_with(ty);
                    *existing = mir_codebase::definitions::wrap_var_type(merged);
                })
                .or_insert_with(|| mir_codebase::definitions::wrap_var_type(ty.clone()));
        }
    }

    InferredFileTypes {
        functions: Arc::new(functions),
        methods: Arc::new(methods),
        properties: Arc::new(properties),
    }
}

pub fn is_unchecked_exception(db: &dyn MirDatabase, fqcn: &str) -> bool {
    extends_or_implements(db, fqcn, "RuntimeException")
        || extends_or_implements(db, fqcn, "LogicException")
}