mir-analyzer 0.65.0

Analysis engine for the mir PHP static analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
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
//! Definition collector.
//!
//! Visits every top-level declaration in the AST and produces a `StubSlice`
//! containing class, function, and constant signatures. No type inference
//! happens here.

use rustc_hash::FxHashMap;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::sync::Arc;

use std::ops::ControlFlow;

use php_ast::ast::Visibility as AstVisibility;
use php_ast::owned::visitor::{walk_owned_program, walk_owned_stmt, OwnedVisitor};
use php_ast::owned::{Program, StmtKind};

use crate::parser::{name_to_string_owned, type_from_hint_owned};
use crate::php_version::PhpVersion;
use mir_codebase::definitions::{
    wrap_return_type, wrap_template_bound, Assertion, DeclaredParam, MethodDef, PropertyDef,
    StubSlice, TemplateParam, Visibility,
};
use mir_issues::{Issue, IssueBuffer};
use mir_types::{Atomic, Location, Name, Type};

mod annotation;
mod class;
mod r#enum;
mod function;
mod interface;
mod resolution;
mod r#trait;
mod version_attrs;

// ---------------------------------------------------------------------------
// Profiling counters for scalar type frequency
// ---------------------------------------------------------------------------

pub(crate) static SCALAR_PARAM_COUNT: AtomicUsize = AtomicUsize::new(0);
pub(crate) static COMPLEX_PARAM_COUNT: AtomicUsize = AtomicUsize::new(0);
pub(crate) static PARAM_WITH_DEFAULT: AtomicUsize = AtomicUsize::new(0);

/// Check if a Type is a simple scalar type (for profiling).
fn is_simple_scalar(u: &Type) -> bool {
    if u.possibly_undefined || u.from_docblock || u.types.len() != 1 {
        return false;
    }
    use mir_types::atomic::Atomic;
    matches!(
        &u.types[0],
        Atomic::TString
            | Atomic::TInt
            | Atomic::TFloat
            | Atomic::TIntegralFloat
            | Atomic::TBool
            | Atomic::TMixed
            | Atomic::TNull
            | Atomic::TVoid
            | Atomic::TNever
    )
}

/// Returns `true` when the native PHP hint is a single concrete scalar (bool/int/float/string)
/// whose scalar family is completely absent from the docblock type.
///
/// Used at collection time (no DB needed) to detect `@param int $x` + `bool $x` style
/// contradictions where the docblock has a *different* scalar family than the hint.
/// In that case the PHP hint is the runtime truth and should take precedence.
///
/// Does NOT fire when the docblock is a refinement of the hint (e.g. `positive-int` + `int`
/// hint, or `non-empty-string` + `string` hint): a refinement always contains atoms from the
/// same family, so `docblock_contains_hint_family` would be true and this returns false.
fn in_bool_family(a: &mir_types::atomic::Atomic) -> bool {
    use mir_types::atomic::Atomic;
    matches!(a, Atomic::TBool | Atomic::TTrue | Atomic::TFalse)
}
fn in_int_family(a: &mir_types::atomic::Atomic) -> bool {
    use mir_types::atomic::Atomic;
    matches!(
        a,
        Atomic::TInt
            | Atomic::TLiteralInt(_)
            | Atomic::TIntRange { .. }
            | Atomic::TPositiveInt
            | Atomic::TNegativeInt
            | Atomic::TNonNegativeInt
    )
}
fn in_float_family(a: &mir_types::atomic::Atomic) -> bool {
    use mir_types::atomic::Atomic;
    matches!(a, Atomic::TFloat | Atomic::TLiteralFloat(_, _))
}
fn in_string_family(a: &mir_types::atomic::Atomic) -> bool {
    use mir_types::atomic::Atomic;
    matches!(
        a,
        Atomic::TString
            | Atomic::TLiteralString(_)
            | Atomic::TClassString(_)
            | Atomic::TInterfaceString(_)
            | Atomic::TNumericString
    )
}
fn is_any_scalar_family(a: &mir_types::atomic::Atomic) -> bool {
    in_bool_family(a) || in_int_family(a) || in_float_family(a) || in_string_family(a)
}

/// When `native` is a single concrete scalar (int/string/bool/float), returns
/// the family-membership check for that scalar's family. `None` when native
/// isn't such a type (no family-based conflict is detectable).
fn native_scalar_family(native: &Type) -> Option<fn(&mir_types::atomic::Atomic) -> bool> {
    if native.types.len() != 1 {
        return None;
    }
    Some(match &native.types[0] {
        a if in_bool_family(a) => in_bool_family,
        a if in_int_family(a) => in_int_family,
        a if in_float_family(a) => in_float_family,
        a if in_string_family(a) => in_string_family,
        _ => return None,
    })
}

pub(crate) fn native_hint_wins_over_docblock_scalar(native: &Type, doc: &Type) -> bool {
    if doc.types.is_empty() {
        return false;
    }
    let Some(family_check) = native_scalar_family(native) else {
        return false;
    };
    // Docblock must contain ONLY scalar atoms from other families (no mixed/null/object that
    // could be a union refinement, and none from the hint's own family).
    doc.types
        .iter()
        .all(|a| is_any_scalar_family(a) && !family_check(a))
}

/// When `native` is a concrete scalar and `doc` contains scalar atoms from a
/// DIFFERENT family, those atoms describe a value the native hint can never
/// actually hold at runtime — PHP enforces the native hint, so it's the
/// runtime truth. Strips such foreign atoms from `doc` (keeping any
/// same-family or non-scalar atoms, e.g. `null`, untouched), falling back to
/// `native` entirely when nothing scalar-compatible survives. Returns `doc`
/// unchanged when `native` isn't a single concrete scalar (no conflict is
/// detectable this way) or when nothing needed stripping.
pub(crate) fn resolve_docblock_scalar_conflict(native: &Type, doc: Type) -> Type {
    let Some(family_check) = native_scalar_family(native) else {
        return doc;
    };
    let has_foreign_scalar = doc
        .types
        .iter()
        .any(|a| is_any_scalar_family(a) && !family_check(a));
    if !has_foreign_scalar {
        return doc;
    }
    let mut filtered = Type::empty();
    filtered.from_docblock = doc.from_docblock;
    filtered.possibly_undefined = doc.possibly_undefined;
    for a in doc.types.iter() {
        if !is_any_scalar_family(a) || family_check(a) {
            filtered.add_type(a.clone());
        }
    }
    if filtered.types.is_empty() {
        native.clone()
    } else {
        filtered
    }
}

/// A native `?Type` hint's nullability is PHP-enforced — always a real
/// possible runtime value — but a `@param` docblock that omits `null`
/// (`@param object $x` alongside a native `?object $x` hint) silently
/// dropped it entirely, since the docblock type otherwise wins outright over
/// the native hint. `resolve_docblock_scalar_conflict` above already guards
/// the scalar family case for a conflicting (non-null) atom; this is the
/// non-scalar counterpart, specifically for the null atom, since a scalar
/// hint's own family-conflict guard doesn't touch nullability at all. Unions
/// `TNull` back in when the native hint has it and the docblock doesn't;
/// otherwise returns `doc` unchanged.
pub(crate) fn preserve_native_nullability(native: &Type, mut doc: Type) -> Type {
    if native.is_nullable() && !doc.is_nullable() {
        doc.add_type(Atomic::TNull);
    }
    doc
}

/// Returns true for PHP built-in type keywords and Psalm pseudo-types that must never be
/// namespace-qualified, even when they appear as TNamedObject (e.g. inside generic params).
fn is_php_builtin_type(name: &str) -> bool {
    matches!(
        name,
        "array"
            | "bool"
            | "callable"
            | "false"
            | "float"
            | "int"
            | "iterable"
            | "list"
            | "mixed"
            | "never"
            | "null"
            | "object"
            | "parent"
            | "positive-int"
            | "scalar"
            | "self"
            | "static"
            | "string"
            | "true"
            | "void"
            | "class-string"
            | "int-mask"
            | "int-mask-of"
            | "key-of"
            | "lowercase-string"
            | "negative-int"
            | "non-empty-array"
            | "non-empty-list"
            | "non-empty-string"
            | "non-falsy-string"
            | "numeric-string"
            | "truthy-string"
            | "value-of"
    )
}

/// Substitute alias names in `union` with their pre-built definitions.
/// Does not touch FQN resolution; that is left to the caller's resolution pass.
///
/// Generic over the alias map's key type so both the collector's in-progress
/// `FxHashMap<String, Type>` and a class-like's already-built
/// `FxHashMap<Arc<str>, Type>` (`ClassLike::type_aliases`) can be passed
/// without cloning keys.
pub(crate) fn expand_aliases_only<K>(union: Type, aliases: &FxHashMap<K, Type>) -> Type
where
    K: std::borrow::Borrow<str> + std::hash::Hash + Eq,
{
    if aliases.is_empty() {
        return union;
    }
    let from_docblock = union.from_docblock;
    let mut result = Type::empty();
    result.possibly_undefined = union.possibly_undefined;
    result.from_docblock = from_docblock;
    for atomic in union.types {
        result.merge_with(&expand_aliases_in_atomic(atomic, aliases));
    }
    result
}

