mago-analyzer 1.26.0

A PHP static analyzer that can detect type errors in PHP code, and provide suggestions for fixing them.
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
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
use foldhash::HashMap;
use foldhash::HashSet;
use foldhash::fast::RandomState;
use indexmap::IndexMap;
use itertools::Itertools;

use mago_atom::Atom;
use mago_atom::ascii_lowercase_atom;
use mago_atom::atom;
use mago_codex::context::ScopeContext;

use mago_codex::metadata::CodebaseMetadata;
use mago_codex::metadata::class_like::ClassLikeMetadata;
use mago_codex::metadata::function_like::FunctionLikeMetadata;
use mago_codex::metadata::property::PropertyMetadata;
use mago_codex::misc::GenericParent;
use mago_codex::ttype::TType;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::generic::TGenericParameter;
use mago_codex::ttype::atomic::scalar::TScalar;
use mago_codex::ttype::atomic::scalar::class_like_string::TClassLikeString;
use mago_codex::ttype::comparator::ComparisonResult;
use mago_codex::ttype::comparator::union_comparator;
use mago_codex::ttype::expander::TypeExpansionOptions;
use mago_codex::ttype::expander::expand_union;
use mago_codex::ttype::template::GenericTemplate;
use mago_codex::ttype::template::TemplateResult;
use mago_codex::ttype::template::definition_type_replacer;
use mago_codex::ttype::template::definition_type_replacer::DefinitionReplacementOptions;
use mago_codex::ttype::template::inferred_type_replacer;
use mago_codex::ttype::union::TUnion;
use mago_codex::visibility::Visibility;
use mago_names::kind::NameKind;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::Class;
use mago_syntax::ast::ClassLikeMember;
use mago_syntax::ast::Enum;
use mago_syntax::ast::EnumCaseItem;
use mago_syntax::ast::Extends;
use mago_syntax::ast::Implements;
use mago_syntax::ast::Interface;
use mago_syntax::ast::Property;
use mago_syntax::ast::Trait;
use mago_syntax::ast::TraitUse;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;
use crate::plugin::context::HookContext;
use crate::statement::attributes::AttributeTarget;
use crate::statement::attributes::analyze_attributes;
use crate::statement::class_like::method_signature::SignatureCompatibilityIssue;
use crate::statement::function_like::report_undefined_type_references;
use crate::utils::missing_type_hints;

pub mod constant;
pub mod enum_case;
pub mod initialization;
pub mod method;
pub mod method_signature;
pub mod override_attribute;
pub mod property;
pub mod unused_members;

/// Reports a duplicate definition issue for class-like types.
fn report_duplicate_definition(
    context: &mut Context<'_, '_>,
    title: &str,
    kind: &str,
    name: &str,
    duplicate_span: Span,
    original_span: Span,
) {
    context.collector.report_with_code(
        IssueCode::DuplicateDefinition,
        Issue::error(format!("{title} `{name}` is already defined elsewhere."))
            .with_annotation(
                Annotation::primary(duplicate_span).with_message(format!("Duplicate {kind} definition here")),
            )
            .with_annotation(Annotation::secondary(original_span).with_message(format!("Original {kind} defined here")))
            .with_note("Each class, interface, trait, or enum must have a unique name within the same namespace.")
            .with_note("The duplicate definition will be ignored during analysis.")
            .with_help(
                "Consider using namespaces to avoid naming conflicts, or remove one of the duplicate definitions.",
            ),
    );
}

/// Helper function to check if a child type is compatible with (contained by) a parent type.
///
/// This is a convenience wrapper around `union_comparator::is_contained_by` with standard
/// settings for inheritance checks (no null/false ignoring, not inside assertion).
#[inline]
fn is_type_compatible(codebase: &CodebaseMetadata, child: &TUnion, parent: &TUnion) -> bool {
    union_comparator::is_contained_by(codebase, child, parent, false, false, false, &mut ComparisonResult::default())
}

/// Checks whether a child's property type violates the variance rules imposed by the parent.
///
/// - When the parent has only a `get` hook, covariance (declaring narrower than parent) is allowed.
/// - When the parent has only a `set` hook, contravariance (declaring wider than parent) is allowed.
/// - Otherwise, invariance is required.
///
/// Returns `true` when the declaring type is incompatible with the parent under these rules.
#[inline]
fn is_property_type_variance_invalid(
    codebase: &CodebaseMetadata,
    declaring_type: &TUnion,
    parent_type: &TUnion,
    parent_only_get: bool,
    parent_only_set: bool,
) -> bool {
    let declaring_is_subtype_of_parent = is_type_compatible(codebase, declaring_type, parent_type);
    let parent_is_subtype_of_declaring = is_type_compatible(codebase, parent_type, declaring_type);

    let declaring_is_narrower = declaring_is_subtype_of_parent && !parent_is_subtype_of_declaring;
    let declaring_is_wider = parent_is_subtype_of_declaring && !declaring_is_subtype_of_parent;

    (declaring_is_wider && !parent_only_set) || (declaring_is_narrower && !parent_only_get)
}

/// Represents different types of property conflicts between traits
#[derive(Debug)]
enum PropertyConflict {
    Visibility(Visibility, Visibility, Visibility, Visibility),
    Static(bool, bool),
    Readonly(bool, bool),
    Type(Option<String>, Option<String>),
    Default(Option<String>, Option<String>),
    HookedProperty,
}

impl PropertyConflict {
    fn describe(&self) -> String {
        match self {
            PropertyConflict::Visibility(r1, w1, r2, w2) => {
                let p1_vis = if r1 == w1 { r1.to_string() } else { format!("{r1} {w1}(set)") };
                let p2_vis = if r2 == w2 { r2.to_string() } else { format!("{r2} {w2}(set)") };
                format!("visibility differs ({p1_vis} vs {p2_vis})")
            }
            PropertyConflict::Static(s1, s2) => {
                let p1_mod = if *s1 { "static" } else { "instance" };
                let p2_mod = if *s2 { "static" } else { "instance" };
                format!("static modifier differs ({p1_mod} vs {p2_mod})")
            }
            PropertyConflict::Readonly(r1, r2) => {
                let p1_mod = if *r1 { "readonly" } else { "not readonly" };
                let p2_mod = if *r2 { "readonly" } else { "not readonly" };
                format!("readonly modifier differs ({p1_mod} vs {p2_mod})")
            }
            PropertyConflict::Type(t1, t2) => match (t1, t2) {
                (Some(type1), Some(type2)) => format!("type declaration differs ({type1} vs {type2})"),
                (Some(type1), None) => format!("type declaration differs ({type1} vs untyped)"),
                (None, Some(type2)) => format!("type declaration differs (untyped vs {type2})"),
                #[allow(clippy::unreachable)]
                (None, None) => unreachable!(),
            },
            PropertyConflict::Default(d1, d2) => match (d1, d2) {
                (Some(def1), Some(def2)) => format!("default value differs ({def1} vs {def2})"),
                (Some(def1), None) => format!("default value differs ({def1} vs no default)"),
                (None, Some(def2)) => format!("default value differs (no default vs {def2})"),
                #[allow(clippy::unreachable)]
                (None, None) => unreachable!(),
            },
            PropertyConflict::HookedProperty => {
                "conflict resolution between hooked properties is not supported".to_string()
            }
        }
    }

    fn get_issue_code(&self) -> IssueCode {
        match self {
            PropertyConflict::Visibility(_, _, _, _) => IssueCode::IncompatiblePropertyVisibility,
            PropertyConflict::Static(_, _) => IssueCode::IncompatiblePropertyStatic,
            PropertyConflict::Readonly(_, _) => IssueCode::IncompatiblePropertyReadonly,
            PropertyConflict::Type(_, _) => IssueCode::IncompatiblePropertyType,
            PropertyConflict::Default(_, _) => IssueCode::IncompatiblePropertyDefault,
            PropertyConflict::HookedProperty => IssueCode::IncompatiblePropertyOverride,
        }
    }
}

/// Checks if a type union contains a reference to a specific template parameter.
fn type_contains_template_param(type_union: &TUnion, param_name: Atom, defining_class: Atom) -> bool {
    use mago_codex::ttype::TypeRef;

    type_union.types.iter().any(|atomic| {
        if let TAtomic::GenericParameter(TGenericParameter {
            parameter_name,
            defining_entity: GenericParent::ClassLike(class_name),
            ..
        }) = atomic
            && *parameter_name == param_name
            && *class_name == defining_class
        {
            return true;
        }

        if let TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic {
            parameter_name,
            defining_entity: GenericParent::ClassLike(class_name),
            ..
        })) = atomic
            && *parameter_name == param_name
            && *class_name == defining_class
        {
            return true;
        }

        atomic.get_all_child_nodes().iter().any(|node| match node {
            TypeRef::Atomic(TAtomic::GenericParameter(gp)) => {
                gp.parameter_name == param_name
                    && matches!(gp.defining_entity, GenericParent::ClassLike(c) if c == defining_class)
            }
            TypeRef::Atomic(TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic {
                parameter_name,
                defining_entity,
                ..
            }))) => {
                *parameter_name == param_name
                    && matches!(defining_entity, GenericParent::ClassLike(c) if *c == defining_class)
            }
            TypeRef::Union(u) => type_contains_template_param(u, param_name, defining_class),
            _ => false,
        })
    })
}

/// Checks for unused template parameters in a class-like declaration.
///
/// A template parameter is considered "used" if it appears in:
/// - A property type
/// - A method parameter type
/// - A method return type
/// - An `@extends`, `@implements`, or `@use` annotation
fn check_unused_template_parameters<'ctx>(
    context: &mut Context<'ctx, '_>,
    class_like_metadata: &'ctx ClassLikeMetadata,
) {
    if !context.settings.find_unused_definitions {
        return;
    }

    if class_like_metadata.template_types.is_empty() {
        return;
    }

    let class_name = class_like_metadata.name;
    let class_original_name = class_like_metadata.original_name;
    let class_kind_str = class_like_metadata.kind.as_str();
    let class_name_span = class_like_metadata.name_span.unwrap_or(class_like_metadata.span);

    for (template_name, _) in &class_like_metadata.template_types {
        if template_name.as_str().starts_with('_') {
            continue;
        }

        let mut is_used = false;

        for extended_params in class_like_metadata.template_extended_parameters.values() {
            for (_param_name, param_type) in extended_params {
                if type_contains_template_param(param_type, *template_name, class_name) {
                    is_used = true;
                    break;
                }
            }

            if is_used {
                break;
            }
        }

        if is_used {
            continue;
        }

        for property_metadata in class_like_metadata.properties.values() {
            if let Some(type_metadata) = &property_metadata.type_metadata
                && type_contains_template_param(&type_metadata.type_union, *template_name, class_name)
            {
                is_used = true;
                break;
            }
        }

        if is_used {
            continue;
        }

        for method_id in class_like_metadata.declaring_method_ids.values() {
            let Some(function_like) =
                context.codebase.get_method(&method_id.get_class_name(), &method_id.get_method_name())
            else {
                continue;
            };

            // Check parameters
            for param in &function_like.parameters {
                if let Some(type_metadata) = &param.type_metadata
                    && type_contains_template_param(&type_metadata.type_union, *template_name, class_name)
                {
                    is_used = true;
                    break;
                }
            }

            if is_used {
                break;
            }

            // Check return type
            if let Some(return_type_metadata) = &function_like.return_type_metadata
                && type_contains_template_param(&return_type_metadata.type_union, *template_name, class_name)
            {
                is_used = true;
                break;
            }
        }

        if is_used {
            continue;
        }

        // Report warning if template parameter is unused
        context.collector.report_with_code(
            IssueCode::UnusedTemplateParameter,
            Issue::warning(format!(
                "Template parameter `{template_name}` is never used in {class_kind_str} `{class_original_name}`."
            ))
            .with_annotation(
                Annotation::primary(class_name_span)
                    .with_message(format!("Template `{template_name}` is defined on this {class_kind_str} but never referenced")),
            )
            .with_help(format!(
                "Remove the unused `@template {template_name}` from the docblock, or use it in a property, method signature, or inherited type."
            )),
        );
    }
}

impl<'ast, 'arena> Analyzable<'ast, 'arena> for Class<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_attributes(
            context,
            block_context,
            artifacts,
            self.attribute_lists.as_slice(),
            AttributeTarget::ClassLike,
        );

        let name = context.resolved_names.get(&self.name);
        let Some(class_like_metadata) = context.codebase.get_class_like(name) else {
            tracing::warn!("Class {} not found in codebase", name);

            return Ok(());
        };

        if class_like_metadata.span != self.span() {
            report_duplicate_definition(context, "Class", "class", name, self.span(), class_like_metadata.span);
            return Ok(());
        }

        // Call plugin on_enter_class hooks
        if context.plugin_registry.has_class_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_enter_class(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        analyze_class_like(
            context,
            artifacts,
            Some(self.name.span),
            self.span(),
            self.extends.as_ref(),
            self.implements.as_ref(),
            class_like_metadata,
            self.members.as_slice(),
        )?;

        if context.settings.enforce_class_finality
            && !class_like_metadata.flags.is_final()
            && !class_like_metadata.flags.is_abstract()
            && !class_like_metadata.flags.is_public_api()
            && class_like_metadata.child_class_likes.as_ref().is_none_or(|children| children.is_empty())
        {
            context.collector.report_with_code(
                IssueCode::ClassMustBeFinal,
                Issue::warning(format!("Class `{}` should be declared `final`.", class_like_metadata.original_name))
                    .with_annotation(
                        Annotation::primary(self.name.span)
                            .with_message("This class is not `final`, `abstract`, or marked with `@api`."),
                    )
                    .with_help(
                        "Declare the class as `final` to prevent inheritance, as `abstract` if it is meant to be extended, or add the `@api` tag to its docblock if backward compatibility must be preserved.",
                    ),
            );
        }

        if context.settings.require_api_or_internal
            && class_like_metadata.flags.is_abstract()
            && !class_like_metadata.flags.is_public_api()
            && !class_like_metadata.flags.is_internal()
        {
            context.collector.report_with_code(
                IssueCode::MissingApiOrInternal,
                Issue::warning(format!(
                    "Abstract class `{}` is missing an `@api` or `@internal` annotation.",
                    class_like_metadata.original_name,
                ))
                .with_annotation(
                    Annotation::primary(self.name.span)
                        .with_message("This abstract class does not declare its extensibility intent."),
                )
                .with_help(
                    "Add `@api` to indicate the class is part of the public API and may be extended by consumers, or `@internal` to indicate it is for internal use only.",
                ),
            );
        }

        if context.settings.check_missing_override {
            override_attribute::check_override_attribute(class_like_metadata, self.members.as_slice(), context);
        }

        let should_check_unused = 'check_unused: {
            if !context.settings.find_unused_definitions {
                break 'check_unused false;
            }

            if !context.settings.diff {
                break 'check_unused true;
            }

            if context.codebase.safe_symbols.contains(&class_like_metadata.name) {
                break 'check_unused false;
            }

            true
        };

        if should_check_unused {
            let unused_members = unused_members::check_unused_members_with_transitivity(
                class_like_metadata.name,
                self.span(),
                class_like_metadata,
                &artifacts.symbol_references,
                context,
            );

            unused_members::check_write_only_properties(
                class_like_metadata.name,
                self.span(),
                class_like_metadata,
                &artifacts.symbol_references,
                &unused_members,
                context,
            );
        }

        // Call plugin on_leave_class hooks
        if context.plugin_registry.has_class_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_leave_class(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        Ok(())
    }
}

