mago-codex 1.45.0

PHP type system representation, comparison logic, and codebase metadata for static analysis.
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
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
use std::borrow::Cow;
use std::collections::hash_map::Entry;

use foldhash::HashMap;
use foldhash::HashSet;

use mago_database::file::File;
use mago_database::file::FileId;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_reporting::IssueCollection;
use mago_span::Span;
use mago_word::Word;
use mago_word::WordMap;
use mago_word::WordSet;
use mago_word::ascii_lowercase_constant_name_word;
use mago_word::ascii_lowercase_word;
use mago_word::empty_word;
use mago_word::word;

use crate::diff::CodebaseDiff;
use crate::identifier::method::MethodIdentifier;
use crate::issue::ScanningIssueKind;
use crate::metadata::class_like::ClassLikeMetadata;
use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
use crate::metadata::constant::ConstantMetadata;
use crate::metadata::enum_case::EnumCaseMetadata;
use crate::metadata::flags::MetadataFlags;
use crate::metadata::function_like::FunctionLikeMetadata;
use crate::metadata::property::PropertyMetadata;
use crate::metadata::ttype::TypeMetadata;
use crate::reference::SymbolReferences;
use crate::signature::FileSignature;
use crate::symbol::SymbolKind;
use crate::symbol::Symbols;
use crate::ttype::atomic::TAtomic;
use crate::ttype::atomic::object::TObject;
use crate::ttype::union::TUnion;
use crate::visibility::Visibility;

pub mod attribute;
pub mod class_like;
pub mod class_like_constant;
pub mod constant;
pub mod enum_case;
pub mod flags;
pub mod function_like;
pub mod parameter;
pub mod property;
pub mod property_hook;
pub mod ttype;
pub mod version_constraint;

/// Lightweight set of keys extracted from a per-file [`CodebaseMetadata`].
///
/// Used by the incremental engine to efficiently remove a file's contributions from the
/// merged codebase without keeping a full `CodebaseMetadata` clone per file.
/// Created via [`CodebaseMetadata::extract_keys()`].
#[derive(Debug, Clone)]
pub struct CodebaseEntryKeys {
    /// Class-like FQCN atoms (also used for symbol removal).
    pub class_like_names: Vec<Word>,
    /// Function-like `(scope, name)` tuples.
    pub function_like_keys: Vec<(Word, Word)>,
    /// Constant FQN atoms.
    pub constant_names: Vec<Word>,
    /// File IDs that had signatures in this metadata.
    pub file_ids: Vec<FileId>,
}

/// Holds all analyzed information about the symbols, structures, and relationships within a codebase.
///
/// This acts as the central repository for metadata gathered during static analysis,
/// including details about classes, interfaces, traits, enums, functions, constants,
/// their members, inheritance, dependencies, and associated types.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
#[allow(clippy::unsafe_derive_deserialize)]
pub struct CodebaseMetadata {
    /// Configuration flag: Should types be inferred based on usage patterns?
    pub infer_types_from_usage: bool,
    /// Map from class-like FQCN (`Word`) to its detailed metadata (`ClassLikeMetadata`).
    pub class_likes: WordMap<ClassLikeMetadata>,
    /// Map from a function/method identifier tuple `(scope_id, function_id)` to its metadata (`FunctionLikeMetadata`).
    /// `scope_id` is the FQCN for methods or often `Word::empty()` for global functions.
    pub function_likes: HashMap<(Word, Word), FunctionLikeMetadata>,
    /// Stores the kind (Class, Interface, etc.) for every known symbol FQCN.
    pub symbols: Symbols,
    /// Map from global constant FQN (`Word`) to its metadata (`ConstantMetadata`).
    pub constants: WordMap<ConstantMetadata>,
    /// Map from class/interface FQCN to the set of all its descendants (recursive).
    pub all_class_like_descendants: WordMap<WordSet>,
    /// Map from class/interface FQCN to the set of its direct descendants (children).
    pub direct_classlike_descendants: WordMap<WordSet>,
    /// Set of symbols (FQCNs) that are considered safe/validated.
    pub safe_symbols: WordSet,
    /// Set of specific members `(SymbolFQCN, MemberName)` that are considered safe/validated.
    pub safe_symbol_members: HashSet<(Word, Word)>,
    /// Each `FileSignature` contains a hierarchical tree of `DefSignatureNode` representing
    /// top-level symbols (classes, functions, constants) and their nested members (methods, properties).
    pub file_signatures: HashMap<FileId, FileSignature>,
    /// Per-patch class-like metadata, keyed by FQCN.
    ///
    /// Vendor and patch files declare symbols under the same FQCN, so patches cannot share
    /// the `class_likes` map. At most one patch may target a given symbol; a second patch for
    /// the same FQCN is diagnosed as a [`PatchDuplicateTarget`](ScanningIssueKind::PatchDuplicateTarget)
    /// rather than silently overwriting the first. Entries here are folded into `class_likes`
    /// by [`apply_patches_pass`](Self::apply_patches_pass).
    pub patch_class_likes: WordMap<ClassLikeMetadata>,
    /// Per-patch function-like metadata, keyed by `(scope, name)`.
    ///
    /// The key matches the existing `function_likes` key shape: the FQCN for methods,
    /// `empty_word()` for free functions.
    pub patch_function_likes: HashMap<(Word, Word), FunctionLikeMetadata>,
    /// Per-patch constant metadata, keyed by FQN.
    pub patch_constants: WordMap<ConstantMetadata>,
}