/// Expand a single atomic, returning the (possibly multi-atom) `Type` it
/// contributes. A bare (non-parameterized) `TNamedObject` matching an alias
/// name substitutes the alias's own definition directly, same as before.
/// Anything else is rebuilt with alias references in its OWN nested types
/// (a generic type argument, an array's key/value type, a shape property's
/// type, an intersection member) recursively expanded — previously a plain
/// alias used only inside one of these nested positions (e.g. `Box<IntList>`,
/// or `IntListList = array<IntList>`'s own definition) silently never
/// expanded at all, since only the single top-level atom was ever checked.
fn expand_aliases_in_atomic<K>(atomic: mir_types::Atomic, aliases: &FxHashMap<K, Type>) -> Type
where
    K: std::borrow::Borrow<str> + std::hash::Hash + Eq,
{
    use mir_types::Atomic;
    match atomic {
        Atomic::TNamedObject {
            ref fqcn,
            ref type_params,
        } if type_params.is_empty() => {
            if let Some(alias_ty) = aliases.get(fqcn.as_ref()) {
                alias_ty.clone()
            } else {
                Type::single(atomic)
            }
        }
        Atomic::TNamedObject { fqcn, type_params } => Type::single(Atomic::TNamedObject {
            fqcn,
            type_params: type_params
                .iter()
                .map(|t| expand_aliases_only(t.clone(), aliases))
                .collect(),
        }),
        Atomic::TArray { key, value } => Type::single(Atomic::TArray {
            key: Box::new(expand_aliases_only(*key, aliases)),
            value: Box::new(expand_aliases_only(*value, aliases)),
        }),
        Atomic::TNonEmptyArray { key, value } => Type::single(Atomic::TNonEmptyArray {
            key: Box::new(expand_aliases_only(*key, aliases)),
            value: Box::new(expand_aliases_only(*value, aliases)),
        }),
        Atomic::TList { value } => Type::single(Atomic::TList {
            value: Box::new(expand_aliases_only(*value, aliases)),
        }),
        Atomic::TNonEmptyList { value } => Type::single(Atomic::TNonEmptyList {
            value: Box::new(expand_aliases_only(*value, aliases)),
        }),
        Atomic::TKeyedArray {
            properties,
            is_open,
            is_list,
        } => {
            let properties = properties
                .into_iter()
                .map(|(k, prop)| {
                    (
                        k,
                        mir_types::atomic::KeyedProperty {
                            ty: expand_aliases_only(prop.ty, aliases),
                            optional: prop.optional,
                        },
                    )
                })
                .collect();
            Type::single(Atomic::TKeyedArray {
                properties: Box::new(properties),
                is_open,
                is_list,
            })
        }
        Atomic::TIntersection { parts } => Type::single(Atomic::TIntersection {
            parts: parts
                .iter()
                .map(|t| expand_aliases_only(t.clone(), aliases))
                .collect(),
        }),
        // `callable(T): R` / `Closure(T): R` — an alias used as a param or
        // return type inside one of these signatures (`@param
        // Closure(): IntList $factory`) previously never expanded at all,
        // since no arm here recursed into either variant.
        Atomic::TCallable {
            params,
            return_type,
        } => Type::single(Atomic::TCallable {
            params: params.map(|ps| {
                ps.iter()
                    .map(|p| mir_types::atomic::FnParam {
                        ty: p.ty.as_ref().map(|t| {
                            mir_types::compact::SimpleType::from_union(expand_aliases_only(
                                t.to_union(),
                                aliases,
                            ))
                        }),
                        out_ty: p.out_ty.as_ref().map(|t| {
                            mir_types::compact::SimpleType::from_union(expand_aliases_only(
                                t.to_union(),
                                aliases,
                            ))
                        }),
                        ..p.clone()
                    })
                    .collect::<Vec<_>>()
                    .into_boxed_slice()
            }),
            return_type: return_type.map(|rt| Box::new(expand_aliases_only(*rt, aliases))),
        }),
        Atomic::TClosure { data } => Type::single(Atomic::TClosure {
            data: Box::new(mir_types::atomic::ClosureData {
                params: data
                    .params
                    .iter()
                    .map(|p| mir_types::atomic::FnParam {
                        ty: p.ty.as_ref().map(|t| {
                            mir_types::compact::SimpleType::from_union(expand_aliases_only(
                                t.to_union(),
                                aliases,
                            ))
                        }),
                        out_ty: p.out_ty.as_ref().map(|t| {
                            mir_types::compact::SimpleType::from_union(expand_aliases_only(
                                t.to_union(),
                                aliases,
                            ))
                        }),
                        ..p.clone()
                    })
                    .collect::<Vec<_>>()
                    .into_boxed_slice(),
                return_type: expand_aliases_only(data.return_type, aliases),
                this_type: data.this_type.map(|t| expand_aliases_only(t, aliases)),
            }),
        }),
        // `@return ($param is X ? A : B)` — a type alias used in either
        // branch (or the subject) of a conditional return type never expanded
        // at all, since no arm here recursed into `TConditional`; it fell
        // through to the `other` catch-all below, leaking the raw
        // unexpanded alias atom into the resolved branch type.
        Atomic::TConditional { data } => Type::single(Atomic::TConditional {
            data: Box::new(mir_types::atomic::ConditionalData {
                param_name: data.param_name,
                subject: expand_aliases_only(data.subject, aliases),
                if_true: expand_aliases_only(data.if_true, aliases),
                if_false: expand_aliases_only(data.if_false, aliases),
            }),
        }),
        other => Type::single(other),
    }
}

/// Print profiling statistics for type collection.
pub(crate) fn print_collector_stats() {
    let scalar = SCALAR_PARAM_COUNT.load(Relaxed);
    let complex = COMPLEX_PARAM_COUNT.load(Relaxed);
    let with_default = PARAM_WITH_DEFAULT.load(Relaxed);
    let total = scalar + complex;
    let scalar_pct = if total > 0 {
        (scalar as f64 / total as f64) * 100.0
    } else {
        0.0
    };
    eprintln!("  [collector stats]");
    eprintln!("    scalar params:        {} ({:.1}%)", scalar, scalar_pct);
    eprintln!("    complex params:       {}", complex);
    eprintln!("    params with default:  {}", with_default);
}

// ---------------------------------------------------------------------------
// Constant value inference
// ---------------------------------------------------------------------------

/// Infer the type of a constant value from its AST expression (owned AST).
/// This handles literal values like integers, strings, etc. used in define().
///
/// `collector` is consulted only for the `ClassConstAccess` arm (`Foo::BAR`),
/// to resolve a same-file, already-collected enum case/constant — this
/// collector has no cross-file or database access, so a reference to a class
/// declared later in the file, or in a different file, still falls through to
/// `None` (the pre-existing `mixed` fallback), same as today.
pub(super) fn infer_const_value(
    collector: &DefinitionCollector,
    expr_kind: &php_ast::owned::ExprKind,
) -> Option<Type> {
    use php_ast::ast::{BinaryOp, UnaryPrefixOp};

    match expr_kind {
        php_ast::owned::ExprKind::Int(i) => Some(Type::single(Atomic::TLiteralInt(*i))),
        php_ast::owned::ExprKind::String(s) => {
            Some(Type::single(Atomic::TLiteralString(Arc::from(&**s))))
        }
        php_ast::owned::ExprKind::Float(_f) => Some(Type::single(Atomic::TFloat)),
        php_ast::owned::ExprKind::Bool(_b) => Some(Type::single(Atomic::TBool)),
        php_ast::owned::ExprKind::Null => Some(Type::single(Atomic::TNull)),
        // For unary expressions like -1, try to evaluate them
        php_ast::owned::ExprKind::UnaryPrefix(u) => match u.op {
            UnaryPrefixOp::Negate => {
                if let php_ast::owned::ExprKind::Int(i) = &u.operand.kind {
                    Some(Type::single(Atomic::TLiteralInt(-i)))
                } else {
                    None
                }
            }
            UnaryPrefixOp::Plus => {
                if let php_ast::owned::ExprKind::Int(i) = &u.operand.kind {
                    Some(Type::single(Atomic::TLiteralInt(*i)))
                } else {
                    None
                }
            }
            _ => None,
        },
        php_ast::owned::ExprKind::Parenthesized(inner) => infer_const_value(collector, &inner.kind),
        // A literal array constant (`const array D = [',', ';', "\t"];`) gets
        // the same keyed-shape/list treatment an inline array literal already
        // gets from `expr/arrays.rs::analyze_array` — building it here (rather
        // than through that function, which needs a live `FlowState` for
        // diagnostics/taint that a compile-time constant expression has no use
        // for) is what lets `self::D` retain its element count and per-element
        // literal types instead of widening to a bare `array`. Bails to `None`
        // (falls back to the native `array` hint, same as today) on anything
        // not fully resolvable at compile time: a spread, a by-ref element, a
        // non-literal key, or any element value that isn't itself inferable.
        php_ast::owned::ExprKind::Array(elements) => {
            use mir_types::atomic::{ArrayKey, KeyedProperty};
            let mut keyed_props: indexmap::IndexMap<ArrayKey, KeyedProperty> =
                indexmap::IndexMap::new();
            let mut is_list = true;
            let mut next_int_key: i64 = 0;
            for elem in elements.iter() {
                if elem.unpack || elem.by_ref {
                    return None;
                }
                let value_ty = infer_const_value(collector, &elem.value.kind)?;
                let key = if let Some(key_expr) = &elem.key {
                    is_list = false;
                    match infer_const_value(collector, &key_expr.kind)?
                        .types
                        .as_slice()
                    {
                        [Atomic::TLiteralString(s)] => ArrayKey::String(s.clone()),
                        [Atomic::TLiteralInt(i)] => {
                            next_int_key = *i + 1;
                            ArrayKey::Int(*i)
                        }
                        _ => return None,
                    }
                } else {
                    let k = ArrayKey::Int(next_int_key);
                    next_int_key += 1;
                    k
                };
                keyed_props.insert(
                    key,
                    KeyedProperty {
                        ty: value_ty,
                        optional: false,
                    },
                );
            }
            Some(Type::single(Atomic::TKeyedArray {
                properties: Box::new(keyed_props),
                is_open: false,
                is_list,
            }))
        }
        // Idiomatic bitflag declarations (`const FLAG_A = 1 << 0;`) and other
        // literal-int arithmetic. Only evaluated when both operands are
        // themselves literal ints, so `self::OTHER_CONST | 1` still falls
        // through to `None` rather than guessing.
        php_ast::owned::ExprKind::Binary(b) => {
            let as_int = |t: Type| -> Option<i64> {
                (t.types.len() == 1)
                    .then(|| match t.types[0] {
                        Atomic::TLiteralInt(n) => Some(n),
                        _ => None,
                    })
                    .flatten()
            };
            let l = as_int(infer_const_value(collector, &b.left.kind)?)?;
            let r = as_int(infer_const_value(collector, &b.right.kind)?)?;
            let result = match b.op {
                BinaryOp::BitwiseOr => l | r,
                BinaryOp::BitwiseAnd => l & r,
                BinaryOp::BitwiseXor => l ^ r,
                BinaryOp::ShiftLeft => l.checked_shl(u32::try_from(r).ok()?)?,
                BinaryOp::ShiftRight => l.checked_shr(u32::try_from(r).ok()?)?,
                BinaryOp::Add => l.checked_add(r)?,
                BinaryOp::Sub => l.checked_sub(r)?,
                BinaryOp::Mul => l.checked_mul(r)?,
                _ => return None,
            };
            Some(Type::single(Atomic::TLiteralInt(result)))
        }
        // `Foo::BAR` / `self::BAR` referencing an enum case or a plain class
        // constant of an already-collected same-file class-like.
        php_ast::owned::ExprKind::ClassConstAccess(cca) => {
            let php_ast::owned::ExprKind::Identifier(class_name) = &cca.class.kind else {
                return None;
            };
            let php_ast::owned::ExprKind::Identifier(const_name) = &cca.member.kind else {
                return None;
            };
            if const_name.as_ref() == "class" {
                return None;
            }
            let resolved = collector.resolve_name(class_name.as_ref());
            if let Some(enum_def) = collector
                .slice
                .enums
                .iter()
                .find(|e| e.fqcn.eq_ignore_ascii_case(&resolved))
            {
                if enum_def.cases.contains_key(const_name.as_ref()) {
                    // Matches `find_class_constant_in_class`'s own enum-case
                    // representation (a plain `TNamedObject`, not
                    // `TLiteralEnumCase` — that atom is reserved for
                    // match-narrowing/contradiction checks) so this constant's
                    // inferred type subtypes the enum the same way a direct
                    // `Suit::Hearts` access already does.
                    return Some(Type::single(Atomic::TNamedObject {
                        fqcn: Name::from(enum_def.fqcn.as_ref()),
                        type_params: mir_types::union::empty_type_params(),
                    }));
                }
                if let Some(c) = enum_def.own_constants.get(const_name.as_ref()) {
                    return Some(c.ty.clone());
                }
                return None;
            }
            collector
                .slice
                .classes
                .iter()
                .find(|c| c.fqcn.eq_ignore_ascii_case(&resolved))
                .and_then(|c| c.own_constants.get(const_name.as_ref()))
                .map(|c| c.ty.clone())
        }
        _ => None,
    }
}