impl<'ast, 'arena> Analyzable<'ast, 'arena> for Interface<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_attributes(
            context,
            block_context,
            artifacts,
            self.attribute_lists.as_slice(),
            AttributeTarget::ClassLike,
        );

        let name = context.resolved_names.get(&self.name);
        let Some(class_like_metadata) = context.codebase.get_class_like(name) else {
            tracing::warn!("Interface {name} not found in codebase");

            return Ok(());
        };

        if class_like_metadata.span != self.span() {
            report_duplicate_definition(context, "Interface", "interface", name, self.span(), class_like_metadata.span);
            return Ok(());
        }

        // Call plugin on_enter_interface hooks
        if context.plugin_registry.has_interface_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_enter_interface(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        analyze_class_like(
            context,
            artifacts,
            Some(self.name.span),
            self.span(),
            self.extends.as_ref(),
            None,
            class_like_metadata,
            self.members.as_slice(),
        )?;

        if context.settings.require_api_or_internal
            && !class_like_metadata.flags.is_public_api()
            && !class_like_metadata.flags.is_internal()
        {
            context.collector.report_with_code(
                IssueCode::MissingApiOrInternal,
                Issue::warning(format!(
                    "Interface `{}` is missing an `@api` or `@internal` annotation.",
                    class_like_metadata.original_name,
                ))
                .with_annotation(
                    Annotation::primary(self.name.span)
                        .with_message("This interface does not declare its extensibility intent."),
                )
                .with_help(
                    "Add `@api` to indicate the interface is part of the public API and may be implemented by consumers, or `@internal` to indicate it is for internal use only.",
                ),
            );
        }

        if context.settings.check_missing_override {
            override_attribute::check_override_attribute(class_like_metadata, self.members.as_slice(), context);
        }

        // Call plugin on_leave_interface hooks
        if context.plugin_registry.has_interface_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_leave_interface(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        Ok(())
    }
}

impl<'ast, 'arena> Analyzable<'ast, 'arena> for Trait<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_attributes(
            context,
            block_context,
            artifacts,
            self.attribute_lists.as_slice(),
            AttributeTarget::ClassLike,
        );

        let name = context.resolved_names.get(&self.name);
        let Some(class_like_metadata) = context.codebase.get_class_like(name) else {
            tracing::warn!("Trait {} not found in codebase", name);

            return Ok(());
        };

        if class_like_metadata.span != self.span() {
            report_duplicate_definition(context, "Trait", "trait", name, self.span(), class_like_metadata.span);
            return Ok(());
        }

        // Call plugin on_enter_trait hooks
        if context.plugin_registry.has_trait_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_enter_trait(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        analyze_class_like(
            context,
            artifacts,
            Some(self.name.span),
            self.span(),
            None,
            None,
            class_like_metadata,
            self.members.as_slice(),
        )?;

        if context.settings.require_api_or_internal
            && !class_like_metadata.flags.is_public_api()
            && !class_like_metadata.flags.is_internal()
        {
            context.collector.report_with_code(
                IssueCode::MissingApiOrInternal,
                Issue::warning(format!(
                    "Trait `{}` is missing an `@api` or `@internal` annotation.",
                    class_like_metadata.original_name,
                ))
                .with_annotation(
                    Annotation::primary(self.name.span)
                        .with_message("This trait does not declare its extensibility intent."),
                )
                .with_help(
                    "Add `@api` to indicate the trait is part of the public API and may be used by consumers, or `@internal` to indicate it is for internal use only.",
                ),
            );
        }

        if context.settings.check_missing_override {
            override_attribute::check_override_attribute(class_like_metadata, self.members.as_slice(), context);
        }

        // Call plugin on_leave_trait hooks
        if context.plugin_registry.has_trait_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_leave_trait(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        Ok(())
    }
}

impl<'ast, 'arena> Analyzable<'ast, 'arena> for Enum<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_attributes(
            context,
            block_context,
            artifacts,
            self.attribute_lists.as_slice(),
            AttributeTarget::ClassLike,
        );

        let name = context.resolved_names.get(&self.name);
        let Some(class_like_metadata) = context.codebase.get_class_like(name) else {
            tracing::warn!("Enum {} not found in codebase", name);

            return Ok(());
        };

        if class_like_metadata.span != self.span() {
            report_duplicate_definition(context, "Enum", "enum", name, self.span(), class_like_metadata.span);
            return Ok(());
        }

        // Call plugin on_enter_enum hooks
        if context.plugin_registry.has_enum_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_enter_enum(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        analyze_class_like(
            context,
            artifacts,
            Some(self.name.span),
            self.span(),
            None,
            self.implements.as_ref(),
            class_like_metadata,
            self.members.as_slice(),
        )?;

        check_duplicate_enum_case_values(context, artifacts, name, self);

        if context.settings.check_missing_override {
            override_attribute::check_override_attribute(class_like_metadata, self.members.as_slice(), context);
        }

        if context.settings.find_unused_definitions {
            unused_members::check_unused_members_with_transitivity(
                class_like_metadata.name,
                self.span(),
                class_like_metadata,
                &artifacts.symbol_references,
                context,
            );
        }

        // Call plugin on_leave_enum hooks
        if context.plugin_registry.has_enum_hooks() {
            let mut hook_context = HookContext::new(context.codebase, block_context, artifacts);
            context.plugin_registry.on_leave_enum(self, class_like_metadata, &mut hook_context)?;
            for reported in hook_context.take_issues() {
                context.collector.report_with_code(reported.code, reported.issue);
            }
        }

        Ok(())
    }
}

fn check_duplicate_enum_case_values<'arena>(
    context: &mut Context<'_, 'arena>,
    artifacts: &AnalysisArtifacts,
    enum_name: &str,
    r#enum: &Enum<'arena>,
) {
    let mut seen: Vec<(Atom, &str, Span)> = Vec::new();

    for member in &r#enum.members {
        let ClassLikeMember::EnumCase(case) = member else {
            continue;
        };

        let EnumCaseItem::Backed(item) = &case.item else {
            continue;
        };

        let case_name = item.name.value;

        let Some(value_type) = artifacts.get_expression_type(item.value) else {
            continue;
        };

        if !value_type.is_single() {
            continue;
        }

        let atomic = value_type.get_single();
        let is_literal = match atomic {
            TAtomic::Scalar(s) => s.is_literal_value(),
            _ => false,
        };

        if !is_literal {
            continue;
        }

        let value_id = value_type.get_id();
        let value_span = item.value.span();

        if let Some((_, prev_case_name, prev_span)) = seen.iter().find(|(id, _, _)| *id == value_id) {
            context.collector.report_with_code(
                IssueCode::DuplicateEnumCaseValue,
                Issue::error(format!(
                    "Duplicate value in enum `{enum_name}`: case `{case_name}` has the same value as case `{prev_case_name}`."
                ))
                .with_annotation(
                    Annotation::primary(value_span).with_message("This value is a duplicate"),
                )
                .with_annotation(
                    Annotation::secondary(*prev_span)
                        .with_message(format!("Case `{prev_case_name}` already uses this value")),
                )
                .with_help("Each case in a backed enum must have a unique value."),
            );
        } else {
            seen.push((value_id, case_name, value_span));
        }
    }
}

pub(crate) fn analyze_class_like<'ctx, 'ast, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    artifacts: &mut AnalysisArtifacts,
    name_span: Option<Span>,
    declaration_span: Span,
    extends_ast: Option<&'ast Extends<'arena>>,
    implements_ast: Option<&'ast Implements<'arena>>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    members: &'ast [ClassLikeMember<'arena>],
) -> Result<(), AnalysisError> {
    if context.settings.diff && context.codebase.safe_symbols.contains(&class_like_metadata.name) {
        return Ok(());
    }

    for parent_class in &class_like_metadata.all_parent_classes {
        artifacts.symbol_references.add_symbol_reference_to_symbol(class_like_metadata.name, *parent_class, true);
    }

    for parent_interface in &class_like_metadata.all_parent_interfaces {
        artifacts.symbol_references.add_symbol_reference_to_symbol(class_like_metadata.name, *parent_interface, true);
    }

    for trait_name in &class_like_metadata.used_traits {
        artifacts.symbol_references.add_symbol_reference_to_symbol(class_like_metadata.name, *trait_name, true);
    }

    if class_like_metadata.flags.is_unchecked() {
        return Ok(());
    }

    let name = &class_like_metadata.original_name;

    let mut checked_signatures: HashSet<(Atom, Atom)> = HashSet::default();

    check_class_like_extends(context, class_like_metadata, extends_ast);
    check_class_like_implements(context, class_like_metadata, implements_ast, &mut checked_signatures);

    for member in members {
        if let ClassLikeMember::TraitUse(used_trait) = member {
            check_class_like_use(context, class_like_metadata, used_trait);
        }
    }

    if !class_like_metadata.invalid_dependencies.is_empty() {
        return Ok(());
    }

    if !class_like_metadata.kind.is_trait() && !class_like_metadata.flags.is_abstract() {
        for (method_name, method_id) in &class_like_metadata.declaring_method_ids {
            if class_like_metadata.kind.is_enum() {
                if method_name.eq_ignore_ascii_case("cases") {
                    continue;
                }

                if class_like_metadata.enum_type.is_some()
                    && (method_name.eq_ignore_ascii_case("from") || method_name.eq_ignore_ascii_case("tryFrom"))
                {
                    continue;
                }
            }

            let Some(declaring_class_like_metadata) = context.codebase.get_class_like(&method_id.get_class_name())
            else {
                continue;
            };

            let Some(function_like) =
                context.codebase.get_method(&method_id.get_class_name(), &method_id.get_method_name())
            else {
                continue;
            };

            let Some(method_metadata) = function_like.method_metadata.as_ref() else {
                continue;
            };

            if method_metadata.is_abstract {
                let fqcn = declaring_class_like_metadata.original_name;
                let method_span = function_like.name_span.unwrap_or(function_like.span);

                context.collector.report_with_code(
                    IssueCode::UnimplementedAbstractMethod,
                    Issue::error(format!(
                        "Class `{name}` does not implement the abstract method `{method_name}`.",
                    ))
                    .with_annotation(
                        Annotation::primary(name_span.unwrap_or(declaration_span))
                            .with_message(format!("`{name}` is not abstract and must implement this method")),
                    )
                    .with_annotation(
                        Annotation::secondary(method_span).with_message(
                            format!("`{fqcn}::{method_name}` is defined as abstract here")
                        ),
                    )
                    .with_note("When a concrete class extends an abstract class or implements an interface, it must provide an implementation for all inherited abstract methods.".to_string())
                    .with_help(format!(
                        "You can either implement the `{method_name}` method in `{name}`, or declare `{name}` as an abstract class.",
                    )),
                );
            }
        }

        for property_name in class_like_metadata.declaring_property_ids.keys() {
            let current_property = class_like_metadata.properties.get(property_name);

            for parent_fqcn in class_like_metadata
                .all_parent_classes
                .iter()
                .chain(class_like_metadata.all_parent_interfaces.iter())
                .chain(class_like_metadata.used_traits.iter())
            {
                let Some(parent_metadata) = context.codebase.get_class_like(parent_fqcn) else {
                    continue;
                };

                let Some(parent_property) = parent_metadata.properties.get(property_name) else {
                    continue;
                };

                for (hook_name, hook_metadata) in &parent_property.hooks {
                    if !hook_metadata.is_abstract {
                        continue;
                    }

                    let is_implemented = current_property
                        .map(|p| {
                            if p.hooks.is_empty() {
                                !p.flags.is_virtual_property()
                            } else {
                                // Property has hooks - check if the specific hook is implemented
                                if p.hooks.get(hook_name).is_some_and(|h| !h.is_abstract) {
                                    return true;
                                }

                                p.hooks.values().any(|h| !h.is_abstract)
                            }
                        })
                        .unwrap_or_else(|| {
                            let mut all_parent_class = class_like_metadata
                                .all_parent_classes
                                .iter()
                                .chain(class_like_metadata.used_traits.iter());

                            all_parent_class.any(|parent_class_fqcn| {
                                context
                                    .codebase
                                    .get_class_like(parent_class_fqcn)
                                    .and_then(|parent| parent.properties.get(property_name))
                                    .is_some_and(|prop| {
                                        if prop.hooks.get(hook_name).is_some_and(|h| !h.is_abstract) {
                                            return true;
                                        }

                                        !prop.flags.is_virtual_property() || prop.hooks.values().any(|h| !h.is_abstract)
                                    })
                            })
                        });

                    if !is_implemented {
                        let fqcn = parent_metadata.original_name;
                        let hook_span = hook_metadata.span;

                        context.collector.report_with_code(
                            IssueCode::UnimplementedAbstractPropertyHook,
                            Issue::error(format!(
                                "Class `{name}` does not implement the abstract property hook `{property_name}::{hook_name}()`.",
                            ))
                            .with_annotation(
                                Annotation::primary(name_span.unwrap_or(declaration_span))
                                    .with_message(format!("`{name}` is not abstract and must implement this hook")),
                            )
                            .with_annotation(
                                Annotation::secondary(hook_span).with_message(
                                    format!("`{fqcn}::{property_name}::{hook_name}()` is defined as abstract here")
                                ),
                            )
                            .with_note("When a concrete class extends an abstract class or implements an interface, it must provide an implementation for all inherited abstract property hooks.".to_string())
                            .with_help(format!(
                                "You can either implement the `{hook_name}` hook for property `{property_name}` in `{name}`, or declare `{name}` as an abstract class.",
                            )),
                        );
                    }
                }
            }
        }
    }

    if !class_like_metadata.kind.is_trait() {
        check_abstract_method_signatures(context, class_like_metadata, &mut checked_signatures);
        check_trait_method_conflicts(context, class_like_metadata, members);
    }

    check_trait_property_conflicts(context, class_like_metadata, members);
    check_readonly_class_trait_properties(context, class_like_metadata, members);

    if !class_like_metadata.template_types.is_empty() {
        for (template_name, _) in &class_like_metadata.template_types {
            let (resolved_template_name, _) = context.scope.resolve(NameKind::Default, template_name);
            if let Some(conflicting_class) = context.codebase.get_class_like(&resolved_template_name) {
                let conflicting_name = &conflicting_class.name;
                let conflicting_class_span = conflicting_class.name_span.unwrap_or(conflicting_class.span);

                context.collector.report_with_code(
                    IssueCode::NameAlreadyInUse,
                    Issue::error(format!(
                        "In class `{name}`, the template parameter `{template_name}` conflicts with an existing class.",
                    ))
                    .with_annotation(
                        Annotation::primary(name_span.unwrap_or(declaration_span))
                            .with_message("The docblock for this class defines the conflicting template parameter"),
                    )
                    .with_annotation(
                        Annotation::secondary(conflicting_class_span)
                            .with_message(format!("The conflicting type `{conflicting_name}` is defined here")),
                    )
                    .with_note("Template parameter names (from `@template`) must not conflict with existing classes, interfaces, enums, or traits in the same scope.")
                    .with_help(format!(
                        "In the docblock for the `{name}` type, rename the `@template {template_name}` parameter to avoid this naming collision.",
                    )),
                );
            }
        }
    }

    check_unused_template_parameters(context, class_like_metadata);
    check_class_like_properties(context, class_like_metadata);

    let mut scope = ScopeContext::new();
    scope.set_class_like(Some(class_like_metadata));
    scope.set_static(true);

    let mut block_context = BlockContext::new(scope, context.settings.register_super_globals);

    for member in members {
        match member {
            ClassLikeMember::Constant(class_like_constant) => {
                if context.settings.diff
                    && let Some(item) = class_like_constant.items.first()
                {
                    let constant_name = atom(item.name.value);
                    if context.codebase.safe_symbol_members.contains(&(class_like_metadata.name, constant_name)) {
                        continue;
                    }
                }

                missing_type_hints::check_constant_type_hint(context, class_like_constant);

                class_like_constant.analyze(context, &mut block_context, artifacts)?;
            }
            ClassLikeMember::Property(property) => {
                if context.settings.diff {
                    let first_var_name = match property {
                        Property::Plain(plain) => plain.items.first().map(|item| atom(item.variable().name)),
                        Property::Hooked(hooked) => Some(atom(hooked.item.variable().name)),
                    };

                    if let Some(var_name) = first_var_name
                        && context.codebase.safe_symbol_members.contains(&(class_like_metadata.name, var_name))
                    {
                        continue;
                    }
                }

                missing_type_hints::check_property_type_hint(context, class_like_metadata, property);

                // Check for imprecise type hints (bare `array` or `iterable`)
                let first_property_name = match property {
                    Property::Plain(plain) => plain.items.first().map(|item| atom(item.variable().name)),
                    Property::Hooked(hooked) => Some(atom(hooked.item.variable().name)),
                };

                let prop_meta = first_property_name.and_then(|name| class_like_metadata.properties.get(&name));
                missing_type_hints::check_imprecise_property_type_hint(context, property, prop_meta);

                let property_names: Vec<Atom> = match property {
                    Property::Plain(plain) => plain.items.iter().map(|item| atom(item.variable().name)).collect(),
                    Property::Hooked(hooked) => {
                        vec![atom(hooked.item.variable().name)]
                    }
                };

                for property_name in property_names {
                    if let Some(prop_meta) = class_like_metadata.properties.get(&property_name)
                        && let Some(type_meta) = &prop_meta.type_metadata
                    {
                        report_undefined_type_references(context, type_meta);

                        if type_meta.from_docblock
                            && let Some(type_decl_meta) = &prop_meta.type_declaration_metadata
                        {
                            report_undefined_type_references(context, type_decl_meta);
                        }
                    }
                }

                property.analyze(context, &mut block_context, artifacts)?;
            }
            ClassLikeMember::EnumCase(enum_case) => {
                if context.settings.diff {
                    let case_name = atom(enum_case.item.name().value);
                    if context.codebase.safe_symbol_members.contains(&(class_like_metadata.name, case_name)) {
                        continue;
                    }
                }

                enum_case.analyze(context, &mut block_context, artifacts)?;
            }
            ClassLikeMember::Method(method) => {
                method.analyze(context, &mut block_context, artifacts)?;
            }
            _ => {}
        }
    }

    // Check trait constant overrides AFTER constants have been analyzed
    // so we can compare their inferred values
    check_class_like_constants(context, class_like_metadata, members);

    initialization::check_property_initialization(context, artifacts, class_like_metadata, declaration_span, name_span);

    Ok(())
}

