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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
use std::panic::AssertUnwindSafe;
use std::sync::Arc;

use rustc_hash::FxHashSet as HashSet;
use salsa::Cancelled;

use super::index_state::{
    hash_files, AnalyzedFile, DefsFreshness, IndexState, QueryGeneration, RefFreshness,
    RefQueryCacheKey, RetireEpoch, SubtypeQueryCacheKey, ViewStamp,
};
use super::queries::{identifier_char_col, span_range, ReferenceGate};
use super::SubtypeClassSite;
use crate::cache::AnalysisCache;
use crate::db::{MirDatabase, MirDbStorage};
use crate::php_version::PhpVersion;

/// A read handle on one revision of an [`super::AnalysisSession`]:
/// `Send + Clone`, for running queries on threads other than the owner's.
///
/// No query writes salsa inputs. Class-likes and built-in stubs the symbol
/// index lacks load on demand as pure reads; the owner adopts them at its
/// next [`super::AnalysisSession::prepare_for_query`], which also settles
/// the index before a snapshot is handed out.
///
/// A snapshot blocks the owner's next input write until it is dropped (salsa
/// waits for outstanding handles), so hand snapshots out per request and
/// never park one. When the owner starts a write, in-flight queries unwind
/// and return `Err(Cancelled)`: drop the snapshot and request a fresh one.
///
/// Queries may still commit to the shared reference/subtype indexes (lazy
/// freshness passes); those commits land in the owner's state too.
#[derive(Clone)]
pub struct AnalysisSnapshot {
    pub(super) db: MirDbStorage,
    pub(super) index: Arc<IndexState>,
    pub(super) cache: Option<Arc<AnalysisCache>>,
    pub(super) php_version: PhpVersion,
    /// [`Self::index_generation`] captured when the owner created the
    /// snapshot, while no write could race it.
    pub(super) index_generation: u64,
    /// Retirements this snapshot's view already reflects; commits for files
    /// retired later are refused.
    pub(super) retire_epoch: RetireEpoch,
}

const _: () = {
    const fn assert_send_clone<T: Send + Clone>() {}
    assert_send_clone::<AnalysisSnapshot>();
};

/// An [`AnalysisSnapshot`] that borrows its owner, so the owner's next
/// `&mut self` write can't start while it's alive. A live handle across that
/// write would deadlock the owner in salsa's `cancel_others`.
pub(crate) struct DbView<'a> {
    snapshot: AnalysisSnapshot,
    _owner: std::marker::PhantomData<&'a super::AnalysisSession>,
}

impl<'a> DbView<'a> {
    pub(super) fn new(_owner: &'a super::AnalysisSession, snapshot: AnalysisSnapshot) -> Self {
        Self {
            snapshot,
            _owner: std::marker::PhantomData,
        }
    }
}

// Without a `Drop` impl, NLL ends the owner borrow at the view's last use
// while its db clone lives on to the end of scope.
struct ConstantDeclSite {
    file: Arc<str>,
    line: u32,
    stmt_col: u32,
    stmt_end: u32,
    name_col: u32,
    name_len: u32,
}

impl Drop for DbView<'_> {
    fn drop(&mut self) {}
}

impl std::ops::Deref for DbView<'_> {
    type Target = AnalysisSnapshot;
    fn deref(&self) -> &AnalysisSnapshot {
        &self.snapshot
    }
}

/// Analyses staged by [`AnalysisSnapshot::stage_warm`], awaiting commit.
struct WarmPass {
    mention_scanner: Option<Arc<crate::db::class_mention_index::MentionScanner>>,
    analyzed: Vec<AnalyzedFile>,
}

/// A fallback mention scan `(file, text scanned, names found)`, recorded
/// after the pass so later gate checks become set lookups.
type MentionScanRecord = (Arc<str>, Arc<str>, Box<[mir_types::Name]>);

pub(super) fn catch<T>(f: impl FnOnce() -> T) -> Result<T, Cancelled> {
    Cancelled::catch(AssertUnwindSafe(f))
}

/// Raise `cancelled` the way salsa does, for code already inside [`catch`].
pub(super) fn unwind(cancelled: Cancelled) -> ! {
    std::panic::resume_unwind(Box::new(cancelled))
}

impl AnalysisSnapshot {
    /// The salsa database this snapshot reads.
    ///
    /// **Internal API — exposes Salsa types.** Subject to change without
    /// notice. Queries on it unwind with [`Cancelled`] rather than returning
    /// it; use [`Self::read`] to catch that.
    #[doc(hidden)]
    pub fn db(&self) -> &MirDbStorage {
        &self.db
    }

    /// Run `f` against the database, catching cancellation.
    ///
    /// **Internal API — exposes Salsa types.** Subject to change without
    /// notice.
    #[doc(hidden)]
    pub fn read<R>(&self, f: impl FnOnce(&dyn MirDatabase) -> R) -> Result<R, Cancelled> {
        catch(|| f(&self.db))
    }

    pub(crate) fn index(&self) -> &IndexState {
        &self.index
    }

    pub(crate) fn stamp(&self) -> ViewStamp {
        ViewStamp {
            generation: self.index_generation,
            retire_epoch: self.retire_epoch,
        }
    }

    pub fn php_version(&self) -> PhpVersion {
        self.php_version
    }

    /// See [`super::AnalysisSession::index_generation`].
    pub fn index_generation(&self) -> u64 {
        self.index_generation
    }

    /// See [`super::AnalysisSession::text_revision`].
    pub fn text_revision(&self) -> salsa::Revision {
        self.db.current_revision()
    }

    /// The combined generation the query memos key on: salsa's text revision
    /// plus the off-salsa subtype-edge epoch and retirement seq. The epoch
    /// covers what the revision can't — subtype edges and anonymous-class
    /// `impl:` postings committed *within* one revision (e.g. a subtype BFS
    /// admitting a file the reference gate skipped), which change a member
    /// query's hierarchy fan-out without any text write. The seq covers a
    /// retire whose ingest writes nothing, so a query that read the cleared
    /// postings is never memoized.
    pub(crate) fn query_cache_generation(&self) -> QueryGeneration {
        (
            self.db.current_revision(),
            self.db.subtype_edges_epoch(),
            self.index.retire_seq(),
        )
    }