/// A native scalar type hint on a class/interface/enum constant (PHP 8.3+)
/// otherwise wins over literal inference outright, discarding precision a
/// same-kind literal would give (`const int ID = 5;` typing as bare `int`
/// instead of `5`). Narrows back to the literal only when the hint is
/// exactly the literal's own base scalar — anything else (e.g. a `float`
/// hint on an int literal, which PHP coerces to a float value at runtime)
/// keeps the hint as-is.
pub(super) fn const_type_with_literal_narrowing(
    hint_ty: Option<Type>,
    literal_ty: Option<Type>,
) -> Option<Type> {
    let narrows = match (
        hint_ty.as_ref().map(|t| t.types.as_slice()),
        literal_ty.as_ref().map(|t| t.types.as_slice()),
    ) {
        (Some([Atomic::TInt]), Some([Atomic::TLiteralInt(_)]))
        | (Some([Atomic::TString]), Some([Atomic::TLiteralString(_)])) => true,
        // A bare `array` hint (key/value both unannotated `mixed`) narrows to
        // the literal's own keyed-shape/list type the same way — an explicitly
        // narrower hint (`array<int, string>`) is left as-is, since the
        // literal might not actually satisfy it and this isn't the place to
        // check that.
        (Some([Atomic::TArray { key, value }]), Some([Atomic::TKeyedArray { .. }])) => {
            key.is_mixed() && value.is_mixed()
        }
        _ => false,
    };
    if narrows {
        literal_ty
    } else {
        hint_ty.or(literal_ty)
    }
}

// ---------------------------------------------------------------------------
// DefinitionCollector
// ---------------------------------------------------------------------------

pub struct DefinitionCollector<'a> {
    slice: StubSlice,
    file: Arc<str>,
    source: &'a str,
    source_map: &'a php_rs_parser::source_map::SourceMap,
    namespace: Option<String>,
    /// `use` aliases: alias → FQCN. `UseKind::Normal` only — every consumer
    /// resolves a class/type/attribute/exception name, so a `use function`/
    /// `use const` alias must never appear here.
    use_aliases: FxHashMap<String, String>,
    issues: IssueBuffer,
    /// When `Some`, stub symbols annotated with `@since`/`@removed` are filtered
    /// against this target version. `None` disables filtering (user code).
    php_version: Option<PhpVersion>,
    /// The first namespace declaration seen in this file. Matches the semantics
    /// of `project.rs` which only records the first namespace per file.
    first_namespace: Option<String>,
    /// All `use` imports ever encountered in this file — every `UseKind`,
    /// unlike `use_aliases` — accumulated across all namespace blocks. Unlike
    /// `use_aliases`, this is never cleared or restored, so braced-namespace
    /// imports are not lost. Feeds `slice.imports` / `file_imports()`, which
    /// Pass-2 function-call resolution relies on for `use function` aliases.
    accumulated_imports: FxHashMap<String, String>,
    /// Subset of `accumulated_imports` containing only `UseKind::Normal`
    /// (class/interface/trait/enum) aliases — excludes `use function`/`use const`.
    /// Feeds `slice.class_imports`, consulted by class-name resolution so a
    /// function/constant import can't shadow a same-named class reference.
    accumulated_class_imports: FxHashMap<String, String>,
}

impl<'a> DefinitionCollector<'a> {
    pub fn new_for_slice(
        file: Arc<str>,
        source: &'a str,
        source_map: &'a php_rs_parser::source_map::SourceMap,
    ) -> Self {
        let slice = StubSlice {
            file: Some(file.clone()),
            ..StubSlice::default()
        };
        Self {
            source_map,
            slice,
            file,
            source,
            namespace: None,
            use_aliases: FxHashMap::default(),
            issues: IssueBuffer::new(),
            php_version: None,
            first_namespace: None,
            accumulated_imports: FxHashMap::default(),
            accumulated_class_imports: FxHashMap::default(),
        }
    }

    /// Enable `@since`/`@removed` filtering against the given target PHP
    /// version. Used by the stub loader so that symbols introduced after, or
    /// removed at or before, the target version are not registered.
    pub fn with_php_version(mut self, version: PhpVersion) -> Self {
        self.php_version = Some(version);
        self
    }

    /// Returns `true` if a docblock's `@since`/`@removed` tags allow this
    /// symbol to exist at the configured target version. When no target is
    /// configured (user code), always returns `true`.
    fn version_allows(&self, doc: &crate::parser::ParsedDocblock) -> bool {
        match self.php_version {
            Some(v) => v.includes_symbol(doc.since.as_deref(), doc.removed.as_deref()),
            None => true,
        }
    }

    /// Whether a stub element (function/method/param) carrying
    /// `#[PhpStormStubsElementAvailable]` is available at the configured target
    /// version. Always `true` for user code (`php_version == None`) or when the
    /// attribute is absent. See [`version_attrs`].
    fn version_attr_available(&self, attrs: &[php_ast::owned::Attribute]) -> bool {
        match self.php_version {
            Some(v) => version_attrs::is_available(attrs, &self.use_aliases, v),
            None => true,
        }
    }

    /// The `#[LanguageLevelTypeAware]` type-string override for the target
    /// version, if any. `None` for user code, an absent attribute, or an empty
    /// (`default: ''`) resolution. Callers parse the string via
    /// [`parse_type_string`](crate::parser::docblock::parse_type_string).
    fn version_attr_type_string(&self, attrs: &[php_ast::owned::Attribute]) -> Option<String> {
        let v = self.php_version?;
        version_attrs::type_aware(attrs, &self.use_aliases, v)
    }

    fn parse_docblock_from_node(
        &self,
        doc_comment: Option<&php_ast::owned::Comment>,
    ) -> crate::parser::ParsedDocblock {
        doc_comment
            .map(|c| crate::parser::DocblockParser::parse(&c.text))
            .unwrap_or_default()
    }

    /// Writes accumulated namespace and import data into `self.slice` so that
    /// `file_namespace()` and `file_imports()` can derive them via
    /// `collect_file_definitions`. Called at the end of `collect_slice`.
    fn finalize_slice(&mut self) {
        if let Some(ns) = self.first_namespace.take() {
            self.slice.namespace = Some(Arc::from(ns.as_str()));
        }
        if !self.accumulated_imports.is_empty() {
            // Convert collector's String-keyed map into the storage shape:
            // Arc<FxHashMap<Name, Name>>. `Name::new` interns each string
            // via the global ustr pool once per unique alias/FQCN.
            let raw = std::mem::take(&mut self.accumulated_imports);
            let mut interned: FxHashMap<mir_types::Name, mir_types::Name> =
                FxHashMap::with_capacity_and_hasher(raw.len(), Default::default());
            for (alias, fqcn) in raw {
                interned.insert(mir_types::Name::new(&alias), mir_types::Name::new(&fqcn));
            }
            self.slice.imports = Arc::new(interned);
        }
        if !self.accumulated_class_imports.is_empty() {
            let raw = std::mem::take(&mut self.accumulated_class_imports);
            let mut interned: FxHashMap<mir_types::Name, mir_types::Name> =
                FxHashMap::with_capacity_and_hasher(raw.len(), Default::default());
            for (alias, fqcn) in raw {
                interned.insert(mir_types::Name::new(&alias), mir_types::Name::new(&fqcn));
            }
            self.slice.class_imports = Arc::new(interned);
        }
    }

    pub fn collect_slice(mut self, program: &Program) -> (StubSlice, Vec<Issue>) {
        let _ = self.visit_program(program);
        self.finalize_slice();
        (self.slice, self.issues.into_all_issues())
    }

    // -----------------------------------------------------------------------
    // FQCN resolution helpers
    // -----------------------------------------------------------------------
    // Type Resolution (delegating to resolution module)
    // -----------------------------------------------------------------------

    fn resolve_name(&self, name: &str) -> String {
        resolution::resolve_name(name, &self.namespace, &self.use_aliases)
    }

    /// Compute the FQCN a class/interface/trait/enum *declaration* establishes
    /// for its own short name: `current_namespace \ short_name`, never run
    /// through `use`-alias substitution. A declaration names a new symbol, it
    /// doesn't reference an existing one — unlike `resolve_name`, which must
    /// consult `use_aliases` because callers pass it names being *referenced*
    /// (`extends`, `implements`, type hints, ...). Using `resolve_name` here
    /// misfires when the short name collides with a `use function`/`use
    /// const` alias of the same spelling (legal in PHP, since functions and
    /// constants live in a separate symbol table from classes): the
    /// declaration would be silently registered under the alias's target
    /// FQCN instead of its own namespace.
    fn declared_fqn(&self, short_name: &str) -> String {
        match &self.namespace {
            Some(ns) => format!("{ns}\\{short_name}"),
            None => short_name.to_string(),
        }
    }

    fn resolve_type_name(&self, name: &str, full_qualify: bool) -> mir_types::Name {
        resolution::resolve_type_name(name, full_qualify, &self.namespace, &self.use_aliases)
    }

    fn fill_self_static_parent(union: Type, class_fqcn: &str) -> Type {
        resolution::fill_self_static_parent(union, class_fqcn)
    }

    fn resolve_union_doc(&self, union: Type) -> Type {
        resolution::resolve_union_doc(union, &self.namespace, &self.use_aliases)
    }

    fn resolve_union_doc_with_aliases(
        &self,
        union: Type,
        aliases: &FxHashMap<String, Type>,
    ) -> Type {
        resolution::resolve_union_doc_with_aliases(
            union,
            aliases,
            &self.namespace,
            &self.use_aliases,
        )
    }

    fn resolve_union_opt(&self, opt: Option<Type>) -> Option<Type> {
        resolution::resolve_union_opt(opt, &self.namespace, &self.use_aliases)
    }

    /// Like `resolve_union_doc_with_templates`, but also expands a bare class
    /// name matching a same-file `@psalm-type`/`@phpstan-type` alias before
    /// falling back to template/namespace resolution. Used for magic
    /// `@property`/`@method` docblock member types (`add_docblock_members`),
    /// which — unlike a real member's `@var`/`@param`/`@return` — previously
    /// went through `resolve_union_doc_with_aliases` alone: that resolver
    /// deliberately leaves a bare, non-aliased class name namespace-unqualified
    /// (see the comment on `substitute_template_params`), so `@property Foo $x`
    /// inside a namespaced file stored the literal, unqualified name `Foo`
    /// instead of `App\Foo` — silently failing every existence check and
    /// reference recording done against it.
    fn resolve_docblock_member_type(
        &self,
        union: Type,
        aliases: &FxHashMap<String, Type>,
        template_names: &rustc_hash::FxHashSet<String>,
        template_params: &[TemplateParam],
        defining_entity: &str,
    ) -> Type {
        // Alias substitution first (recurses into nested positions — a
        // generic type argument, an array's key/value type, … — via
        // `expand_aliases_only`), THEN template/namespace resolution, same
        // ordering as the other docblock-type resolution call sites.
        let expanded = expand_aliases_only(union, aliases);
        self.resolve_union_doc_with_templates(
            expanded,
            template_names,
            defining_entity,
            template_params,
        )
    }