#[allow(clippy::unwrap_used)]
fn check_class_like_extends<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    extends_ast: Option<&Extends<'arena>>,
) {
    // This check only applies to classes and interfaces, which can use `extends`.
    if !class_like_metadata.kind.is_class() && !class_like_metadata.kind.is_interface() {
        return;
    }

    let Some(extends) = extends_ast else {
        return;
    };

    let using_kind_str = class_like_metadata.kind.as_str();
    let using_kind_capitalized =
        format!("{}{}", using_kind_str.chars().next().unwrap().to_uppercase(), &using_kind_str[1..]);
    let using_name = class_like_metadata.original_name;
    let using_class_span = class_like_metadata.name_span.unwrap_or(class_like_metadata.span);

    for extended_type in &extends.types {
        let extended_type_str = context.resolved_names.get(&extended_type);
        let extended_class_metadata = context.codebase.get_class_like(extended_type_str);

        // Case: The extended type does not exist.
        let Some(extended_class_metadata) = extended_class_metadata else {
            let extended_name = extended_type.value();

            context.collector.report_with_code(
                IssueCode::NonExistentClassLike,
                Issue::error(format!("{using_kind_capitalized} `{using_name}` cannot extend unknown type `{extended_name}`"))
                    .with_annotation(Annotation::primary(extended_type.span()).with_message("This type could not be found"))
                    .with_note("Mago could not find a definition for this class, interface, or trait.")
                    .with_help("Ensure the name is correct, including its namespace, and that it is properly defined and autoloadable."),
            );
            continue;
        };

        let extended_name = extended_class_metadata.original_name;
        let extended_kind_str = extended_class_metadata.kind.as_str();
        let extended_kind_prefix =
            if extended_class_metadata.kind.is_class() || extended_class_metadata.kind.is_trait() { "a" } else { "an" };
        let extended_class_span = extended_class_metadata.name_span.unwrap_or(extended_class_metadata.span);

        if extended_class_metadata.flags.is_deprecated() {
            context.collector.report_with_code(
                IssueCode::DeprecatedClass,
                Issue::warning(format!("Use of deprecated class `{extended_name}` in `extends` clause"))
                    .with_annotation(Annotation::primary(extended_type.span()).with_message("This class is marked as deprecated"))
                    .with_annotation(Annotation::secondary(extended_class_span).with_message(format!("`{extended_name}` was marked deprecated here")))
                    .with_note("The parent type is deprecated and may be removed in a future version, which would break this child type.")
                    .with_help("Consider refactoring to avoid extending this type, or consult its documentation for alternatives."),
            );
        }

        if context.settings.check_experimental
            && extended_class_metadata.flags.is_experimental()
            && !class_like_metadata.flags.is_experimental()
        {
            context.collector.report_with_code(
                IssueCode::ExperimentalUsage,
                Issue::warning(format!("Usage of experimental class-like `{extended_name}`."))
                    .with_annotation(
                        Annotation::primary(extended_type.span())
                            .with_message(format!("`{extended_name}` is marked as `@experimental`.")),
                    )
                    .with_note("Experimental APIs may change or be removed without notice.")
                    .with_help("Mark the current class as `@experimental` to suppress this warning."),
            );
        }

        if class_like_metadata.kind.is_interface() {
            if !extended_class_metadata.kind.is_interface() {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Interface `{using_name}` cannot extend non-interface type `{extended_name}`"))
                        .with_annotation(Annotation::primary(extended_type.span())
                            .with_message(format!("...because it is {extended_kind_prefix} {extended_kind_str}, not an interface")))
                        .with_annotation(Annotation::secondary(extended_class_span)
                            .with_message(format!("`{extended_name}` is defined as {extended_kind_prefix} {extended_kind_str} here")))
                        .with_note("In PHP, an interface can only extend other interfaces.")
                        .with_help(format!("To resolve this, change `{extended_name}` to be an interface, or change `{using_name}` to a class if you intended to extend a class.")),
                );

                continue;
            }

            if extended_class_metadata.flags.is_enum_interface() && !class_like_metadata.flags.is_enum_interface() {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Interface `{using_name}` cannot extend enum-interface `{extended_name}`"))
                        .with_annotation(Annotation::primary(using_class_span).with_message("This interface is not an `@enum-interface`..."))
                        .with_annotation(Annotation::secondary(extended_type.span()).with_message("...but it extends an `@enum-interface`"))
                        .with_note("An interface marked with `@enum-interface` can only be extended by other interfaces that are also marked with `@enum-interface`.")
                        .with_help(format!("To resolve this, add the `@enum-interface` PHPDoc tag to `{using_name}`, or extend a regular, non-enum interface.")),
                );
            }
        }

        if class_like_metadata.kind.is_class() {
            if !extended_class_metadata.kind.is_class() {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Class `{using_name}` cannot extend non-class type `{extended_name}`"))
                        .with_annotation(Annotation::primary(extended_type.span()).with_message(format!(
                            "...because it is {extended_kind_prefix} {extended_kind_str}, not a class"
                        )))
                        .with_annotation(Annotation::secondary(extended_class_span).with_message(format!(
                            "`{extended_name}` is defined as {extended_kind_prefix} {extended_kind_str} here"
                        )))
                        .with_note("In PHP, a class can only extend another class.")
                        .with_help("To inherit from an interface, use `implements`. To use a trait, use `use`."),
                );

                continue;
            }

            if extended_class_metadata.flags.is_final() {
                context.collector.report_with_code(
                    IssueCode::ExtendFinalClass,
                    Issue::error(format!("Class `{using_name}` cannot extend final class `{extended_name}`"))
                        .with_annotation(Annotation::primary(extended_type.span()).with_message("This inheritance is not allowed"))
                        .with_annotation(Annotation::secondary(extended_class_span).with_message(format!("`{extended_name}` is declared 'final' here")))
                        .with_note("A class marked as `final` cannot be extended by any other class.")
                        .with_help(format!("To resolve this, either remove the `final` keyword from `{extended_name}`, or choose a different class to extend.")),
                );
            }

            if extended_class_metadata.flags.is_readonly() && !class_like_metadata.flags.is_readonly() {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Non-readonly class `{using_name}` cannot extend readonly class `{extended_name}`"))
                        .with_annotation(Annotation::primary(using_class_span).with_message("This class is not `readonly`..."))
                        .with_annotation(Annotation::secondary(extended_class_span).with_message(format!("...but it extends `{extended_name}`, which is `readonly`")))
                        .with_note("A `readonly` class can only be extended by another `readonly` class.")
                        .with_help(format!("To resolve this, either make the `{using_name}` class `readonly`, or extend a different, non-readonly class.")),
                );
            } else if !extended_class_metadata.flags.is_readonly() && class_like_metadata.flags.is_readonly() {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Readonly class `{using_name}` cannot extend non-readonly class `{extended_name}`"))
                        .with_annotation(Annotation::primary(using_class_span).with_message("This class is `readonly`..."))
                        .with_annotation(Annotation::secondary(extended_class_span).with_message(format!("...but it extends `{extended_name}`, which is not `readonly`")))
                        .with_note("A non-`readonly` class can only be extended by another non-`readonly` class.")
                        .with_help(format!("To resolve this, either make the `{using_name}` class non-`readonly`, or extend a different, readonly class.")),
                );
            } else {
                // readonly status matches between parent and child; no inheritance error
            }

            if let Some(required_interface) =
                class_like_metadata.get_missing_required_interface(extended_class_metadata)
            {
                context.collector.report_with_code(
                    IssueCode::MissingRequiredInterface,
                    Issue::error(format!("Class `{using_name}` must implement required interface `{required_interface}`"))
                        .with_annotation(Annotation::primary(using_class_span).with_message(format!("...because its parent `{extended_name}` requires it")))
                        .with_annotation(Annotation::secondary(extended_class_span).with_message("Requirement declared here (likely via `@require-implements`)"))
                        .with_note("When a class uses `@require-implements`, all of its concrete child classes must implement the specified interface.")
                        .with_help(format!("Add `implements {required_interface}` to the `{using_name}` definition, or declare `{using_name}` as `abstract`.")),
                );
            }

            if !class_like_metadata.is_permitted_to_inherit(extended_class_metadata) {
                context.collector.report_with_code(
                    IssueCode::InvalidExtend,
                    Issue::error(format!("Class `{using_name}` is not permitted to extend `{extended_name}`"))
                        .with_annotation(Annotation::primary(extended_type.span()).with_message("This inheritance is restricted"))
                        .with_annotation(Annotation::secondary(extended_class_span)
                            .with_message(format!("The `@inheritors` annotation on this class does not include `{using_name}`")))
                        .with_note("The `@inheritors` annotation on a class or interface restricts which types are allowed to extend it.")
                        .with_help(format!("To allow this, add `{using_name}` to the list in the `@inheritors` PHPDoc tag for `{extended_name}`.")),
                );
            }

            let actual_parameters_count = class_like_metadata
                .template_type_extends_count
                .get(&extended_class_metadata.name)
                .copied()
                .unwrap_or(0);

            check_template_parameters(
                context,
                class_like_metadata,
                extended_class_metadata,
                actual_parameters_count,
                InheritanceKind::Extends(extended_type.span()),
            );
        }
    }
}

#[allow(clippy::unwrap_used)]
fn check_class_like_implements<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    implements_ast: Option<&Implements<'arena>>,
    checked_signatures: &mut HashSet<(Atom, Atom)>,
) {
    // This check only applies to classes and enums, which can use `implements`.
    if !class_like_metadata.kind.is_class() && !class_like_metadata.kind.is_enum() {
        // A separate check in the semantic analyzer will catch `implements` on an invalid type like a trait or interface.
        return;
    }

    let Some(implements) = implements_ast else {
        return;
    };

    let using_kind_str = class_like_metadata.kind.as_str();
    let using_kind_capitalized =
        format!("{}{}", using_kind_str.chars().next().unwrap().to_uppercase(), &using_kind_str[1..]);
    let using_name = class_like_metadata.original_name;
    let using_class_span = class_like_metadata.name_span.unwrap_or(class_like_metadata.span);

    for implemented_type in &implements.types {
        let implemented_type_str = context.resolved_names.get(&implemented_type);
        let implemented_interface_metadata = context.codebase.get_class_like(implemented_type_str);

        if let Some(implemented_metadata) = implemented_interface_metadata {
            let implemented_name = implemented_metadata.original_name;
            let implemented_kind_str = implemented_metadata.kind.as_str();
            let implemented_class_span = implemented_metadata.name_span.unwrap_or(implemented_metadata.span);
            let implemented_kind_prefix =
                if implemented_metadata.kind.is_class() || implemented_metadata.kind.is_trait() { "a" } else { "an" };

            if !implemented_metadata.kind.is_interface() {
                context.collector.report_with_code(
                    IssueCode::InvalidImplement,
                    Issue::error(format!("{using_kind_capitalized} `{using_name}` cannot implement non-interface type `{implemented_name}`"))
                        .with_annotation(Annotation::primary(implemented_type.span())
                            .with_message(format!("...because it is {implemented_kind_prefix} {implemented_kind_str}, not an interface")))
                        .with_annotation(Annotation::secondary(implemented_class_span)
                            .with_message(format!("`{implemented_name}` is defined as {implemented_kind_prefix} {implemented_kind_str} here")))
                        .with_note("The `implements` keyword is exclusively for implementing interfaces.")
                        .with_help("To inherit from a class, use `extends`. To use a trait, use `use`."),
                );

                continue;
            }

            if context.settings.check_experimental
                && implemented_metadata.flags.is_experimental()
                && !class_like_metadata.flags.is_experimental()
            {
                context.collector.report_with_code(
                    IssueCode::ExperimentalUsage,
                    Issue::warning(format!("Usage of experimental interface `{implemented_name}`."))
                        .with_annotation(
                            Annotation::primary(implemented_type.span())
                                .with_message(format!("`{implemented_name}` is marked as `@experimental`.")),
                        )
                        .with_note("Experimental APIs may change or be removed without notice.")
                        .with_help("Mark the current class as `@experimental` to suppress this warning."),
                );
            }

            if implemented_metadata.flags.is_enum_interface() && !class_like_metadata.kind.is_enum() {
                context.collector.report_with_code(
                    IssueCode::InvalidImplement,
                    Issue::error(format!("{using_kind_capitalized} `{using_name}` cannot implement enum-only interface `{implemented_name}`"))
                        .with_annotation(Annotation::primary(using_class_span).with_message(format!("This {using_kind_str} is not an enum...")))
                        .with_annotation(Annotation::secondary(implemented_type.span()).with_message("...but it implements an interface restricted to enums"))
                        .with_annotation(Annotation::secondary(implemented_class_span).with_message("This interface is marked with `@enum-interface` here"))
                        .with_note("An interface marked with `@enum-interface` can only be implemented by enums.")
                        .with_help(format!("To resolve this, either change `{using_name}` to be an enum, or implement a different, non-enum interface.")),
                );
            }

            if !class_like_metadata.is_permitted_to_inherit(implemented_metadata) {
                context.collector.report_with_code(
                    IssueCode::InvalidImplement,
                    Issue::error(format!("{using_kind_capitalized} `{using_name}` is not permitted to implement `{implemented_name}`"))
                         .with_annotation(Annotation::primary(implemented_type.span()).with_message("This implementation is restricted"))
                        .with_annotation(Annotation::secondary(implemented_class_span)
                            .with_message(format!("The `@inheritors` annotation on this interface does not include `{using_name}`")))
                        .with_note("The `@inheritors` annotation on an interface restricts which types are allowed to implement it.")
                        .with_help(format!("To allow this, add `{using_name}` to the list in the `@inheritors` PHPDoc tag for `{implemented_name}`.")),
                );
            }

            let actual_parameters_count = class_like_metadata
                .template_type_implements_count
                .get(&implemented_metadata.name)
                .copied()
                .unwrap_or(0);

            check_template_parameters(
                context,
                class_like_metadata,
                implemented_metadata,
                actual_parameters_count,
                InheritanceKind::Implements(implemented_type.span()),
            );

            check_interface_method_signatures(context, class_like_metadata, implemented_metadata, checked_signatures);
        } else {
            let implemented_name = implemented_type.value();

            context.collector.report_with_code(
                IssueCode::NonExistentClassLike,
                Issue::error(format!("{using_kind_capitalized} `{using_name}` cannot implement unknown type `{implemented_name}`"))
                    .with_annotation(Annotation::primary(implemented_type.span()).with_message("This type could not be found"))
                    .with_note("Mago could not find a definition for this interface. The `implements` keyword is for interfaces only.")
                    .with_help("Ensure the name is correct, including its namespace, and that it is properly defined and autoloadable."),
            );
        }
    }
}