impl CodebaseMetadata {
    /// Creates a new, empty `CodebaseMetadata` with default values.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Checks if a class exists in the codebase (case-insensitive).
    ///
    /// # Examples
    /// ```ignore
    /// if codebase.class_exists("MyClass") {
    ///     // MyClass is a class
    /// }
    /// ```
    #[inline]
    #[must_use]
    pub fn class_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class))
    }

    /// Checks if an interface exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn interface_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Interface))
    }

    /// Checks if a trait exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn trait_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Trait))
    }

    /// Checks if an enum exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn enum_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Enum))
    }

    /// Checks if a class-like (class, interface, trait, or enum) exists (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_like_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        self.symbols.contains(lowercase_name)
    }

    /// Checks if a namespace exists (case-insensitive).
    #[inline]
    #[must_use]
    pub fn namespace_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        self.symbols.contains_namespace(lowercase_name)
    }

    /// Checks if a class or trait exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_or_trait_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class | SymbolKind::Trait))
    }

    /// Checks if a class or interface exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_or_interface_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class | SymbolKind::Interface))
    }

    /// Checks if a method identifier exists in the codebase.
    #[inline]
    #[must_use]
    pub fn method_identifier_exists(&self, method_id: &MethodIdentifier) -> bool {
        let lowercase_class = ascii_lowercase_word(method_id.get_class_name().as_bytes());
        let lowercase_method = ascii_lowercase_word(method_id.get_method_name().as_bytes());
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes.contains_key(&identifier)
    }

    /// Checks if a global function exists in the codebase (case-insensitive).
    #[inline]
    #[must_use]
    pub fn function_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        let identifier = (empty_word(), lowercase_name);
        self.function_likes.contains_key(&identifier)
    }

    /// Checks if a global constant exists in the codebase.
    /// The namespace part is case-insensitive, but the constant name is case-sensitive.
    #[inline]
    #[must_use]
    pub fn constant_exists(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_constant_name_word(name);
        self.constants.contains_key(&lowercase_name)
    }

    /// Checks if a method exists on a class-like, including inherited methods (case-insensitive).
    #[inline]
    #[must_use]
    pub fn method_exists(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        self.class_likes
            .get(&lowercase_class)
            .is_some_and(|meta| meta.appearing_method_ids.contains_key(&lowercase_method))
    }

    /// Checks if a property exists on a class-like, including inherited properties.
    /// Class name is case-insensitive, property name is case-sensitive.
    /// Sees real declarations only; magic `@property*` tags are reachable through
    /// `ClassLikeMetadata::magic_property_ids`.
    #[inline]
    #[must_use]
    pub fn property_exists(&self, class: &[u8], property: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        self.class_likes
            .get(&lowercase_class)
            .is_some_and(|meta| meta.appearing_property_ids.contains_key(&property_name))
    }

    /// Checks if a class constant or enum case exists on a class-like.
    /// Class name is case-insensitive, constant/case name is case-sensitive.
    #[inline]
    #[must_use]
    pub fn class_constant_exists(&self, class: &[u8], constant: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let constant_name = word(constant);
        self.class_likes.get(&lowercase_class).is_some_and(|meta| {
            meta.constants.contains_key(&constant_name) || meta.enum_cases.contains_key(&constant_name)
        })
    }

    /// Checks if a method is declared directly in a class (not inherited).
    #[inline]
    #[must_use]
    pub fn method_is_declared_in_class(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        self.class_likes
            .get(&lowercase_class)
            .and_then(|meta| meta.declaring_method_ids.get(&lowercase_method))
            .is_some_and(|method_id| method_id.get_class_name() == lowercase_class)
    }

    /// Checks if a property is declared directly in a class (not inherited).
    #[inline]
    #[must_use]
    pub fn property_is_declared_in_class(&self, class: &[u8], property: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        self.class_likes.get(&lowercase_class).is_some_and(|meta| meta.properties.contains_key(&property_name))
    }

    /// Retrieves metadata for a class (case-insensitive).
    /// Returns `None` if the name doesn't correspond to a class.
    #[inline]
    #[must_use]
    pub fn get_class(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        if self.symbols.contains_class(lowercase_name) { self.class_likes.get(&lowercase_name) } else { None }
    }

    /// Retrieves metadata for an interface (case-insensitive).
    #[inline]
    #[must_use]
    pub fn get_interface(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        if self.symbols.contains_interface(lowercase_name) { self.class_likes.get(&lowercase_name) } else { None }
    }

    /// Retrieves metadata for a trait (case-insensitive).
    #[inline]
    #[must_use]
    pub fn get_trait(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        if self.symbols.contains_trait(lowercase_name) { self.class_likes.get(&lowercase_name) } else { None }
    }

    /// Retrieves metadata for an enum (case-insensitive).
    #[inline]
    #[must_use]
    pub fn get_enum(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        if self.symbols.contains_enum(lowercase_name) { self.class_likes.get(&lowercase_name) } else { None }
    }

    /// Retrieves metadata for any class-like structure (case-insensitive).
    #[inline]
    #[must_use]
    pub fn get_class_like(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        self.class_likes.get(&lowercase_name)
    }

    /// Retrieves metadata for a global function (case-insensitive).
    #[inline]
    #[must_use]
    pub fn get_function(&self, name: &[u8]) -> Option<&FunctionLikeMetadata> {
        let lowercase_name = ascii_lowercase_word(name);
        let identifier = (empty_word(), lowercase_name);
        self.function_likes.get(&identifier)
    }

    /// Retrieves metadata for a method (case-insensitive for both class and method names).
    #[inline]
    #[must_use]
    pub fn get_method(&self, class: &[u8], method: &[u8]) -> Option<&FunctionLikeMetadata> {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes.get(&identifier)
    }

    /// Retrieves metadata for a closure or arrow function by its synthetic
    /// name (e.g. `{closure:src/foo.php:12:5}`).
    #[inline]
    #[must_use]
    pub fn get_closure(&self, synthetic_name: &Word) -> Option<&FunctionLikeMetadata> {
        self.function_likes.get(&(empty_word(), *synthetic_name))
    }

    /// Retrieves metadata for a closure declared at the given file and span.
    /// Convenience wrapper that rebuilds the synthetic name and delegates to
    /// [`Self::get_closure`].
    #[inline]
    #[must_use]
    pub fn get_closure_at(&self, file: &File, span: Span) -> Option<&FunctionLikeMetadata> {
        let name = crate::build_synthetic_name("closure", file, span);
        self.get_closure(&name)
    }

    /// Retrieves method metadata by `MethodIdentifier`.
    #[inline]
    #[must_use]
    pub fn get_method_by_id(&self, method_id: &MethodIdentifier) -> Option<&FunctionLikeMetadata> {
        let lowercase_class = ascii_lowercase_word(method_id.get_class_name().as_bytes());
        let lowercase_method = ascii_lowercase_word(method_id.get_method_name().as_bytes());
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes.get(&identifier)
    }

    /// Retrieves the declaring method metadata, following the inheritance chain.
    /// This finds where the method is actually implemented.
    #[inline]
    #[must_use]
    pub fn get_declaring_method(&self, class: &[u8], method: &[u8]) -> Option<&FunctionLikeMetadata> {
        let method_id = MethodIdentifier::new(word(class), word(method));
        let declaring_method_id = self.get_declaring_method_identifier(&method_id);
        self.get_method(
            declaring_method_id.get_class_name().as_bytes(),
            declaring_method_id.get_method_name().as_bytes(),
        )
    }

    /// Retrieves metadata for any function-like construct (function, method, or closure).
    /// This is a convenience method that delegates to the appropriate getter based on the identifier type.
    #[inline]
    #[must_use]
    pub fn get_function_like(
        &self,
        identifier: &crate::identifier::function_like::FunctionLikeIdentifier,
    ) -> Option<&FunctionLikeMetadata> {
        use crate::identifier::function_like::FunctionLikeIdentifier;
        match identifier {
            FunctionLikeIdentifier::Function(name) => self.get_function(name.as_bytes()),
            FunctionLikeIdentifier::Method(class, method) => self.get_method(class.as_bytes(), method.as_bytes()),
            FunctionLikeIdentifier::Closure(name) => self.get_closure(name),
        }
    }

    /// Retrieves metadata for a global constant.
    /// Namespace lookup is case-insensitive, constant name is case-sensitive.
    #[inline]
    #[must_use]
    pub fn get_constant(&self, name: &[u8]) -> Option<&ConstantMetadata> {
        let lowercase_name = ascii_lowercase_constant_name_word(name);
        self.constants.get(&lowercase_name)
    }

    /// The declaration name span of a top-level symbol named `name`: a
    /// class-like (class/interface/trait/enum), a function, or a constant.
    ///
    /// Prefers the symbol's name span over its full declaration span, so callers
    /// land on the identifier rather than the whole declaration body. The lookup
    /// is case-insensitive, like every symbol lookup here.
    #[inline]
    #[must_use]
    pub fn span_of(&self, name: &[u8]) -> Option<Span> {
        if let Some(meta) = self.get_class_like(name) {
            return Some(meta.name_span.unwrap_or(meta.span));
        }

        if let Some(meta) = self.get_function(name) {
            return Some(meta.name_span.unwrap_or(meta.span));
        }

        self.get_constant(name).map(|meta| meta.span)
    }

    /// Retrieves metadata for a class constant.
    /// Class name is case-insensitive, constant name is case-sensitive.
    #[inline]
    #[must_use]
    pub fn get_class_constant(&self, class: &[u8], constant: &[u8]) -> Option<&ClassLikeConstantMetadata> {
        let lowercase_class = ascii_lowercase_word(class);
        let constant_name = word(constant);
        self.class_likes.get(&lowercase_class).and_then(|meta| meta.constants.get(&constant_name))
    }

    /// Retrieves metadata for an enum case.
    #[inline]
    #[must_use]
    pub fn get_enum_case(&self, class: &[u8], case: &[u8]) -> Option<&EnumCaseMetadata> {
        let lowercase_class = ascii_lowercase_word(class);
        let case_name = word(case);
        self.class_likes.get(&lowercase_class).and_then(|meta| meta.enum_cases.get(&case_name))
    }

    /// Retrieves metadata for a property directly from the class where it's declared.
    /// Class name is case-insensitive, property name is case-sensitive.
    /// Sees real declarations only; magic `@property*` tags are reachable through
    /// `ClassLikeMetadata::magic_property_ids`.
    #[inline]
    #[must_use]
    pub fn get_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        self.class_likes.get(&lowercase_class)?.properties.get(&property_name)
    }

    /// Retrieves the property metadata, potentially from a parent class if inherited.
    #[inline]
    #[must_use]
    pub fn get_declaring_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        let declaring_class = self.class_likes.get(&lowercase_class)?.declaring_property_ids.get(&property_name)?;
        self.class_likes.get(declaring_class)?.properties.get(&property_name)
    }
    // Type Resolution

    /// Gets the type of a property, resolving it from the declaring class if needed.
    #[inline]
    #[must_use]
    pub fn get_property_type(&self, class: &[u8], property: &[u8]) -> Option<&TUnion> {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        let declaring_class = self.class_likes.get(&lowercase_class)?.declaring_property_ids.get(&property_name)?;
        let property_meta = self.class_likes.get(declaring_class)?.properties.get(&property_name)?;
        property_meta.type_metadata.as_ref().map(|tm| &tm.type_union)
    }

    /// Gets the type of a class constant, considering both type hints and inferred types.
    #[must_use]
    pub fn get_class_constant_type<'meta>(&'meta self, class: &[u8], constant: &[u8]) -> Option<Cow<'meta, TUnion>> {
        let lowercase_class = ascii_lowercase_word(class);
        let constant_name = word(constant);
        let class_meta = self.class_likes.get(&lowercase_class)?;

        // Check if it's an enum case
        if class_meta.kind.is_enum() && class_meta.enum_cases.contains_key(&constant_name) {
            let atomic = TAtomic::Object(TObject::new_enum_case(class_meta.original_name, constant_name));
            return Some(Cow::Owned(TUnion::from_atomic(atomic)));
        }

        // It's a regular class constant
        let constant_meta = class_meta.constants.get(&constant_name)?;

        // Prefer the type signature if available
        if let Some(type_meta) = constant_meta.type_metadata.as_ref() {
            return Some(Cow::Borrowed(&type_meta.type_union));
        }

        // Fall back to inferred type
        constant_meta.inferred_type.as_ref().map(|atomic| Cow::Owned(TUnion::from_atomic(atomic.clone())))
    }

    /// Gets the literal value of a class constant if it was inferred.
    #[inline]
    #[must_use]
    pub fn get_class_constant_literal_value(&self, class: &[u8], constant: &[u8]) -> Option<&TAtomic> {
        let lowercase_class = ascii_lowercase_word(class);
        let constant_name = word(constant);
        self.class_likes
            .get(&lowercase_class)
            .and_then(|meta| meta.constants.get(&constant_name))
            .and_then(|constant_meta| constant_meta.inferred_type.as_ref())
    }
    // Inheritance Queries

    /// Checks if a child class extends a parent class (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_extends(&self, child: &[u8], parent: &[u8]) -> bool {
        let lowercase_child = ascii_lowercase_word(child);
        let lowercase_parent = ascii_lowercase_word(parent);
        self.class_likes.get(&lowercase_child).is_some_and(|meta| meta.all_parent_classes.contains(&lowercase_parent))
    }

    /// Checks if a class directly extends a parent class (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_directly_extends(&self, child: &[u8], parent: &[u8]) -> bool {
        let lowercase_child = ascii_lowercase_word(child);
        let lowercase_parent = ascii_lowercase_word(parent);
        self.class_likes
            .get(&lowercase_child)
            .is_some_and(|meta| meta.direct_parent_class.as_ref() == Some(&lowercase_parent))
    }

    /// Checks if a class implements an interface (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_implements(&self, class: &[u8], interface: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_interface = ascii_lowercase_word(interface);
        self.class_likes
            .get(&lowercase_class)
            .is_some_and(|meta| meta.all_parent_interfaces.contains(&lowercase_interface))
    }

    /// Checks if a class directly implements an interface (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_directly_implements(&self, class: &[u8], interface: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_interface = ascii_lowercase_word(interface);
        self.class_likes
            .get(&lowercase_class)
            .is_some_and(|meta| meta.direct_parent_interfaces.contains(&lowercase_interface))
    }

    /// Checks if a class uses a trait (case-insensitive).
    #[inline]
    #[must_use]
    pub fn class_uses_trait(&self, class: &[u8], trait_name: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_trait = ascii_lowercase_word(trait_name);
        self.class_likes.get(&lowercase_class).is_some_and(|meta| meta.used_traits.contains(&lowercase_trait))
    }

    /// Checks if a trait has `@require-extends` for a class (case-insensitive).
    /// Returns true if the trait requires extending the specified class or any of its parents.
    #[inline]
    #[must_use]
    pub fn trait_requires_extends(&self, trait_name: &[u8], class_name: &[u8]) -> bool {
        let lowercase_trait = ascii_lowercase_word(trait_name);

        self.class_likes.get(&lowercase_trait).is_some_and(|meta| {
            meta.require_extends.iter().any(|required| self.is_instance_of(class_name, required.as_bytes()))
        })
    }

    /// Checks if child is an instance of parent (via extends or implements).
    #[inline]
    #[must_use]
    pub fn is_instance_of(&self, child: &[u8], parent: &[u8]) -> bool {
        if child == parent {
            return true;
        }

        let lowercase_child = ascii_lowercase_word(child);
        let lowercase_parent = ascii_lowercase_word(parent);

        if lowercase_child == lowercase_parent {
            return true;
        }

        self.class_likes.get(&lowercase_child).is_some_and(|meta| {
            meta.all_parent_classes.contains(&lowercase_parent)
                || meta.all_parent_interfaces.contains(&lowercase_parent)
                || meta.used_traits.contains(&lowercase_parent)
                || meta.require_extends.contains(&lowercase_parent)
                || meta.require_implements.contains(&lowercase_parent)
        })
    }

    /// Checks if the given name is an enum or final class.
    #[inline]
    #[must_use]
    pub fn is_enum_or_final_class(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        self.class_likes.get(&lowercase_name).is_some_and(|meta| meta.kind.is_enum() || meta.flags.is_final())
    }

    /// Checks if a class-like can be part of an intersection.
    /// Generally, only final classes and enums cannot be intersected.
    #[inline]
    #[must_use]
    pub fn is_inheritable(&self, name: &[u8]) -> bool {
        let lowercase_name = ascii_lowercase_word(name);
        match self.symbols.get_kind(lowercase_name) {
            Some(SymbolKind::Class) => self.class_likes.get(&lowercase_name).is_some_and(|meta| !meta.flags.is_final()),
            Some(SymbolKind::Enum) => false,
            Some(SymbolKind::Interface | SymbolKind::Trait) | None => true,
        }
    }

    /// Gets all descendants of a class (recursive).
    #[inline]
    #[must_use]
    pub fn get_class_descendants(&self, class: &[u8]) -> WordSet {
        let lowercase_class = ascii_lowercase_word(class);
        let mut all_descendants = WordSet::default();
        let mut queue = vec![&lowercase_class];
        let mut visited = WordSet::default();
        visited.insert(lowercase_class);

        while let Some(current_name) = queue.pop() {
            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
                for descendant in direct_descendants {
                    if visited.insert(*descendant) {
                        all_descendants.insert(*descendant);
                        queue.push(descendant);
                    }
                }
            }
        }

        all_descendants
    }

    /// Gets all ancestors of a class (parents + interfaces).
    #[inline]
    #[must_use]
    pub fn get_class_ancestors(&self, class: &[u8]) -> WordSet {
        let lowercase_class = ascii_lowercase_word(class);
        let mut ancestors = WordSet::default();
        if let Some(meta) = self.class_likes.get(&lowercase_class) {
            ancestors.extend(meta.all_parent_classes.iter().copied());
            ancestors.extend(meta.all_parent_interfaces.iter().copied());
        }
        ancestors
    }

    /// Gets the class where a method is declared (following inheritance).
    #[inline]
    #[must_use]
    pub fn get_declaring_method_class(&self, class: &[u8], method: &[u8]) -> Option<Word> {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);

        self.class_likes
            .get(&lowercase_class)?
            .declaring_method_ids
            .get(&lowercase_method)
            .map(|method_id| method_id.get_class_name())
    }

    /// Gets the class where a method appears (could be the declaring class or child class).
    #[inline]
    #[must_use]
    pub fn get_appearing_method_class(&self, class: &[u8], method: &[u8]) -> Option<Word> {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        self.class_likes
            .get(&lowercase_class)?
            .appearing_method_ids
            .get(&lowercase_method)
            .map(|method_id| method_id.get_class_name())
    }

    /// Gets the declaring method identifier for a method.
    #[must_use]
    pub fn get_declaring_method_identifier(&self, method_id: &MethodIdentifier) -> MethodIdentifier {
        let lowercase_class = ascii_lowercase_word(method_id.get_class_name().as_bytes());
        let lowercase_method = ascii_lowercase_word(method_id.get_method_name().as_bytes());

        let Some(class_meta) = self.class_likes.get(&lowercase_class) else {
            return *method_id;
        };

        if let Some(declaring_method_id) = class_meta.declaring_method_ids.get(&lowercase_method) {
            return *declaring_method_id;
        }

        if class_meta.flags.is_abstract()
            && let Some(overridden_map) = class_meta.overridden_method_ids.get(&lowercase_method)
            && let Some((_, first_method_id)) = overridden_map.first()
        {
            return *first_method_id;
        }

        *method_id
    }

    /// Checks if a method is overriding a parent method.
    #[inline]
    #[must_use]
    pub fn method_is_overriding(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        self.class_likes
            .get(&lowercase_class)
            .is_some_and(|meta| meta.overridden_method_ids.contains_key(&lowercase_method))
    }

    /// Checks if a method is abstract.
    #[inline]
    #[must_use]
    pub fn method_is_abstract(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes
            .get(&identifier)
            .and_then(|meta| meta.method_metadata.as_ref())
            .is_some_and(|method_meta| method_meta.is_abstract)
    }

    /// Checks if a method is static.
    #[inline]
    #[must_use]
    pub fn method_is_static(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes
            .get(&identifier)
            .and_then(|meta| meta.method_metadata.as_ref())
            .is_some_and(|method_meta| method_meta.is_static)
    }

    /// Checks if a method is final.
    #[inline]
    #[must_use]
    pub fn method_is_final(&self, class: &[u8], method: &[u8]) -> bool {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);
        let identifier = (lowercase_class, lowercase_method);
        self.function_likes
            .get(&identifier)
            .and_then(|meta| meta.method_metadata.as_ref())
            .is_some_and(|method_meta| method_meta.is_final)
    }

    /// Gets the effective visibility of a method, taking into account trait alias visibility overrides.
    ///
    /// When a trait method is aliased with a visibility modifier (e.g., `use Trait { method as public aliasedMethod; }`),
    /// the visibility is stored in the class's `trait_visibility_map`. This method checks that map first,
    /// then falls back to the method's declared visibility.
    #[inline]
    #[must_use]
    pub fn get_method_visibility(&self, class: &[u8], method: &[u8]) -> Option<Visibility> {
        let lowercase_class = ascii_lowercase_word(class);
        let lowercase_method = ascii_lowercase_word(method);

        // First check if there's a trait visibility override for this method
        if let Some(class_meta) = self.class_likes.get(&lowercase_class)
            && let Some(overridden_visibility) = class_meta.trait_visibility_map.get(&lowercase_method)
        {
            return Some(*overridden_visibility);
        }

        // Fall back to the method's declared visibility
        let declaring_class = self.get_declaring_method_class(class, method)?;
        let identifier = (declaring_class, lowercase_method);

        self.function_likes
            .get(&identifier)
            .and_then(|meta| meta.method_metadata.as_ref())
            .map(|method_meta| method_meta.visibility)
    }

    /// Gets thrown types for a function-like, including inherited throws.
    #[must_use]
    pub fn get_function_like_thrown_types<'meta>(
        &'meta self,
        class_like: Option<&'meta ClassLikeMetadata>,
        function_like: &'meta FunctionLikeMetadata,
    ) -> &'meta [TypeMetadata] {
        if !function_like.thrown_types.is_empty() {
            return function_like.thrown_types.as_slice();
        }

        if !function_like.kind.is_method() {
            return &[];
        }

        let Some(class_like) = class_like else {
            return &[];
        };

        let method_name = &function_like.name;

        if let Some(overridden_map) = class_like.overridden_method_ids.get(method_name) {
            for (parent_class_name, parent_method_id) in overridden_map {
                if class_like.name.as_bytes().eq_ignore_ascii_case(parent_class_name.as_bytes()) {
                    continue; // Skip self-recursion if the method overrides itself
                }

                let Some(parent_class) = self.class_likes.get(parent_class_name) else {
                    continue;
                };

                let parent_method_key = (parent_method_id.get_class_name(), parent_method_id.get_method_name());
                if let Some(parent_method) = self.function_likes.get(&parent_method_key) {
                    let thrown = self.get_function_like_thrown_types(Some(parent_class), parent_method);
                    if !thrown.is_empty() {
                        return thrown;
                    }
                }
            }
        }

        &[]
    }

    /// Gets the class where a property is declared.
    /// Sees real declarations only; magic `@property*` tags are reachable through
    /// `ClassLikeMetadata::magic_property_ids`.
    #[inline]
    #[must_use]
    pub fn get_declaring_property_class(&self, class: &[u8], property: &[u8]) -> Option<Word> {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        self.class_likes.get(&lowercase_class)?.declaring_property_ids.get(&property_name).copied()
    }

    /// Gets the class where a property appears.
    #[inline]
    #[must_use]
    pub fn get_appearing_property_class(&self, class: &[u8], property: &[u8]) -> Option<Word> {
        let lowercase_class = ascii_lowercase_word(class);
        let property_name = word(property);
        self.class_likes.get(&lowercase_class)?.appearing_property_ids.get(&property_name).copied()
    }

    /// Gets all descendants of a class (recursive).
    #[must_use]
    pub fn get_all_descendants(&self, class: &[u8]) -> WordSet {
        let lowercase_class = ascii_lowercase_word(class);
        let mut all_descendants = WordSet::default();
        let mut queue = vec![&lowercase_class];
        let mut visited = WordSet::default();
        visited.insert(lowercase_class);

        while let Some(current_name) = queue.pop() {
            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
                for descendant in direct_descendants {
                    if visited.insert(*descendant) {
                        all_descendants.insert(*descendant);
                        queue.push(descendant);
                    }
                }
            }
        }

        all_descendants
    }

    /// Generates the synthetic display name for an anonymous class based on
    /// its declaring file and span. Delegates to [`crate::get_anonymous_class_name`].
    #[must_use]
    pub fn get_anonymous_class_name(file: &File, span: Span) -> Word {
        crate::get_anonymous_class_name(file, span)
    }

    /// Retrieves the metadata for an anonymous class based on its declaring
    /// file and span.
    #[must_use]
    pub fn get_anonymous_class(&self, file: &File, span: Span) -> Option<&ClassLikeMetadata> {
        let name = Self::get_anonymous_class_name(file, span);
        self.get_class_like(name.as_bytes())
    }

    /// Gets the file signature for a given file ID.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The file identifier
    ///
    /// # Returns
    ///
    /// A reference to the `FileSignature` if it exists, or `None` if the file has no signature.
    #[inline]
    #[must_use]
    pub fn get_file_signature(&self, file_id: &FileId) -> Option<&FileSignature> {
        self.file_signatures.get(file_id)
    }

    /// Adds or updates a file signature for a given file ID.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The file identifier
    /// * `signature` - The file signature
    ///
    /// # Returns
    ///
    /// The previous `FileSignature` if it existed.
    #[inline]
    pub fn set_file_signature(&mut self, file_id: FileId, signature: FileSignature) -> Option<FileSignature> {
        self.file_signatures.insert(file_id, signature)
    }

    /// Removes the file signature for a given file ID.
    ///
    /// # Arguments
    ///
    /// * `file_id` - The file identifier
    ///
    /// # Returns
    ///
    /// The removed `FileSignature` if it existed.
    #[inline]
    pub fn remove_file_signature(&mut self, file_id: &FileId) -> Option<FileSignature> {
        self.file_signatures.remove(file_id)
    }

    /// Marks safe symbols based on diff and invalidation cascade.
    ///
    /// After this function runs, `self.safe_symbols` and `self.safe_symbol_members`
    /// will contain all symbols that can be safely skipped during analysis.
    ///
    /// # Arguments
    ///
    /// * `diff` - The computed diff between old and new code
    /// * `references` - Symbol reference graph from previous run
    ///
    /// # Returns
    /// Returns `Some(global_scope_invalid)` on success, where `global_scope_invalid`
    /// is `true` when global-scope code (the `(empty, empty)` pseudo-symbol) references
    /// something that changed. Returns `None` if the cascade was too large to compute.
    pub fn mark_safe_symbols(&mut self, diff: &CodebaseDiff, references: &SymbolReferences) -> Option<bool> {
        let (invalid_symbols, partially_invalid) = references.get_invalid_symbols(diff)?;

        // Mark all symbols in 'keep' set as safe (unless invalidated by cascade)
        for keep_symbol in diff.get_keep() {
            if !invalid_symbols.contains(keep_symbol) {
                if keep_symbol.1.is_empty() {
                    // Top-level symbol (class, function, constant)
                    if !partially_invalid.contains(&keep_symbol.0) {
                        self.safe_symbols.insert(keep_symbol.0);
                    }
                } else {
                    // Member (method, property, class constant)
                    self.safe_symbol_members.insert(*keep_symbol);
                }
            }
        }

        Some(invalid_symbols.contains(&(empty_word(), empty_word())))
    }

    /// Merges information from another `CodebaseMetadata` into this one.
    ///
    /// When both metadata have the same priority, the one with the smaller span is kept
    /// for deterministic results regardless of scan order.
    pub fn extend(&mut self, other: CodebaseMetadata) {
        for (k, mut v) in other.class_likes {
            match self.class_likes.entry(k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        v.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(v);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint);
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }

        for (k, mut v) in other.function_likes {
            match self.function_likes.entry(k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        v.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(v);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint);
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }

        for (k, mut v) in other.constants {
            match self.constants.entry(k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        v.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(v);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint);
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }

        self.symbols.extend(other.symbols);

        for (k, v) in other.all_class_like_descendants {
            self.all_class_like_descendants.entry(k).or_default().extend(v);
        }

        for (k, v) in other.direct_classlike_descendants {
            self.direct_classlike_descendants.entry(k).or_default().extend(v);
        }

        self.file_signatures.extend(other.file_signatures);
        self.safe_symbols.extend(other.safe_symbols);
        self.safe_symbol_members.extend(other.safe_symbol_members);
        self.infer_types_from_usage |= other.infer_types_from_usage;
        self.merge_patch_class_likes(other.patch_class_likes);
        self.merge_patch_function_likes(other.patch_function_likes);
        self.merge_patch_constants(other.patch_constants);
    }

    /// Extends this codebase with another by reference, cloning only individual entries.
    ///
    /// This is more efficient than `extend(other.clone())` because it avoids allocating
    /// a full clone of the source metadata's outer HashMap/WordMap structures. Only
    /// individual entries that need insertion are cloned.
    pub fn extend_ref(&mut self, other: &CodebaseMetadata) {
        for (k, v) in &other.class_likes {
            match self.class_likes.entry(*k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        let mut new = v.clone();
                        new.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(new);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v.clone());
                }
            }
        }

        for (k, v) in &other.function_likes {
            match self.function_likes.entry(*k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        let mut new = v.clone();
                        new.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(new);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v.clone());
                }
            }
        }

        for (k, v) in &other.constants {
            match self.constants.entry(*k) {
                Entry::Occupied(mut entry) => {
                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
                        let mut new = v.clone();
                        new.version_constraint.merge(entry.get().version_constraint.clone());
                        entry.insert(new);
                    } else {
                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v.clone());
                }
            }
        }

        self.symbols.extend_ref(&other.symbols);

        for (k, v) in &other.all_class_like_descendants {
            self.all_class_like_descendants.entry(*k).or_default().extend(v.iter().copied());
        }

        for (k, v) in &other.direct_classlike_descendants {
            self.direct_classlike_descendants.entry(*k).or_default().extend(v.iter().copied());
        }

        for (k, v) in &other.file_signatures {
            self.file_signatures.insert(*k, v.clone());
        }
        self.safe_symbols.extend(other.safe_symbols.iter().copied());
        self.safe_symbol_members.extend(other.safe_symbol_members.iter().copied());
        self.infer_types_from_usage |= other.infer_types_from_usage;
        self.merge_patch_class_likes(other.patch_class_likes.iter().map(|(k, v)| (*k, v.clone())));
        self.merge_patch_function_likes(other.patch_function_likes.iter().map(|(k, v)| (*k, v.clone())));
        self.merge_patch_constants(other.patch_constants.iter().map(|(k, v)| (*k, v.clone())));
    }

    /// Merges patch class-likes from another codebase, diagnosing collisions.
    ///
    /// At most one patch may target a given symbol. When two patches collide, the first-merged
    /// entry is kept and a [`PatchDuplicateTarget`](ScanningIssueKind::PatchDuplicateTarget)
    /// diagnostic referencing both sites is attached to it, rather than letting one silently
    /// overwrite the other in hash-order.
    fn merge_patch_class_likes(&mut self, incoming: impl IntoIterator<Item = (Word, ClassLikeMetadata)>) {
        for (k, v) in incoming {
            match self.patch_class_likes.entry(k) {
                Entry::Occupied(mut entry) => {
                    let diagnostic = duplicate_patch_class_diagnostic(entry.get(), &v);
                    entry.get_mut().issues.push(diagnostic);
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }
    }

    /// Merges patch function-likes from another codebase, diagnosing collisions on free
    /// functions. Method collisions are subsumed by the enclosing class's duplicate
    /// diagnostic, so only keys with an empty class component are reported here.
    fn merge_patch_function_likes(&mut self, incoming: impl IntoIterator<Item = ((Word, Word), FunctionLikeMetadata)>) {
        for (k, v) in incoming {
            match self.patch_function_likes.entry(k) {
                Entry::Occupied(mut entry) => {
                    if k.0.is_empty() {
                        let diagnostic = duplicate_patch_function_diagnostic(entry.get(), &v);
                        entry.get_mut().issues.push(diagnostic);
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }
    }

    /// Merges patch constants from another codebase, diagnosing collisions.
    fn merge_patch_constants(&mut self, incoming: impl IntoIterator<Item = (Word, ConstantMetadata)>) {
        for (k, v) in incoming {
            match self.patch_constants.entry(k) {
                Entry::Occupied(mut entry) => {
                    let diagnostic = duplicate_patch_constant_diagnostic(entry.get(), &v);
                    entry.get_mut().issues.push(diagnostic);
                }
                Entry::Vacant(entry) => {
                    entry.insert(v);
                }
            }
        }
    }

    /// Moves every scanned entry of this per-file partial into the patch maps.
    ///
    /// Called on a per-file partial right after `scan_program` when the file is a
    /// [`FileType::Patch`]. Symbols and descendants from a patch partial are dropped — the
    /// FQCN belongs to whichever non-patch source originally declared it (or it's an orphan
    /// which `apply_patches_pass` will diagnose later).
    pub fn convert_partial_to_patch(&mut self) {
        for (k, v) in std::mem::take(&mut self.class_likes) {
            self.patch_class_likes.insert(k, v);
        }

        for (k, v) in std::mem::take(&mut self.function_likes) {
            self.patch_function_likes.insert(k, v);
        }

        for (k, v) in std::mem::take(&mut self.constants) {
            self.patch_constants.insert(k, v);
        }

        self.symbols = Symbols::new();
        self.all_class_like_descendants.clear();
        self.direct_classlike_descendants.clear();
    }

    /// Folds every entry in the `patch_*` maps into the matching vendor / built-in entry,
    /// attaching validation diagnostics to the patch entry's `issues` list.
    ///
    /// At most one patch may target a given symbol, so each entry is applied directly to its
    /// target. A patch whose target is user-defined is inert (user definitions win); a patch
    /// with no matching target is diagnosed as an orphan.
    ///
    /// Must be called after all partials have been merged so the slots patches target are
    /// present.
    pub fn apply_patches_pass(&mut self) {
        // `(class, method)` slots where a patch overrides a method inherited from an ancestor.
        // No function-like exists at these keys yet, so the function loop below materializes
        // them from the patch's own scanned declaration rather than treating them as orphans.
        let mut inherited_overrides: HashSet<(Word, Word)> = HashSet::default();

        let class_keys: Vec<Word> = self.patch_class_likes.keys().copied().collect();
        for fqcn in class_keys {
            let Some(target) = self.class_likes.get(&fqcn) else {
                if let Some(p) = self.patch_class_likes.get_mut(&fqcn) {
                    let diag = orphan_patch_class_diagnostic(p);
                    p.issues.push(diag);
                }
                continue;
            };
            // User-defined targets win; the patch entry is inert. Leave any scan-time issues
            // on it intact — they still belong to the patch source.
            if target.flags.is_user_defined() {
                continue;
            }

            let mut working = target.clone();
            let inherited =
                collect_inherited_patch_methods(&working, &self.patch_class_likes[&fqcn], &self.class_likes);
            inherited_overrides.extend(inherited.iter().map(|method| (fqcn, *method)));
            if let Some(patch_entry) = self.patch_class_likes.get_mut(&fqcn) {
                working.apply_patch(patch_entry, &inherited);
            }
            self.class_likes.insert(fqcn, working);
        }

        let func_keys: Vec<(Word, Word)> = self.patch_function_likes.keys().copied().collect();
        for key in func_keys {
            let Some(target) = self.function_likes.get(&key) else {
                if inherited_overrides.contains(&key) {
                    // The patch overrides a method inherited from an ancestor, so no slot exists
                    // at `(class, method)` yet. The patch file declares the method in full, so
                    // promote its scanned function-like as this class's own declaration; the
                    // class loop has already pointed the declaring/appearing ids at this slot.
                    if let Some(p) = self.patch_function_likes.get(&key) {
                        let materialized = p.clone();
                        self.function_likes.insert(key, materialized);
                    }
                    continue;
                }
                // Methods of an orphan patch class are covered by the class-level diagnostic;
                // only free functions need their own orphan diagnostic.
                if key.0.is_empty()
                    && let Some(p) = self.patch_function_likes.get_mut(&key)
                {
                    let diag = orphan_patch_function_diagnostic(p);
                    p.issues.push(diag);
                }
                continue;
            };
            if target.flags.is_user_defined() {
                continue;
            }

            let mut working = target.clone();
            if let Some(patch_entry) = self.patch_function_likes.get_mut(&key) {
                working.apply_patch(patch_entry);
            }
            self.function_likes.insert(key, working);
        }

        let const_keys: Vec<Word> = self.patch_constants.keys().copied().collect();
        for fqcn in const_keys {
            let Some(target) = self.constants.get(&fqcn) else {
                if let Some(p) = self.patch_constants.get_mut(&fqcn) {
                    let diag = orphan_patch_constant_diagnostic(p);
                    p.issues.push(diag);
                }
                continue;
            };
            if target.flags.is_user_defined() {
                continue;
            }

            let mut working = target.clone();
            if let Some(patch_entry) = self.patch_constants.get(&fqcn) {
                working.apply_patch(patch_entry);
            }
            self.constants.insert(fqcn, working);
        }
    }

    /// Removes all entries that were contributed by the given per-file scan metadata.
    ///
    /// This is the inverse of [`extend_ref()`]: it removes class_likes, function_likes,
    /// constants, symbols, and file_signatures whose keys match those in `file_metadata`.
    ///
    /// Used by the incremental engine to patch the codebase in-place when files change,
    /// avoiding a full rebuild from base + all files.
    ///
    /// Note: This does NOT remove descendant map entries — those are rebuilt from scratch
    /// by `populate_codebase()` on every run.
    pub fn remove_entries_of(&mut self, file_metadata: &CodebaseMetadata) {
        for k in file_metadata.class_likes.keys() {
            self.class_likes.remove(k);
        }

        for k in file_metadata.function_likes.keys() {
            self.function_likes.remove(k);
        }

        for k in file_metadata.constants.keys() {
            self.constants.remove(k);
        }

        // Remove symbols that were contributed by this file.
        // We can only remove class-like symbols (not namespaces, since they may be shared).
        for k in file_metadata.class_likes.keys() {
            self.symbols.remove(*k);
        }

        for k in file_metadata.file_signatures.keys() {
            self.file_signatures.remove(k);
        }

        // Drop any patch entry that originated from a file signature we just removed; a patch
        // entry's originating file is recorded on its span.
        let removed_files: HashSet<FileId> = file_metadata.file_signatures.keys().copied().collect();
        self.patch_class_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
        self.patch_function_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
        self.patch_constants.retain(|_, m| !removed_files.contains(&m.span.file_id));
    }

    /// Extracts the set of keys from this metadata for use with [`remove_entries_by_keys()`].
    ///
    /// This is much cheaper than keeping a full `CodebaseMetadata` clone — it only stores
    /// the keys needed to undo an `extend_ref()` operation.
    #[must_use]
    pub fn extract_keys(&self) -> CodebaseEntryKeys {
        CodebaseEntryKeys {
            class_like_names: self.class_likes.keys().copied().collect(),
            function_like_keys: self.function_likes.keys().copied().collect(),
            constant_names: self.constants.keys().copied().collect(),
            file_ids: self.file_signatures.keys().copied().collect(),
        }
    }

    /// Extracts only the keys that this per-file metadata currently "owns" in the given
    /// merged codebase; i.e. keys whose span in `merged` matches this metadata's span.
    ///
    /// This is what you want for incremental fingerprints. [`extract_keys`](Self::extract_keys)
    /// captures *every* key the scan produced, including ones that lost the tiebreak in
    /// [`extend`](Self::extend) / [`extend_ref`](Self::extend_ref) when another file defined
    /// the same FQN. Using `extract_keys` as a removal fingerprint then causes a nasty
    /// cross-file bug: touching file *B* can remove an entry that file *A* actually owns,
    /// because [`remove_entries_by_keys`](Self::remove_entries_by_keys) deletes by FQN
    /// without checking who the current owner is. The analyzer then reports a spurious
    /// "duplicate definition" when it walks *A* and finds *B*'s span in the codebase.
    ///
    /// By only recording the keys whose spans still match *this* metadata, removing the
    /// fingerprint later becomes a safe no-op when another file won the merge. The
    /// removal only drops the entries this file genuinely put into the merged codebase.
    #[must_use]
    pub fn extract_owned_keys(&self, merged: &CodebaseMetadata) -> CodebaseEntryKeys {
        let class_like_names = self
            .class_likes
            .iter()
            .filter(|(name, meta)| merged.class_likes.get(*name).is_some_and(|m| m.span == meta.span))
            .map(|(name, _)| *name)
            .collect();

        let function_like_keys = self
            .function_likes
            .iter()
            .filter(|(key, meta)| merged.function_likes.get(*key).is_some_and(|m| m.span == meta.span))
            .map(|(key, _)| *key)
            .collect();

        let constant_names = self
            .constants
            .iter()
            .filter(|(name, meta)| merged.constants.get(*name).is_some_and(|m| m.span == meta.span))
            .map(|(name, _)| *name)
            .collect();

        // A file signature is always owned by its file (there is at most one per file).
        let file_ids = self.file_signatures.keys().copied().collect();

        CodebaseEntryKeys { class_like_names, function_like_keys, constant_names, file_ids }
    }

    /// Removes entries whose keys match the given [`CodebaseEntryKeys`].
    ///
    /// This is the lightweight equivalent of [`remove_entries_of()`] — it performs the
    /// same removals but from a compact key set instead of a full `CodebaseMetadata` reference.
    pub fn remove_entries_by_keys(&mut self, keys: &CodebaseEntryKeys) {
        for k in &keys.class_like_names {
            self.class_likes.remove(k);
            self.symbols.remove(*k);
        }

        for k in &keys.function_like_keys {
            self.function_likes.remove(k);
        }

        for k in &keys.constant_names {
            self.constants.remove(k);
        }

        for k in &keys.file_ids {
            self.file_signatures.remove(k);
        }

        // Drop any patch entry that originated from a file signature we just removed; a patch
        // entry's originating file is recorded on its span.
        let removed_files: HashSet<FileId> = keys.file_ids.iter().copied().collect();
        self.patch_class_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
        self.patch_function_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
        self.patch_constants.retain(|_, m| !removed_files.contains(&m.span.file_id));
    }

    /// Takes all issues from the codebase metadata.
    pub fn take_issues(&mut self, user_defined: bool) -> IssueCollection {
        let mut issues = IssueCollection::new();

        for meta in self.class_likes.values_mut() {
            if user_defined && !meta.flags.is_user_defined() {
                continue;
            }
            issues.extend(meta.take_issues());
        }

        for meta in self.function_likes.values_mut() {
            if user_defined && !meta.flags.is_user_defined() {
                continue;
            }
            issues.extend(meta.take_issues());
        }

        for meta in self.constants.values_mut() {
            if user_defined && !meta.flags.is_user_defined() {
                continue;
            }
            issues.extend(meta.take_issues());
        }

        // Patches are user-authored, so their issues are always reported regardless of the
        // `user_defined` filter. They live in their own maps and never appear in the regular
        // class_likes/function_likes/constants iteration above.
        for meta in self.patch_class_likes.values_mut() {
            issues.extend(meta.take_issues());
        }

        for meta in self.patch_function_likes.values_mut() {
            issues.extend(meta.take_issues());
        }

        for meta in self.patch_constants.values_mut() {
            issues.extend(meta.take_issues());
        }

        issues
    }

    /// Gets all file IDs that have signatures in this metadata.
    ///
    /// This is a helper method for incremental analysis to iterate over all files.
    #[must_use]
    pub fn get_all_file_ids(&self) -> Vec<FileId> {
        self.file_signatures.keys().copied().collect()
    }
}

impl Default for CodebaseMetadata {
    #[inline]
    fn default() -> Self {
        Self {
            class_likes: WordMap::default(),
            function_likes: HashMap::default(),
            symbols: Symbols::new(),
            infer_types_from_usage: false,
            constants: WordMap::default(),
            all_class_like_descendants: WordMap::default(),
            direct_classlike_descendants: WordMap::default(),
            safe_symbols: WordSet::default(),
            safe_symbol_members: HashSet::default(),
            file_signatures: HashMap::default(),
            patch_class_likes: WordMap::default(),
            patch_function_likes: HashMap::default(),
            patch_constants: WordMap::default(),
        }
    }
}

/// Returns the subset of methods declared by `patch` that are inherited by `target` from
/// an ancestor but not declared on `target` itself. Used by `apply_patch` on class-like
/// metadata to distinguish patch-declared overrides of inherited methods (allowed) from
/// patch-introduced new methods (disallowed).
fn collect_inherited_patch_methods(
    target: &ClassLikeMetadata,
    patch: &ClassLikeMetadata,
    class_likes: &WordMap<ClassLikeMetadata>,
) -> WordSet {
    if patch.methods.is_empty() {
        return WordSet::default();
    }
    let ancestor_methods = class_like::collect_ancestor_methods(target, class_likes);
    patch.methods.iter().filter(|m| ancestor_methods.contains(*m)).copied().collect()
}

fn duplicate_patch_class_diagnostic(kept: &ClassLikeMetadata, dropped: &ClassLikeMetadata) -> Issue {
    Issue::error(format!(
        "Multiple patches target `{}`; at most one patch may target a given symbol.",
        kept.original_name
    ))
    .with_code(ScanningIssueKind::PatchDuplicateTarget)
    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this symbol."))
    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
}

fn duplicate_patch_function_diagnostic(kept: &FunctionLikeMetadata, dropped: &FunctionLikeMetadata) -> Issue {
    Issue::error(format!(
        "Multiple patches target function `{}`; at most one patch may target a given symbol.",
        kept.name
    ))
    .with_code(ScanningIssueKind::PatchDuplicateTarget)
    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this function."))
    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
}

fn duplicate_patch_constant_diagnostic(kept: &ConstantMetadata, dropped: &ConstantMetadata) -> Issue {
    Issue::error(format!(
        "Multiple patches target constant `{}`; at most one patch may target a given symbol.",
        kept.name
    ))
    .with_code(ScanningIssueKind::PatchDuplicateTarget)
    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this constant."))
    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
}

fn orphan_patch_class_diagnostic(meta: &ClassLikeMetadata) -> Issue {
    Issue::error(format!(
        "Patch declares `{}` but no vendored or built-in definition exists to patch.",
        meta.original_name,
    ))
    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
    .with_annotation(Annotation::primary(meta.span))
    .with_help(
        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
         check the symbol name and verify the patch still matches the upstream source.",
    )
}

fn orphan_patch_function_diagnostic(meta: &FunctionLikeMetadata) -> Issue {
    Issue::error(format!(
        "Patch declares function `{}` but no vendored or built-in definition exists to patch.",
        meta.name,
    ))
    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
    .with_annotation(Annotation::primary(meta.span))
    .with_help(
        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
         check the function name and verify the patch still matches the upstream source.",
    )
}

fn orphan_patch_constant_diagnostic(meta: &ConstantMetadata) -> Issue {
    Issue::error(format!(
        "Patch declares constant `{}` but no vendored or built-in definition exists to patch.",
        meta.name,
    ))
    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
    .with_annotation(Annotation::primary(meta.span))
    .with_help(
        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
         check the constant name and verify the patch still matches the upstream source.",
    )
}

/// Determines which metadata value to keep when merging duplicates.
///
/// Priority:
///   1. user-defined > patch > built-in > other.
///   2. non-polyfill > polyfill — tools like rector/phpstan/psalm ship
///      skeleton stubs gated by `if (!class_exists('X'))` that should never
///      shadow a concrete definition.
///   3. smaller span wins as a deterministic tie-breaker.
///
/// Returns `true` if the new value should replace the existing one.
fn should_replace_metadata(
    existing_flags: MetadataFlags,
    existing_span: Span,
    new_flags: MetadataFlags,
    new_span: Span,
) -> bool {
    let new_is_user_defined = new_flags.is_user_defined();
    let existing_is_user_defined = existing_flags.is_user_defined();

    if new_is_user_defined != existing_is_user_defined {
        return new_is_user_defined;
    }

    let new_is_patch = new_flags.is_patch();
    let existing_is_patch = existing_flags.is_patch();

    if new_is_patch != existing_is_patch {
        return new_is_patch;
    }

    let new_is_built_in = new_flags.is_built_in();
    let existing_is_built_in = existing_flags.is_built_in();

    if new_is_built_in != existing_is_built_in {
        return new_is_built_in;
    }

    let new_is_polyfill = new_flags.is_polyfill();
    let existing_is_polyfill = existing_flags.is_polyfill();

    if new_is_polyfill != existing_is_polyfill {
        return !new_is_polyfill;
    }

    new_span < existing_span
}

#[cfg(test)]
mod should_replace_metadata_tests {
    use super::*;

    #[test]
    fn non_polyfill_replaces_polyfill() {
        let polyfill = MetadataFlags::POLYFILL;
        let real = MetadataFlags::empty();
        assert!(should_replace_metadata(polyfill, Span::dummy(0, 100), real, Span::dummy(0, 100)));
        assert!(!should_replace_metadata(real, Span::dummy(0, 100), polyfill, Span::dummy(0, 100)));
    }

    #[test]
    fn polyfill_does_not_replace_non_polyfill_even_with_smaller_span() {
        let real = MetadataFlags::empty();
        let polyfill = MetadataFlags::POLYFILL;
        assert!(!should_replace_metadata(real, Span::dummy(500, 600), polyfill, Span::dummy(0, 10)));
    }

    #[test]
    fn user_defined_beats_polyfill_flag() {
        let polyfill_user = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
        let plain = MetadataFlags::empty();
        assert!(!should_replace_metadata(polyfill_user, Span::dummy(0, 10), plain, Span::dummy(0, 10)));
        assert!(should_replace_metadata(plain, Span::dummy(0, 10), polyfill_user, Span::dummy(0, 10)));
    }

    #[test]
    fn two_user_defined_fall_through_to_polyfill_check() {
        let a = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
        let b = MetadataFlags::USER_DEFINED;
        assert!(should_replace_metadata(a, Span::dummy(0, 10), b, Span::dummy(0, 10)));
        assert!(!should_replace_metadata(b, Span::dummy(0, 10), a, Span::dummy(0, 10)));
    }

    #[test]
    fn two_non_polyfills_fall_through_to_priority_rules() {
        let user = MetadataFlags::USER_DEFINED;
        let builtin = MetadataFlags::BUILTIN;
        assert!(!should_replace_metadata(user, Span::dummy(0, 10), builtin, Span::dummy(0, 10)));
        assert!(should_replace_metadata(builtin, Span::dummy(0, 10), user, Span::dummy(0, 10)));
    }

    #[test]
    fn patch_beats_vendored() {
        let vendored = MetadataFlags::empty();
        let patch = MetadataFlags::PATCH;
        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), vendored, Span::dummy(0, 100)));
    }

    #[test]
    fn patch_beats_builtin() {
        let builtin = MetadataFlags::BUILTIN;
        let patch = MetadataFlags::PATCH;
        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), builtin, Span::dummy(0, 100)));
    }

    #[test]
    fn user_defined_beats_patch() {
        let user = MetadataFlags::USER_DEFINED;
        let patch = MetadataFlags::PATCH;
        assert!(!should_replace_metadata(user, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
        assert!(should_replace_metadata(patch, Span::dummy(0, 100), user, Span::dummy(0, 100)));
    }

    #[test]
    fn patch_does_not_beat_user_defined_even_with_smaller_span() {
        let user = MetadataFlags::USER_DEFINED;
        let patch = MetadataFlags::PATCH;
        assert!(!should_replace_metadata(user, Span::dummy(500, 600), patch, Span::dummy(0, 10)));
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn patch_function_like_leaves_vendor_owning_slot() {
        // Patches may only refine type information on an existing function-like; they must
        // never become the slot owner. The non-patch source's span/file id stay put so that
        // `extract_owned_keys` records vendor-as-owner — otherwise the patch's entry would
        // outlive a vendor deletion in incremental mode (orphan function-like bug).
        use crate::metadata::function_like::FunctionLikeKind;

        let name = word("foo");
        let key = (empty_word(), name);
        let vendor_span = Span::dummy(0, 100);
        let patch_span = Span::dummy(500, 600);

        let vendor =
            FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, vendor_span, MetadataFlags::empty());
        let mut codebase = CodebaseMetadata::new();
        codebase.function_likes.insert(key, vendor);

        let patch = FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, patch_span, MetadataFlags::PATCH);
        codebase.patch_function_likes.insert(key, patch);

        codebase.apply_patches_pass();

        let merged = codebase.function_likes.get(&key).expect("function-like must remain after patch");
        assert_eq!(merged.span, vendor_span, "patch must not move the slot's span");
        assert!(!merged.flags.is_patch(), "patch must not flip the slot's flags");
    }

    #[test]
    fn patch_does_not_apply_to_user_defined_class() {
        let class_name = word("MyClass");
        let method_existing = word("doIt");

        let mut user_class =
            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 100), None, MetadataFlags::USER_DEFINED);
        user_class.methods.insert(method_existing);

        let mut codebase = CodebaseMetadata::new();
        codebase.class_likes.insert(class_name, user_class);

        let mut patch_class =
            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 50), None, MetadataFlags::PATCH);
        let method_new = word("patchedMethod");
        patch_class.methods.insert(method_new);

        codebase.patch_class_likes.insert(class_name, patch_class);

        codebase.apply_patches_pass();

        let class = &codebase.class_likes[&class_name];
        // Patch must not apply to a user-defined class.
        assert!(!class.methods.contains(&method_new));
        // User-defined class must be preserved intact.
        assert!(class.methods.contains(&method_existing));
        assert!(class.flags.is_user_defined());
        // No issues should be emitted.
        assert!(class.issues.is_empty());
    }
}