    pub fn find_class_like(&self, fqcn: &str) -> Result<Option<crate::db::ClassLike>, Cancelled> {
        self.read(|db| crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, fqcn)))
    }

    /// Whether `fqcn` resolves to a class-like declared by an embedded
    /// built-in stub. A workspace class sharing a stub's name (a polyfill's
    /// `Stringable`) shadows it and answers `false`, where
    /// [`crate::stub_path_for_class`] tests the name alone.
    pub fn is_builtin_class(&self, fqcn: &str) -> Result<bool, Cancelled> {
        self.read(|db| {
            let fqcn = fqcn.trim_start_matches('\\');
            crate::db::class_like_decl_file(db, crate::db::Fqcn::from_str(db, fqcn))
                .is_some_and(|file| crate::stubs::is_stub_path(&file))
        })
    }

    pub fn find_function(&self, fqn: &str) -> Result<Option<Arc<crate::FunctionDef>>, Cancelled> {
        self.read(|db| crate::db::find_function(db, crate::db::Fqcn::from_str(db, fqn)))
    }

    /// `method` as resolved along `class`'s ancestor chain (then mixins), as
    /// `(declaring class, method)`.
    #[allow(clippy::type_complexity)]
    pub fn find_method_in_chain(
        &self,
        class: &str,
        method: &str,
    ) -> Result<Option<(Arc<str>, Arc<mir_codebase::definitions::MethodDef>)>, Cancelled> {
        self.read(|db| {
            crate::db::find_method_in_chain(db, crate::db::Fqcn::from_str(db, class), method)
        })
    }

    /// Declaration location of `symbol`. Symbols the index lacks load on
    /// demand; no input is written.
    pub fn definition_of_cached(
        &self,
        symbol: &crate::Name,
    ) -> Result<Result<mir_types::Location, crate::SymbolLookupError>, Cancelled> {
        catch(|| self.definition_of_unguarded(symbol))
    }

    fn definition_of_unguarded(
        &self,
        symbol: &crate::Name,
    ) -> Result<mir_types::Location, crate::SymbolLookupError> {
        let db = &self.db;
        match symbol {
            crate::Name::Class(fqcn) => {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                let class = crate::db::find_class_like(db, here)
                    .ok_or(crate::SymbolLookupError::NotFound)?;
                class
                    .location()
                    .cloned()
                    .ok_or(crate::SymbolLookupError::NoSourceLocation)
            }
            crate::Name::Function(fqn) => {
                let here = crate::db::Fqcn::from_str(db, fqn.as_ref());
                let f =
                    crate::db::find_function(db, here).ok_or(crate::SymbolLookupError::NotFound)?;
                f.location
                    .clone()
                    .ok_or(crate::SymbolLookupError::NoSourceLocation)
            }
            crate::Name::Method { .. }
            | crate::Name::Property { .. }
            | crate::Name::ClassConstant { .. } => {
                crate::db::member_location(db, symbol).ok_or(crate::SymbolLookupError::NotFound)
            }
            crate::Name::GlobalConstant(fqn) => self
                .global_constant_location(fqn)
                .ok_or(crate::SymbolLookupError::NoSourceLocation),
        }
    }

    /// Which of `files` currently mention `class_name` as a whole identifier
    /// (case-insensitive) — the same persistent, incrementally-maintained
    /// mechanism [`Self::indexed_references_to`]'s own gate uses (see
    /// `db::class_mention_index`), exposed so a host needn't re-implement a
    /// from-scratch text scan for its own narrowing. A file already scanned
    /// against a universe that included `class_name` answers via an O(log n)
    /// lookup; only a never-scanned or since-edited file pays a scan, and
    /// that scan is recorded for every other name in the universe too.
    pub fn files_mentioning_class(
        &self,
        files: &[Arc<str>],
        class_name: &str,
    ) -> Result<Vec<Arc<str>>, Cancelled> {
        self.files_mentioning_any(files, &[class_name])
    }

    /// Which of `files` currently mention ANY of `needles` as a whole
    /// identifier (case-insensitive). Every needle is admitted into the
    /// shared universe verbatim (no short-name stripping) before querying,
    /// so the answer is never conservative on account of an unknown needle.
    pub fn files_mentioning_any(
        &self,
        files: &[Arc<str>],
        needles: &[&str],
    ) -> Result<Vec<Arc<str>>, Cancelled> {
        catch(|| self.mentioning_any_unguarded(files, needles))
    }

    fn mentioning_any_unguarded(&self, files: &[Arc<str>], needles: &[&str]) -> Vec<Arc<str>> {
        use rayon::prelude::*;

        if needles.is_empty() {
            return files.to_vec();
        }
        let db = self.db.clone();
        db.add_literal_mention_names(needles.iter().copied());
        // Admission just grew the universe, so these only fail defensively.
        let queries: Vec<_> = needles
            .iter()
            .filter_map(|n| db.prepare_class_mention_query(n))
            .collect();
        if queries.is_empty() {
            return files.to_vec();
        }
        let Some(scanner) = db.class_mention_scanner() else {
            return files.to_vec();
        };

        files
            .par_iter()
            .map_with(db, |db, f| -> Option<Arc<str>> {
                let sf = db.lookup_source_file(f.as_ref())?;
                let text = sf.text(&*db as &dyn MirDatabase).clone();
                for q in &queries {
                    match db.class_mention_answer(f.as_ref(), q, &text) {
                        Some(true) => return Some(f.clone()),
                        Some(false) => continue,
                        None => {
                            let names = scanner.scan(text.as_ref());
                            let hit = queries
                                .iter()
                                .any(|q2| names.binary_search(&q2.name).is_ok());
                            db.set_file_class_mentions(f, &text, scanner.epoch(), names);
                            return hit.then(|| f.clone());
                        }
                    }
                }
                None
            })
            .flatten()
            .collect()
    }

    /// Inverted-index find-references: posting-list lookup plus an on-demand
    /// freshness/completeness pass over `files` (the host's candidate scope
    /// — passing the whole workspace is fine; see the gate in
    /// `stale_reference_candidates_unguarded`).
    ///
    /// A candidate whose postings were committed from its current text (Arc
    /// identity) is answered from the index with no salsa work. Stale or
    /// never-committed candidates are analyzed via the memoized
    /// `analyze_file` query and committed, so each file pays that cost once
    /// per text change — after a background warm sweep the steady state is a
    /// pure lookup, O(results) instead of O(candidates). Hosts need no text
    /// prefilter of their own, and must not use one: a host-side filter
    /// cannot know the gate's matching semantics.
    ///
    /// Results are filtered to `files`. With `include_declaration`, the
    /// symbol's declaration name span is appended when it lies inside the
    /// scope.
    ///
    /// Returned ranges use mir's native coordinates: 1-based lines and
    /// 0-based Unicode code-point columns (UTF-32/LSP `positionEncoding`
    /// `"utf-32"`).
    ///
    /// Stale candidates are analyzed against whatever the owner has loaded.
    /// Classes load on demand, but Composer `autoload.files` functions only
    /// load in the owner's warm-up: a candidate analyzed before it records
    /// unresolved names and is re-verified after the owner's next load bumps
    /// the generation. Run [`super::AnalysisSession::prepare_references_query`]
    /// before taking the snapshot to warm the stale candidates first.
    ///
    /// Memoized per `(symbol, files, include_declaration, includes,
    /// query generation)` — see `RefQueryCacheKey` — so a repeat query
    /// against unchanged state (a code-lens refresh) is one hashmap lookup
    /// instead of an O(candidates) freshness scan.
    pub fn indexed_references_to(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
        include_declaration: bool,
        includes: crate::ReferenceIncludes,
    ) -> Result<Vec<(Arc<str>, crate::Range)>, Cancelled> {
        let key = self.reference_query_key(symbol, files, include_declaration, includes);
        if let Some(hit) = self.index.ref_queries.get(&key) {
            return Ok(hit);
        }
        let stale = catch(|| self.stale_reference_candidates_unguarded(symbol, files))?;
        if !stale.is_empty() {
            self.commit_reference_candidates(&stale)?;
        }
        let out = catch(|| self.read_references(symbol, files, include_declaration, includes))?;
        self.ensure_no_retire_since(key.generation)?;
        self.memoize_references(key, &out);
        Ok(out)
    }

    /// `Err` when the owner retired a file since `generation`: postings read
    /// in between may lack that file, and its replacing write is under way.
    pub(super) fn ensure_no_retire_since(
        &self,
        generation: QueryGeneration,
    ) -> Result<(), Cancelled> {
        if self.index.retire_seq() == generation.2 {
            Ok(())
        } else {
            Err(Cancelled::PendingWrite)
        }
    }

    /// `use` import items (`use Foo\Bar;`, `use function ...;`,
    /// `use const ...;`) for `symbol` — [`Self::indexed_references_to`] with
    /// [`crate::ReferenceIncludes::UseImports`].
    pub fn indexed_use_import_locations(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
    ) -> Result<Vec<(Arc<str>, crate::Range)>, Cancelled> {
        self.indexed_references_to(symbol, files, false, crate::ReferenceIncludes::UseImports)
    }

    pub(super) fn reference_query_key(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
        include_declaration: bool,
        includes: crate::ReferenceIncludes,
    ) -> RefQueryCacheKey {
        RefQueryCacheKey {
            symbol: symbol.codebase_key(),
            include_declaration,
            includes,
            generation: self.query_cache_generation(),
            files_hash: hash_files(files),
        }
    }

    /// Cache `out` unless the generation moved while computing it (an edit,
    /// or a defs commit growing the subtype index — possibly this query's
    /// own): such a key can never be looked up again, and the next identical
    /// query recomputes once against settled state and caches then.
    pub(super) fn memoize_references(
        &self,
        key: RefQueryCacheKey,
        out: &[(Arc<str>, crate::Range)],
    ) {
        let generation = self.query_cache_generation();
        if generation == key.generation {
            self.index.ref_queries.insert(generation, key, out);
        }
    }

    /// The candidates in `files` that [`Self::indexed_references_to`] would
    /// analyze and commit: those whose postings are not exact for their
    /// current text. Empty means the owner-side prelude
    /// ([`super::AnalysisSession::prepare_references_query`]) has nothing to
    /// warm, so a host can check this off its lock and skip taking it; when
    /// not empty it passes this list to the prelude, so the O(candidates)
    /// scan never runs under the lock.
    pub fn stale_reference_candidates(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
    ) -> Result<Vec<Arc<str>>, Cancelled> {
        catch(|| self.stale_reference_candidates_unguarded(symbol, files))
    }

    /// Freshness pass: candidates whose postings are not exact for their
    /// current text. Files not registered as `SourceFile` inputs are
    /// skipped. Never-committed files — no commit mark, hence no postings at
    /// all (every mark drop accompanies a posting clear) — are further gated
    /// on their text mentioning the symbol's name: such a file can neither
    /// hold stale postings nor produce new ones, so a cold query on a common
    /// name skips the bulk of the workspace instead of analyzing it. A
    /// LIVE-analyzed file stale only by generation gets the same gate.
    /// Everything else — a genuinely edited file, or a commit seeded by an
    /// unverified disk-cache replay — re-analyzes unconditionally. Same
    /// discipline as [`Self::commit_defs_for_matching`] on the defs index.
    ///
    /// The whole gate answers from the persistent mention index: every
    /// needle is admitted, so a recorded mention set answers with lookups
    /// and only a never-scanned or since-edited file pays one scan against
    /// the whole universe, recorded for every later consumer. A needle new
    /// to the universe epoch-invalidates older recordings for itself only.
    ///
    /// Intentionally serial: each request already runs on its caller
    /// thread, and putting every concurrent request back onto the shared
    /// rayon pool lets an index batch monopolize the workers.
    pub(super) fn stale_reference_candidates_unguarded(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
    ) -> Vec<Arc<str>> {
        let db = &self.db;
        let gate = self.reference_gate(symbol);
        let has_needles = !gate.idents.is_empty() || !gate.raw.is_empty();
        let (mention_queries, mention_scanner) = if has_needles {
            db.add_literal_mention_names(gate.idents.iter().map(|s| s.as_str()));
            db.add_raw_mention_needles(gate.raw.iter().map(|s| s.as_str()));
            let queries: Vec<_> = gate
                .idents
                .iter()
                .chain(gate.raw.iter())
                .filter_map(|s| db.prepare_class_mention_query(s))
                .collect();
            (queries, db.class_mention_scanner())
        } else {
            (Vec::new(), None)
        };
        // Admission guarantees a query per needle and a non-empty universe;
        // anything else is defensive — the gate then admits every candidate
        // (analyze rather than skip, the conservative direction).
        let gate_complete = mention_queries.len() == gate.idents.len() + gate.raw.len()
            && mention_scanner.is_some();
        let current_gen = self.index_generation;
        let mut stale = Vec::new();
        let mut scanned: Vec<MentionScanRecord> = Vec::new();
        for f in files {
            let Some(sf) = db.lookup_source_file(f.as_ref()) else {
                continue;
            };
            let text = sf.text(db as &dyn MirDatabase);
            match self.index.ref_freshness(sf, text, current_gen) {
                RefFreshness::Fresh => continue,
                RefFreshness::Stale => {
                    stale.push(f.clone());
                    continue;
                }
                RefFreshness::StaleByGenerationOnly | RefFreshness::Uncommitted => {}
            }
            if has_needles && gate_complete {
                // Any needle answering `true` admits the file; an
                // unanswerable one forces the single recorded scan, which
                // settles every needle at once.
                let mut answer = Some(false);
                for q in &mention_queries {
                    match db.class_mention_answer(f.as_ref(), q, text) {
                        Some(true) => {
                            answer = Some(true);
                            break;
                        }
                        Some(false) => {}
                        None => answer = None,
                    }
                }
                match answer {
                    Some(true) => {}
                    Some(false) => continue,
                    None => {
                        let scanner = mention_scanner
                            .as_ref()
                            .expect("gate_complete implies a scanner");
                        let names = scanner.scan(text);
                        let hit = mention_queries
                            .iter()
                            .any(|q| names.binary_search(&q.name).is_ok());
                        scanned.push((f.clone(), text.clone(), names));
                        if hit {
                            stale.push(f.clone());
                        }
                        continue;
                    }
                }
            }
            stale.push(f.clone());
        }
        // Recorded regardless of how the query proceeds: each is a complete,
        // current mention set for its file.
        if let Some(scanner) = &mention_scanner {
            for (file, text, names) in scanned {
                db.set_file_class_mentions(&file, &text, scanner.epoch(), names);
            }
        }
        stale
    }

    /// Analyze `stale` and commit their postings and class edges.
    pub(super) fn commit_reference_candidates(&self, stale: &[Arc<str>]) -> Result<(), Cancelled> {
        self.warm_pass(stale, &crate::IndexCancel::new()).map(drop)
    }

    /// Analyze `files` and commit their reference postings, class edges and
    /// mention scans to the index shared with the owner, so later queries
    /// find them fresh. `Ok(false)` when `cancel` stopped the pass first.
    ///
    /// A commit with unresolved names stays tied to this snapshot's
    /// [`Self::index_generation`], so the next workspace change re-opens it.
    pub fn warm_files(
        &self,
        files: &[Arc<str>],
        cancel: &crate::IndexCancel,
    ) -> Result<bool, Cancelled> {
        Ok(self.warm_pass(files, cancel)?.is_some())
    }

    /// The read half of [`super::AnalysisSession::reanalyze_files_cancellable`]:
    /// analyze `files`, commit their reference postings and class edges, and
    /// return each file's diagnostics (`symbols` are empty). Files without
    /// registered text are absent. `Ok(None)` when `cancel` stopped the pass
    /// first, with nothing committed.
    ///
    /// Run the owner-side prelude first: `prepare_for_query(None)`, then
    /// `prepare_file_for_analysis` per file, a map lookup for files ingested
    /// with `ingest_file_prepared`.
    #[allow(clippy::type_complexity)]
    pub fn reanalyze_files(
        &self,
        files: &[Arc<str>],
        cancel: &crate::IndexCancel,
    ) -> Result<Option<Vec<(Arc<str>, crate::FileAnalysis)>>, Cancelled> {
        Ok(self.warm_pass(files, cancel)?.map(|analyzed| {
            analyzed
                .into_iter()
                .map(|a| {
                    (
                        a.file,
                        crate::FileAnalysis {
                            issues: a.out.issues.to_vec(),
                            symbols: Vec::new(),
                        },
                    )
                })
                .collect()
        }))
    }

    pub(super) fn warm_pass(
        &self,
        files: &[Arc<str>],
        cancel: &crate::IndexCancel,
    ) -> Result<Option<Vec<AnalyzedFile>>, Cancelled> {
        let Some(mut pass) = self.stage_warm(files, cancel)? else {
            return Ok(None);
        };
        self.commit_warm(&mut pass)?;
        Ok(Some(pass.analyzed))
    }

    /// Freezes the workspace index on a pass-scoped clone (borrow-only
    /// symbol lookups + pass-shared subtype cache). On-demand loads leave the
    /// index untouched and an owner write cancels the pass, so the frozen
    /// view can't go stale. Same discipline as the batch body pass.
    fn stage_warm(
        &self,
        files: &[Arc<str>],
        cancel: &crate::IndexCancel,
    ) -> Result<Option<WarmPass>, Cancelled> {
        catch(|| {
            let mut db = self.db.clone();
            db.freeze_workspace_index();
            let mention_scanner = db.class_mention_scanner();
            let cache = self.cache.as_deref();
            let mut analyzed = Vec::with_capacity(files.len());
            for path in files {
                if cancel.is_cancelled() {
                    return None;
                }
                analyzed.extend(self.index.stage_analyzed(
                    &db,
                    cache,
                    mention_scanner.as_deref(),
                    path,
                ));
            }
            Some(WarmPass {
                mention_scanner,
                analyzed,
            })
        })
    }

    /// Marks record the exact text Arc each file was analyzed against, so an
    /// owner text write racing the pass leaves the file stale, never fresh.
    fn commit_warm(&self, pass: &mut WarmPass) -> Result<(), Cancelled> {
        self.index.commit_analyzed(
            &self.db,
            self.cache.as_deref(),
            pass.mention_scanner.as_deref(),
            &mut pass.analyzed,
            self.stamp(),
        )
    }

    /// Posting lookup for `symbol`, filtered to the candidate scope.
    ///
    /// Member symbols resolve against the queried class plus its hierarchy
    /// (mir records member refs under the *declaring* class, so a query on
    /// an interface method must include implementor keys and vice versa).
    /// Name-only fallback postings — receivers whose type couldn't be
    /// resolved — are consulted only when the typed keys produce nothing:
    /// exact results when resolution succeeds, by-name matches when nothing
    /// resolves. `__construct` stays exact: `new Sub()` invokes
    /// `Sub::__construct` even when only a parent declares one, so hierarchy
    /// fan-out would wrongly return subtype instantiation sites for a parent
    /// query.
    pub(super) fn read_references(
        &self,
        symbol: &crate::Name,
        files: &[Arc<str>],
        include_declaration: bool,
        includes: crate::ReferenceIncludes,
    ) -> Vec<(Arc<str>, crate::Range)> {
        let key = symbol.codebase_key();
        let hierarchy: Vec<String> = match symbol {
            crate::Name::Method { class, name } => {
                if class.is_empty() {
                    Vec::new()
                } else if name.as_ref() == "__construct" {
                    vec![class.trim_start_matches('\\').to_string()]
                } else {
                    self.member_hierarchy_classes(class.as_ref())
                }
            }
            crate::Name::Property { class, .. } | crate::Name::ClassConstant { class, .. } => {
                if class.is_empty() {
                    Vec::new()
                } else {
                    self.member_hierarchy_classes(class.as_ref())
                }
            }
            _ => Vec::new(),
        };
        let scope: HashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
        let read_symbol_key = |symbol_key: &str| -> Vec<(Arc<str>, crate::Range)> {
            self.db
                .reference_locations(symbol_key)
                .into_iter()
                .filter(|(file, ..)| scope.contains(file.as_ref()))
                .map(|(file, line, col_start, col_end)| {
                    (file, span_range(line, col_start as u32, col_end as u32))
                })
                .collect()
        };
        let mut scratch_key = String::new();
        let mut read_composed_key = |prefix: &str, middle: &str, separator: &str, suffix: &str| {
            scratch_key.clear();
            scratch_key.reserve(prefix.len() + middle.len() + separator.len() + suffix.len());
            scratch_key.push_str(prefix);
            scratch_key.push_str(middle);
            scratch_key.push_str(separator);
            scratch_key.push_str(suffix);
            read_symbol_key(&scratch_key)
        };
        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
        if !matches!(includes, crate::ReferenceIncludes::UseImports) {
            let member_prefix = match symbol {
                crate::Name::Method { name, .. } => Some(("meth:", name)),
                crate::Name::Property { name, .. } => Some(("prop:", name)),
                crate::Name::ClassConstant { name, .. } => Some(("cnst:", name)),
                _ => None,
            };
            match member_prefix {
                Some((prefix, name)) => {
                    for class in &hierarchy {
                        out.extend(read_composed_key(prefix, class, "::", name));
                    }
                }
                None => out.extend(read_symbol_key(key.as_str())),
            }
        }
        if !matches!(includes, crate::ReferenceIncludes::Plain) {
            out.extend(read_composed_key("use:", key.as_str(), "", ""));
        }
        if matches!(includes, crate::ReferenceIncludes::Plain) && out.is_empty() {
            match symbol {
                crate::Name::Method { name, .. } => {
                    out = read_composed_key("methname:", name.as_ref(), "", "");
                }
                crate::Name::Property { name, .. } => {
                    out = read_composed_key("propname:", name.as_ref(), "", "");
                }
                _ => {}
            }
        }
        out.sort_by(|a, b| {
            a.0.cmp(&b.0)
                .then(a.1.start.line.cmp(&b.1.start.line))
                .then(a.1.start.column.cmp(&b.1.start.column))
        });
        out.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);

        if include_declaration {
            let decls: Vec<(Arc<str>, crate::Range)> = match symbol {
                crate::Name::Method { class, name }
                | crate::Name::Property { class, name }
                | crate::Name::ClassConstant { class, name } => {
                    if class.is_empty() {
                        // Unknown owner: declarations by name, recorded as
                        // `methdecl:`/`propdecl:`/`cnstdecl:` postings during
                        // class/trait/interface/enum analysis.
                        let prefix = match symbol {
                            crate::Name::Method { .. } => "methdecl:",
                            crate::Name::Property { .. } => "propdecl:",
                            _ => "cnstdecl:",
                        };
                        read_composed_key(prefix, name.as_ref(), "", "")
                    } else {
                        self.member_decl_sites(&hierarchy, symbol)
                    }
                }
                _ => self.declaration_name_range(symbol).into_iter().collect(),
            };
            for (file, range) in decls {
                if scope.contains(file.as_ref())
                    && !out.iter().any(|(f, r)| *f == file && *r == range)
                {
                    out.push((file, range));
                }
            }
        }
        out
    }

    /// The queried class plus every class its members' references could be
    /// keyed under: resolved ancestors (a call on a subtype instance records
    /// the declaring ancestor) and transitive subtypes including trait users
    /// (a call on a subtype that overrides records the subtype). Display-form
    /// FQCNs, deduplicated case-insensitively.
    fn member_hierarchy_classes(&self, class_fqn: &str) -> Vec<String> {
        let target = class_fqn.trim_start_matches('\\');
        let mut out = vec![target.to_string()];
        let db = &self.db;
        let here = crate::db::Fqcn::from_str(db, target);
        // Ancestors include the class itself first.
        let ancestors = crate::db::class_ancestors_by_fqcn(db, here)
            .iter()
            .skip(1)
            .map(|a| a.trim_start_matches('\\').to_string())
            .collect::<Vec<_>>();
        out.extend(ancestors);
        out.extend(
            db.subtype_sites_of(target, true)
                .into_iter()
                .map(|s| s.fqcn.trim_start_matches('\\').to_string()),
        );
        let mut seen: HashSet<String> = HashSet::default();
        out.retain(|c| seen.insert(c.to_ascii_lowercase()));
        out
    }

    /// Own-member declaration sites for `symbol` across `classes`: each class
    /// that itself declares the member (not inherited) contributes its name
    /// token. Kind-specific lookups — a class often declares a property and a
    /// method with the same short name, and `member_location` can't tell them
    /// apart.
    fn member_decl_sites(
        &self,
        classes: &[String],
        symbol: &crate::Name,
    ) -> Vec<(Arc<str>, crate::Range)> {
        let mut out: Vec<(Arc<str>, crate::Range)> = Vec::new();
        let db = &self.db;
        for class in classes {
            let here = crate::db::Fqcn::from_str(db, class);
            let (loc, needle) = match symbol {
                crate::Name::Method { name, .. } => {
                    let Some(m) = crate::db::find_method_in_class(db, here, name) else {
                        continue;
                    };
                    (m.location.clone(), name.to_string())
                }
                crate::Name::Property { name, .. } => {
                    let Some(p) = crate::db::find_property_in_class(db, here, name) else {
                        continue;
                    };
                    (p.location.clone(), name.to_string())
                }
                crate::Name::ClassConstant { name, .. } => {
                    let Some(c) = crate::db::find_class_constant_in_class(db, here, name) else {
                        continue;
                    };
                    (c.location.clone(), name.to_string())
                }
                _ => continue,
            };
            let Some(loc) = loc else { continue };
            let range = self.refine_location_to_name(&loc, &needle);
            out.push((loc.file.clone(), range));
        }
        out
    }

    /// The symbol's declaration site among already-loaded state, narrowed
    /// from the collector's whole-declaration span to the declared name's
    /// own token (matching the span shape of recorded references).
    pub(super) fn declaration_name_range(
        &self,
        symbol: &crate::Name,
    ) -> Option<(Arc<str>, crate::Range)> {
        if let crate::Name::GlobalConstant(fqn) = symbol {
            return self.global_constant_decl_range(fqn);
        }
        let loc = self.definition_of_unguarded(symbol).ok()?;
        let short = match symbol {
            crate::Name::Class(f) | crate::Name::Function(f) | crate::Name::GlobalConstant(f) => {
                crate::db::subtype_index::short_name_of(f)
            }
            crate::Name::Method { name, .. }
            | crate::Name::Property { name, .. }
            | crate::Name::ClassConstant { name, .. } => name.as_ref(),
        };
        // Property declarations carry a `$` sigil in source, but reference
        // ranges cover the bare name; the word-boundary search below lands on
        // the name right after the sigil.
        let range = self.refine_location_to_name(&loc, short);
        Some((loc.file.clone(), range))
    }

    /// Narrow a whole-declaration [`mir_types::Location`] to the first
    /// word-boundary occurrence of `needle` inside its line span. Falls back
    /// to the location's own coordinates when the text is unavailable or the
    /// name doesn't appear (e.g. stub-only declarations).
    fn refine_location_to_name(&self, loc: &mir_types::Location, needle: &str) -> crate::Range {
        let fallback = span_range(loc.line, loc.col_start as u32, loc.col_end as u32);
        let Some(text) = self
            .db
            .lookup_source_file(loc.file.as_ref())
            .map(|sf| sf.text(&self.db as &dyn MirDatabase).clone())
        else {
            return fallback;
        };
        let needle_chars = needle.chars().count() as u32;
        let first_line = loc.line.saturating_sub(1) as usize;
        // Exact-case first: PHP property/constant names are case-sensitive
        // and an early case-insensitive hit can land on an unrelated token
        // (a type hint sharing the name). Case-insensitive second, for
        // method/class needles that arrive lowercase-normalized.
        for case_insensitive in [false, true] {
            for (idx, line_text) in text.lines().enumerate().skip(first_line) {
                let line_no = idx as u32 + 1;
                if line_no > loc.line_end {
                    break;
                }
                let min_col = if line_no == loc.line {
                    loc.col_start as usize
                } else {
                    0
                };
                if let Some(col) = identifier_char_col(line_text, needle, min_col, case_insensitive)
                {
                    return span_range(line_no, col, col + needle_chars);
                }
            }
        }
        fallback
    }

    /// Declaring line of a global constant. Constant slices carry no stored
    /// location, so this finds the declaring file via the workspace constants
    /// index and locates the `const NAME` / `define('NAME'` line textually.
    fn global_constant_decl_site(&self, fqn: &str) -> Option<ConstantDeclSite> {
        let short = crate::db::subtype_index::short_name_of(fqn);
        let db = &self.db;
        let index = crate::db::workspace_index(db);
        let loc = index.constant_loc(mir_types::Name::from(fqn.trim_start_matches('\\')))?;
        let file = loc.file().path(db).clone();
        let sf = db.lookup_source_file(file.as_ref())?;
        let text = sf.text(db as &dyn MirDatabase);
        for (idx, line) in text.lines().enumerate() {
            let trimmed = line.trim_start();
            let is_decl_line = trimmed.starts_with("const ")
                || trimmed.contains("define(")
                || trimmed.contains("define (");
            if !is_decl_line {
                continue;
            }
            if let Some(name_col) = identifier_char_col(line, short, 0, false) {
                let stmt_end = match line.find(';') {
                    Some(byte) => line[..=byte].chars().count(),
                    None => line.chars().count(),
                };
                return Some(ConstantDeclSite {
                    file,
                    line: idx as u32 + 1,
                    stmt_col: (line.chars().count() - trimmed.chars().count()) as u32,
                    stmt_end: stmt_end as u32,
                    name_col,
                    name_len: short.chars().count() as u32,
                });
            }
        }
        None
    }

    fn global_constant_decl_range(&self, fqn: &str) -> Option<(Arc<str>, crate::Range)> {
        let site = self.global_constant_decl_site(fqn)?;
        let range = span_range(site.line, site.name_col, site.name_col + site.name_len);
        Some((site.file, range))
    }

    /// Whole-statement location of a user global constant's declaration.
    fn global_constant_location(&self, fqn: &str) -> Option<mir_types::Location> {
        let site = self.global_constant_decl_site(fqn)?;
        Some(mir_types::Location {
            file: site.file,
            line: site.line,
            line_end: site.line,
            col_start: site.stmt_col as u16,
            col_end: site.stmt_end as u16,
        })
    }

    /// Files declaring transitive subclasses of `class_fqn` anywhere in the
    /// workspace, excluding `class_fqn`'s own declaring file — the caller
    /// adds it. Subclasses are matched by resolved FQCN, so `extends \Ns\Base`
    /// and aliased `use` forms are all found.
    pub fn subtype_files(&self, class_fqn: &str) -> Result<Vec<Arc<str>>, Cancelled> {
        let files = self.db.source_file_paths();
        let mut out: Vec<Arc<str>> = self
            .indexed_subtype_classes(class_fqn, &files, false)?
            .into_iter()
            .map(|s| s.file)
            .collect();
        out.sort();
        out.dedup();
        Ok(out)
    }

    /// Transitive subtypes of `class_fqn` (classes/interfaces/enums whose
    /// resolved ancestor chain reaches it), answered from the maintained
    /// subtype edge index.
    ///
    /// `files` is the host's candidate scope for the on-demand completeness
    /// pass: per BFS round, not-yet-committed files whose text mentions a
    /// frontier short name get their definitions committed, so results are
    /// complete even before a background sweep has covered the workspace.
    /// That short-name gate is only candidate discovery; subtype identity is
    /// resolved from the edge index by exact canonical FQCN. Committed files
    /// answer from the index with no parsing at all.
    ///
    /// `include_trait_users` also counts `use Trait;` composition as a
    /// subtype edge (visibility-scoping semantics); leave it off for
    /// goto-implementation semantics (extends/implements only).
    ///
    /// Memoized per `(class_fqn, include_trait_users, files, query
    /// generation)`, same rationale as [`Self::indexed_references_to`].
    pub fn indexed_subtype_classes(
        &self,
        class_fqn: &str,
        files: &[Arc<str>],
        include_trait_users: bool,
    ) -> Result<Vec<SubtypeClassSite>, Cancelled> {
        catch(|| {
            let key = SubtypeQueryCacheKey {
                class_fqn: class_fqn.trim_start_matches('\\').to_ascii_lowercase(),
                include_trait_users,
                generation: self.query_cache_generation(),
                files_hash: hash_files(files),
            };
            if let Some(hit) = self.index.subtype_queries.get(&key) {
                return hit;
            }
            let out = self.subtype_classes_uncached(class_fqn, files, include_trait_users);
            if let Err(cancelled) = self.ensure_no_retire_since(key.generation) {
                unwind(cancelled);
            }
            // See `memoize_references` for why a moved generation skips.
            let generation = self.query_cache_generation();
            if generation == key.generation {
                self.index.subtype_queries.insert(generation, key, &out);
            }
            out
        })
    }

    fn subtype_classes_uncached(
        &self,
        class_fqn: &str,
        files: &[Arc<str>],
        include_trait_users: bool,
    ) -> Vec<SubtypeClassSite> {
        let db = &self.db;
        let mut scanned: HashSet<String> = HashSet::default();
        let mut pending: Vec<String> = vec![class_fqn.trim_start_matches('\\').to_string()];
        let mut sites: Vec<crate::db::SubtypeSite> = Vec::new();
        while !pending.is_empty() {
            // Short names only discover stale/uncommitted files worth
            // collecting; the result itself comes from the edge index.
            let needles: Vec<String> = pending
                .drain(..)
                .filter(|f| scanned.insert(f.clone()))
                .map(|f| crate::db::subtype_index::short_name_of(&f).to_string())
                .collect();
            if !needles.is_empty() {
                self.commit_defs_for_matching(files, &needles);
            }
            sites = db.subtype_sites_of(class_fqn, include_trait_users);
            pending = sites
                .iter()
                .map(|s| s.fqcn.trim_start_matches('\\').to_string())
                .filter(|f| !scanned.contains(f))
                .collect();
        }
        let mut out: Vec<SubtypeClassSite> = sites
            .into_iter()
            .filter_map(|s| {
                let loc = s.location.as_ref()?;
                let short = crate::db::subtype_index::short_name_of(&s.fqcn).to_string();
                let range = self.refine_location_to_name(loc, &short);
                Some(SubtypeClassSite {
                    fqcn: s.fqcn,
                    kind: s.kind,
                    is_abstract: s.is_abstract,
                    file: s.file,
                    range,
                })
            })
            .collect();
        // Anonymous classes never reach the definition collector; their
        // `new class implements X {}` sites are recorded under the resolved
        // canonical parent FQCN during body analysis.
        let root_lc = class_fqn.trim_start_matches('\\').to_ascii_lowercase();
        let scope: HashSet<&str> = files.iter().map(|f| f.as_ref()).collect();
        for (file, line, cs, ce) in db.reference_locations(&format!("impl:{root_lc}")) {
            if !scope.contains(file.as_ref()) {
                continue;
            }
            let range = span_range(line, cs as u32, ce as u32);
            if out.iter().any(|s| s.file == file && s.range == range) {
                continue;
            }
            out.push(SubtypeClassSite {
                fqcn: Arc::from("class@anonymous"),
                kind: crate::db::ClassLikeKind::Class,
                is_abstract: false,
                file,
                range,
            });
        }
        out
    }

    /// Concrete implementations of `class_fqn::method` across its transitive
    /// subtypes: the same-named non-abstract method available to each subtype
    /// (its own declaration, or one inherited/composed from a parent, trait,
    /// or mixin), as `(subtype fqcn, file, name range)`. Subtypes resolving to
    /// the same declaring location collapse to a single entry.
    #[allow(clippy::type_complexity)]
    pub fn indexed_method_implementations(
        &self,
        class_fqn: &str,
        method: &str,
        files: &[Arc<str>],
    ) -> Result<Vec<(Arc<str>, Arc<str>, crate::Range)>, Cancelled> {
        let subs = self.indexed_subtype_classes(class_fqn, files, false)?;
        catch(|| {
            let db = &self.db;
            let mut out: Vec<(Arc<str>, Arc<str>, crate::Range)> = Vec::new();
            for sub in &subs {
                let here = crate::db::Fqcn::from_str(db, sub.fqcn.as_ref());
                let Some((_, m)) = crate::db::find_method_in_chain(db, here, method) else {
                    continue;
                };
                if m.is_abstract {
                    continue;
                }
                let Some(loc) = m.location.as_ref() else {
                    continue;
                };
                let range = self.refine_location_to_name(loc, method);
                out.push((sub.fqcn.clone(), loc.file.clone(), range));
            }
            out.sort_by(|a, b| a.1.cmp(&b.1).then(a.2.start.line.cmp(&b.2.start.line)));
            out.dedup_by(|a, b| a.1 == b.1 && a.2 == b.2);
            out
        })
    }

    /// Commit definitions (class edges + freshness) for every file in `files`
    /// that is stale (committed against older text) or that has never been
    /// committed and mentions one of `shorts` as a whole identifier.
    ///
    /// The textual gate answers from the shared per-file mention cache — the
    /// same one [`Self::indexed_references_to`]'s gate populates — so a file
    /// scanned by either consumer answers the other with a set lookup. A file
    /// the cache can't answer for is scanned once against the whole name
    /// universe and recorded.
    ///
    /// Unwinds with [`Cancelled`] when a file was retired after this
    /// snapshot, once every other file is committed.
    fn commit_defs_for_matching(&self, files: &[Arc<str>], shorts: &[String]) {
        use rayon::prelude::*;

        // Admit the frontier names before preparing, so every needle gets a
        // real query (a declared class's short name is already in the
        // universe from indexing — admission then changes nothing).
        self.db
            .add_literal_mention_names(shorts.iter().map(|s| s.as_str()));
        let queries: Vec<_> = shorts
            .iter()
            .filter_map(|s| self.db.prepare_class_mention_query(s))
            .collect();
        let mention_scanner = self.db.class_mention_scanner();
        // Admission guarantees a query per needle and a non-empty universe;
        // anything else is defensive — the gate then admits every candidate
        // (recommit rather than skip, the conservative direction).
        let use_mentions = queries.len() == shorts.len() && mention_scanner.is_some();
        type Work = (Arc<str>, Arc<str>, Vec<crate::db::SubtypeEntry>);
        let index = &*self.index;
        let results: Vec<(Option<Work>, Option<MentionScanRecord>)> = files
            .par_iter()
            .map_with(self.db.clone(), |db, path| {
                let Some(sf) = db.lookup_source_file(path.as_ref()) else {
                    return (None, None);
                };
                let text = sf.text(&*db as &dyn MirDatabase).clone();
                let freshness = index.defs_freshness(sf, &text);
                if freshness == DefsFreshness::Fresh {
                    return (None, None);
                }
                // Never-committed files must mention a frontier name; stale
                // (previously committed) files recommit unconditionally —
                // their classes may have re-parented.
                let mut scan_rec: Option<MentionScanRecord> = None;
                if use_mentions && freshness == DefsFreshness::Uncommitted {
                    let mut answer = Some(false);
                    for q in &queries {
                        match db.class_mention_answer(path.as_ref(), q, &text) {
                            Some(true) => {
                                answer = Some(true);
                                break;
                            }
                            Some(false) => {}
                            None => answer = None,
                        }
                    }
                    let hit = match answer {
                        Some(hit) => hit,
                        None => {
                            // Uncoverable entry: one scan answers every
                            // query and is recorded below.
                            let scanner = mention_scanner.as_ref().unwrap();
                            let names = scanner.scan(&text);
                            let hit = queries.iter().any(|q| names.binary_search(&q.name).is_ok());
                            scan_rec = Some((path.clone(), text.clone(), names));
                            hit
                        }
                    };
                    if !hit {
                        return (None, scan_rec);
                    }
                }
                let defs = crate::db::collect_file_definitions(&*db as &dyn MirDatabase, sf);
                let entries = crate::db::subtype_index::entries_from_slice(&defs.slice);
                (Some((path.clone(), text, entries)), scan_rec)
            })
            .collect();
        // Record the fallback scans regardless of hit/miss: each is a
        // complete, current mention set for its file, so the next round's
        // (and the references gate's) checks become set lookups.
        let mut refused = Ok(());
        for (work, scan_rec) in results {
            if let (Some(scanner), Some((file, text, names))) = (&mention_scanner, scan_rec) {
                self.db
                    .set_file_class_mentions(&file, &text, scanner.epoch(), names);
            }
            if let Some((file, text, entries)) = work {
                if let Err(cancelled) = self.index.commit_class_edges(
                    &self.db,
                    &file,
                    &text,
                    entries,
                    self.retire_epoch,
                ) {
                    refused = Err(cancelled);
                }
            }
        }
        if let Err(cancelled) = refused {
            unwind(cancelled);
        }
    }

    /// Class-level issues (inheritance violations, abstract-method gaps,
    /// override incompatibilities) for `files`.
    ///
    /// These checks are cross-file by nature and are not emitted by
    /// [`Self::analyze`]. Circular-inheritance checks always run against the
    /// full workspace graph regardless of the `files` filter — a cycle is a
    /// workspace-wide problem.
    pub fn class_issues(&self, files: &[Arc<str>]) -> Result<Vec<crate::Issue>, Cancelled> {
        catch(|| {
            let db = &self.db;
            let file_set: HashSet<Arc<str>> = files.iter().cloned().collect();
            let file_data: Vec<(Arc<str>, Arc<str>)> = files
                .iter()
                .filter_map(|f| {
                    let sf = db.lookup_source_file(f)?;
                    Some((f.clone(), sf.text(db as &dyn MirDatabase).clone()))
                })
                .collect();
            crate::class::ClassAnalyzer::with_files(db, file_set, &file_data).analyze_all()
        })
    }

    /// Collector-phase issues (e.g. `BackedEnumCaseTypeMismatch`,
    /// `InvalidReadonlyPropertyDeclaration`, `InvalidDocblock`, and raw parse
    /// errors) for `files`.
    ///
    /// These are found while building a file's declaration slice, before body
    /// analysis or cross-file class checks run — neither [`Self::analyze`]
    /// nor [`Self::class_issues`] reports them, so a caller merging just those
    /// two sources silently drops every collector-time diagnostic.
    pub fn collector_issues(&self, files: &[Arc<str>]) -> Result<Vec<crate::Issue>, Cancelled> {
        catch(|| {
            files
                .iter()
                .filter_map(|f| self.db.lookup_source_file(f))
                .flat_map(|sf| {
                    crate::db::collect_file_definitions(&self.db, sf)
                        .issues
                        .as_ref()
                        .clone()
                })
                .collect()
        })
    }

    /// Admission predicate for [`Self::stale_reference_candidates_unguarded`]; see
    /// [`ReferenceGate`] and `reference_gate_needles`.
    ///
    /// Instance/static methods other than `__construct`/`__invoke` on a
    /// resolvable owner gate on the member name alone: every call site
    /// spells it (`->name(`, `::name(`), while the owner's short name would
    /// admit every file mentioning the class for any reason.
    /// `__construct` gates on the owner's short name plus the raw call tokens
    /// `->__construct` / `::__construct`. `__invoke` keeps the general
    /// owner/name gate because `$obj()` call sites do not spell `__invoke`.
    pub(super) fn reference_gate(&self, symbol: &crate::Name) -> ReferenceGate {
        ReferenceGate::for_symbol(&self.db, symbol)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AnalysisSession, IndexCancel, Name, ReferenceIncludes};
    use salsa::Database as _;

    const BASE: &str =
        "<?php\nclass Base { public function run(): void {} public function stop(): void {} }\n";
    const CALLS_RUN: &str = "<?php\nfunction go(Base $b): void { $b->run(); }\n";
    const CALLS_STOP: &str = "<?php\nfunction go(Base $b): void { $b->stop(); }\n";

    /// Pins the warm pass's commit landing after an owner text write has
    /// started but before it applies: the commit must not leave the file
    /// fresh for the incoming text.
    #[test]
    fn warm_commit_racing_a_text_write_leaves_the_file_stale() {
        let (mut session, files) = prepared_workspace(CALLS_RUN);
        let snap = session.snapshot();
        let mut pass = snap
            .stage_warm(&files[1..], &IndexCancel::new())
            .unwrap()
            .unwrap();

        let caller = files[1].clone();
        let writer = std::thread::spawn(move || {
            session.upsert_source_file(caller, Arc::from(CALLS_STOP), salsa::Durability::LOW);
            session
        });
        await_pending_write(&snap);
        snap.commit_warm(&mut pass).unwrap();
        drop(snap);
        let mut session = writer.join().unwrap();

        assert_eq!(callers_of(&mut session, &files, "stop"), [files[1].clone()]);
        assert!(callers_of(&mut session, &files, "run").is_empty());
    }

    #[test]
    fn warm_commit_after_an_ingest_retired_the_file_is_refused() {
        let (session, files) = prepared_workspace(CALLS_RUN);
        let snap = session.snapshot();
        let mut pass = snap
            .stage_warm(&files[1..], &IndexCancel::new())
            .unwrap()
            .unwrap();

        let caller = files[1].clone();
        let writer = std::thread::spawn(move || {
            let mut session = session;
            session.ingest_file(caller, Arc::from(CALLS_STOP));
            session
        });
        await_pending_write(&snap);
        assert!(snap.commit_warm(&mut pass).is_err());
        drop(snap);
        let mut session = writer.join().unwrap();

        assert!(callers_of(&mut session, &files, "run").is_empty());
        assert_eq!(callers_of(&mut session, &files, "stop"), [files[1].clone()]);
    }

    #[test]
    fn commits_after_invalidate_file_retired_the_file_are_refused() {
        const CHILD_CALLS_RUN: &str =
            "<?php\nclass Child extends Base {}\nfunction go(Base $b): void { $b->run(); }\n";
        let (session, files) = prepared_workspace(CHILD_CALLS_RUN);
        let snap = session.snapshot();
        let mut pass = snap
            .stage_warm(&files[1..], &IndexCancel::new())
            .unwrap()
            .unwrap();
        let parsed = php_rs_parser::parse(CHILD_CALLS_RUN);

        let caller = files[1].clone();
        let writer = std::thread::spawn(move || {
            let mut session = session;
            session.invalidate_file(&caller);
            session
        });
        await_pending_write(&snap);
        assert!(snap.commit_warm(&mut pass).is_err());
        assert!(snap
            .analyze(
                files[1].clone(),
                CHILD_CALLS_RUN,
                &parsed.program,
                &parsed.source_map
            )
            .is_err());
        drop(snap);
        let mut session = writer.join().unwrap();

        assert!(callers_of(&mut session, &files, "run").is_empty());
        assert!(session
            .indexed_subtype_classes("Base", &files, false)
            .is_empty());
    }

    #[test]
    fn cancelled_reference_commit_reports_cancellation() {
        let (mut session, files) = prepared_workspace(CALLS_RUN);
        let snap = session.snapshot();
        let stale = snap.stale_reference_candidates_unguarded(&Name::method("Base", "run"), &files);
        assert!(stale.contains(&files[1]));

        let caller = files[1].clone();
        let writer = std::thread::spawn(move || {
            session.upsert_source_file(caller, Arc::from(CALLS_STOP), salsa::Durability::LOW);
            session
        });
        await_pending_write(&snap);
        assert!(snap.commit_reference_candidates(&stale).is_err());
        drop(snap);
        writer.join().unwrap();
    }

    /// Top-level code only: ingesting it defines no symbols, so the ingest
    /// itself writes nothing to salsa.
    const ROUTES_CALLS_RUN: &str = "<?php\n(new Base())->run();\n";

    /// A workspace whose `routes.php` is registered and committed by a
    /// references query but was never passed through `ingest_file` — the
    /// state of a file an editor opens after the initial scan.
    fn registered_routes_workspace() -> (AnalysisSession, Vec<Arc<str>>) {
        let mut session = AnalysisSession::new(PhpVersion::LATEST);
        let files: Vec<Arc<str>> = vec![Arc::from("base.php"), Arc::from("routes.php")];
        session.ingest_file(files[0].clone(), Arc::from(BASE));
        session.upsert_source_file(
            files[1].clone(),
            Arc::from(ROUTES_CALLS_RUN),
            salsa::Durability::LOW,
        );
        session.prepare_for_query(None);
        assert_eq!(callers_of(&mut session, &files, "run"), [files[1].clone()]);
        (session, files)
    }

    /// Opening the file lands between a query's freshness pass and its
    /// posting read. Nothing cancels the query, so it must still see the
    /// file's postings — and must not memoize a result without them.
    #[test]
    fn ingest_of_unchanged_text_mid_query_keeps_references() {
        let (mut session, files) = registered_routes_workspace();
        let symbol = Name::method("Base", "run");
        let revision = session.text_revision();

        let snap = session.snapshot();
        let key = snap.reference_query_key(&symbol, &files, false, ReferenceIncludes::Plain);
        assert!(snap
            .stale_reference_candidates_unguarded(&symbol, &files)
            .is_empty());
        session.ingest_file(files[1].clone(), Arc::from(ROUTES_CALLS_RUN));
        let out = snap.read_references(&symbol, &files, false, ReferenceIncludes::Plain);
        assert!(snap.ensure_no_retire_since(key.generation).is_ok());
        snap.memoize_references(key, &out);
        drop(snap);

        assert_eq!(session.text_revision(), revision, "ingest wrote salsa");
        assert_eq!(
            out.into_iter().map(|(file, _)| file).collect::<Vec<_>>(),
            [files[1].clone()]
        );
        assert_eq!(callers_of(&mut session, &files, "run"), [files[1].clone()]);
    }

    /// Any retire without a salsa write (e.g. `re_analyze_file` on unchanged
    /// text, between its clear and re-record) must cancel a query that read
    /// the cleared postings and keep its result out of the memo.
    #[test]
    fn query_spanning_a_retirement_is_cancelled_and_not_memoized() {
        let (mut session, files) = registered_routes_workspace();
        let symbol = Name::method("Base", "run");

        let snap = session.snapshot();
        let key = snap.reference_query_key(&symbol, &files, false, ReferenceIncludes::Plain);
        assert!(snap
            .stale_reference_candidates_unguarded(&symbol, &files)
            .is_empty());
        session
            .index
            .retire_references(&session.db.salsa, files[1].as_ref());
        let out = snap.read_references(&symbol, &files, false, ReferenceIncludes::Plain);
        assert!(out.is_empty());
        assert!(snap.ensure_no_retire_since(key.generation).is_err());
        snap.memoize_references(key, &out);
        drop(snap);

        let hits = session.ref_query_cache_hits();
        assert_eq!(callers_of(&mut session, &files, "run"), [files[1].clone()]);
        assert_eq!(session.ref_query_cache_hits(), hits);
    }

    /// The cache-hit fast path replaces postings without a salsa write, so
    /// it must retire like the analysis path: a query spanning it cancels.
    #[test]
    fn re_analyze_file_cache_hit_cancels_spanning_queries() {
        let dir = tempfile::tempdir().unwrap();
        let mut session = AnalysisSession::new(PhpVersion::LATEST).with_cache_dir(dir.path());
        let files: Vec<Arc<str>> = vec![Arc::from("base.php"), Arc::from("caller.php")];
        let opts = crate::BatchOptions::new();
        session.ingest_file(files[0].clone(), Arc::from(BASE));
        session.re_analyze_file(&files[1], CALLS_RUN, &opts);
        session.prepare_for_query(None);
        assert_eq!(callers_of(&mut session, &files, "run"), [files[1].clone()]);

        let symbol = Name::method("Base", "run");
        let snap = session.snapshot();
        let key = snap.reference_query_key(&symbol, &files, false, ReferenceIncludes::Plain);
        let revision = session.text_revision();
        session.re_analyze_file(&files[1], CALLS_RUN, &opts);
        assert_eq!(session.text_revision(), revision, "took the analysis path");
        assert!(snap.ensure_no_retire_since(key.generation).is_err());
        drop(snap);

        assert_eq!(callers_of(&mut session, &files, "run"), [files[1].clone()]);
    }

    fn prepared_workspace(caller_text: &str) -> (AnalysisSession, Vec<Arc<str>>) {
        let mut session = AnalysisSession::new(PhpVersion::LATEST);
        let files: Vec<Arc<str>> = vec![Arc::from("base.php"), Arc::from("caller.php")];
        session.ingest_file(files[0].clone(), Arc::from(BASE));
        session.ingest_file(files[1].clone(), Arc::from(caller_text));
        session.prepare_for_query(Some(&files[1]));
        (session, files)
    }

    /// Spins until an owner write has tripped cancellation; the writer then
    /// waits for `snap` to drop before applying.
    fn await_pending_write(snap: &AnalysisSnapshot) {
        while catch(|| snap.db.unwind_if_revision_cancelled()).is_ok() {
            std::thread::yield_now();
        }
    }

    fn callers_of(
        session: &mut AnalysisSession,
        files: &[Arc<str>],
        method: &str,
    ) -> Vec<Arc<str>> {
        session
            .indexed_references_to(
                &Name::method("Base", method),
                files,
                false,
                ReferenceIncludes::Plain,
                &|| false,
            )
            .unwrap()
            .into_iter()
            .map(|(file, _)| file)
            .collect()
    }

    /// Everything a whole-file analysis leaves behind that a later one could
    /// observe: loaded dependencies, the warm-up skip mark, and the result.
    #[derive(Debug, PartialEq)]
    struct AnalysisOutcome {
        issues: Vec<String>,
        symbols: usize,
        vendor_class_loaded: bool,
        vendor_function_loaded: bool,
        eager_files_drained: bool,
        stubs_loaded: usize,
        prepared: bool,
        prepare_generation: u64,
        references: Vec<String>,
    }

    const DEPENDENT: &str = "<?php\nnamespace App;\nfunction go(\\Vendor\\Base $b): void { vendor_helper('x'); new \\ArrayObject(); }\n";

    fn composer_project(root: &std::path::Path) -> AnalysisSession {
        let vendor = root.join("vendor");
        std::fs::create_dir_all(vendor.join("composer")).unwrap();
        std::fs::create_dir_all(vendor.join("helpers")).unwrap();
        std::fs::create_dir_all(root.join("lib")).unwrap();
        std::fs::write(
            vendor.join("composer/autoload_files.php"),
            "<?php\n$vendorDir = dirname(__DIR__);\n$baseDir = dirname($vendorDir);\nreturn array(\n    'abc123' => $vendorDir . '/helpers/functions.php',\n);\n",
        )
        .unwrap();
        for empty in ["psr4", "classmap", "namespaces"] {
            std::fs::write(
                vendor.join(format!("composer/autoload_{empty}.php")),
                "<?php\nreturn [];\n",
            )
            .unwrap();
        }
        std::fs::write(
            vendor.join("helpers/functions.php"),
            "<?php\nfunction vendor_helper(string $s): string { return $s; }\n",
        )
        .unwrap();
        std::fs::write(
            root.join("lib/Base.php"),
            "<?php\nnamespace Vendor;\nclass Base {}\n",
        )
        .unwrap();
        std::fs::write(
            root.join("composer.json"),
            r#"{"autoload":{"psr-4":{"App\\":"src/","Vendor\\":"lib/"}}}"#,
        )
        .unwrap();
        let psr4 = crate::composer::Psr4Map::from_composer(root).unwrap();
        AnalysisSession::new(PhpVersion::LATEST).with_psr4(Arc::new(psr4))
    }

    fn outcome(
        session: &AnalysisSession,
        file: &Arc<str>,
        analysis: crate::FileAnalysis,
    ) -> AnalysisOutcome {
        let text = session.source_of(file).unwrap();
        AnalysisOutcome {
            issues: analysis
                .issues
                .iter()
                .map(|i| format!("{:?}", i.kind))
                .collect(),
            symbols: analysis.symbols.len(),
            vendor_class_loaded: {
                let view = session.db_view();
                let db = view.db();
                crate::db::class_like_indexed(db, crate::db::Fqcn::from_str(db, "Vendor\\Base"))
            },
            vendor_function_loaded: session.contains_function("vendor_helper"),
            eager_files_drained: session.pending_eager_function_files.is_none(),
            stubs_loaded: session.loaded_stub_count(),
            prepared: session.is_prepared_for_analysis(
                file,
                &text,
                session.prepare_generation_snapshot(),
            ),
            prepare_generation: session.prepare_generation_snapshot(),
            references: ["cls:Vendor\\Base", "fn:vendor_helper", "cls:ArrayObject"]
                .into_iter()
                .map(|key| format!("{key}={:?}", session.reference_locations(key)))
                .collect(),
        }
    }

    /// A host that ingests + `prepare_for_query(Some(file))` under its lock and
    /// then runs `AnalysisSnapshot::analyze` leaves the session as
    /// `FileAnalyzer::analyze` does, including the warm-up skip mark.
    #[test]
    fn prepare_for_query_then_snapshot_analyze_matches_file_analyzer() {
        let file: Arc<str> = Arc::from("consumer.php");
        let parsed = php_rs_parser::parse(DEPENDENT);

        let root = tempfile::tempdir().unwrap();
        let mut via_analyzer = composer_project(root.path());
        via_analyzer.ingest_file(file.clone(), Arc::from(DEPENDENT));
        let analysis = crate::FileAnalyzer::new(&mut via_analyzer).analyze(
            file.clone(),
            DEPENDENT,
            &parsed.program,
            &parsed.source_map,
        );
        let expected = outcome(&via_analyzer, &file, analysis);

        let root = tempfile::tempdir().unwrap();
        let mut via_snapshot = composer_project(root.path());
        via_snapshot.ingest_file(file.clone(), Arc::from(DEPENDENT));
        via_snapshot.prepare_for_query(Some(&file));
        let analysis = via_snapshot
            .snapshot()
            .analyze(file.clone(), DEPENDENT, &parsed.program, &parsed.source_map)
            .unwrap();
        let actual = outcome(&via_snapshot, &file, analysis);

        assert!(
            expected.prepared && expected.vendor_function_loaded,
            "{expected:#?}"
        );
        assert_eq!(actual, expected);
    }

    /// `FileAnalyzer::analyze` warms up from the AST it is handed, so it works
    /// on a file never ingested; `prepare_for_query` finds no input to warm
    /// from, so the host must ingest before the snapshot analysis.
    #[test]
    fn prepare_for_query_warms_nothing_for_a_file_that_was_never_ingested() {
        let file: Arc<str> = Arc::from("consumer.php");
        let parsed = php_rs_parser::parse(DEPENDENT);
        let unresolved = |analysis: &crate::FileAnalysis| {
            analysis
                .issues
                .iter()
                .any(|i| matches!(i.kind, crate::IssueKind::UndefinedFunction { .. }))
        };

        let root = tempfile::tempdir().unwrap();
        let mut via_analyzer = composer_project(root.path());
        let analysis = crate::FileAnalyzer::new(&mut via_analyzer).analyze(
            file.clone(),
            DEPENDENT,
            &parsed.program,
            &parsed.source_map,
        );
        assert!(!unresolved(&analysis), "{:?}", analysis.issues);

        let root = tempfile::tempdir().unwrap();
        let mut via_snapshot = composer_project(root.path());
        via_snapshot.prepare_for_query(Some(&file));
        let analysis = via_snapshot
            .snapshot()
            .analyze(file, DEPENDENT, &parsed.program, &parsed.source_map)
            .unwrap();
        assert!(unresolved(&analysis), "{:?}", analysis.issues);
    }
}