#[allow(clippy::unwrap_used)]
fn check_class_like_use<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    trait_use: &TraitUse<'arena>,
) {
    let using_kind_str = class_like_metadata.kind.as_str();
    let using_kind_capitalized =
        format!("{}{}", using_kind_str.chars().next().unwrap().to_uppercase(), &using_kind_str[1..]);
    let using_name = class_like_metadata.original_name;
    let using_class_span = class_like_metadata.name_span.unwrap_or(class_like_metadata.span);

    for used_type in &trait_use.trait_names {
        let used_type_str = context.resolved_names.get(&used_type);
        let used_trait_metadata = context.codebase.get_class_like(used_type_str);

        let Some(used_trait_metadata) = used_trait_metadata else {
            let used_name = used_type.value();

            context.collector.report_with_code(
                IssueCode::NonExistentClassLike,
                Issue::error(format!("{using_kind_capitalized} `{using_name}` cannot use unknown type `{used_name}`"))
                    .with_annotation(Annotation::primary(used_type.span()).with_message("This type could not be found"))
                    .with_note("Mago could not find a definition for this trait. The `use` keyword is for traits only.")
                    .with_help("Ensure the name is correct, including its namespace, and that it is properly defined and autoloadable."),
            );

            continue;
        };

        let used_name = used_trait_metadata.original_name;
        let used_kind_str = used_trait_metadata.kind.as_str();
        let used_kind_prefix =
            if used_trait_metadata.kind.is_class() || used_trait_metadata.kind.is_trait() { "a" } else { "an" };
        let used_class_span = used_trait_metadata.name_span.unwrap_or(used_trait_metadata.span);

        // Case: Using something that is not a trait.
        if !used_trait_metadata.kind.is_trait() {
            context.collector.report_with_code(
                IssueCode::InvalidTraitUse,
                Issue::error(format!(
                    "{using_kind_capitalized} `{using_name}` cannot use non-trait type `{used_name}`"
                ))
                .with_annotation(
                    Annotation::primary(used_type.span())
                        .with_message(format!("...because it is {used_kind_prefix} {used_kind_str}, not a trait")),
                )
                .with_annotation(
                    Annotation::secondary(used_class_span)
                        .with_message(format!("`{used_name}` is defined as {used_kind_prefix} {used_kind_str} here")),
                )
                .with_note("The `use` keyword is exclusively for including traits in classes, enums, or other traits.")
                .with_help("To inherit from a class, use `extends`. To implement an interface, use `implements`."),
            );

            continue;
        }

        if context.settings.check_experimental
            && used_trait_metadata.flags.is_experimental()
            && !class_like_metadata.flags.is_experimental()
        {
            context.collector.report_with_code(
                IssueCode::ExperimentalUsage,
                Issue::warning(format!("Usage of experimental trait `{used_name}`."))
                    .with_annotation(
                        Annotation::primary(used_type.span())
                            .with_message(format!("`{used_name}` is marked as `@experimental`.")),
                    )
                    .with_note("Experimental APIs may change or be removed without notice.")
                    .with_help("Mark the current class as `@experimental` to suppress this warning."),
            );
        }

        if used_trait_metadata.flags.is_deprecated() {
            context.collector.report_with_code(
                IssueCode::DeprecatedTrait,
                Issue::error(format!("Use of deprecated trait `{used_name}` in `{using_name}`"))
                    .with_annotation(Annotation::primary(used_type.span()).with_message("This trait is marked as deprecated"))
                    .with_annotation(Annotation::secondary(used_class_span).with_message(format!("`{used_name}` was marked as deprecated here")))
                    .with_note("This trait is deprecated and may be removed in a future version, which would break the consuming type.")
                    .with_help("Consider refactoring to avoid using this trait, or consult its documentation for alternatives."),
            );
        }

        if let Some(required_interface) = class_like_metadata.get_missing_required_interface(used_trait_metadata) {
            context.collector.report_with_code(
                IssueCode::MissingRequiredInterface,
                Issue::error(format!("{using_kind_capitalized} `{using_name}` must implement required interface `{required_interface}`"))
                    .with_annotation(Annotation::primary(using_class_span).with_message(format!("...because the trait `{used_name}` requires it")))
                    .with_annotation(Annotation::secondary(used_type.span()).with_message(format!("The requirement is introduced by using `{used_name}` here")))
                    .with_note("When a trait uses `@require-implements`, any concrete class using that trait must implement the specified interface.")
                    .with_help(format!("Add `implements {required_interface}` to the `{using_name}` definition, or declare it as `abstract`.")),
            );
        }

        if let Some(required_class) = class_like_metadata.get_missing_required_extends(used_trait_metadata) {
            context.collector.report_with_code(
                IssueCode::MissingRequiredParent,
                Issue::error(format!(
                    "{using_kind_capitalized} `{using_name}` must extend required class `{required_class}`"
                ))
                .with_annotation(
                    Annotation::primary(using_class_span)
                        .with_message(format!("...because the trait `{used_name}` requires it")),
                )
                .with_annotation(
                    Annotation::secondary(used_type.span())
                        .with_message(format!("The requirement is introduced by using `{used_name}` here")),
                )
                .with_note(
                    "When a trait uses `@require-extends`, any class using that trait must extend the specified class.",
                )
                .with_help(format!(
                    "Add `extends {required_class}` to the `{using_name}` definition, or ensure it is a parent class."
                )),
            );
        }

        if !class_like_metadata.is_permitted_to_inherit(used_trait_metadata) {
            context.collector.report_with_code(
                IssueCode::InvalidTraitUse,
                Issue::error(format!(
                    "{using_kind_capitalized} `{using_name}` is not permitted to use trait `{used_name}`"
                ))
                .with_annotation(Annotation::primary(used_type.span()).with_message("This usage is restricted"))
                .with_annotation(Annotation::secondary(used_class_span).with_message(format!(
                    "The `@inheritors` annotation on this trait does not include `{using_name}`"
                )))
                .with_note("The `@inheritors` annotation on a trait restricts which types are allowed to use it.")
                .with_help(format!(
                    "To allow this, add `{using_name}` to the list in the `@inheritors` PHPDoc tag for `{used_name}`."
                )),
            );
        }

        check_template_parameters(
            context,
            class_like_metadata,
            used_trait_metadata,
            class_like_metadata.template_type_uses_count.get(&used_trait_metadata.name).copied().unwrap_or(0),
            InheritanceKind::Use(used_type.span()),
        );
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InheritanceKind {
    Extends(Span),
    Implements(Span),
    Use(Span),
}

impl HasSpan for InheritanceKind {
    fn span(&self) -> Span {
        match self {
            InheritanceKind::Extends(span) => *span,
            InheritanceKind::Implements(span) => *span,
            InheritanceKind::Use(span) => *span,
        }
    }
}

fn check_template_parameters<'ctx>(
    context: &mut Context<'ctx, '_>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    parent_metadata: &'ctx ClassLikeMetadata,
    actual_parameters_count: usize,
    inheritance: InheritanceKind,
) {
    let expected_parameters_count = parent_metadata.template_types.len();
    let min_required_parameters_count =
        parent_metadata.template_types.values().take_while(|t| t.default.is_none()).count();

    let class_name = class_like_metadata.original_name;
    let class_kind_str = class_like_metadata.kind.as_str();
    let parent_name = parent_metadata.original_name;
    let class_name_span = class_like_metadata.name_span.unwrap_or(class_like_metadata.span);
    let parent_definition_span = parent_metadata.name_span.unwrap_or(parent_metadata.span);
    let primary_annotation_span = inheritance.span();
    let (inheritance_keyword, inheritance_tag) = match inheritance {
        InheritanceKind::Extends(_) => ("extends", "@extends"),
        InheritanceKind::Implements(_) => ("implements", "@implements"),
        InheritanceKind::Use(_) => ("uses", "@use"),
    };

    if min_required_parameters_count > actual_parameters_count {
        let issue = Issue::error(format!(
            "Too few template arguments for `{parent_name}`: expected at least {min_required_parameters_count}, but found {actual_parameters_count}."
        ))
        .with_annotation(
            Annotation::primary(primary_annotation_span)
                .with_message(format!("Too few template arguments provided here when `{class_name}` {inheritance_keyword} `{parent_name}`")),
        )
        .with_annotation(
            Annotation::secondary(class_name_span)
                .with_message(format!("Declaration of `{class_name}` is here")),
        )
        .with_annotation(
            Annotation::secondary(parent_definition_span)
                .with_message(format!("`{parent_name}` is defined with {expected_parameters_count} template parameters")),
        )
        .with_help(format!("Provide all {expected_parameters_count} required template arguments in the `{inheritance_tag}` docblock tag for `{class_name}`."));

        context.collector.report_with_code(IssueCode::MissingTemplateParameter, issue);
    } else if expected_parameters_count < actual_parameters_count {
        let issue = Issue::error(format!(
            "Too many template arguments for `{parent_name}`: expected {expected_parameters_count}, but found {actual_parameters_count}."
        ))
        .with_annotation(
            Annotation::primary(primary_annotation_span)
                .with_message(format!("Too many template arguments provided here when `{class_name}` {inheritance_keyword} `{parent_name}`")),
        )
        .with_annotation(
            Annotation::secondary(class_name_span)
                .with_message(format!("Declaration of `{class_name}` is here")),
        )
        .with_annotation(
            Annotation::secondary(parent_definition_span)
                .with_message(format!("`{parent_name}` is defined with {expected_parameters_count} template parameters")),
        )
        .with_help(format!("Remove the extra arguments from the `{inheritance_tag}` tag for `{class_name}`."));

        context.collector.report_with_code(IssueCode::ExcessTemplateParameter, issue);
    } else {
        // template argument count matches expectation; nothing to report
    }

    let own_template_parameters_len = class_like_metadata.template_types.len();
    if parent_metadata.flags.has_consistent_templates() && own_template_parameters_len != expected_parameters_count {
        context.collector.report_with_code(
            IssueCode::InconsistentTemplate,
            Issue::error(format!(
                "Template parameter count mismatch: `{class_name}` must have {expected_parameters_count} template parameters to match `{parent_name}`."
            ))
            .with_annotation(Annotation::primary(class_name_span).with_message(format!("This {class_kind_str} defines {own_template_parameters_len} template parameters...")))
            .with_annotation(Annotation::secondary(parent_definition_span).with_message(format!("...but parent `{parent_name}` is marked `@consistent-templates` and expects {expected_parameters_count}.")))
            .with_help("Ensure the number of template parameters on this {class_kind_str} matches its parent."),
        );
    }

    if expected_parameters_count > 0
        && let Some(extended_parameters) = class_like_metadata.template_extended_parameters.get(&parent_metadata.name)
    {
        let mut i = 0;
        let mut previous_extended_types: IndexMap<Atom, Vec<GenericTemplate>, RandomState> = IndexMap::default();

        for (template_name, _) in &parent_metadata.template_types {
            if let Some(extended_type) = extended_parameters.get(template_name) {
                previous_extended_types
                    .entry(*template_name)
                    .or_default()
                    .push(GenericTemplate::new(GenericParent::ClassLike(parent_metadata.name), extended_type.clone()));
            }
        }

        for (template_name, parent_template) in &parent_metadata.template_types {
            let Some(mut extended_type) = extended_parameters.get(template_name).cloned() else {
                i += 1;
                continue;
            };

            let mut template_type = parent_template.constraint.clone();

            expand_union(
                context.codebase,
                &mut extended_type,
                &TypeExpansionOptions { self_class: Some(class_like_metadata.original_name), ..Default::default() },
            );

            expand_union(
                context.codebase,
                &mut template_type,
                &TypeExpansionOptions { self_class: Some(class_like_metadata.original_name), ..Default::default() },
            );

            let extended_type_str = extended_type.get_id();

            if parent_metadata
                .template_variance
                .get(i)
                .is_some_and(mago_codex::ttype::template::variance::Variance::is_invariant)
            {
                for extended_type_atomic in extended_type.types.as_ref() {
                    let TAtomic::GenericParameter(generic_parameter) = extended_type_atomic else {
                        continue;
                    };

                    let Some(local_offset) = class_like_metadata
                        .template_types
                        .iter()
                        .position(|(name, _)| *name == generic_parameter.parameter_name)
                    else {
                        continue;
                    };

                    if class_like_metadata
                        .template_variance
                        .get(local_offset)
                        .is_some_and(mago_codex::ttype::template::variance::Variance::is_covariant)
                    {
                        let child_template_name = generic_parameter.parameter_name;

                        context.collector.report_with_code(
                            IssueCode::InvalidTemplateParameter,
                            Issue::error("Invalid template variance: cannot use a covariant template to satisfy an invariant one.")
                                .with_annotation(Annotation::primary(class_name_span).with_message(format!("In the definition of `{class_name}`")))
                                .with_note(format!("The parent `{parent_name}` defines template `{template_name}` as invariant (`@template`)."))
                                .with_note(format!("But it is being satisfied by the covariant template `{child_template_name}` (`@template-covariant`) from `{class_name}`."))
                                .with_help("Make the child template parameter invariant as well (`@template`), or change the parent's variance if appropriate."),
                        );
                    }
                }
            }

            if parent_metadata.flags.has_consistent_templates() {
                for extended_type_atomic in extended_type.types.as_ref() {
                    let extended_as_template = extended_type_atomic.get_generic_parameter_name();
                    if extended_as_template.is_none() {
                        context.collector.report_with_code(
                            IssueCode::InvalidTemplateParameter,
                            Issue::error("Inconsistent template: expected a template parameter, but found a concrete type.")
                                .with_annotation(Annotation::primary(parent_definition_span).with_message(format!(
                                    "Expected a template parameter, but got `{}`",
                                    extended_type.get_id(),
                                )))
                                .with_note(format!("Because `{parent_name}` is marked `@consistent-templates`, its template parameters must be extended with other template parameters, not concrete types."))
                                .with_help(format!("Change this to a template parameter defined on `{class_name}`.")),
                        );
                    } else if let Some(child_template_name) = extended_as_template
                        && let Some(child_template) = class_like_metadata.get_template_type(child_template_name)
                        && let child_template_type = &child_template.constraint
                        && child_template_type.get_id() != template_type.get_id()
                    {
                        context.collector.report_with_code(
                            IssueCode::InvalidTemplateParameter,
                            Issue::error("Inconsistent template: template parameter constraints do not match.")
                                .with_annotation(Annotation::primary(class_name_span).with_message(format!("This template parameter has constraint `{}`...", child_template_type.get_id())))
                                .with_annotation(Annotation::secondary(parent_definition_span).with_message(format!("...but parent `{parent_name}` requires a constraint of `{}` for this template.", template_type.get_id())))
                                .with_note(format!("Because `{parent_name}` is marked `@consistent-templates`, the constraints of its template parameters must be identical in child classes."))
                                .with_help("Adjust the constraint on the child template parameter to match the parent's."),
                        );
                    } else {
                        // child template name resolves to a matching constraint; no inconsistency to report
                    }
                }
            }

            if template_type.is_mixed() {
                previous_extended_types
                    .entry(*template_name)
                    .or_default()
                    .push(GenericTemplate::new(GenericParent::ClassLike(parent_metadata.name), extended_type));
            } else {
                let mut template_result = TemplateResult::new(previous_extended_types.clone(), HashMap::default());
                let mut replaced_template_type = definition_type_replacer::replace(
                    &template_type,
                    &mut template_result,
                    context.codebase,
                    DefinitionReplacementOptions::default(),
                );

                expand_union(
                    context.codebase,
                    &mut replaced_template_type,
                    &TypeExpansionOptions { self_class: Some(class_like_metadata.original_name), ..Default::default() },
                );

                if is_type_compatible(context.codebase, &extended_type, &replaced_template_type) {
                    previous_extended_types
                        .entry(*template_name)
                        .or_default()
                        .push(GenericTemplate::new(GenericParent::ClassLike(parent_metadata.name), extended_type));
                } else {
                    let replaced_type_str = replaced_template_type.get_id();

                    context.collector.report_with_code(
                        IssueCode::InvalidTemplateParameter,
                        Issue::error(format!(
                            "Template argument for `{parent_name}` is not compatible with its constraint."
                        ))
                        .with_annotation(
                            Annotation::primary(class_name_span)
                                .with_message(format!("In the definition of `{class_name}`")),
                        )
                        .with_note(format!("The type `{extended_type_str}` provided for template `{template_name}`..."))
                        .with_note(format!(
                            "...does not satisfy the required constraint of `{replaced_type_str}` from `{parent_name}`."
                        ))
                        .with_help("Change the provided type to be compatible with the template constraint."),
                    );
                }
            }

            i += 1;
        }
    }
}

/// Checks if this is the same method that was inherited (not overridden).
/// Example: `StringBox` extends Box and inherits `Box::setValue` without overriding it.
#[inline]
fn should_skip_same_method(appearing_fqcn: &str, overridden_fqcn: &str) -> bool {
    appearing_fqcn.eq_ignore_ascii_case(overridden_fqcn)
}

/// Checks if this is a trait-to-trait abstract method conflict that should be handled
/// by `check_trait_method_conflicts` instead of here.
///
/// We skip when BOTH methods are:
/// - From different traits
/// - Both are abstract
/// - Both traits are used by the current class
#[inline]
fn should_skip_trait_to_trait_conflict(
    appearing_class: &ClassLikeMetadata,
    appearing_method: &FunctionLikeMetadata,
    overridden_class: &ClassLikeMetadata,
    overridden_method: &FunctionLikeMetadata,
    class_like_metadata: &ClassLikeMetadata,
) -> bool {
    if !appearing_class.kind.is_trait() || !overridden_class.kind.is_trait() {
        return false;
    }

    let appearing_is_abstract = appearing_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);
    let overridden_is_abstract = overridden_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);

    if !appearing_is_abstract || !overridden_is_abstract {
        return false;
    }

    let appearing_lowercase = ascii_lowercase_atom(&appearing_class.name);
    let overridden_lowercase = ascii_lowercase_atom(&overridden_class.name);

    if !class_like_metadata.used_traits.contains(&appearing_lowercase)
        || !class_like_metadata.used_traits.contains(&overridden_lowercase)
    {
        return false;
    }

    appearing_lowercase != overridden_lowercase
}