    fn resolve_union_doc_with_templates(
        &self,
        union: Type,
        template_names: &rustc_hash::FxHashSet<String>,
        defining_entity: &str,
        template_params: &[TemplateParam],
    ) -> Type {
        let mut result = Type::empty();
        result.possibly_undefined = union.possibly_undefined;
        result.from_docblock = union.from_docblock;
        for atomic in union.types {
            match &atomic {
                mir_types::Atomic::TNamedObject { fqcn, type_params }
                    if type_params.is_empty() && template_names.contains(fqcn.as_ref()) =>
                {
                    // Find the bound for this template parameter
                    let bound = template_params
                        .iter()
                        .find(|tp| tp.name.as_ref() == fqcn.as_ref())
                        .and_then(|tp| tp.bound.as_deref().cloned())
                        .unwrap_or_else(Type::mixed);

                    // This is a template parameter reference
                    result.add_type(mir_types::Atomic::TTemplateParam {
                        name: *fqcn,
                        as_type: Box::new(bound),
                        defining_entity: defining_entity.into(),
                    });
                }
                // A generic class like ObjectProphecy<T>: the outer class name must be
                // FQN-qualified (it is a real class, not a template), and type_params are
                // recursed through this function so template names inside (e.g. T) are
                // properly converted to TTemplateParam.
                // Guard: PHP built-in pseudo-types (array, iterable, callable, …) can appear
                // as TNamedObject with type params in some docblock parse paths; do not
                // namespace-qualify those — fall through to resolve_union_doc.
                mir_types::Atomic::TNamedObject { fqcn, type_params }
                    if !type_params.is_empty() && !is_php_builtin_type(fqcn.as_ref()) =>
                {
                    let resolved_fqcn = resolution::resolve_type_name(
                        fqcn.as_ref(),
                        true,
                        &self.namespace,
                        &self.use_aliases,
                    );
                    let new_params: Vec<Type> = type_params
                        .iter()
                        .map(|p| {
                            self.resolve_union_doc_with_templates(
                                p.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            )
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TNamedObject {
                        fqcn: resolved_fqcn,
                        type_params: mir_types::union::vec_to_type_params(new_params),
                    });
                }
                // Bare non-template class name (empty type_params, not a template param):
                // FQN-qualify it so same-namespace class references in docblocks are stored
                // with their full path. PHP built-in type keywords (array, list, callable, …)
                // are excluded — they must not be namespace-qualified even if the docblock
                // parser emits them as TNamedObject.
                mir_types::Atomic::TNamedObject { fqcn, .. }
                    if !is_php_builtin_type(fqcn.as_ref()) =>
                {
                    let resolved_fqcn = resolution::resolve_type_name(
                        fqcn.as_ref(),
                        true,
                        &self.namespace,
                        &self.use_aliases,
                    );
                    result.add_type(mir_types::Atomic::TNamedObject {
                        fqcn: resolved_fqcn,
                        type_params: mir_types::union::empty_type_params(),
                    });
                }
                // Intersection bound like `Type&Named`: recurse into each part so every
                // class name inside is FQN-qualified and template references are converted.
                mir_types::Atomic::TIntersection { parts } => {
                    let new_parts: Vec<Type> = parts
                        .iter()
                        .map(|p| {
                            self.resolve_union_doc_with_templates(
                                p.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            )
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TIntersection {
                        parts: mir_types::union::vec_to_type_params(new_parts),
                    });
                }
                // Array types: recurse into key and value with template awareness so that
                // bare template names like `L` inside `array<int, L>` are converted to
                // TTemplateParam rather than left as unresolved TNamedObject references.
                mir_types::Atomic::TArray { key, value } => {
                    result.add_type(mir_types::Atomic::TArray {
                        key: Box::new(self.resolve_union_doc_with_templates(
                            *key.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                        value: Box::new(self.resolve_union_doc_with_templates(
                            *value.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                    });
                }
                mir_types::Atomic::TNonEmptyArray { key, value } => {
                    result.add_type(mir_types::Atomic::TNonEmptyArray {
                        key: Box::new(self.resolve_union_doc_with_templates(
                            *key.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                        value: Box::new(self.resolve_union_doc_with_templates(
                            *value.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                    });
                }
                mir_types::Atomic::TList { value } => {
                    result.add_type(mir_types::Atomic::TList {
                        value: Box::new(self.resolve_union_doc_with_templates(
                            *value.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                    });
                }
                mir_types::Atomic::TNonEmptyList { value } => {
                    result.add_type(mir_types::Atomic::TNonEmptyList {
                        value: Box::new(self.resolve_union_doc_with_templates(
                            *value.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        )),
                    });
                }
                mir_types::Atomic::TKeyedArray {
                    properties,
                    is_open,
                    is_list,
                } => {
                    let mut new_props = properties.clone();
                    for prop in new_props.values_mut() {
                        prop.ty = self.resolve_union_doc_with_templates(
                            prop.ty.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        );
                    }
                    result.add_type(mir_types::Atomic::TKeyedArray {
                        properties: new_props,
                        is_open: *is_open,
                        is_list: *is_list,
                    });
                }
                // Conditional return type: recurse into subject and both branches with the
                // same template context so class names and template references inside them
                // are resolved correctly.
                mir_types::Atomic::TConditional { data } => {
                    result.add_type(mir_types::Atomic::TConditional {
                        data: Box::new(mir_types::atomic::ConditionalData {
                            param_name: data.param_name,
                            subject: self.resolve_union_doc_with_templates(
                                data.subject.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            ),
                            if_true: self.resolve_union_doc_with_templates(
                                data.if_true.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            ),
                            if_false: self.resolve_union_doc_with_templates(
                                data.if_false.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            ),
                        }),
                    });
                }
                // Closure/callable param & return types: recurse with template awareness so
                // a bare template name used inside `Closure(T): R` (e.g. a higher-order
                // function's predicate/mapper param) is converted to TTemplateParam instead
                // of falling through to resolve_union_doc, which has no template context and
                // would leave it as an unresolved bare class-like reference to "T".
                mir_types::Atomic::TClosure { data } => {
                    let new_params = data
                        .params
                        .iter()
                        .map(|p| {
                            let mut p = p.clone();
                            p.ty = p.ty.as_ref().map(|t| {
                                mir_types::compact::SimpleType::from_union(
                                    self.resolve_union_doc_with_templates(
                                        t.to_union(),
                                        template_names,
                                        defining_entity,
                                        template_params,
                                    ),
                                )
                            });
                            p
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TClosure {
                        data: Box::new(mir_types::atomic::ClosureData {
                            params: new_params,
                            return_type: self.resolve_union_doc_with_templates(
                                data.return_type.clone(),
                                template_names,
                                defining_entity,
                                template_params,
                            ),
                            this_type: data.this_type.clone(),
                        }),
                    });
                }
                mir_types::Atomic::TCallable {
                    params,
                    return_type,
                } => {
                    let new_params = params.as_ref().map(|ps| {
                        ps.iter()
                            .map(|p| {
                                let mut p = p.clone();
                                p.ty = p.ty.as_ref().map(|t| {
                                    mir_types::compact::SimpleType::from_union(
                                        self.resolve_union_doc_with_templates(
                                            t.to_union(),
                                            template_names,
                                            defining_entity,
                                            template_params,
                                        ),
                                    )
                                });
                                p
                            })
                            .collect()
                    });
                    let new_return_type = return_type.as_deref().map(|t| {
                        Box::new(self.resolve_union_doc_with_templates(
                            t.clone(),
                            template_names,
                            defining_entity,
                            template_params,
                        ))
                    });
                    result.add_type(mir_types::Atomic::TCallable {
                        params: new_params,
                        return_type: new_return_type,
                    });
                }
                _ => {
                    let resolved_union = self.resolve_union_doc(Type::single(atomic.clone()));
                    for resolved_atomic in resolved_union.types {
                        result.add_type(resolved_atomic);
                    }
                }
            }
        }
        result
    }

    /// Post-resolution template substitution for method params.
    ///
    /// `resolve_union_doc` / `resolve_union_doc_with_aliases` use `full_qualify=false`
    /// so bare names like `Closure` or `Countable` stay bare (correct behavior for params).
    /// But template param names (e.g. `TRelatedModel`) also stay bare — they need a second
    /// pass to become `TTemplateParam`. This function does ONLY that conversion without
    /// touching qualification, so it is safe to call after `resolve_union_doc`.
    fn substitute_template_params(
        &self,
        ty: Type,
        template_names: &rustc_hash::FxHashSet<String>,
        template_params: &[TemplateParam],
        defining_entity: &str,
    ) -> Type {
        let mut result = Type::empty();
        result.possibly_undefined = ty.possibly_undefined;
        result.from_docblock = ty.from_docblock;
        for atomic in ty.types {
            match &atomic {
                mir_types::Atomic::TNamedObject { fqcn, type_params }
                    if type_params.is_empty() && template_names.contains(fqcn.as_ref()) =>
                {
                    let bound = template_params
                        .iter()
                        .find(|tp| tp.name.as_ref() == fqcn.as_ref())
                        .and_then(|tp| tp.bound.as_deref().cloned())
                        .unwrap_or_else(Type::mixed);
                    result.add_type(mir_types::Atomic::TTemplateParam {
                        name: *fqcn,
                        as_type: Box::new(bound),
                        defining_entity: defining_entity.into(),
                    });
                }
                mir_types::Atomic::TNamedObject { fqcn, type_params }
                    if !type_params.is_empty() =>
                {
                    let new_params: Vec<Type> = type_params
                        .iter()
                        .map(|p| {
                            self.substitute_template_params(
                                p.clone(),
                                template_names,
                                template_params,
                                defining_entity,
                            )
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TNamedObject {
                        fqcn: *fqcn,
                        type_params: mir_types::union::vec_to_type_params(new_params),
                    });
                }
                mir_types::Atomic::TIntersection { parts } => {
                    let new_parts: Vec<Type> = parts
                        .iter()
                        .map(|p| {
                            self.substitute_template_params(
                                p.clone(),
                                template_names,
                                template_params,
                                defining_entity,
                            )
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TIntersection {
                        parts: mir_types::union::vec_to_type_params(new_parts),
                    });
                }
                mir_types::Atomic::TArray { key, value } => {
                    result.add_type(mir_types::Atomic::TArray {
                        key: Box::new(self.substitute_template_params(
                            *key.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                        value: Box::new(self.substitute_template_params(
                            *value.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                    });
                }
                mir_types::Atomic::TNonEmptyArray { key, value } => {
                    result.add_type(mir_types::Atomic::TNonEmptyArray {
                        key: Box::new(self.substitute_template_params(
                            *key.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                        value: Box::new(self.substitute_template_params(
                            *value.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                    });
                }
                mir_types::Atomic::TList { value } => {
                    result.add_type(mir_types::Atomic::TList {
                        value: Box::new(self.substitute_template_params(
                            *value.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                    });
                }
                mir_types::Atomic::TNonEmptyList { value } => {
                    result.add_type(mir_types::Atomic::TNonEmptyList {
                        value: Box::new(self.substitute_template_params(
                            *value.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        )),
                    });
                }
                mir_types::Atomic::TKeyedArray {
                    properties,
                    is_open,
                    is_list,
                } => {
                    let mut new_props = properties.clone();
                    for prop in new_props.values_mut() {
                        prop.ty = self.substitute_template_params(
                            prop.ty.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        );
                    }
                    result.add_type(mir_types::Atomic::TKeyedArray {
                        properties: new_props,
                        is_open: *is_open,
                        is_list: *is_list,
                    });
                }
                mir_types::Atomic::TClosure { data } => {
                    let new_params = data
                        .params
                        .iter()
                        .map(|p| {
                            let mut p = p.clone();
                            p.ty = p.ty.as_ref().map(|t| {
                                mir_types::compact::SimpleType::from_union(
                                    self.substitute_template_params(
                                        t.to_union(),
                                        template_names,
                                        template_params,
                                        defining_entity,
                                    ),
                                )
                            });
                            p
                        })
                        .collect();
                    result.add_type(mir_types::Atomic::TClosure {
                        data: Box::new(mir_types::atomic::ClosureData {
                            params: new_params,
                            return_type: self.substitute_template_params(
                                data.return_type.clone(),
                                template_names,
                                template_params,
                                defining_entity,
                            ),
                            this_type: data.this_type.clone(),
                        }),
                    });
                }
                mir_types::Atomic::TCallable {
                    params,
                    return_type,
                } => {
                    let new_params = params.as_ref().map(|ps| {
                        ps.iter()
                            .map(|p| {
                                let mut p = p.clone();
                                p.ty = p.ty.as_ref().map(|t| {
                                    mir_types::compact::SimpleType::from_union(
                                        self.substitute_template_params(
                                            t.to_union(),
                                            template_names,
                                            template_params,
                                            defining_entity,
                                        ),
                                    )
                                });
                                p
                            })
                            .collect()
                    });
                    let new_return_type = return_type.as_deref().map(|t| {
                        Box::new(self.substitute_template_params(
                            t.clone(),
                            template_names,
                            template_params,
                            defining_entity,
                        ))
                    });
                    result.add_type(mir_types::Atomic::TCallable {
                        params: new_params,
                        return_type: new_return_type,
                    });
                }
                _ => result.add_type(atomic),
            }
        }
        result
    }

    fn build_assertions(
        &self,
        doc: &crate::parser::ParsedDocblock,
        type_aliases: Option<&FxHashMap<String, Type>>,
    ) -> Vec<Assertion> {
        // Expand local type aliases before resolving, matching every other
        // type position (@param/@return/template bounds) — an assertion type
        // named after a `@psalm-type` alias previously stayed an unresolved,
        // unexpandable bare atom.
        annotation::build_assertions(doc, |u| {
            let expanded = match type_aliases {
                Some(a) => expand_aliases_only(u, a),
                None => u,
            };
            self.resolve_union_doc(expanded)
        })
    }

    fn location(&self, start: u32, end: u32) -> Location {
        let src = self.source;
        let start_off = start as usize;
        let line_start = src[..start_off].rfind('\n').map(|p| p + 1).unwrap_or(0);
        let line = self.source_map.offset_to_line_col(start).line + 1;
        let col_start = src[line_start..start_off].chars().count() as u16;

        let end_off = (end as usize).min(src.len());
        let end_line_start = src[..end_off].rfind('\n').map(|p| p + 1).unwrap_or(0);
        let line_end = self.source_map.offset_to_line_col(end_off as u32).line + 1;
        let col_end = src[end_line_start..end_off].chars().count() as u16;

        Location::new(self.file.clone(), line, line_end, col_start, col_end)
    }

    // -----------------------------------------------------------------------
    // Docblock issue emission
    // -----------------------------------------------------------------------

    fn emit_docblock_issues(&mut self, doc: &crate::parser::ParsedDocblock, span_start: u32) {
        annotation::emit_docblock_issues(
            doc,
            span_start,
            self.php_version,
            self.file.clone(),
            self.source_map,
            &mut self.issues,
        );
    }

    /// `@deprecated` docblock tag, falling back to a bare `#[Deprecated]` /
    /// `#[\Deprecated]` attribute when there's no docblock tag. Shared by
    /// every declaration kind that carries both a docblock and attributes
    /// (interface/trait/enum decls, class-level already has its own inline
    /// copy of this same fallback).
    fn deprecated_from_doc_or_attrs(
        doc_tag: Option<&str>,
        attributes: &[php_ast::owned::Attribute],
    ) -> Option<Arc<str>> {
        doc_tag.map(Arc::from).or_else(|| {
            if attributes.iter().any(|a| {
                a.name
                    .parts
                    .last()
                    .map(|p| p.as_ref().eq_ignore_ascii_case("Deprecated"))
                    .unwrap_or(false)
            }) {
                Some(Arc::from(""))
            } else {
                None
            }
        })
    }

    // -----------------------------------------------------------------------
    // Visibility conversion
    // -----------------------------------------------------------------------

    fn convert_visibility(v: Option<AstVisibility>) -> Visibility {
        match v {
            Some(AstVisibility::Public) | None => Visibility::Public,
            Some(AstVisibility::Protected) => Visibility::Protected,
            Some(AstVisibility::Private) => Visibility::Private,
        }
    }

    fn build_type_aliases(&self, doc: &crate::parser::ParsedDocblock) -> FxHashMap<String, Type> {
        let mut aliases = FxHashMap::default();
        for alias in &doc.type_aliases {
            if alias.name.is_empty() || alias.type_expr.is_empty() {
                continue;
            }
            let mut ty = crate::parser::docblock::parse_type_string(&alias.type_expr);
            ty.from_docblock = true;
            aliases.insert(alias.name.clone(), self.resolve_union_doc(ty));
        }

        // Resolve same-file @psalm-import-type declarations. Cross-file imports
        // stay in `pending_import_types` and are resolved after all slices are
        // injected.
        for import in &doc.import_types {
            if import.from_class.is_empty() {
                continue;
            }
            let from_resolved = self.resolve_type_name(import.from_class.as_str(), true);
            // A `@psalm-import-type` source can be any class-like kind, not
            // just a class — interfaces/traits/enums can declare their own
            // `@psalm-type`/`@phpstan-type` aliases too.
            let resolved = self
                .slice
                .classes
                .iter()
                .find(|cls| cls.fqcn.as_ref() == from_resolved.as_ref())
                .and_then(|cls| cls.type_aliases.get(import.original.as_str()).cloned())
                .or_else(|| {
                    self.slice
                        .interfaces
                        .iter()
                        .find(|i| i.fqcn.as_ref() == from_resolved.as_ref())
                        .and_then(|i| i.type_aliases.get(import.original.as_str()).cloned())
                })
                .or_else(|| {
                    self.slice
                        .traits
                        .iter()
                        .find(|t| t.fqcn.as_ref() == from_resolved.as_ref())
                        .and_then(|t| t.type_aliases.get(import.original.as_str()).cloned())
                })
                .or_else(|| {
                    self.slice
                        .enums
                        .iter()
                        .find(|e| e.fqcn.as_ref() == from_resolved.as_ref())
                        .and_then(|e| e.type_aliases.get(import.original.as_str()).cloned())
                });
            if let Some(ty) = resolved {
                aliases.insert(import.local.clone(), ty);
            }
        }

        self.expand_type_aliases_fixpoint(&mut aliases);
        aliases
    }

    /// An alias body can itself reference another alias in the same map
    /// (`@psalm-type A = B`, `@psalm-type B = int`); `resolve_union_doc`
    /// above has no knowledge of `aliases` and leaves such a reference as a
    /// bare `TNamedObject`, so without this pass `A` would resolve to `B`
    /// instead of fully expanding to `int`. Re-expanding every alias against
    /// the full map, bounded by the alias count, converges a finite chain of
    /// any depth in one pass per link and turns a cyclic definition
    /// (`A = B`, `B = A`) into a stable self-reference instead of looping
    /// forever.
    fn expand_type_aliases_fixpoint(&self, aliases: &mut FxHashMap<String, Type>) {
        for _ in 0..aliases.len() {
            let snapshot = aliases.clone();
            for ty in aliases.values_mut() {
                *ty = expand_aliases_only(ty.clone(), &snapshot);
            }
        }
        // A genuinely self- or mutually-referential alias (`Tree = array{value:
        // int, children: array<Tree>}`) can never fully expand — the loop above
        // only guarantees an ACYCLIC chain of N aliases is fully resolved within
        // N passes. Any bare alias-name atom still present after that many
        // passes is, by construction, part of a real cycle — there's no other
        // way it could have survived — so it can never resolve to a real class.
        // Previously left as-is, it silently became a phantom reference to a
        // nonexistent class two-plus levels into the expansion. Substitute
        // `mixed` for every alias name at this point instead: any part of a
        // body that was NOT part of a cycle no longer contains an atom
        // matching an alias name at all (it was already fully expanded away
        // above), so this only ever touches genuinely-cyclic residue.
        let neutralize_cycles: FxHashMap<String, Type> = aliases
            .keys()
            .map(|name| (name.clone(), Type::mixed()))
            .collect();
        for ty in aliases.values_mut() {
            *ty = expand_aliases_only(ty.clone(), &neutralize_cycles);
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn add_docblock_members(
        &self,
        doc: &crate::parser::ParsedDocblock,
        aliases: &FxHashMap<String, Type>,
        class_fqcn: &str,
        own_methods: &mut mir_codebase::definitions::MemberMap<Arc<MethodDef>>,
        own_properties: &mut mir_codebase::definitions::MemberMap<PropertyDef>,
        location: Option<Location>,
        template_names: &rustc_hash::FxHashSet<String>,
        template_params: &[TemplateParam],
    ) {
        for prop in &doc.properties {
            if prop.name.is_empty() || own_properties.contains_key(prop.name.as_str()) {
                continue;
            }
            let ty = if prop.type_hint.is_empty() {
                None
            } else {
                let mut parsed = crate::parser::docblock::parse_type_string(&prop.type_hint);
                parsed.from_docblock = true;
                Some(self.resolve_docblock_member_type(
                    parsed,
                    aliases,
                    template_names,
                    template_params,
                    class_fqcn,
                ))
            };
            own_properties.insert(
                Arc::from(prop.name.as_str()),
                PropertyDef {
                    name: Arc::from(prop.name.as_str()),
                    ty: mir_codebase::definitions::wrap_property_type(ty),
                    native_ty: None,
                    inferred_ty: None,
                    visibility: Visibility::Public,
                    is_static: false,
                    is_readonly: prop.read_only,
                    default: None,
                    location: location.clone(),
                    deprecated: None,
                    has_native_readonly: false,
                    // Magic `@property` declarations carry no PHP native type.
                    has_native_type: false,
                    from_docblock: true,
                },
            );
        }

        for method in &doc.methods {
            if method.name.is_empty() {
                continue;
            }
            let key = Arc::from(crate::util::php_ident_lowercase(&method.name).as_str());
            if own_methods.contains_key(&key) {
                continue;
            }
            let return_type_opt = if method.return_type.is_empty() {
                None
            } else {
                let mut parsed = crate::parser::docblock::parse_type_string(&method.return_type);
                parsed.from_docblock = true;
                Some(Self::fill_self_static_parent(
                    self.resolve_docblock_member_type(
                        parsed,
                        aliases,
                        template_names,
                        template_params,
                        class_fqcn,
                    ),
                    class_fqcn,
                ))
            };
            let params = method
                .params
                .iter()
                .map(|p| {
                    let ty = if p.type_hint.is_empty() {
                        None
                    } else {
                        let mut parsed = crate::parser::docblock::parse_type_string(&p.type_hint);
                        parsed.from_docblock = true;
                        Some(self.resolve_docblock_member_type(
                            parsed,
                            aliases,
                            template_names,
                            template_params,
                            class_fqcn,
                        ))
                    };
                    DeclaredParam {
                        name: Name::new(p.name.as_str()),
                        ty: mir_codebase::wrap_param_type(ty),
                        out_ty: None,
                        has_default: p.is_optional,
                        is_variadic: p.is_variadic,
                        is_byref: p.is_byref,
                        is_optional: p.is_optional,
                    }
                })
                .collect();
            own_methods.insert(
                key,
                Arc::new(MethodDef {
                    name: Arc::from(method.name.as_str()),
                    fqcn: Arc::from(class_fqcn),
                    params,
                    return_type: wrap_return_type(return_type_opt),
                    inferred_return_type: None,
                    visibility: Visibility::Public,
                    is_static: method.is_static,
                    is_abstract: false,
                    is_final: false,
                    is_constructor: false,
                    template_params: vec![],
                    assertions: vec![],
                    throws: vec![],
                    deprecated: None,
                    is_internal: false,
                    is_pure: false,
                    no_named_arguments: false,
                    is_override: false,
                    location: location.clone(),
                    docstring: None,
                    is_virtual: true,
                    taint_sink_params: vec![],
                    is_taint_source: false,
                    if_this_is: None,
                    self_out: None,
                    is_inherit_doc: false,
                    is_mutation_free: false,
                    is_external_mutation_free: false,
                    data_provider_targets: vec![],
                }),
            );
        }
    }

    // -----------------------------------------------------------------------
    // Process statements
    // -----------------------------------------------------------------------

    fn process_stmts(&mut self, stmts: &[php_ast::owned::Stmt]) -> ControlFlow<()> {
        for stmt in stmts.iter() {
            self.visit_stmt(stmt)?;
        }
        ControlFlow::Continue(())
    }

    // -----------------------------------------------------------------------
    // Global variable registry
    // -----------------------------------------------------------------------

    /// Scan a single statement: if it is `global $x` with a preceding
    /// `/** @var Type $x */` docblock, register the type in the codebase.
    fn try_collect_global_var_annotation(&mut self, stmt: &php_ast::owned::Stmt) {
        let php_ast::owned::StmtKind::Global(vars) = &stmt.kind else {
            return;
        };
        let Some(doc_comment) = stmt.leading_doc_comment() else {
            return;
        };
        let parsed = crate::parser::DocblockParser::parse(&doc_comment.text);
        self.emit_docblock_issues(&parsed, stmt.span.start);
        let Some(var_type) = parsed.var_type else {
            return;
        };
        let resolved_ty = self.resolve_union_doc(var_type);

        for var in vars.iter() {
            if let php_ast::owned::ExprKind::Variable(raw_name) = &var.kind {
                let name = raw_name.trim_start_matches('$');
                // If @var specifies a variable name, only register when it matches.
                if let Some(ref ann_name) = parsed.var_name {
                    if ann_name != name {
                        continue;
                    }
                }
                self.slice
                    .global_vars
                    .push((Arc::from(name), resolved_ty.clone()));
            }
        }
    }

    /// Scan a list of statements and register any `@var`-annotated `global`
    /// declarations. Used for function bodies where the visitor does not recurse.
    fn scan_stmts_for_global_vars(&mut self, stmts: &[php_ast::owned::Stmt]) {
        for stmt in stmts.iter() {
            self.try_collect_global_var_annotation(stmt);
        }
    }

    /// Registers a `define('NAME', value)` call as a global constant. mir does
    /// no call-graph reachability analysis, so — like the guarded
    /// `function_exists()`-wrapped declarations above — a `define()` found
    /// anywhere is treated as unconditionally available, not gated on whether
    /// its enclosing function is ever actually called.
    fn try_collect_define(&mut self, stmt: &php_ast::owned::Stmt, expr: &php_ast::owned::Expr) {
        let php_ast::owned::ExprKind::FunctionCall(call) = &expr.kind else {
            return;
        };
        let php_ast::owned::ExprKind::Identifier(fn_name) = &call.name.kind else {
            return;
        };
        if !fn_name.eq_ignore_ascii_case("define") {
            return;
        }
        let Some(name_arg) = call.args.first() else {
            return;
        };
        let php_ast::owned::ExprKind::String(name) = &name_arg.value.kind else {
            return;
        };
        let define_doc = stmt
            .leading_doc_comment()
            .map(|c| crate::parser::DocblockParser::parse(&c.text))
            .unwrap_or_default();
        self.emit_docblock_issues(&define_doc, stmt.span.start);
        if !self.version_allows(&define_doc) {
            return;
        }
        let fqn: Arc<str> = Arc::from(&**name);
        // Try to infer the type of the constant value from the second argument
        let const_type = call
            .args
            .get(1)
            .and_then(|arg| infer_const_value(self, &arg.value.kind))
            .unwrap_or(Type::mixed());
        self.slice.constants.push((fqn, const_type));
    }

    /// Recurses through control-flow wrappers to find `define()` calls inside
    /// a function/method body, which the top-level visitor never re-enters
    /// (see `visit_expr` below). Mirrors `stmts_use_func_get_args`'s
    /// recursion shape but deliberately does NOT descend into nested
    /// function/class declarations — those aren't collected by this pass
    /// either, so scanning inside them would be inconsistent scope creep.
    fn scan_stmts_for_defines(&mut self, stmts: &[php_ast::owned::Stmt]) {
        for stmt in stmts.iter() {
            self.scan_stmt_for_defines(stmt);
        }
    }

    fn scan_stmt_for_defines(&mut self, stmt: &php_ast::owned::Stmt) {
        match &stmt.kind {
            StmtKind::Expression(expr) => self.try_collect_define(stmt, expr),
            StmtKind::If(s) => {
                self.scan_stmt_for_defines(&s.then_branch);
                for branch in s.elseif_branches.iter() {
                    self.scan_stmt_for_defines(&branch.body);
                }
                if let Some(else_branch) = &s.else_branch {
                    self.scan_stmt_for_defines(else_branch);
                }
            }
            StmtKind::While(s) => self.scan_stmt_for_defines(&s.body),
            StmtKind::DoWhile(s) => self.scan_stmt_for_defines(&s.body),
            StmtKind::For(s) => self.scan_stmt_for_defines(&s.body),
            StmtKind::Foreach(s) => self.scan_stmt_for_defines(&s.body),
            StmtKind::Switch(s) => {
                for case in s.body.cases.iter() {
                    self.scan_stmts_for_defines(&case.body);
                }
            }
            StmtKind::TryCatch(t) => {
                self.scan_stmts_for_defines(&t.body.stmts);
                for catch in t.catches.iter() {
                    self.scan_stmts_for_defines(&catch.body.stmts);
                }
                if let Some(finally) = &t.finally {
                    self.scan_stmts_for_defines(&finally.stmts);
                }
            }
            StmtKind::Block(b) => self.scan_stmts_for_defines(&b.stmts),
            _ => {}
        }
    }
}

impl<'a> OwnedVisitor for DefinitionCollector<'a> {
    fn visit_program(&mut self, program: &Program) -> ControlFlow<()> {
        walk_owned_program(self, program)
    }

    fn visit_stmt(&mut self, stmt: &php_ast::owned::Stmt) -> ControlFlow<()> {
        match &stmt.kind {
            StmtKind::Namespace(ns) => {
                let new_ns = ns.name.as_ref().map(name_to_string_owned);
                if self.first_namespace.is_none() {
                    self.first_namespace = new_ns.clone();
                }
                self.namespace = new_ns;
                match &ns.body {
                    php_ast::owned::NamespaceBody::Braced(stmts) => {
                        // Save and restore use aliases per namespace block
                        let saved_aliases = self.use_aliases.clone();
                        self.use_aliases.clear();
                        let flow = self.process_stmts(&stmts.stmts);
                        self.use_aliases = saved_aliases;
                        flow?;
                    }
                    php_ast::owned::NamespaceBody::Simple => {
                        // Simple namespace — affects all subsequent declarations
                    }
                }
            }

            StmtKind::Use(use_decl) => {
                use php_ast::ast::UseKind;
                for item in use_decl.uses.iter() {
                    let full_name = name_to_string_owned(&item.name)
                        .trim_start_matches('\\')
                        .to_string();
                    let alias = item
                        .alias
                        .as_deref()
                        .unwrap_or_else(|| full_name.rsplit('\\').next().unwrap_or(&full_name));
                    // `accumulated_imports` (→ `file_imports()`) keeps every kind: Pass 2
                    // function-call resolution (`call/function.rs`) relies on `use
                    // function` aliases showing up there. `use_aliases` and
                    // `accumulated_class_imports` (→ `file_class_imports()`) are
                    // Normal-only: every Pass-1 consumer of `use_aliases` resolves a
                    // class/type/attribute/exception name, so a `use function`/`use
                    // const` alias (including per-item overrides inside a grouped `use
                    // Foo\{Bar, function baz, const QUX}`) must never populate them —
                    // otherwise a type hint/`new`/`extends` reference sharing that short
                    // name would incorrectly resolve to the function/constant's FQN.
                    self.accumulated_imports
                        .insert(alias.to_string(), full_name.clone());
                    if item.kind.unwrap_or(use_decl.kind) == UseKind::Normal {
                        self.use_aliases
                            .insert(alias.to_string(), full_name.clone());
                        self.accumulated_class_imports
                            .insert(alias.to_string(), full_name);
                    }
                }
            }

            StmtKind::Function(decl) => {
                self.collect_function(decl, stmt.span);
            }

            StmtKind::Global(_) => {
                self.collect_global_stmt(stmt);
            }

            StmtKind::Class(decl) => {
                return self.collect_class(decl, stmt.span);
            }

            StmtKind::Interface(decl) => {
                return self.collect_interface(decl, stmt.span);
            }

            StmtKind::Trait(decl) => {
                return self.collect_trait(decl, stmt.span);
            }

            StmtKind::Enum(decl) => {
                return self.collect_enum(decl, stmt.span);
            }

            StmtKind::Const(items) => {
                for item in items.iter() {
                    let const_doc = item
                        .doc_comment
                        .as_ref()
                        .map(|c| crate::parser::DocblockParser::parse(&c.text))
                        .unwrap_or_default();
                    let const_doc_span = item
                        .doc_comment
                        .as_ref()
                        .map(|c| c.span.start)
                        .unwrap_or(item.span.start);
                    self.emit_docblock_issues(&const_doc, const_doc_span);
                    if !self.version_allows(&const_doc) {
                        continue;
                    }
                    let name_str = item.name.as_deref().unwrap_or_default();
                    let fqn: Arc<str> = if let Some(ns) = &self.namespace {
                        format!("{}\\{}", ns, name_str).into()
                    } else {
                        Arc::from(name_str)
                    };
                    self.slice.constants.push((fqn, Type::mixed()));
                }
            }

            // Collect top-level define('NAME', value) calls as global constants.
            // phpstorm-stubs uses this form extensively in *_defines.php files.
            StmtKind::Expression(expr) => {
                self.try_collect_define(stmt, expr);
            }

            // Recurse through control-flow wrappers (`if`/`while`/`for`/`foreach`/
            // `do`/`switch`/`try`/blocks) so a declaration nested inside one is
            // collected identically to a top-level declaration. This is what makes
            // Laravel's global helpers visible: every one is declared inside an
            // `if (! function_exists('foo')) { function foo() {} }` guard, as are
            // Symfony polyfills and WordPress pluggable functions. Indexing is
            // unconditional — the guard is a runtime concern (which copy wins when
            // the file loads), irrelevant to static symbol candidacy, and the
            // codebase dedups by FQCN so a polyfill declared in several packages
            // produces no redeclaration noise.
            //
            // `walk_owned_stmt` only re-enters `visit_stmt` for nested statements;
            // it never reaches a declaration's own body because the `Function`/
            // `Class`/`Interface`/`Trait`/`Enum` arms above return without walking.
            // Closures and anonymous classes live in expressions, which `visit_expr`
            // (below) deliberately does not descend into — so a function declared
            // inside a closure is not wrongly registered at file scope.
            _ => return walk_owned_stmt(self, stmt),
        }
        ControlFlow::Continue(())
    }

    /// The collector registers statement-level declarations only; it has no
    /// reason to look inside expressions. Overriding this to a no-op stops the
    /// control-flow recursion in `visit_stmt` from descending into closure and
    /// arrow-function bodies (reached via `walk_owned_stmt`'s expression walk),
    /// which would otherwise register locally-scoped declarations at file scope.
    fn visit_expr(&mut self, _expr: &php_ast::owned::Expr) -> ControlFlow<()> {
        ControlFlow::Continue(())
    }
}

impl<'a> DefinitionCollector<'a> {
    fn build_method_storage(
        &mut self,
        m: &php_ast::owned::MethodDecl,
        class_fqcn: &str,
        span: Option<&php_ast::Span>,
        aliases: Option<&FxHashMap<String, Type>>,
        class_template_params: &[TemplateParam],
    ) -> Option<MethodDef> {
        let doc = m
            .doc_comment
            .as_ref()
            .map(|c| crate::parser::DocblockParser::parse(&c.text))
            .unwrap_or_default();

        if let Some(c) = m.doc_comment.as_ref() {
            self.emit_docblock_issues(&doc, c.span.start);
        }

        if !self.version_allows(&doc) || !self.version_attr_available(&m.attributes) {
            return None;
        }

        // Merge method-level type aliases with the class-level ones. Method aliases
        // (defined via `@psalm-type` / `@phpstan-type` on the method docblock) take
        // precedence; class aliases fill in the rest.
        let method_type_aliases = self.build_type_aliases(&doc);
        let merged_aliases: FxHashMap<String, mir_types::Type> = if method_type_aliases.is_empty() {
            aliases.cloned().unwrap_or_default()
        } else {
            let mut merged = aliases.cloned().unwrap_or_default();
            merged.extend(method_type_aliases);
            merged
        };
        let effective_aliases: Option<&FxHashMap<String, mir_types::Type>> =
            if merged_aliases.is_empty() {
                None
            } else {
                Some(&merged_aliases)
            };

        // Build combined template name set before param resolution so docblock param types
        // that reference class-level template params (e.g. `TRelatedModel`) are stored as
        // TTemplateParam instead of being wrongly namespace-qualified.
        // Includes both method-level and class-level template names.
        let template_names: rustc_hash::FxHashSet<String> = doc
            .templates
            .iter()
            .map(|(n, _, _, _)| n.to_string())
            .chain(
                class_template_params
                    .iter()
                    .map(|tp| tp.name.as_ref().to_string()),
            )
            .collect();

        // Extract template params; bounds are resolved with template-awareness so a bound
        // that is itself a template param (e.g. `@template T of A` where A is another
        // template) is stored as TTemplateParam rather than being wrongly FQN-qualified.
        let template_params: Vec<TemplateParam> = doc
            .templates
            .iter()
            .map(|(name, bound, variance, default)| TemplateParam {
                name: name.as_str().into(),
                bound: wrap_template_bound(bound.clone().map(|b| {
                    let b = match effective_aliases {
                        Some(a) => expand_aliases_only(b, a),
                        None => b,
                    };
                    Self::fill_self_static_parent(
                        self.resolve_union_doc_with_templates(
                            b,
                            &template_names,
                            class_fqcn,
                            class_template_params,
                        ),
                        class_fqcn,
                    )
                })),
                default: wrap_template_bound(default.clone().map(|d| {
                    let d = match effective_aliases {
                        Some(a) => expand_aliases_only(d, a),
                        None => d,
                    };
                    Self::fill_self_static_parent(
                        self.resolve_union_doc_with_templates(
                            d,
                            &template_names,
                            class_fqcn,
                            class_template_params,
                        ),
                        class_fqcn,
                    )
                })),
                defining_entity: class_fqcn.into(),
                variance: *variance,
            })
            .collect();

        // Combined param list for bound lookup: method-level first (they shadow class-level),
        // then class-level. Used only for resolve_union_doc_with_templates, not stored in MethodDef.
        let combined_template_params: Vec<TemplateParam>;
        let template_params_for_resolve: &[TemplateParam] = if class_template_params.is_empty() {
            &template_params
        } else {
            combined_template_params = template_params
                .iter()
                .chain(
                    class_template_params
                        .iter()
                        .filter(|ctp| !template_params.iter().any(|tp| tp.name == ctp.name)),
                )
                .cloned()
                .collect();
            &combined_template_params
        };

        let mut params = Vec::new();
        let mut local_scalar = 0usize;
        let mut local_complex = 0usize;
        let mut local_defaults = 0usize;
        for p in m.params.iter() {
            // phpstorm-stubs `#[PhpStormStubsElementAvailable]`: omit a param
            // that does not exist at the target version (preserves arity).
            if !self.version_attr_available(&p.attributes) {
                continue;
            }
            let param_name = p.name.as_deref().unwrap_or_default();
            let native_ty = self.resolve_union_opt(
                p.type_hint
                    .as_ref()
                    .map(|h| type_from_hint_owned(h, Some(class_fqcn))),
            );
            let ty = self
                // phpstorm-stubs `#[LanguageLevelTypeAware]` type override wins.
                .version_attr_type_string(&p.attributes)
                .map(|s| crate::parser::docblock::parse_type_string(&s))
                .or_else(|| {
                    doc.get_param_type(param_name).cloned().map(|u| {
                        // Use full_qualify=false resolution (same as before) so bare
                        // names like `Closure` stay bare and don't get namespaced.
                        // After that, run a template-only substitution pass to convert
                        // bare names matching class/method template params (e.g. TRelatedModel)
                        // into TTemplateParam without touching other names.
                        let resolved = effective_aliases
                            .map(|a| self.resolve_union_doc_with_aliases(u.clone(), a))
                            .unwrap_or_else(|| self.resolve_union_doc(u));
                        let doc_ty = self.substitute_template_params(
                            resolved,
                            &template_names,
                            template_params_for_resolve,
                            class_fqcn,
                        );
                        // When the native hint is a concrete scalar and the docblock has only
                        // atoms from a different scalar family (e.g. `@param int` + `bool` hint),
                        // the PHP type hint is the runtime truth — prefer it over the docblock.
                        if native_ty
                            .as_ref()
                            .is_some_and(|n| native_hint_wins_over_docblock_scalar(n, &doc_ty))
                        {
                            return native_ty.clone().unwrap();
                        }
                        // Partial conflict (e.g. `@param int|string` on a native `int`
                        // hint): strip the atoms foreign to the hint's family instead
                        // of storing the raw union.
                        let mut doc_ty = match native_ty.as_ref() {
                            Some(n) => preserve_native_nullability(
                                n,
                                resolve_docblock_scalar_conflict(n, doc_ty),
                            ),
                            None => doc_ty,
                        };
                        // Mark the type as docblock-sourced so signature checks (e.g.
                        // param contravariance) can tell a `@param` refinement apart
                        // from a native type hint.
                        doc_ty.from_docblock = true;
                        Self::fill_self_static_parent(doc_ty, class_fqcn)
                    })
                })
                .or(native_ty);
            if let Some(ty_ref) = &ty {
                if is_simple_scalar(ty_ref) {
                    local_scalar += 1;
                } else {
                    local_complex += 1;
                }
            }
            let has_default = p.default.is_some();
            if has_default {
                local_defaults += 1;
            }

            let out_ty = doc.get_out_param_type(param_name).cloned().map(|u| {
                let resolved = effective_aliases
                    .map(|a| self.resolve_union_doc_with_aliases(u.clone(), a))
                    .unwrap_or_else(|| self.resolve_union_doc(u));
                let mut resolved = self.substitute_template_params(
                    resolved,
                    &template_names,
                    template_params_for_resolve,
                    class_fqcn,
                );
                resolved.from_docblock = true;
                Self::fill_self_static_parent(resolved, class_fqcn)
            });
            params.push(DeclaredParam {
                name: Name::new(param_name),
                ty: mir_codebase::wrap_param_type(ty),
                out_ty: mir_codebase::wrap_param_type(out_ty),
                has_default,
                is_variadic: p.variadic,
                is_byref: p.by_ref,
                is_optional: has_default || p.variadic,
            });
        }
        if local_scalar > 0 {
            SCALAR_PARAM_COUNT.fetch_add(local_scalar, Relaxed);
        }
        if local_complex > 0 {
            COMPLEX_PARAM_COUNT.fetch_add(local_complex, Relaxed);
        }
        if local_defaults > 0 {
            PARAM_WITH_DEFAULT.fetch_add(local_defaults, Relaxed);
        }

        // Same func_get_args detection as for free functions (see collector/function.rs).
        let last_is_variadic = params.last().is_some_and(|p| p.is_variadic);
        if !last_is_variadic {
            let body_stmts = m
                .body
                .as_deref()
                .map(|b| b.stmts.as_ref())
                .unwrap_or_default();
            if crate::collector::function::stmts_use_func_get_args(body_stmts) {
                params.push(DeclaredParam {
                    name: mir_types::Name::new("..."),
                    ty: None,
                    out_ty: None,
                    has_default: false,
                    is_variadic: true,
                    is_byref: false,
                    is_optional: true,
                });
            }
        }

        // phpstorm-stubs `#[LanguageLevelTypeAware]` return type wins, routed
        // through the same resolution + self/static/parent filling.
        let attr_return = self.version_attr_type_string(&m.attributes).map(|s| {
            let mut ty = crate::parser::docblock::parse_type_string(&s);
            ty.from_docblock = true;
            ty
        });
        let return_type = match (
            attr_return.or_else(|| doc.return_type.clone()),
            m.return_type.as_ref(),
        ) {
            (Some(mut ty), _) => {
                ty.from_docblock = true;
                // Expand type aliases first (no FQN change), then resolve.
                let expanded =
                    effective_aliases.map_or(ty.clone(), |a| expand_aliases_only(ty.clone(), a));
                // Template-aware resolution even with no templates in scope: it
                // FQN-qualifies class names in generic return types (e.g.
                // `Builder<static>` on a template-free method), which the plain
                // doc resolution leaves relative — and nothing downstream
                // resolves a stored return type against its declaring file.
                let resolved = self.resolve_union_doc_with_templates(
                    expanded,
                    &template_names,
                    class_fqcn,
                    template_params_for_resolve,
                );
                Some(Self::fill_self_static_parent(resolved, class_fqcn))
            }
            (None, Some(h)) => {
                self.resolve_union_opt(Some(type_from_hint_owned(h, Some(class_fqcn))))
            }
            (None, None) => None,
        };

        let throws = doc
            .throws
            .iter()
            .map(|t| {
                Arc::from(resolution::resolve_name(t, &self.namespace, &self.use_aliases).as_str())
            })
            .collect();

        // Resolve `@if-this-is` while the template-param borrow is still live
        // (it must not outlive the `template_params` move into MethodDef below).
        let if_this_is_resolved: Option<Arc<Type>> = doc.if_this_is.clone().map(|mut ty| {
            ty.from_docblock = true;
            // Expand type aliases first, matching every other type position
            // (@param/@return/template bounds) — this and @psalm-self-out
            // below were the only two still skipping it.
            let ty = effective_aliases.map_or(ty.clone(), |a| expand_aliases_only(ty, a));
            let resolved = if template_names.is_empty() {
                self.resolve_union_doc(ty)
            } else {
                self.resolve_union_doc_with_templates(
                    ty,
                    &template_names,
                    class_fqcn,
                    template_params_for_resolve,
                )
            };
            Arc::new(Self::fill_self_static_parent(resolved, class_fqcn))
        });

        // Resolve `@psalm-self-out` the same way as `@if-this-is` above.
        let self_out_resolved: Option<Arc<Type>> = doc.self_out.clone().map(|mut ty| {
            ty.from_docblock = true;
            let ty = effective_aliases.map_or(ty.clone(), |a| expand_aliases_only(ty, a));
            let resolved = if template_names.is_empty() {
                self.resolve_union_doc(ty)
            } else {
                self.resolve_union_doc_with_templates(
                    ty,
                    &template_names,
                    class_fqcn,
                    template_params_for_resolve,
                )
            };
            Arc::new(Self::fill_self_static_parent(resolved, class_fqcn))
        });

        let method_name = m.name.as_deref().unwrap_or_default();
        let is_override = m.attributes.iter().any(|a| {
            a.name
                .parts
                .last()
                .map(|p| p.as_ref().eq_ignore_ascii_case("Override"))
                .unwrap_or(false)
        });
        // PHPUnit invokes `@dataProvider`/`#[DataProvider]` targets by name via
        // reflection, so they never get an ordinary call-site reference.
        let mut data_provider_targets: Vec<Arc<str>> = doc
            .data_providers
            .iter()
            .map(|s| Arc::from(s.as_str()))
            .collect();
        data_provider_targets.extend(m.attributes.iter().filter_map(|a| {
            let is_data_provider = a
                .name
                .parts
                .last()
                .map(|p| p.as_ref().eq_ignore_ascii_case("DataProvider"))
                .unwrap_or(false);
            if !is_data_provider {
                return None;
            }
            match a.args.first().map(|arg| &arg.value.kind) {
                Some(php_ast::owned::ExprKind::String(s)) => Some(Arc::from(s.as_ref())),
                _ => None,
            }
        }));
        Some(MethodDef {
            name: Arc::from(method_name),
            fqcn: class_fqcn.into(),
            params: Arc::from(params.into_boxed_slice()),
            return_type: wrap_return_type(return_type),
            inferred_return_type: None,
            visibility: Self::convert_visibility(m.visibility),
            is_static: m.is_static,
            is_abstract: m.is_abstract,
            is_final: m.is_final,
            is_constructor: method_name == "__construct",
            template_params,
            assertions: self.build_assertions(&doc, effective_aliases),
            throws,
            deprecated: doc.deprecated.as_deref().map(Arc::from).or_else(|| {
                if m.attributes.iter().any(|a| {
                    a.name
                        .parts
                        .last()
                        .map(|p| p.as_ref().eq_ignore_ascii_case("Deprecated"))
                        .unwrap_or(false)
                }) {
                    Some(Arc::from(""))
                } else {
                    None
                }
            }),
            is_internal: doc.is_internal,
            is_pure: doc.is_pure,
            no_named_arguments: doc.no_named_arguments,
            is_override,
            is_virtual: false,
            location: span.map(|s| self.location(s.start, s.end)),
            docstring: if doc.description.trim().is_empty() {
                None
            } else {
                Some(Arc::from(doc.description.as_str()))
            },
            taint_sink_params: doc
                .taint_sinks
                .iter()
                .map(|(param, kind)| (Arc::from(param.as_str()), Arc::from(kind.as_str())))
                .collect(),
            is_taint_source: doc.is_taint_source,
            if_this_is: if_this_is_resolved,
            self_out: self_out_resolved,
            is_inherit_doc: doc.is_inherit_doc,
            is_mutation_free: doc.is_mutation_free,
            is_external_mutation_free: doc.is_external_mutation_free,
            data_provider_targets,
        })
    }
}

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

    fn parse_and_collect_slice(file: &str, src: &str) -> StubSlice {
        let result = php_rs_parser::parse(src);
        let collector =
            DefinitionCollector::new_for_slice(Arc::from(file), src, &result.source_map);
        let (slice, _) = collector.collect_slice(&result.program);
        slice
    }

    // These three tests guard the DefinitionCollector → StubSlice contract for
    // namespace and import data.
    //
    // Background: collect_slice is the pure output path used by incremental /
    // salsa pipelines (LSP, re_analyze_file). For StubSlice-based consumers to
    // produce correct diagnostics, the slice must carry the same namespace and
    // import data that project.rs collects via its separate AST walk. If either
    // field is missing from the slice, StatementsAnalyzer receives empty maps
    // during body analysis and emits false UndefinedClass diagnostics for use-aliased
    // or same-namespace classes.

    #[test]
    fn collect_slice_captures_namespace() {
        // The first namespace declaration must end up in slice.namespace so
        // that file_namespace() can derive it via collect_file_definitions.
        let slice = parse_and_collect_slice(
            "src/Service.php",
            "<?php\nnamespace App\\Service;\nclass Handler {}\n",
        );
        assert_eq!(
            slice.namespace.as_deref(),
            Some("App\\Service"),
            "collect_slice must capture the file namespace"
        );
    }

    #[test]
    fn collect_slice_captures_use_imports() {
        // All `use` imports (plain and aliased) must end up in slice.imports so
        // that file_imports() can derive them via collect_file_definitions and
        // body analysis can resolve short names like `new Entity()` correctly.
        let slice = parse_and_collect_slice(
            "src/Handler.php",
            "<?php\nnamespace App\\Service;\nuse App\\Model\\Entity;\nuse App\\Repository\\EntityRepo as Repo;\nclass Handler {}\n",
        );
        let imports = &slice.imports;
        assert_eq!(
            imports
                .get(&mir_types::Name::new("Entity"))
                .map(|s| s.as_str()),
            Some("App\\Model\\Entity"),
            "collect_slice must capture plain use import"
        );
        assert_eq!(
            imports
                .get(&mir_types::Name::new("Repo"))
                .map(|s| s.as_str()),
            Some("App\\Repository\\EntityRepo"),
            "collect_slice must capture aliased use import"
        );
    }

    #[test]
    fn collect_slice_class_imports_excludes_use_function_and_const() {
        // `use function`/`use const` (plain or grouped) must still land in
        // slice.imports (Pass-2 function-call resolution needs them), but never
        // in slice.class_imports — otherwise a same-named class/type-hint
        // reference would incorrectly resolve to the function/constant's FQN.
        let slice = parse_and_collect_slice(
            "src/Handler.php",
            concat!(
                "<?php\n",
                "namespace App\\Service;\n",
                "use App\\Model\\Entity;\n",
                "use function App\\Helpers\\foo;\n",
                "use const App\\Helpers\\BAR;\n",
                "use App\\Helpers\\{Baz, function qux, const QUUX};\n",
                "class Handler {}\n",
            ),
        );

        for (alias, fqcn) in [
            ("Entity", "App\\Model\\Entity"),
            ("foo", "App\\Helpers\\foo"),
            ("BAR", "App\\Helpers\\BAR"),
            ("Baz", "App\\Helpers\\Baz"),
            ("qux", "App\\Helpers\\qux"),
            ("QUUX", "App\\Helpers\\QUUX"),
        ] {
            assert_eq!(
                slice
                    .imports
                    .get(&mir_types::Name::new(alias))
                    .map(|s| s.as_str()),
                Some(fqcn),
                "slice.imports must capture every UseKind for alias {alias}"
            );
        }

        assert_eq!(
            slice
                .class_imports
                .get(&mir_types::Name::new("Entity"))
                .map(|s| s.as_str()),
            Some("App\\Model\\Entity"),
            "slice.class_imports must capture a Normal-kind alias"
        );
        assert_eq!(
            slice
                .class_imports
                .get(&mir_types::Name::new("Baz"))
                .map(|s| s.as_str()),
            Some("App\\Helpers\\Baz"),
            "slice.class_imports must capture a Normal-kind alias from a grouped use"
        );
        for alias in ["foo", "BAR", "qux", "QUUX"] {
            assert!(
                slice
                    .class_imports
                    .get(&mir_types::Name::new(alias))
                    .is_none(),
                "slice.class_imports must not contain function/const alias {alias}"
            );
        }
    }

    #[test]
    fn collect_slice_captures_namespace_none_when_no_namespace() {
        // Global-scope files have no namespace declaration; slice.namespace must
        // be None so file_namespace() correctly returns None for global-scope files.
        let slice = parse_and_collect_slice("src/global.php", "<?php\nfunction foo(): void {}\n");
        assert!(
            slice.namespace.is_none(),
            "collect_slice must not set namespace for global-scope files"
        );
    }

    #[test]
    fn trait_require_extends_is_collected() {
        let src = r#"<?php
class Model {}

/**
 * @psalm-require-extends Model
 */
trait HasTimestamps {}
"#;
        let slice = parse_and_collect_slice("test.php", src);
        let tr = slice
            .traits
            .iter()
            .find(|tr| tr.fqcn.as_ref() == "HasTimestamps")
            .expect("HasTimestamps should be collected");
        assert_eq!(
            tr.require_extends,
            vec![std::sync::Arc::from("Model")],
            "require_extends should contain Model"
        );
    }

    #[test]
    fn trait_require_extends_via_project_analyzer() {
        let src = r#"<?php
/** @psalm-require-extends Model */
trait HasTimestamps {
    public function touch(): void {}
}

class Model {}

class NotAModel {
    use HasTimestamps;
}
"#;
        let result = crate::test_utils::check(src);
        assert!(
            result.iter().any(|i| i.kind.name() == "InvalidTraitUse"),
            "Expected InvalidTraitUse issue"
        );
    }
}