/// Checks if this is an enum implementing BackedEnum/UnitEnum, which is allowed
/// to narrow the method signatures (e.g., `from(string)` instead of `from(int|string)`).
#[inline]
fn should_skip_enum_builtin_interface(class_like_metadata: &ClassLikeMetadata, interface_fqcn: &str) -> bool {
    class_like_metadata.kind.is_enum() && (interface_fqcn == "backedenum" || interface_fqcn == "unitenum")
}

fn check_abstract_method_signatures<'ctx>(
    context: &mut Context<'ctx, '_>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    checked_signatures: &mut HashSet<(Atom, Atom)>,
) {
    for (method_name_atom, overridden_method_ids) in &class_like_metadata.overridden_method_ids {
        let method_name_str = method_name_atom.as_ref();

        let Some(declaring_method_id) = class_like_metadata.declaring_method_ids.get(method_name_atom) else {
            continue;
        };

        let declaring_fqcn_str = declaring_method_id.get_class_name().as_str();
        let declaring_method_opt = context.codebase.get_method(declaring_fqcn_str, method_name_str);

        let (method_fqcn_str, appearing_method) = if let Some(method) = declaring_method_opt {
            (declaring_fqcn_str, method)
        } else if let Some(appearing_method_id) = class_like_metadata.appearing_method_ids.get(method_name_atom) {
            let appearing_fqcn_str = appearing_method_id.get_class_name().as_str();
            let Some(method) = context.codebase.get_method(appearing_fqcn_str, method_name_str) else {
                continue;
            };

            (appearing_fqcn_str, method)
        } else {
            continue;
        };

        for (parent_fqcn, parent_declaring_method_id) in overridden_method_ids {
            let parent_fqcn_str = parent_fqcn.as_ref();

            let declaring_class_name = parent_declaring_method_id.get_class_name();
            let declaring_class_name_str = declaring_class_name.as_ref();

            if should_skip_same_method(method_fqcn_str, parent_fqcn_str) {
                continue;
            }

            if !checked_signatures.insert((declaring_class_name, *method_name_atom)) {
                continue;
            }

            let Some(overridden_method) =
                context.codebase.get_declaring_method(declaring_class_name_str, method_name_str)
            else {
                continue;
            };

            let Some(overridden_class) = context.codebase.get_class_like(declaring_class_name_str) else {
                continue;
            };

            let Some(appearing_class) = context.codebase.get_class_like(method_fqcn_str) else {
                continue;
            };

            if should_skip_trait_to_trait_conflict(
                appearing_class,
                appearing_method,
                overridden_class,
                overridden_method,
                class_like_metadata,
            ) {
                continue;
            }

            if should_skip_enum_builtin_interface(class_like_metadata, declaring_class_name_str) {
                continue;
            }

            let substituted_overridden_method =
                get_substituted_method(overridden_method, class_like_metadata, declaring_class_name, context.codebase);

            let substituted_appearing_method =
                get_substituted_method(appearing_method, class_like_metadata, atom(method_fqcn_str), context.codebase);

            let issues = method_signature::validate_method_signature_compatibility(
                context.codebase,
                class_like_metadata.name,
                &substituted_appearing_method,
                &substituted_overridden_method,
            );

            if issues.is_empty() {
                continue;
            }

            let error_span = if appearing_class.kind.is_trait() {
                class_like_metadata.name_span.unwrap_or(class_like_metadata.span)
            } else {
                appearing_method.name_span.unwrap_or(appearing_method.span)
            };

            for incompatibility in issues {
                report_signature_compatibility_issue(
                    context,
                    class_like_metadata,
                    overridden_class,
                    *method_name_atom,
                    appearing_method,
                    incompatibility,
                    error_span,
                );
            }
        }
    }
}

fn check_trait_method_conflicts<'ctx, 'ast, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    members: &'ast [ClassLikeMember<'arena>],
) {
    let mut trait_uses: Vec<(&'ast TraitUse<'arena>, Vec<Atom>)> = Vec::new();

    for member in members {
        if let ClassLikeMember::TraitUse(trait_use) = member {
            let mut trait_names = Vec::new();
            for trait_name_id in &trait_use.trait_names {
                let (trait_fqcn, _) = context.scope.resolve(NameKind::Default, trait_name_id.value());
                trait_names.push(Atom::from(trait_fqcn.as_str()));
            }
            trait_uses.push((trait_use, trait_names));
        }
    }

    for i in 0..trait_uses.len() {
        let (first_trait_use, first_traits) = &trait_uses[i];

        for k in 0..first_traits.len() {
            for l in (k + 1)..first_traits.len() {
                let first_trait_fqcn = &first_traits[k];
                let second_trait_fqcn = &first_traits[l];

                let Some(first_trait_metadata) = context.codebase.get_class_like(first_trait_fqcn.as_ref()) else {
                    continue;
                };
                let Some(second_trait_metadata) = context.codebase.get_class_like(second_trait_fqcn.as_ref()) else {
                    continue;
                };

                for (method_name, first_method_id) in &first_trait_metadata.declaring_method_ids {
                    if let Some(second_method_id) = second_trait_metadata.declaring_method_ids.get(method_name) {
                        let first_method_str = method_name.as_ref();
                        let Some(first_method) = context
                            .codebase
                            .get_declaring_method(first_method_id.get_class_name().as_ref(), first_method_str)
                        else {
                            continue;
                        };
                        let Some(second_method) = context
                            .codebase
                            .get_declaring_method(second_method_id.get_class_name().as_ref(), first_method_str)
                        else {
                            continue;
                        };

                        let first_is_abstract = first_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);
                        let second_is_abstract = second_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);

                        if first_is_abstract || second_is_abstract {
                            let issues = method_signature::validate_method_signature_compatibility(
                                context.codebase,
                                class_like_metadata.name,
                                second_method,
                                first_method,
                            );

                            for incompatibility in issues {
                                let trait_use_span = first_trait_use.span();

                                report_signature_compatibility_issue(
                                    context,
                                    class_like_metadata,
                                    first_trait_metadata,
                                    *method_name,
                                    second_method,
                                    incompatibility,
                                    trait_use_span,
                                );
                            }
                        }
                    }
                }
            }
        }

        for (second_trait_use, second_traits) in trait_uses.iter().skip(i + 1) {
            for first_trait_fqcn in first_traits {
                let Some(first_trait_metadata) = context.codebase.get_class_like(first_trait_fqcn.as_ref()) else {
                    continue;
                };

                for second_trait_fqcn in second_traits {
                    let Some(second_trait_metadata) = context.codebase.get_class_like(second_trait_fqcn.as_ref())
                    else {
                        continue;
                    };

                    for (method_name, first_method_id) in &first_trait_metadata.declaring_method_ids {
                        if let Some(second_method_id) = second_trait_metadata.declaring_method_ids.get(method_name) {
                            let first_method_str = method_name.as_ref();
                            let Some(first_method) = context
                                .codebase
                                .get_declaring_method(first_method_id.get_class_name().as_ref(), first_method_str)
                            else {
                                continue;
                            };
                            let Some(second_method) = context
                                .codebase
                                .get_declaring_method(second_method_id.get_class_name().as_ref(), first_method_str)
                            else {
                                continue;
                            };

                            let first_is_abstract =
                                first_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);
                            let second_is_abstract =
                                second_method.method_metadata.as_ref().is_some_and(|m| m.is_abstract);

                            if first_is_abstract || second_is_abstract {
                                let issues = method_signature::validate_method_signature_compatibility(
                                    context.codebase,
                                    class_like_metadata.name,
                                    second_method,
                                    first_method,
                                );

                                for incompatibility in issues {
                                    let second_trait_use_span = second_trait_use.span();

                                    report_signature_compatibility_issue(
                                        context,
                                        class_like_metadata,
                                        first_trait_metadata,
                                        *method_name,
                                        second_method,
                                        incompatibility,
                                        second_trait_use_span,
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

fn check_trait_property_conflicts<'ctx, 'ast, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    members: &'ast [ClassLikeMember<'arena>],
) {
    let mut trait_uses: Vec<(&'ast TraitUse<'arena>, Vec<Atom>)> = Vec::new();

    for member in members {
        if let ClassLikeMember::TraitUse(trait_use) = member {
            let mut trait_names = Vec::new();
            for trait_name_id in &trait_use.trait_names {
                let (trait_fqcn, _) = context.scope.resolve(NameKind::Default, trait_name_id.value());
                trait_names.push(Atom::from(trait_fqcn.as_str()));
            }
            trait_uses.push((trait_use, trait_names));
        }
    }

    let mut class_properties: IndexMap<Atom, &PropertyMetadata> = IndexMap::new();
    for (property_name, property_metadata) in class_like_metadata.properties.iter().sorted_by_key(|(k, _)| *k) {
        if let Some(declaring_class) = class_like_metadata.declaring_property_ids.get(property_name)
            && declaring_class == &class_like_metadata.name
        {
            class_properties.insert(*property_name, property_metadata);
        }
    }

    for i in 0..trait_uses.len() {
        let (first_trait_use, first_traits) = &trait_uses[i];

        for k in 0..first_traits.len() {
            for l in (k + 1)..first_traits.len() {
                let first_trait_fqcn = &first_traits[k];
                let second_trait_fqcn = &first_traits[l];

                let Some(first_trait_metadata) = context.codebase.get_class_like(first_trait_fqcn.as_ref()) else {
                    continue;
                };
                let Some(second_trait_metadata) = context.codebase.get_class_like(second_trait_fqcn.as_ref()) else {
                    continue;
                };

                for (property_name, first_property) in first_trait_metadata.properties.iter().sorted_by_key(|(k, _)| *k)
                {
                    let Some(second_property) = second_trait_metadata.properties.get(property_name) else {
                        continue;
                    };

                    if properties_are_compatible(first_property, second_property) {
                        continue;
                    }

                    report_trait_property_conflict(
                        context,
                        class_like_metadata.name,
                        *property_name,
                        *first_trait_fqcn,
                        *second_trait_fqcn,
                        first_trait_use.span(),
                        first_property,
                        second_property,
                    );
                }
            }
        }

        for (second_trait_use, second_traits) in trait_uses.iter().skip(i + 1) {
            for first_trait_fqcn in first_traits {
                let Some(first_trait_metadata) = context.codebase.get_class_like(first_trait_fqcn.as_ref()) else {
                    continue;
                };

                for second_trait_fqcn in second_traits {
                    let Some(second_trait_metadata) = context.codebase.get_class_like(second_trait_fqcn.as_ref())
                    else {
                        continue;
                    };

                    for (property_name, first_property) in
                        first_trait_metadata.properties.iter().sorted_by_key(|(k, _)| *k)
                    {
                        let Some(second_property) = second_trait_metadata.properties.get(property_name) else {
                            continue;
                        };

                        if properties_are_compatible(first_property, second_property) {
                            continue;
                        }

                        report_trait_property_conflict(
                            context,
                            class_like_metadata.name,
                            *property_name,
                            *first_trait_fqcn,
                            *second_trait_fqcn,
                            second_trait_use.span(),
                            first_property,
                            second_property,
                        );
                    }
                }
            }
        }

        for first_trait_fqcn in first_traits {
            let Some(first_trait_metadata) = context.codebase.get_class_like(first_trait_fqcn.as_ref()) else {
                continue;
            };

            for (property_name, trait_property) in first_trait_metadata.properties.iter().sorted_by_key(|(k, _)| *k) {
                let Some(class_property) = class_properties.get(property_name) else {
                    continue;
                };

                if properties_are_compatible(trait_property, class_property) {
                    continue;
                }

                let conflict_span = members
                    .iter()
                    .find_map(|member| {
                        if let ClassLikeMember::Property(prop) = member {
                            match prop {
                                Property::Plain(plain_prop) => {
                                    for item in &plain_prop.items {
                                        let var_name = Atom::from(item.variable().name);
                                        if var_name == *property_name {
                                            return Some(prop.span());
                                        }
                                    }
                                }
                                Property::Hooked(hooked_prop) => {
                                    let var_name = Atom::from(hooked_prop.item.variable().name);
                                    if var_name == *property_name {
                                        return Some(prop.span());
                                    }
                                }
                            }
                        }
                        None
                    })
                    .unwrap_or_else(|| first_trait_use.span());

                report_trait_property_conflict(
                    context,
                    class_like_metadata.name,
                    *property_name,
                    *first_trait_fqcn,
                    class_like_metadata.name,
                    conflict_span,
                    trait_property,
                    class_property,
                );
            }
        }
    }
}

fn properties_are_compatible(prop1: &PropertyMetadata, prop2: &PropertyMetadata) -> bool {
    // PHP 8.4: Conflict resolution between hooked properties is not supported
    if !prop1.hooks.is_empty() || !prop2.hooks.is_empty() {
        return false;
    }

    if prop1.read_visibility != prop2.read_visibility {
        return false;
    }
    if prop1.write_visibility != prop2.write_visibility {
        return false;
    }

    if prop1.flags.is_static() != prop2.flags.is_static() {
        return false;
    }

    if prop1.flags.is_readonly() != prop2.flags.is_readonly() {
        return false;
    }

    match (&prop1.type_declaration_metadata, &prop2.type_declaration_metadata) {
        (Some(t1), Some(t2)) => {
            if t1.type_union.get_id() != t2.type_union.get_id() {
                return false;
            }
        }
        (None, None) => {}
        _ => return false,
    }

    match (&prop1.default_type_metadata, &prop2.default_type_metadata) {
        (Some(d1), Some(d2)) => {
            if d1.type_union.get_id() != d2.type_union.get_id() {
                return false;
            }
        }
        (None, None) => {}
        _ => return false,
    }

    true
}

/// Check if two properties are compatible, returns Err with specific conflict type if not
fn check_property_compatibility(prop1: &PropertyMetadata, prop2: &PropertyMetadata) -> Result<(), PropertyConflict> {
    // PHP 8.4: Conflict resolution between hooked properties is not supported
    if !prop1.hooks.is_empty() || !prop2.hooks.is_empty() {
        return Err(PropertyConflict::HookedProperty);
    }

    if prop1.read_visibility != prop2.read_visibility || prop1.write_visibility != prop2.write_visibility {
        return Err(PropertyConflict::Visibility(
            prop1.read_visibility,
            prop1.write_visibility,
            prop2.read_visibility,
            prop2.write_visibility,
        ));
    }

    if prop1.flags.is_static() != prop2.flags.is_static() {
        return Err(PropertyConflict::Static(prop1.flags.is_static(), prop2.flags.is_static()));
    }

    if prop1.flags.is_readonly() != prop2.flags.is_readonly() {
        return Err(PropertyConflict::Readonly(prop1.flags.is_readonly(), prop2.flags.is_readonly()));
    }

    match (&prop1.type_declaration_metadata, &prop2.type_declaration_metadata) {
        (Some(t1), Some(t2)) => {
            if t1.type_union.get_id() != t2.type_union.get_id() {
                return Err(PropertyConflict::Type(
                    Some(format!("{:?}", t1.type_union)),
                    Some(format!("{:?}", t2.type_union)),
                ));
            }
        }
        (Some(t1), None) => {
            return Err(PropertyConflict::Type(Some(format!("{:?}", t1.type_union)), None));
        }
        (None, Some(t2)) => {
            return Err(PropertyConflict::Type(None, Some(format!("{:?}", t2.type_union))));
        }
        (None, None) => {}
    }

    match (&prop1.default_type_metadata, &prop2.default_type_metadata) {
        (Some(d1), Some(d2)) => {
            if d1.type_union.get_id() != d2.type_union.get_id() {
                return Err(PropertyConflict::Default(
                    Some(format!("{:?}", d1.type_union)),
                    Some(format!("{:?}", d2.type_union)),
                ));
            }
        }
        (Some(d1), None) => {
            return Err(PropertyConflict::Default(Some(format!("{:?}", d1.type_union)), None));
        }
        (None, Some(d2)) => {
            return Err(PropertyConflict::Default(None, Some(format!("{:?}", d2.type_union))));
        }
        (None, None) => {}
    }

    Ok(())
}

fn report_trait_property_conflict(
    context: &mut Context,
    class_name: Atom,
    property_name: Atom,
    trait1_name: Atom,
    trait2_name: Atom,
    conflict_span: Span,
    prop1: &PropertyMetadata,
    prop2: &PropertyMetadata,
) {
    let conflict = match check_property_compatibility(prop1, prop2) {
        Ok(()) => {
            PropertyConflict::Type(None, None) // Dummy value
        }
        Err(conflict) => conflict,
    };

    let conflict_description = conflict.describe();
    let issue_code = conflict.get_issue_code();

    context.collector.report_with_code(
        issue_code,
        Issue::error(format!(
            "Property `{property_name}` is defined differently in `{trait1_name}` and `{trait2_name}` used by `{class_name}`: {conflict_description}"
        ))
        .with_annotation(Annotation::primary(conflict_span).with_message("Conflicting property definitions"))
        .with_note(format!("In PHP, this will cause a fatal error: '{trait1_name} and {trait2_name} define the same property ({property_name}) in the composition of {class_name}. However, the definition differs and is considered incompatible.'"))
        .with_help("Ensure both sources define the property identically (same visibility, type, default value, and modifiers), or use only one source."),
    );
}

/// Apply template parameter substitution to a method's parameter and return types
///
/// For example, if interface has `K` and `V` template parameters, and the implementation
/// maps them to `TKey` and `TValue`, this function replaces all occurrences of `K` with `TKey`
/// and `V` with `TValue` in the method signature.
///
/// Gets the substituted method by applying template parameter mapping from the class.
/// Returns the original method if no template substitution is needed.
#[inline]
fn get_substituted_method(
    method: &FunctionLikeMetadata,
    class_like_metadata: &ClassLikeMetadata,
    parent_class_name: Atom,
    codebase: &CodebaseMetadata,
) -> FunctionLikeMetadata {
    let template_mapping =
        class_like_metadata.template_extended_parameters.get(&parent_class_name).cloned().unwrap_or_default();

    if template_mapping.is_empty() {
        method.clone()
    } else {
        let mut template_result = TemplateResult::default();
        for (template_name, concrete_type) in template_mapping {
            template_result.add_lower_bound(template_name, GenericParent::ClassLike(parent_class_name), concrete_type);
        }

        apply_template_substitution_to_method(method, &template_result, codebase)
    }
}

fn apply_template_substitution_to_method(
    method: &FunctionLikeMetadata,
    template_result: &TemplateResult,
    codebase: &CodebaseMetadata,
) -> FunctionLikeMetadata {
    let mut substituted_method = method.clone();

    for param in &mut substituted_method.parameters {
        if let Some(type_metadata) = &mut param.type_metadata {
            type_metadata.type_union =
                inferred_type_replacer::replace(&type_metadata.type_union, template_result, codebase);
        }
    }

    if let Some(return_type) = &mut substituted_method.return_type_declaration_metadata {
        return_type.type_union = inferred_type_replacer::replace(&return_type.type_union, template_result, codebase);
    }

    substituted_method
}

fn check_interface_method_signatures<'ctx>(
    context: &mut Context<'ctx, '_>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    interface_metadata: &'ctx ClassLikeMetadata,
    checked_signatures: &mut HashSet<(Atom, Atom)>,
) {
    let interface_fqcn_str: &str = interface_metadata.name.as_ref();
    if should_skip_enum_builtin_interface(class_like_metadata, interface_fqcn_str) {
        return;
    }

    for (method_name_atom, interface_method_id) in &interface_metadata.declaring_method_ids {
        let method_name_str = method_name_atom.as_ref();
        let interface_fqcn_str = interface_method_id.get_class_name().as_str();

        let Some(interface_method) = context.codebase.get_declaring_method(interface_fqcn_str, method_name_str) else {
            continue;
        };

        let Some(class_method_id) = class_like_metadata.declaring_method_ids.get(method_name_atom) else {
            continue;
        };

        let class_fqcn_str = class_method_id.get_class_name().as_str();
        let Some(class_method) = context.codebase.get_declaring_method(class_fqcn_str, method_name_str) else {
            continue;
        };

        if should_skip_same_method(class_fqcn_str, interface_fqcn_str) {
            continue;
        }

        if !checked_signatures.insert((interface_method_id.get_class_name(), *method_name_atom)) {
            continue;
        }

        let substituted_interface_method = get_substituted_method(
            interface_method,
            class_like_metadata,
            interface_method_id.get_class_name(),
            context.codebase,
        );

        let substituted_class_method = get_substituted_method(
            class_method,
            class_like_metadata,
            class_method_id.get_class_name(),
            context.codebase,
        );

        let issues = method_signature::validate_method_signature_compatibility(
            context.codebase,
            class_like_metadata.name,
            &substituted_class_method,
            &substituted_interface_method,
        );

        for incompatibility in issues {
            // Use the method span as primary location (where the issue actually is)
            let method_span = class_method.name_span.unwrap_or(class_method.span);

            // Get the actual declaring class for error reporting
            let declaring_class = context.codebase.get_class_like(interface_fqcn_str).unwrap_or(interface_metadata);

            report_signature_compatibility_issue(
                context,
                class_like_metadata,
                declaring_class,
                *method_name_atom,
                class_method,
                incompatibility,
                method_span,
            );
        }
    }
}

fn report_signature_compatibility_issue<'ctx>(
    context: &mut Context<'ctx, '_>,
    child_class: &'ctx ClassLikeMetadata,
    parent_class: &'ctx ClassLikeMetadata,
    method_name: Atom,
    parent_method: &FunctionLikeMetadata,
    incompatibility: SignatureCompatibilityIssue,
    primary_span: Span,
) {
    let child_name = child_class.original_name;
    let parent_name = parent_class.original_name;
    let child_class_span = child_class.name_span.unwrap_or(child_class.span);
    let parent_class_span = parent_class.name_span.unwrap_or(parent_class.span);

    use method_signature::SignatureCompatibilityIssue;

    match incompatibility {
        SignatureCompatibilityIssue::FinalMethodOverride => {
            context.collector.report_with_code(
                IssueCode::OverrideFinalMethod,
                Issue::error(format!("Cannot override final method `{parent_name}::{method_name}()`"))
                    .with_annotation(
                        Annotation::primary(primary_span).with_message("Attempting to override final method here"),
                    )
                    .with_annotation(
                        Annotation::secondary(parent_class_span)
                            .with_message(format!("Method `{parent_name}::{method_name}()` is declared as final")),
                    )
                    .with_annotation(
                        Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                    )
                    .with_note("Final methods cannot be overridden in child classes or traits.")
                    .with_help(format!(
                        "Remove the method `{method_name}()` from `{child_name}`, or remove the final modifier from the parent method."
                    )),
            );
        }
        SignatureCompatibilityIssue::StaticModifierMismatch { child_is_static, parent_is_static: _ } => {
            let (child_modifier, parent_modifier) =
                if child_is_static { ("static", "non-static") } else { ("non-static", "static") };

            context.collector.report_with_code(
                IssueCode::IncompatibleStaticModifier,
                Issue::error(format!(
                    "Cannot make {parent_modifier} method `{parent_name}::{method_name}()` {child_modifier} in class `{child_name}`"
                ))
                .with_annotation(
                    Annotation::primary(primary_span)
                        .with_message(format!("This method is {child_modifier} but should be {parent_modifier}")),
                )
                .with_annotation(Annotation::secondary(parent_class_span).with_message(format!(
                    "`{parent_name}::{method_name}()` is defined as {parent_modifier} here"
                )))
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("The static modifier must match exactly between parent and child methods.")
                .with_help(format!("Change the method in `{child_name}` to be {parent_modifier} like the parent.")),
            );
        }
        SignatureCompatibilityIssue::VisibilityNarrowed { child_visibility, parent_visibility } => {
            context.collector.report_with_code(
                IssueCode::IncompatibleVisibility,
                Issue::error(format!(
                    "Visibility of `{child_name}::{method_name}()` must not be narrowed from {parent_visibility} to {child_visibility}"
                ))
                .with_annotation(Annotation::primary(primary_span).with_message(format!(
                    "Method declared as {child_visibility} but should be {parent_visibility} or wider"
                )))
                .with_annotation(Annotation::secondary(parent_class_span).with_message(format!(
                    "Parent method `{parent_name}::{method_name}()` is declared as {parent_visibility} here"
                )))
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("Visibility can only be widened (e.g., protected → public) not narrowed.")
                .with_help(format!("Change the visibility to {parent_visibility} or wider.")),
            );
        }
        SignatureCompatibilityIssue::ParameterCountMismatch { child_required_count, parent_required_count } => {
            context.collector.report_with_code(
                IssueCode::IncompatibleParameterCount,
                Issue::error(format!(
                    "`{child_name}::{method_name}()` must accept at least {parent_required_count} required parameters like `{parent_name}::{method_name}()`"
                ))
                .with_annotation(Annotation::primary(primary_span).with_message(format!(
                    "Method requires {child_required_count} parameters but parent requires {parent_required_count}"
                )))
                .with_annotation(Annotation::secondary(parent_class_span).with_message(format!(
                    "Parent method `{parent_name}::{method_name}()` requires {parent_required_count} parameters"
                )))
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("Child methods must accept at least as many required parameters as the parent.")
                .with_help("Add optional parameters or reduce the number of required parameters in the child method."),
            );
        }
        SignatureCompatibilityIssue::IncompatibleParameterType { parameter_index, child_type, parent_type } => {
            let param_name = parent_method.parameters.get(parameter_index).map_or("unknown", |p| p.name.0.as_ref());

            context.collector.report_with_code(
                IssueCode::IncompatibleParameterType,
                Issue::error(format!(
                    "Parameter `{param_name}` of `{child_name}::{method_name}()` expects type `{child_type}` but parent `{parent_name}::{method_name}()` expects type `{parent_type}`"
                ))
                .with_annotation(Annotation::primary(primary_span).with_message(format!(
                    "Parameter `{param_name}` expects type `{child_type}` but parent expects `{parent_type}`"
                )))
                .with_annotation(
                    Annotation::secondary(parent_class_span).with_message(format!(
                        "Parent method `{parent_name}::{method_name}()` parameter defined here"
                    )),
                )
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("Parameter types must be contravariant: child must accept equal or wider types than parent.")
                .with_help("Change the parameter type to be compatible with the parent method."),
            );
        }
        SignatureCompatibilityIssue::IncompatibleReturnType { child_type, parent_type } => {
            context.collector.report_with_code(
                IssueCode::IncompatibleReturnType,
                Issue::error(format!(
                    "Return type `{child_type}` of `{child_name}::{method_name}()` is incompatible with parent return type `{parent_type}` of `{parent_name}::{method_name}()`"
                ))
                .with_annotation(
                    Annotation::primary(primary_span)
                        .with_message(format!("Returns type `{child_type}` but parent expects `{parent_type}`")),
                )
                .with_annotation(Annotation::secondary(parent_class_span).with_message(format!(
                    "Parent method `{parent_name}::{method_name}()` return type defined here"
                )))
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("Return types must be covariant: child must return equal or narrower types than parent.")
                .with_help("Change the return type to be compatible with the parent method."),
            );
        }
        SignatureCompatibilityIssue::ParameterNameMismatch {
            parameter_index,
            child_name: child_param_name,
            parent_name: parent_param_name,
        } => {
            context.collector.report_with_code(
                IssueCode::IncompatibleParameterName,
                Issue::warning(format!(
                    "Parameter #{} of `{}::{}()` is named `{}` but parent `{}::{}()` names it `{}`",
                    parameter_index + 1,
                    child_name,
                    method_name,
                    child_param_name,
                    parent_name,
                    method_name,
                    parent_param_name
                ))
                .with_annotation(Annotation::primary(primary_span).with_message(format!(
                    "Parameter named `{child_param_name}` but parent uses `{parent_param_name}`",
                )))
                .with_annotation(Annotation::secondary(parent_class_span).with_message(format!(
                    "Parent method `{parent_name}::{method_name}()` parameter `{parent_param_name}` defined here",
                )))
                .with_annotation(
                    Annotation::secondary(child_class_span).with_message(format!("In class `{child_name}`")),
                )
                .with_note("Parameter name changes can break code using named arguments.")
                .with_help(format!(
                    "Consider renaming the parameter to `{parent_param_name}` to match the parent method."
                )),
            );
        }
    }
}

#[allow(clippy::similar_names)]
fn check_class_like_properties<'ctx>(context: &mut Context<'ctx, '_>, class_like_metadata: &'ctx ClassLikeMetadata) {
    if class_like_metadata.kind.is_enum() {
        return;
    }

    // Check properties declared directly in this class against parent classes
    for (property_name, property_metadata) in &class_like_metadata.properties {
        // Only check properties declared in this class, not inherited ones
        let Some(declaring_fqcn) = class_like_metadata.declaring_property_ids.get(property_name) else {
            continue;
        };

        if declaring_fqcn != &class_like_metadata.name {
            // Property is inherited, not declared in this class
            continue;
        }

        // Validate set hook parameter type is supertype of property type
        if let Some(set_hook) = property_metadata.hooks.get(&atom("set"))
            && let Some(param) = &set_hook.parameter
            && let Some(param_type) = param.type_declaration_metadata.as_ref()
            && let Some(property_type) = property_metadata.type_metadata.as_ref()
        {
            // The set hook parameter type must contain the property type (contravariance)
            // i.e., any value assignable to the property type should be accepted by the hook
            if !is_type_compatible(context.codebase, &property_type.type_union, &param_type.type_union) {
                let property_type_id = property_type.type_union.get_id();
                let param_type_id = param_type.type_union.get_id();
                let class_name = class_like_metadata.original_name;

                context.collector.report_with_code(
                    IssueCode::IncompatiblePropertyHookParameterType,
                    Issue::error(format!(
                        "Set hook parameter type `{param_type_id}` for property `{class_name}::{property_name}` is incompatible with property type `{property_type_id}`."
                    ))
                    .with_annotation(
                        Annotation::primary(param_type.span)
                            .with_message(format!("This type `{param_type_id}` does not accept all values of type `{property_type_id}`")),
                    )
                    .with_annotation(
                        Annotation::secondary(property_type.span)
                            .with_message(format!("Property is declared with type `{property_type_id}`")),
                    )
                    .with_note("The set hook parameter type must be equal to or wider than the property type (contravariance).")
                    .with_help(format!("Change the set hook parameter type to `{property_type_id}` or a wider type that contains `{property_type_id}`.")),
                );
            }
        }

        // Validate docblock param type >= native param type
        if let Some(set_hook) = property_metadata.hooks.get(&atom("set"))
            && let Some(param) = &set_hook.parameter
            && let Some(native_type) = param.type_declaration_metadata.as_ref()
            && let Some(effective_type) = param.type_metadata.as_ref()
            && effective_type.from_docblock
            && !is_type_compatible(context.codebase, &native_type.type_union, &effective_type.type_union)
        {
            let native_type_str = native_type.type_union.get_id();
            let docblock_type_str = effective_type.type_union.get_id();

            context.collector.report_with_code(
                    IssueCode::DocblockTypeMismatch,
                    Issue::error(format!(
                        "Docblock type `{docblock_type_str}` is narrower than native parameter type `{native_type_str}`."
                    ))
                    .with_annotation(
                        Annotation::primary(effective_type.span)
                            .with_message(format!("Docblock type `{docblock_type_str}` cannot narrow native type `{native_type_str}`")),
                    )
                    .with_note(
                        "The @param docblock type must be a supertype of the native type. It can widen the type (e.g., int to int|string) but not narrow it.",
                    )
                    .with_help(format!(
                        "Change the docblock type to `{native_type_str}` or a wider type.",
                    )),
                );
        }

        // Check each parent class for this property
        for parent_fqcn in &class_like_metadata.all_parent_classes {
            let parent_fqcn_str = parent_fqcn.as_ref();
            let Some(parent_metadata) = context.codebase.get_class_like(parent_fqcn_str) else {
                continue;
            };

            let Some(parent_property) = parent_metadata.properties.get(property_name) else {
                continue;
            };

            if parent_property.read_visibility.is_private() && parent_property.write_visibility.is_private() {
                continue;
            }

            let property_span = property_metadata.name_span.unwrap_or(class_like_metadata.span);
            let parent_property_span = parent_property.name_span.unwrap_or(parent_metadata.span);
            let declaring_class_name = class_like_metadata.original_name;
            let parent_class_name = parent_metadata.original_name;

            if parent_property.flags.is_final() {
                context.collector.report_with_code(
                    IssueCode::OverrideFinalProperty,
                    Issue::error(format!(
                        "Cannot override final property `{parent_class_name}::{property_name}`."
                    ))
                    .with_annotation(
                        Annotation::primary(property_span)
                            .with_message("Attempting to override final property here"),
                    )
                    .with_annotation(
                        Annotation::secondary(parent_property_span)
                            .with_message(format!("Property `{parent_class_name}::{property_name}` is declared as final")),
                    )
                    .with_note("Final properties cannot be overridden in child classes.")
                    .with_help(format!(
                        "Remove the property `{property_name}` from `{declaring_class_name}`, or remove the final modifier from the parent property.",
                    )),
                );
            }

            for (hook_name, child_hook) in &property_metadata.hooks {
                if let Some(parent_hook) = parent_property.hooks.get(hook_name)
                    && parent_hook.flags.is_final()
                {
                    context.collector.report_with_code(
                            IssueCode::OverrideFinalPropertyHook,
                            Issue::error(format!(
                                "Cannot override final property hook `{parent_class_name}::{property_name}::{hook_name}()`."
                            ))
                            .with_annotation(
                                Annotation::primary(child_hook.span)
                                    .with_message("Attempting to override final hook here"),
                            )
                            .with_annotation(
                                Annotation::secondary(parent_hook.span)
                                    .with_message(format!("Hook `{parent_class_name}::{property_name}::{hook_name}()` is declared as final")),
                            )
                            .with_note("Final property hooks cannot be overridden in child classes.")
                            .with_help(format!(
                                "Remove the `{hook_name}` hook from `{declaring_class_name}::{property_name}`, or remove the final modifier from the parent hook.",
                            )),
                        );
                }
            }

            // Backed property with by-ref get + set hook is invalid
            if parent_property.hooks.is_empty()
                && let Some(get_hook) = property_metadata.hooks.get(&atom("get"))
                && get_hook.returns_by_ref
                && property_metadata.hooks.contains_key(&atom("set"))
            {
                context.collector.report_with_code(
                    IssueCode::BackedPropertyReferenceHook,
                    Issue::error(format!(
                        "Get hook of backed property `{declaring_class_name}::{property_name}` with set hook may not return by reference."
                    ))
                    .with_annotation(
                        Annotation::primary(get_hook.span)
                            .with_message("This get hook returns by reference"),
                    )
                    .with_annotation(
                        Annotation::secondary(parent_property_span)
                            .with_message(format!("Property `{parent_class_name}::{property_name}` creates a backing store")),
                    )
                    .with_note("A backed property (with backing store) that has a set hook cannot have a by-reference get hook.")
                    .with_help("Remove the `&` from the get hook declaration, or remove the set hook."),
                );
            }

            if property_metadata.read_visibility > parent_property.read_visibility {
                let property_span = property_metadata.name_span.unwrap_or(class_like_metadata.span);
                let parent_property_span = parent_property.name_span.unwrap_or(parent_metadata.span);

                let declaring_class_name = class_like_metadata.original_name;
                let parent_class_name = parent_metadata.original_name;

                context.collector.report_with_code(
                        IssueCode::IncompatiblePropertyAccess,
                        Issue::error(format!(
                            "Property `{declaring_class_name}::{property_name}` has a different read access level than `{parent_class_name}::{property_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(property_span)
                                .with_message(format!("This property is declared as `{}`", property_metadata.read_visibility.as_str())),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_property_span)
                                .with_message(format!("Parent property is declared as `{}`", parent_property.read_visibility.as_str())),
                        )
                        .with_note("The access level of an overridden property must not be more restrictive than the parent property.")
                        .with_help("Adjust the access level of the property in the child class to match or be less restrictive than the parent class."),
                    );
            }

            if (property_metadata.write_visibility != property_metadata.read_visibility
                || parent_property.write_visibility != parent_property.read_visibility)
                && property_metadata.write_visibility > parent_property.write_visibility
            {
                let property_span = property_metadata.name_span.unwrap_or(class_like_metadata.span);
                let parent_property_span = parent_property.name_span.unwrap_or(parent_metadata.span);

                let declaring_class_name = class_like_metadata.original_name;
                let parent_class_name = parent_metadata.original_name;

                context.collector.report_with_code(
                        IssueCode::IncompatiblePropertyAccess,
                        Issue::error(format!(
                            "Property `{declaring_class_name}::{property_name}` has a different write access level than `{parent_class_name}::{property_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(property_span)
                                .with_message(format!("This property is declared as `{}(set)`", property_metadata.write_visibility.as_str())),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_property_span)
                                .with_message(format!("Parent property is declared as `{}(set)`", parent_property.write_visibility.as_str())),
                        )
                        .with_note("The access level of an overridden property must not be more restrictive than the parent property.")
                        .with_help("Adjust the access level of the property in the child class to match or be less restrictive than the parent class."),
                    );
            }

            // Check static modifier consistency
            if property_metadata.flags.is_static() != parent_property.flags.is_static() {
                let property_span = property_metadata.name_span.unwrap_or(class_like_metadata.span);
                let parent_property_span = parent_property.name_span.unwrap_or(parent_metadata.span);

                let declaring_class_name = class_like_metadata.original_name;
                let parent_class_name = parent_metadata.original_name;
                let (child_modifier, parent_modifier) = if property_metadata.flags.is_static() {
                    ("static", "non-static")
                } else {
                    ("non-static", "static")
                };

                context.collector.report_with_code(
                        IssueCode::IncompatibleStaticModifier,
                        Issue::error(format!(
                            "Cannot redeclare {parent_modifier} property `{parent_class_name}::{property_name}` as {child_modifier} `{declaring_class_name}::{property_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(property_span)
                                .with_message(format!("This property is declared as `{child_modifier}`")),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_property_span)
                                .with_message(format!("Parent property is declared as `{parent_modifier}`")),
                        )
                        .with_note("Properties must maintain the same static modifier when overriding parent properties.")
                        .with_help(format!("Change this property to be `{parent_modifier}` to match the parent class.")),
                    );
            }

            // Check readonly modifier consistency
            if property_metadata.flags.is_readonly() != parent_property.flags.is_readonly() {
                let property_span = property_metadata.name_span.unwrap_or(class_like_metadata.span);
                let parent_property_span = parent_property.name_span.unwrap_or(parent_metadata.span);

                let declaring_class_name = class_like_metadata.original_name;
                let parent_class_name = parent_metadata.original_name;
                let (child_modifier, parent_modifier) = if property_metadata.flags.is_readonly() {
                    ("readonly", "non-readonly")
                } else {
                    ("non-readonly", "readonly")
                };

                context.collector.report_with_code(
                        IssueCode::IncompatibleReadonlyModifier,
                        Issue::error(format!(
                            "Cannot redeclare {parent_modifier} property `{parent_class_name}::{property_name}` as {child_modifier} `{declaring_class_name}::{property_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(property_span)
                                .with_message(format!("This property is declared as `{child_modifier}`")),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_property_span)
                                .with_message(format!("Parent property is declared as `{parent_modifier}`")),
                        )
                        .with_note("Properties must maintain the same readonly modifier when overriding parent properties.")
                        .with_help(format!("Change this property to be `{parent_modifier}` to match the parent class.")),
                    );
            }

            // Determine allowed variance based on parent hooks:
            // - Virtual property with only `get` hook: covariance (declaring narrower than parent)
            //   is safe because consumers only read, so a more specific type upholds the contract.
            // - Virtual property with only `set` hook: contravariance (declaring wider than parent)
            //   is safe because consumers only write, so accepting a wider type upholds the contract.
            // - Otherwise, invariance is required.
            let parent_is_virtual = parent_property.flags.is_virtual_property();
            let parent_has_get_hook = parent_property.hooks.contains_key(&atom("get"));
            let parent_has_set_hook = parent_property.hooks.contains_key(&atom("set"));
            let parent_only_get = parent_is_virtual && parent_has_get_hook && !parent_has_set_hook;
            let parent_only_set = parent_is_virtual && parent_has_set_hook && !parent_has_get_hook;

            let mut has_type_incompatibility = false;
            match (
                property_metadata.type_declaration_metadata.as_ref(),
                parent_property.type_declaration_metadata.as_ref(),
            ) {
                (Some(declaring_type), Some(parent_type)) => {
                    if is_property_type_variance_invalid(
                        context.codebase,
                        &declaring_type.type_union,
                        &parent_type.type_union,
                        parent_only_get,
                        parent_only_set,
                    ) {
                        has_type_incompatibility = true;

                        let declaring_type_id = declaring_type.type_union.get_id();
                        let parent_type_id = parent_type.type_union.get_id();
                        let property_name = property_metadata.name.0;
                        let class_name = class_like_metadata.original_name;

                        context.collector.report_with_code(
                                IssueCode::IncompatiblePropertyType,
                                Issue::error(format!(
                                    "Property `{class_name}::{property_name}` has an incompatible type declaration."
                                ))
                                .with_annotation(
                                    Annotation::primary(declaring_type.span)
                                        .with_message(format!("This type `{declaring_type_id}` is incompatible with the parent's type.")),
                                )
                                .with_annotation(
                                    Annotation::secondary(parent_type.span)
                                        .with_message(format!("The parent property is defined with type `{parent_type_id}` here.")),
                                )
                                .with_note("PHP requires property types to be invariant, meaning the type declaration in a child class must be exactly the same as in the parent class.")
                                .with_help(format!("Change the type of `{property_name}` to `{parent_type_id}` to match the parent property."))
                            );
                    }
                }
                (Some(declaring_type), None) => {
                    has_type_incompatibility = true;

                    let property_name = property_metadata.name.0;
                    let class_name = class_like_metadata.original_name;

                    let mut issue = Issue::error(format!(
                        "Property `{class_name}::{property_name}` adds a type that is missing on the parent property."
                    ))
                    .with_annotation(
                        Annotation::primary(declaring_type.span)
                            .with_message("This type declaration is not present on the parent property"),
                    );

                    if let Some(parent_property_span) = parent_property.name_span {
                        issue = issue.with_annotation(
                            Annotation::secondary(parent_property_span)
                                .with_message("The parent property is defined here without a type"),
                        );
                    }

                    context.collector.report_with_code(IssueCode::IncompatiblePropertyType, issue
                            .with_note("Adding a type to a property that was untyped in a parent class is an incompatible change.")
                                   .with_help("You can either remove the type from this property or add an identical type to the property in the parent class."));
                }
                (None, Some(parent_type)) => {
                    has_type_incompatibility = true;

                    if let Some(property_span) = property_metadata.name_span {
                        let property_name = property_metadata.name.0;
                        let class_name = class_like_metadata.original_name;
                        let parent_type_id = parent_type.type_union.get_id();

                        context.collector.report_with_code(
                                IssueCode::IncompatiblePropertyType,
                                Issue::error(format!(
                                    "Property `{class_name}::{property_name}` is missing the type declaration from its parent."
                                ))
                                .with_annotation(
                                    Annotation::primary(property_span)
                                        .with_message("This property declaration is missing a type"),
                                )
                                .with_annotation(
                                    Annotation::secondary(parent_type.span)
                                        .with_message(format!("The parent property is defined with type `{parent_type_id}` here")),
                                )
                                .with_note("Removing a type from a property that was typed in a parent class is an incompatible change.")
                                .with_help(format!("Add the type declaration `{parent_type_id}` to this property to match the parent definition."))
                            );
                    }
                }
                (None, None) => {
                    // no type declaration, nothing to check
                }
            }

            if !has_type_incompatibility
                && let Some(declaring_type) = &property_metadata.type_metadata
                && declaring_type.from_docblock
                && let Some(parent_type) = &parent_property.type_metadata
                && is_property_type_variance_invalid(
                    context.codebase,
                    &declaring_type.type_union,
                    &parent_type.type_union,
                    parent_only_get,
                    parent_only_set,
                )
            {
                let declaring_type_id = declaring_type.type_union.get_id();
                let parent_type_id = parent_type.type_union.get_id();
                let property_name = property_metadata.name.0;
                let class_name = class_like_metadata.original_name;

                context.collector.report_with_code(
                        IssueCode::IncompatiblePropertyType,
                        Issue::error(format!(
                            "Property `{class_name}::{property_name}` has an incompatible type declaration from docblock."
                        ))
                        .with_annotation(
                            Annotation::primary(declaring_type.span)
                                .with_message(format!("This type `{declaring_type_id}` is incompatible with the parent's type.")),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_type.span)
                                .with_message(format!("The parent property is defined with type `{parent_type_id}` here.")),
                        )
                        .with_note("PHP requires property types to be invariant, meaning the type declaration in a child class must be exactly the same as in the parent class.")
                        .with_help(format!("Change the type of `{property_name}` to `{parent_type_id}` to match the parent property.")),
                    );
            }
        }

        // Check interface hook by-ref signature compatibility
        for interface_fqcn in &class_like_metadata.all_parent_interfaces {
            let Some(interface_metadata) = context.codebase.get_class_like(interface_fqcn) else {
                continue;
            };

            let Some(interface_property) = interface_metadata.properties.get(property_name) else {
                continue;
            };

            for (hook_name, interface_hook) in &interface_property.hooks {
                if !interface_hook.returns_by_ref {
                    continue;
                }

                let Some(impl_hook) = property_metadata.hooks.get(hook_name) else {
                    continue;
                };

                if impl_hook.returns_by_ref {
                    continue;
                }

                let declaring_class_name = class_like_metadata.original_name;
                let interface_name = interface_metadata.original_name;

                context.collector.report_with_code(
                    IssueCode::IncompatiblePropertyHookSignature,
                    Issue::error(format!(
                        "Declaration of `{declaring_class_name}::{property_name}::{hook_name}()` must be compatible with `& {interface_name}::{property_name}::{hook_name}()`."
                    ))
                    .with_annotation(
                        Annotation::primary(impl_hook.span)
                            .with_message("This hook does not return by reference"),
                    )
                    .with_annotation(
                        Annotation::secondary(interface_hook.span)
                            .with_message(format!("Interface `{interface_name}` requires this hook to return by reference")),
                    )
                    .with_note("When an interface declares a by-reference hook (`&get`), the implementing class must also return by reference.")
                    .with_help(format!("Add `&` to the `{hook_name}` hook declaration: `&{hook_name} => ...`")),
                );
            }
        }
    }
}

fn check_class_like_constants<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    members: &[ClassLikeMember<'arena>],
) {
    for member in members {
        let ClassLikeMember::Constant(constant) = member else {
            continue;
        };

        for item in &constant.items {
            let constant_name = atom(item.name.value);

            let Some(trait_fqcn) = class_like_metadata.trait_constant_ids.get(&constant_name) else {
                continue;
            };

            let Some(trait_metadata) = context.codebase.get_class_like(trait_fqcn) else {
                continue;
            };

            let Some(trait_constant) = trait_metadata.constants.get(&constant_name) else {
                continue;
            };
            let Some(class_constant) = class_like_metadata.constants.get(&constant_name) else {
                continue;
            };

            let value_matches = trait_constant.inferred_type == class_constant.inferred_type;
            let visibility_matches = trait_constant.visibility == class_constant.visibility;
            let finality_matches = trait_constant.flags.is_final() == class_constant.flags.is_final();

            if value_matches && visibility_matches && finality_matches {
                continue;
            }

            let class_name = class_like_metadata.original_name;
            let trait_name = trait_metadata.original_name;

            if !value_matches && visibility_matches && finality_matches {
                context.collector.report_with_code(
                    IssueCode::TraitConstantOverride,
                    Issue::error(format!(
                        "Class `{class_name}` cannot override constant `{constant_name}` from trait `{trait_name}` with a different value."
                    ))
                    .with_annotation(
                        Annotation::primary(item.name.span())
                            .with_message(format!("This constant has a different value than in trait `{trait_name}`")),
                    )
                    .with_note("PHP does not allow a class to override constants from traits it directly uses with a different value.")
                    .with_note(format!("Trait `{trait_name}` declares constant `{constant_name}`, which is inherited by `{class_name}`."))
                    .with_help(format!("Either use the same value as in the trait, remove the constant declaration from `{class_name}`, or remove the `use {trait_name}` statement.")),
                );
            } else {
                let mut conflicts = Vec::new();
                if !value_matches {
                    conflicts.push("value");
                }
                if !visibility_matches {
                    conflicts.push("visibility");
                }
                if !finality_matches {
                    conflicts.push("finality");
                }
                let conflicts_str = conflicts.join(", ");

                context.collector.report_with_code(
                    IssueCode::IncompatibleConstantOverride,
                    Issue::error(format!(
                        "{class_name} and {trait_name} define the same constant ({constant_name}) in the composition of {class_name}. However, the definition differs and is considered incompatible."
                    ))
                    .with_annotation(
                        Annotation::primary(item.name.span())
                            .with_message(format!("This constant differs from trait definition ({conflicts_str} differ)")),
                    )
                    .with_note(format!("Trait `{trait_name}` declares constant `{constant_name}`, which is inherited by `{class_name}`."))
                    .with_note("PHP requires that constants from traits match exactly in value, visibility, and finality when redeclared.")
                    .with_help(format!("Either match the trait's definition exactly, remove the constant declaration from `{class_name}`, or remove the `use {trait_name}` statement.")),
                );
            }
        }
    }

    for member in members {
        let ClassLikeMember::Constant(constant) = member else {
            continue;
        };

        for item in &constant.items {
            let constant_name = atom(item.name.value);

            let Some(child_constant) = class_like_metadata.constants.get(&constant_name) else {
                continue;
            };

            for parent_fqcn in &class_like_metadata.all_parent_classes {
                let parent_fqcn_str = parent_fqcn.as_ref();
                let Some(parent_metadata) = context.codebase.get_class_like(parent_fqcn_str) else {
                    continue;
                };

                let Some(parent_constant) = parent_metadata.constants.get(&constant_name) else {
                    continue;
                };

                if parent_constant.flags.is_final() {
                    let child_span = item.name.span();
                    let parent_span = parent_constant.span;
                    let class_name = class_like_metadata.original_name;
                    let parent_class_name = parent_metadata.original_name;

                    context.collector.report_with_code(
                        IssueCode::OverrideFinalConstant,
                        Issue::error(format!(
                            "Class `{class_name}` cannot override final constant `{constant_name}` from parent class `{parent_class_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(child_span)
                                .with_message("This constant attempts to override a final constant"),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_span)
                                .with_message(format!("The constant is declared as final in parent class `{parent_class_name}` here")),
                        )
                        .with_note("PHP 8.1+ allows constants to be marked as final to prevent overriding in child classes.")
                        .with_help(format!("Remove this constant declaration from `{class_name}` or remove the final modifier from the parent constant.")),
                    );
                }

                if child_constant.visibility > parent_constant.visibility {
                    let child_span = item.name.span();
                    let parent_span = parent_constant.span;
                    let class_name = class_like_metadata.original_name;
                    let parent_class_name = parent_metadata.original_name;
                    let child_visibility = child_constant.visibility;
                    let parent_visibility = parent_constant.visibility;

                    context.collector.report_with_code(
                        IssueCode::IncompatibleConstantAccess,
                        Issue::error(format!(
                            "Constant `{class_name}::{constant_name}` has narrower visibility than parent constant."
                        ))
                        .with_annotation(
                            Annotation::primary(child_span)
                                .with_message(format!("This constant is declared as `{child_visibility}`, which is narrower than the parent's `{parent_visibility}`")),
                        )
                        .with_annotation(
                            Annotation::secondary(parent_span)
                                .with_message(format!("Parent constant is declared as `{parent_visibility}` in `{parent_class_name}` here")),
                        )
                        .with_note("PHP requires that overriding constants maintain or widen visibility (public → protected → private).")
                        .with_help(format!("Change the visibility of `{constant_name}` to at least `{parent_visibility}` to match the parent constant.")),
                    );
                }

                let (Some(child_type), Some(parent_type)) =
                    (&child_constant.type_declaration, &parent_constant.type_declaration)
                else {
                    continue;
                };

                if is_type_compatible(context.codebase, &child_type.type_union, &parent_type.type_union) {
                    continue;
                }
                let child_type_id = child_type.type_union.get_id();
                let parent_type_id = parent_type.type_union.get_id();
                let class_name = class_like_metadata.original_name;
                let parent_class_name = parent_metadata.original_name;

                context.collector.report_with_code(
                    IssueCode::IncompatibleConstantType,
                    Issue::error(format!(
                        "Constant `{class_name}::{constant_name}` has an incompatible type declaration."
                    ))
                    .with_annotation(
                        Annotation::primary(child_type.span)
                            .with_message(format!("This type `{child_type_id}` is not compatible with the parent's type")),
                    )
                    .with_annotation(
                        Annotation::secondary(parent_type.span)
                            .with_message(format!("The parent constant is defined with type `{parent_type_id}` in `{parent_class_name}` here")),
                    )
                    .with_note("PHP 8.3+ allows typed constants with covariance, meaning the child type must be a subtype of the parent type.")
                    .with_help(format!("Change the type of `{constant_name}` to be compatible with `{parent_type_id}`.")),
                );
            }
        }
    }

    for member in members {
        let ClassLikeMember::Constant(constant) = member else {
            continue;
        };

        for item in &constant.items {
            let constant_name = atom(item.name.value);

            let Some(child_constant) = class_like_metadata.constants.get(&constant_name) else {
                continue;
            };

            for interface_fqcn in &class_like_metadata.all_parent_interfaces {
                let interface_fqcn_str = interface_fqcn.as_ref();
                let Some(interface_metadata) = context.codebase.get_class_like(interface_fqcn_str) else {
                    continue;
                };

                let Some(interface_constant) = interface_metadata.constants.get(&constant_name) else {
                    continue;
                };

                if child_constant.visibility != Visibility::Public {
                    let child_span = item.name.span();
                    let interface_span = interface_constant.span;
                    let class_name = class_like_metadata.original_name;
                    let interface_name = interface_metadata.original_name;
                    let child_visibility = child_constant.visibility;

                    context.collector.report_with_code(
                        IssueCode::IncompatibleConstantVisibility,
                        Issue::error(format!(
                            "Constant `{class_name}::{constant_name}` must be public to implement interface `{interface_name}`."
                        ))
                        .with_annotation(
                            Annotation::primary(child_span)
                                .with_message(format!("This constant is declared as `{child_visibility}`, but must be `public`")),
                        )
                        .with_annotation(
                            Annotation::secondary(interface_span)
                                .with_message(format!("Interface constant is declared in `{interface_name}` here")),
                        )
                        .with_note("All interface constants are implicitly public and implementing classes must maintain public visibility.")
                        .with_help(format!("Change the visibility of `{constant_name}` to `public`.")),
                    );
                }

                if let (Some(child_type), Some(interface_type)) =
                    (&child_constant.type_declaration, &interface_constant.type_declaration)
                    && !is_type_compatible(context.codebase, &child_type.type_union, &interface_type.type_union)
                {
                    let child_type_id = child_type.type_union.get_id();
                    let interface_type_id = interface_type.type_union.get_id();
                    let class_name = class_like_metadata.original_name;
                    let interface_name = interface_metadata.original_name;

                    context.collector.report_with_code(
                            IssueCode::IncompatibleConstantType,
                            Issue::error(format!(
                                "Constant `{class_name}::{constant_name}` has an incompatible type declaration."
                            ))
                            .with_annotation(
                                Annotation::primary(child_type.span)
                                    .with_message(format!("This type `{child_type_id}` is not compatible with the interface's type")),
                            )
                            .with_annotation(
                                Annotation::secondary(interface_type.span)
                                    .with_message(format!("The interface constant is defined with type `{interface_type_id}` in `{interface_name}` here")),
                            )
                            .with_note("Constants implementing interface constants must have compatible types (covariance allowed).")
                            .with_help(format!("Change the type of `{constant_name}` to be compatible with `{interface_type_id}`.")),
                        );
                }
            }
        }
    }
}

/// Check that a readonly class does not use traits with non-readonly properties.
///
/// In PHP, a readonly class can only use traits where all properties are declared readonly.
/// Using a trait with non-readonly properties in a readonly class causes a fatal error.
fn check_readonly_class_trait_properties<'ctx, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    members: &[ClassLikeMember<'arena>],
) {
    if !class_like_metadata.flags.is_readonly() {
        return;
    }

    for member in members {
        if let ClassLikeMember::TraitUse(trait_use) = member {
            for trait_name_id in &trait_use.trait_names {
                let (trait_fqcn, _) = context.scope.resolve(NameKind::Default, trait_name_id.value());
                let trait_fqcn = Atom::from(trait_fqcn.as_str());

                let Some(trait_metadata) = context.codebase.get_class_like(trait_fqcn.as_ref()) else {
                    continue;
                };

                for (property_name, property) in &trait_metadata.properties {
                    if !property.flags.is_readonly() {
                        context.collector.report_with_code(
                            IssueCode::InvalidTraitUse,
                            Issue::error(format!(
                                "Readonly class `{}` cannot use trait `{}` which has non-readonly property `{}`",
                                class_like_metadata.name, trait_fqcn, property_name
                            ))
                            .with_annotation(Annotation::primary(trait_name_id.span()).with_message("Trait used here"))
                            .with_note("All properties in a trait used by a readonly class must be declared readonly.")
                            .with_help(format!(
                                "Add the `readonly` modifier to property `{}` in trait `{}`.",
                                property_name, trait_fqcn
                            )),
                        );
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::code::IssueCode;
    use crate::test_analysis;

    test_analysis! {
        name = direct_interface_incompatible_parameter_name,
        code = "<?php
            interface Sizer {
                public function getSize(string $document): int;
            }
            class SizerImpl implements Sizer {
                public function getSize(string $file): int { return 100; }
            }
        ",
        issues = [IssueCode::IncompatibleParameterName],
    }

    test_analysis! {
        name = diamond_inheritance_incompatible_parameter_name,
        code = "<?php
            interface Logger {
                public function log(string $message): void;
            }
            interface FileLogger extends Logger {}
            interface DatabaseLogger extends Logger {}
            class CompositeLogger implements FileLogger, DatabaseLogger {
                public function log(string $entry): void {}
            }
        ",
        issues = [IssueCode::IncompatibleParameterName],
    }

    test_analysis! {
        name = indirect_interface_incompatible_parameter_name,
        code = "<?php
            interface Serializer {
                public function serialize(mixed $data): string;
            }
            interface JsonSerializer extends Serializer {}
            class DefaultJsonSerializer implements JsonSerializer {
                public function serialize(mixed $payload): string { return ''; }
            }
        ",
        issues = [IssueCode::IncompatibleParameterName],
    }
}