phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
/// Variable type resolution for completion subjects.
///
/// This module resolves the type of a `$variable` by re-parsing the file
/// and walking the method / function body that contains the cursor.  It
/// examines:
///
///   - Assignments: `$var = new ClassName(…)`, `$var = $obj->method()`, etc.
///   - Method/function parameter type hints
///   - Inline `/** @var Type */` docblock overrides
///   - Conditional branches (if/else, try/catch, loops) — collects all
///     possible types when the variable is assigned differently in each
///     branch.
///   - Match expressions: `$var = match(…) { … => new A(), … => new B() }`
///     collects all possible types from all arms.
///   - Ternary expressions: `$var = $cond ? new A() : new B()` collects
///     types from both branches.  Short ternary `$a ?: new B()` and
///     null-coalescing `$a ?? new B()` are also supported.
///   - Foreach value variables: when iterating over a variable annotated
///     with a generic iterable type (e.g. `@var list<User>`, `@param
///     list<User>`, `User[]`), the foreach value variable is resolved to
///     the element type.
///   - Foreach key variables: when iterating over a two-parameter generic
///     (e.g. `SplObjectStorage<Request, Response>`), the key variable is
///     resolved to the first type parameter.
///   - Array destructuring: `[$a, $b] = getUsers()` and `list($a, $b) = $var`
///     infer element types from the RHS's generic iterable annotation
///     (function return types, variable/property annotations, inline @var).
///
/// Type narrowing (instanceof, assert, custom type guards) is delegated
/// to the [`crate::completion::type_narrowing`] module.  Closure/arrow-function scope
/// handling is delegated to [`super::closure_resolution`].
use std::cell::Cell;
use std::sync::Arc;

use mago_span::HasSpan;
use mago_syntax::ast::*;

use crate::completion::types::narrowing;
use crate::docblock;
use crate::parser::{extract_hint_type, with_parsed_program};
use crate::php_type::{PhpType, ShapeEntry, is_keyword_type};
use crate::types::{ClassInfo, ParameterInfo, ResolvedType};

use crate::completion::resolver::{Loaders, VarResolutionCtx};

// ── Re-entrancy guard for resolve_variable_types ────────────────────
//
// PHP allows `foreach ($x->method() as $x)` where the foreach value
// variable shadows the iterator receiver.  Resolving `$x` finds the
// foreach, which resolves the iterator expression `$x->method()`,
// which resolves `$x` again — infinite recursion.
//
// The guard lives here, at the very top of `resolve_variable_types`,
// so that the depth check executes before `with_parsed_program`
// allocates its large closure frame on the stack.  Placing the guard
// in a caller (e.g. `resolve_variable_fallback`) is insufficient
// because several other call sites invoke `resolve_variable_types`
// directly (diagnostics, hover, foreach resolution).
thread_local! {
    static VAR_RESOLUTION_DEPTH: Cell<u8> = const { Cell::new(0) };
    /// Sticky flag set when `resolve_variable_types` returns empty
    /// because the depth guard fired.  The flag stays set until the
    /// outermost `resolve_variable_types` call returns, so callers
    /// up the stack (e.g. `resolve_target_classes`) can detect that
    /// an empty result was caused by the depth limit — not because
    /// the variable is genuinely unresolvable — and skip caching it.
    static VAR_RESOLUTION_DEPTH_LIMITED: Cell<bool> = const { Cell::new(false) };
}

/// Maximum nesting depth for `resolve_variable_types` calls.
///
/// Four levels covers legitimate nested resolution such as:
///   depth 0: resolve `$arr` built via `$arr[$key] = ['k' => $var]`
///   depth 1: resolve `$var` (array element variable in the shape literal)
///   depth 2: resolve `$item->prop` (RHS of `$var = $item->prop`)
///   depth 3: resolve `$item` (foreach value binding → iterable param)
///
/// Cycles like `foreach ($x->method() as $x)` are caught by a
/// targeted check in `try_resolve_foreach_value_type` (which skips
/// resolution when the value variable shadows the iterator receiver)
/// rather than by this depth limit alone.  The depth limit is a
/// safety net for any remaining recursive patterns.
const MAX_VAR_RESOLUTION_DEPTH: u8 = 4;

/// Returns `true` when any `resolve_variable_types` call on the
/// current stack has returned empty because the depth guard fired.
///
/// The flag is sticky: once set, it stays `true` until the outermost
/// `resolve_variable_types` call returns and clears it.  This lets
/// callers further up the stack (e.g. `resolve_target_classes`) detect
/// that an empty result was caused by the depth limit — not because
/// the variable is genuinely unresolvable — and skip caching it.
pub(crate) fn is_var_resolution_depth_limited() -> bool {
    VAR_RESOLUTION_DEPTH_LIMITED.with(|f| f.get())
}

/// Build a [`VarClassStringResolver`] closure from a [`VarResolutionCtx`].
///
/// The returned closure resolves a variable name (e.g. `"$requestType"`)
/// to the class names it holds as class-string values by delegating to
/// [`resolve_class_string_targets`](super::class_string_resolution::resolve_class_string_targets).
pub(in crate::completion) fn build_var_resolver_from_ctx<'a>(
    ctx: &'a VarResolutionCtx<'a>,
) -> impl Fn(&str) -> Vec<String> + 'a {
    move |var_name: &str| -> Vec<String> {
        super::class_string_resolution::resolve_class_string_targets(
            var_name,
            ctx.current_class,
            ctx.all_classes,
            ctx.content,
            ctx.cursor_offset,
            ctx.class_loader,
        )
        .iter()
        .map(|c| c.name.clone())
        .collect()
    }
}

/// Check whether a type hint should be enriched with generic args for
/// Eloquent scope method Builder parameters.
///
/// When `type_str` resolves to `Builder` (the Eloquent Builder, without
/// generic parameters) and the enclosing method is a scope on a class
/// that extends Eloquent Model, returns a `PhpType::Generic` wrapping
/// the builder name and the enclosing model.  Otherwise returns `None`,
/// meaning the caller should use the original type.
///
/// A method is considered a scope when it uses the `scopeX` naming
/// convention (name starts with `scope`, len > 5) **or** when
/// `has_scope_attr` is `true` (the method has `#[Scope]`).
fn enrich_builder_type_in_scope(
    type_hint: &PhpType,
    method_name: &str,
    has_scope_attr: bool,
    current_class: &ClassInfo,
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<PhpType> {
    use crate::virtual_members::laravel::{ELOQUENT_BUILDER_FQN, extends_eloquent_model};

    // Only applies inside scope methods: either the scopeX naming
    // convention or the #[Scope] attribute.
    let is_convention_scope = method_name.starts_with("scope") && method_name.len() > 5;
    if !is_convention_scope && !has_scope_attr {
        return None;
    }

    // Only applies when the enclosing class extends Eloquent Model.
    if !extends_eloquent_model(current_class, class_loader) {
        return None;
    }

    // Check if the type is the Eloquent Builder (without generic args).
    // Accept both the FQN and the short name `Builder` (common in use
    // imports).  If the type already has generic args (e.g.
    // `Builder<User>`), do not enrich — the user-supplied generics
    // should be used as-is.
    if type_hint.has_type_structure() {
        return None;
    }
    let type_name = match type_hint {
        PhpType::Named(n) => n.as_str(),
        _ => return None,
    };
    let is_eloquent_builder = type_name == ELOQUENT_BUILDER_FQN || type_name == "Builder";
    if !is_eloquent_builder {
        return None;
    }

    // Build the enriched type with the enclosing model as the generic arg.
    Some(PhpType::Generic(
        type_name.to_string(),
        vec![PhpType::Named(current_class.name.clone())],
    ))
}

/// Resolve the type of `$variable` by re-parsing the file and walking
/// the method body that contains `cursor_offset`.
///
/// Looks at:
///   1. Assignments: `$var = new ClassName(…)` / `new self` / `new static`
///   2. Assignments from function calls: `$var = app()` → look up return type
///   3. Method parameter type hints
///
/// Returns all possible types when the variable is assigned different
/// types in conditional branches.
pub(crate) fn resolve_variable_types(
    var_name: &str,
    current_class: &ClassInfo,
    all_classes: &[Arc<ClassInfo>],
    content: &str,
    cursor_offset: u32,
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    loaders: Loaders<'_>,
) -> Vec<ResolvedType> {
    // ── Depth guard ─────────────────────────────────────────────
    let depth = VAR_RESOLUTION_DEPTH.with(|d| {
        let cur = d.get();
        d.set(cur.saturating_add(1));
        cur
    });
    if depth >= MAX_VAR_RESOLUTION_DEPTH {
        VAR_RESOLUTION_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
        VAR_RESOLUTION_DEPTH_LIMITED.with(|f| f.set(true));
        return vec![];
    }

    let result = with_parsed_program(content, "resolve_variable_types", |program, _content| {
        let ctx = VarResolutionCtx {
            var_name,
            current_class,
            all_classes,
            content,
            cursor_offset,
            class_loader,
            loaders,
            resolved_class_cache: None,
            enclosing_return_type: None,
            branch_aware: false,
        };

        resolve_variable_in_statements(program.statements.iter(), &ctx)
    });

    let new_depth = VAR_RESOLUTION_DEPTH.with(|d| {
        let v = d.get().saturating_sub(1);
        d.set(v);
        v
    });
    // Clear the depth-limited flag when the outermost call returns.
    // Inner calls leave it set so that every caller in the stack
    // can observe it.
    if new_depth == 0 {
        VAR_RESOLUTION_DEPTH_LIMITED.with(|f| f.set(false));
    }
    result
}

/// Resolve variable types with branch-aware if/else handling.
///
/// Like [`resolve_variable_types`], but when the cursor is inside a
/// specific if/else/elseif branch, only that branch's assignments
/// contribute to the result.  This produces the single type visible
/// at the cursor position, which is what hover needs (e.g. only `Lamp`
/// inside an if-branch, not `Lamp|Faucet`).
pub(crate) fn resolve_variable_types_branch_aware(
    var_name: &str,
    current_class: &ClassInfo,
    all_classes: &[Arc<ClassInfo>],
    content: &str,
    cursor_offset: u32,
    class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
    loaders: Loaders<'_>,
) -> Vec<ResolvedType> {
    // ── Depth guard (same as resolve_variable_types) ────────────
    let depth = VAR_RESOLUTION_DEPTH.with(|d| {
        let cur = d.get();
        d.set(cur.saturating_add(1));
        cur
    });
    if depth >= MAX_VAR_RESOLUTION_DEPTH {
        VAR_RESOLUTION_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
        VAR_RESOLUTION_DEPTH_LIMITED.with(|f| f.set(true));
        return vec![];
    }

    let result = with_parsed_program(
        content,
        "resolve_variable_types_branch_aware",
        |program, _content| {
            let ctx = VarResolutionCtx {
                var_name,
                current_class,
                all_classes,
                content,
                cursor_offset,
                class_loader,
                loaders,
                resolved_class_cache: None,
                enclosing_return_type: None,
                branch_aware: true,
            };

            resolve_variable_in_statements(program.statements.iter(), &ctx)
        },
    );

    let new_depth = VAR_RESOLUTION_DEPTH.with(|d| {
        let v = d.get().saturating_sub(1);
        d.set(v);
        v
    });
    if new_depth == 0 {
        VAR_RESOLUTION_DEPTH_LIMITED.with(|f| f.set(false));
    }
    result
}

/// Walk a sequence of top-level statements to find the class or
/// function body that contains the cursor, then resolve the target
/// variable's type within that scope.
pub(in crate::completion) fn resolve_variable_in_statements<'b>(
    statements: impl Iterator<Item = &'b Statement<'b>>,
    ctx: &VarResolutionCtx<'_>,
) -> Vec<ResolvedType> {
    // Collect so we can iterate twice: once to check class bodies,
    // once (if needed) to walk top-level statements.
    let stmts: Vec<&Statement> = statements.collect();

    for &stmt in &stmts {
        match stmt {
            Statement::Class(class) => {
                let start = class.left_brace.start.offset;
                let end = class.right_brace.end.offset;
                if ctx.cursor_offset < start || ctx.cursor_offset > end {
                    continue;
                }
                // The cursor is inside this class body.  PHP method
                // scopes are isolated — they cannot access variables
                // from enclosing or top-level code.  Return whatever
                // the member scan found (even if empty, e.g. after
                // `unset($var)`), and never fall through to the
                // top-level walk.
                return resolve_variable_in_members(class.members.iter(), ctx);
            }
            Statement::Interface(iface) => {
                let start = iface.left_brace.start.offset;
                let end = iface.right_brace.end.offset;
                if ctx.cursor_offset < start || ctx.cursor_offset > end {
                    continue;
                }
                return resolve_variable_in_members(iface.members.iter(), ctx);
            }
            Statement::Enum(enum_def) => {
                let start = enum_def.left_brace.start.offset;
                let end = enum_def.right_brace.end.offset;
                if ctx.cursor_offset < start || ctx.cursor_offset > end {
                    continue;
                }
                return resolve_variable_in_members(enum_def.members.iter(), ctx);
            }
            Statement::Trait(trait_def) => {
                let start = trait_def.left_brace.start.offset;
                let end = trait_def.right_brace.end.offset;
                if ctx.cursor_offset < start || ctx.cursor_offset > end {
                    continue;
                }
                return resolve_variable_in_members(trait_def.members.iter(), ctx);
            }
            Statement::Namespace(ns) => {
                let results = resolve_variable_in_statements(ns.statements().iter(), ctx);
                if !results.is_empty() {
                    return results;
                }
            }
            // ── Top-level function declarations ──
            // If the cursor is inside a `function foo(Type $p) { … }`
            // at the top level, resolve the variable from its params
            // and walk its body.
            Statement::Function(func) => {
                if let Some(results) = try_resolve_in_function(func, ctx) {
                    return results;
                }
            }
            // ── Functions inside if-guards / blocks ──
            // The common PHP pattern `if (! function_exists('foo'))
            // { function foo(Type $p) { … } }` nests the function
            // declaration inside an if body.  Recurse into blocks
            // and if-bodies so the function's parameters and body
            // assignments are still resolved.
            Statement::If(_) | Statement::Block(_) => {
                if let Some(results) = try_resolve_in_nested_function(stmt, ctx) {
                    return results;
                }
            }
            _ => {}
        }

        // ── Anonymous classes inside expressions ──
        // Anonymous classes (`new class { … }`) appear as expressions
        // inside statements (e.g. `return new class extends Foo { … };`
        // or `$x = new class { … };`).  If the cursor falls inside one,
        // resolve variables from its member methods just like we do for
        // named classes above.
        let stmt_span = stmt.span();
        if ctx.cursor_offset >= stmt_span.start.offset
            && ctx.cursor_offset <= stmt_span.end.offset
            && let Some(anon) = find_anonymous_class_containing_cursor(stmt, ctx.cursor_offset)
        {
            return resolve_variable_in_members(anon.members.iter(), ctx);
        }
    }

    // The cursor is not inside any class/interface/enum body — it must
    // be in top-level code.  Walk all top-level statements to find
    // variable assignments (e.g. `$user = new User(…);`).
    let mut results: Vec<ResolvedType> = Vec::new();
    walk_statements_for_assignments(stmts.into_iter(), ctx, &mut results, false);
    results
}

/// Recursively walk a statement's expression tree looking for an
/// `AnonymousClass` whose body (between `{` and `}`) contains the
/// given cursor offset.  Returns a reference to the first matching
/// anonymous class node, or `None`.
fn find_anonymous_class_containing_cursor<'a>(
    stmt: &'a Statement<'a>,
    cursor_offset: u32,
) -> Option<&'a AnonymousClass<'a>> {
    /// Walk an expression tree for an anonymous class containing the cursor.
    fn walk_expr<'a>(expr: &'a Expression<'a>, cursor: u32) -> Option<&'a AnonymousClass<'a>> {
        let sp = expr.span();
        if cursor < sp.start.offset || cursor > sp.end.offset {
            return None;
        }
        match expr {
            Expression::AnonymousClass(anon) => {
                if cursor >= anon.left_brace.start.offset && cursor <= anon.right_brace.end.offset {
                    return Some(anon);
                }
                None
            }
            Expression::Parenthesized(p) => walk_expr(p.expression, cursor),
            Expression::Assignment(a) => {
                walk_expr(a.lhs, cursor).or_else(|| walk_expr(a.rhs, cursor))
            }
            Expression::Binary(b) => walk_expr(b.lhs, cursor).or_else(|| walk_expr(b.rhs, cursor)),
            Expression::Conditional(c) => walk_expr(c.condition, cursor)
                .or_else(|| c.then.and_then(|e| walk_expr(e, cursor)))
                .or_else(|| walk_expr(c.r#else, cursor)),
            Expression::Call(call) => match call {
                Call::Function(fc) => walk_args(&fc.argument_list.arguments, cursor),
                Call::Method(mc) => walk_expr(mc.object, cursor)
                    .or_else(|| walk_args(&mc.argument_list.arguments, cursor)),
                Call::NullSafeMethod(mc) => walk_expr(mc.object, cursor)
                    .or_else(|| walk_args(&mc.argument_list.arguments, cursor)),
                Call::StaticMethod(sc) => walk_expr(sc.class, cursor)
                    .or_else(|| walk_args(&sc.argument_list.arguments, cursor)),
            },
            Expression::Array(arr) => {
                for elem in arr.elements.iter() {
                    let found = match elem {
                        ArrayElement::KeyValue(kv) => {
                            walk_expr(kv.key, cursor).or_else(|| walk_expr(kv.value, cursor))
                        }
                        ArrayElement::Value(v) => walk_expr(v.value, cursor),
                        ArrayElement::Variadic(v) => walk_expr(v.value, cursor),
                        _ => None,
                    };
                    if found.is_some() {
                        return found;
                    }
                }
                None
            }
            Expression::LegacyArray(arr) => {
                for elem in arr.elements.iter() {
                    let found = match elem {
                        ArrayElement::KeyValue(kv) => {
                            walk_expr(kv.key, cursor).or_else(|| walk_expr(kv.value, cursor))
                        }
                        ArrayElement::Value(v) => walk_expr(v.value, cursor),
                        ArrayElement::Variadic(v) => walk_expr(v.value, cursor),
                        _ => None,
                    };
                    if found.is_some() {
                        return found;
                    }
                }
                None
            }
            Expression::Closure(closure) => {
                // The anonymous class could be inside a closure body.
                for inner in closure.body.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor) {
                        return Some(anon);
                    }
                }
                None
            }
            Expression::ArrowFunction(arrow) => walk_expr(arrow.expression, cursor),
            Expression::Instantiation(inst) => {
                if let Some(ref args) = inst.argument_list {
                    walk_args(&args.arguments, cursor)
                } else {
                    None
                }
            }
            Expression::UnaryPrefix(u) => walk_expr(u.operand, cursor),
            Expression::UnaryPostfix(u) => walk_expr(u.operand, cursor),
            Expression::Throw(t) => walk_expr(t.exception, cursor),
            Expression::Clone(c) => walk_expr(c.object, cursor),
            Expression::Match(m) => {
                if let Some(found) = walk_expr(m.expression, cursor) {
                    return Some(found);
                }
                for arm in m.arms.iter() {
                    if let Some(found) = walk_expr(arm.expression(), cursor) {
                        return Some(found);
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Walk a list of call arguments.
    fn walk_args<'a>(
        arguments: &'a mago_syntax::ast::sequence::TokenSeparatedSequence<'a, Argument<'a>>,
        cursor: u32,
    ) -> Option<&'a AnonymousClass<'a>> {
        for arg in arguments.iter() {
            let arg_expr = match arg {
                Argument::Positional(pos) => pos.value,
                Argument::Named(named) => named.value,
            };
            if let Some(found) = walk_expr(arg_expr, cursor) {
                return Some(found);
            }
        }
        None
    }

    match stmt {
        Statement::Expression(expr_stmt) => walk_expr(expr_stmt.expression, cursor_offset),
        Statement::Return(ret) => ret.value.as_ref().and_then(|v| walk_expr(v, cursor_offset)),
        Statement::Block(block) => {
            for inner in block.statements.iter() {
                if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset) {
                    return Some(anon);
                }
            }
            None
        }
        Statement::If(if_stmt) => match &if_stmt.body {
            IfBody::Statement(body) => {
                find_anonymous_class_containing_cursor(body.statement, cursor_offset)
            }
            IfBody::ColonDelimited(body) => {
                for inner in body.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
                None
            }
        },
        Statement::Foreach(foreach) => match &foreach.body {
            ForeachBody::Statement(inner) => {
                find_anonymous_class_containing_cursor(inner, cursor_offset)
            }
            ForeachBody::ColonDelimited(body) => {
                for inner in body.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
                None
            }
        },
        Statement::While(while_stmt) => match &while_stmt.body {
            WhileBody::Statement(inner) => {
                find_anonymous_class_containing_cursor(inner, cursor_offset)
            }
            WhileBody::ColonDelimited(body) => {
                for inner in body.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
                None
            }
        },
        Statement::For(for_stmt) => match &for_stmt.body {
            ForBody::Statement(inner) => {
                find_anonymous_class_containing_cursor(inner, cursor_offset)
            }
            ForBody::ColonDelimited(body) => {
                for inner in body.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
                None
            }
        },
        Statement::DoWhile(dw) => {
            find_anonymous_class_containing_cursor(dw.statement, cursor_offset)
        }
        Statement::Try(try_stmt) => {
            for inner in try_stmt.block.statements.iter() {
                if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset) {
                    return Some(anon);
                }
            }
            for catch in try_stmt.catch_clauses.iter() {
                for inner in catch.block.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
            }
            if let Some(finally) = &try_stmt.finally_clause {
                for inner in finally.block.statements.iter() {
                    if let Some(anon) = find_anonymous_class_containing_cursor(inner, cursor_offset)
                    {
                        return Some(anon);
                    }
                }
            }
            None
        }
        _ => None,
    }
}

/// Try to resolve the target variable inside a `Function` declaration.
///
/// Returns `Some(results)` when the cursor falls inside the function body
/// (the function introduces an isolated scope, so we always return even
/// when the result vec is empty).  Returns `None` when the cursor is
/// outside this function.
fn try_resolve_in_function(
    func: &Function<'_>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<Vec<ResolvedType>> {
    let body_start = func.body.left_brace.start.offset;
    let body_end = func.body.right_brace.end.offset;
    if ctx.cursor_offset < body_start || ctx.cursor_offset > body_end {
        return None;
    }
    // Extract the enclosing function's @return type for generator
    // yield inference inside the body.  Use body_start + 1 (just
    // past the opening `{`) so the backward brace scan in
    // find_enclosing_return_type immediately finds the function's
    // own `{` and does NOT get confused by intermediate `{`/`}`
    // from nested control-flow.
    let enclosing_ret =
        crate::docblock::find_enclosing_return_type(ctx.content, (body_start + 1) as usize);
    let body_ctx = ctx.with_enclosing_return_type(enclosing_ret);
    // The cursor is inside this function body.  PHP function scopes
    // are isolated, so return the result directly (even if empty
    // after `unset`).
    let mut results: Vec<ResolvedType> = Vec::new();
    super::closure_resolution::resolve_closure_params(
        &func.parameter_list,
        &body_ctx,
        &mut results,
    );

    // ── Substitute function-level template params with their
    // bounds for standalone function parameters ─────────────────
    // When the resolved parameter type is `class-string<T>` or a
    // bare template name `T` and `T` is a function-level template
    // with an upper bound, replace `T` with the bound so that
    // member access resolves against the bound type.
    let func_start = func.span().start.offset as usize;
    for rt in results.iter_mut() {
        if matches!(&rt.type_string, PhpType::ClassString(Some(inner)) if matches!(inner.as_ref(), PhpType::Named(_)))
        {
            rt.type_string = substitute_class_string_template_bounds(
                rt.type_string.clone(),
                ctx.content,
                func_start,
            );
        }
        // Bare template param → bound (e.g. `T` → `Builder|QueryBuilder`).
        rt.type_string =
            substitute_template_param_bounds(rt.type_string.clone(), ctx.content, func_start);
    }

    walk_statements_for_assignments(func.body.statements.iter(), &body_ctx, &mut results, false);
    if !results.is_empty() {
        return Some(results);
    }

    // Fall back to a standalone `@var` docblock scan when parameter
    // resolution and assignment walking yielded no type.
    super::closure_resolution::try_standalone_var_docblock(&body_ctx, &mut results);
    if !results.is_empty() {
        return Some(results);
    }

    // Generator yield reverse inference for top-level functions.
    if let Some(ref ret_type) = body_ctx.enclosing_return_type {
        let yield_results =
            super::raw_type_inference::try_infer_from_generator_yield(ret_type, &body_ctx);
        if !yield_results.is_empty() {
            return Some(ResolvedType::from_classes(yield_results));
        }
    }

    Some(results)
}

/// Recursively search a statement for a nested `Function` declaration
/// whose body contains the cursor.
///
/// This handles the common PHP pattern where functions are wrapped in
/// `if (! function_exists('name')) { function name(…) { … } }` guards.
/// The function may be nested inside `Block`, `If`, or other compound
/// statements.
fn try_resolve_in_nested_function(
    stmt: &Statement<'_>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<Vec<ResolvedType>> {
    // Quick span check — skip if cursor is outside this statement entirely.
    let span = stmt.span();
    if ctx.cursor_offset < span.start.offset || ctx.cursor_offset > span.end.offset {
        return None;
    }
    match stmt {
        Statement::Function(func) => try_resolve_in_function(func, ctx),
        Statement::Block(block) => {
            for inner in block.statements.iter() {
                if let Some(results) = try_resolve_in_nested_function(inner, ctx) {
                    return Some(results);
                }
            }
            None
        }
        Statement::If(if_stmt) => {
            match &if_stmt.body {
                IfBody::Statement(body) => {
                    if let Some(results) = try_resolve_in_nested_function(body.statement, ctx) {
                        return Some(results);
                    }
                    for else_if in body.else_if_clauses.iter() {
                        if let Some(results) =
                            try_resolve_in_nested_function(else_if.statement, ctx)
                        {
                            return Some(results);
                        }
                    }
                    if let Some(else_clause) = &body.else_clause
                        && let Some(results) =
                            try_resolve_in_nested_function(else_clause.statement, ctx)
                    {
                        return Some(results);
                    }
                }
                IfBody::ColonDelimited(body) => {
                    for inner in body.statements.iter() {
                        if let Some(results) = try_resolve_in_nested_function(inner, ctx) {
                            return Some(results);
                        }
                    }
                    for else_if in body.else_if_clauses.iter() {
                        for inner in else_if.statements.iter() {
                            if let Some(results) = try_resolve_in_nested_function(inner, ctx) {
                                return Some(results);
                            }
                        }
                    }
                    if let Some(else_clause) = &body.else_clause {
                        for inner in else_clause.statements.iter() {
                            if let Some(results) = try_resolve_in_nested_function(inner, ctx) {
                                return Some(results);
                            }
                        }
                    }
                }
            }
            None
        }
        _ => None,
    }
}

/// Resolve a variable's type by scanning class-like members for parameter
/// type hints and assignment expressions.
///
/// Shared between `Statement::Class` and `Statement::Interface`.
///
/// Returns all possible types when the variable is assigned different
/// types in conditional branches.
fn resolve_variable_in_members<'b>(
    members: impl Iterator<Item = &'b ClassLikeMember<'b>>,
    ctx: &VarResolutionCtx<'_>,
) -> Vec<ResolvedType> {
    for member in members {
        if let ClassLikeMember::Method(method) = member {
            // Collect parameter type hint as initial candidate set.
            // We no longer return early here so that the method body
            // can be scanned for instanceof narrowing / reassignments.
            let mut param_results: Vec<ResolvedType> = Vec::new();
            let mut matched_param_is_variadic = false;
            for param in method.parameter_list.parameters.iter() {
                let pname = param.variable.name.to_string();
                if pname == ctx.var_name {
                    matched_param_is_variadic = param.ellipsis.is_some();
                    // Try the native AST type hint first.
                    let native_type = param.hint.as_ref().map(|h| extract_hint_type(h));

                    // ── Eloquent scope Builder inference ────────
                    // When the enclosing method is a scope on an
                    // Eloquent Model and the parameter type is
                    // `Builder` (without generics), enrich it to
                    // `Builder<EnclosingModel>` so that the
                    // generic-args path injects scope methods.
                    let enriched_type = native_type.as_ref().and_then(|nt| {
                        let method_name = method.name.value.to_string();
                        // Check whether the method has a #[Scope]
                        // attribute so that the enrichment also
                        // applies to attribute-style scopes.
                        let has_scope_attr = method.attribute_lists.iter().any(|al| {
                            al.attributes
                                .iter()
                                .any(|a| a.name.last_segment() == "Scope")
                        });
                        enrich_builder_type_in_scope(
                            nt,
                            &method_name,
                            has_scope_attr,
                            ctx.current_class,
                            ctx.class_loader,
                        )
                    });
                    // Prefer the enriched type (Builder<Model>) over the bare native type.
                    let type_for_resolution: Option<&PhpType> =
                        enriched_type.as_ref().or(native_type.as_ref());

                    // Check the `@param` docblock annotation which may
                    // carry a more specific type than the native hint
                    // (e.g. `@param FuncCall $node` on `Node $node`).
                    let method_start = method.span().start.offset as usize;
                    let raw_docblock_type = crate::docblock::find_iterable_raw_type_in_source(
                        ctx.content,
                        method_start,
                        ctx.var_name,
                    );

                    // Pick the effective type: docblock overrides native
                    // when it is a compatible refinement.
                    let native_parsed = if let Some(ref enriched) = enriched_type {
                        Some(enriched.clone())
                    } else {
                        native_type.clone()
                    };
                    let doc_parsed = raw_docblock_type.clone();
                    let effective_type = crate::docblock::resolve_effective_type_typed(
                        native_parsed.as_ref(),
                        doc_parsed.as_ref(),
                    );

                    // ── Substitute method-level template params with
                    // their bounds before class resolution ──────────
                    // When the effective type contains a bare template
                    // parameter name (e.g. `T` from `@template T of
                    // Builder|QueryBuilder`), replace it with the bound
                    // type so that `$query->where(...)` resolves members
                    // on `Builder|QueryBuilder` instead of failing with
                    // "subject type 'T' could not be resolved".
                    let effective_type = effective_type.map(|ty| {
                        substitute_template_param_bounds(
                            ty,
                            ctx.content,
                            method.span().start.offset as usize,
                        )
                    });

                    let resolved_from_effective = effective_type
                        .as_ref()
                        .map(|ty| {
                            crate::completion::type_resolution::type_hint_to_classes_typed(
                                ty,
                                &ctx.current_class.name,
                                ctx.all_classes,
                                ctx.class_loader,
                            )
                        })
                        .unwrap_or_default();

                    if !resolved_from_effective.is_empty() {
                        param_results = ResolvedType::from_classes_with_hint(
                            resolved_from_effective,
                            effective_type.unwrap_or_else(|| {
                                type_for_resolution
                                    .cloned()
                                    .unwrap_or_else(PhpType::untyped)
                            }),
                        );
                        break;
                    }

                    // The effective type didn't resolve to a class (e.g.
                    // `object`, `mixed`, or an object shape). Fall back to
                    // the raw `@param` docblock annotation which may carry
                    // a more specific non-class type such as
                    // `object{foo: int, bar: string}`.
                    if let Some(ref raw_docblock_type) = raw_docblock_type {
                        let parsed_docblock = raw_docblock_type.clone();
                        let resolved =
                            crate::completion::type_resolution::type_hint_to_classes_typed(
                                &parsed_docblock,
                                &ctx.current_class.name,
                                ctx.all_classes,
                                ctx.class_loader,
                            );
                        if !resolved.is_empty() {
                            param_results =
                                ResolvedType::from_classes_with_hint(resolved, parsed_docblock);
                            break;
                        }
                    }

                    // Neither native hint nor docblock resolved to a class.
                    // Check the fully-resolved class (with interface
                    // members merged and `@implements` generics applied)
                    // for a more specific parameter type.  This handles
                    // cases where the class declares `map(object $entity)`
                    // but the interface has `@param TEntity $entity` with
                    // `@implements Interface<Boo>` substituting `TEntity`.
                    let mut merged_type_hint: Option<PhpType> = None;
                    let method_name = method.name.value.to_string();
                    let merged = crate::virtual_members::resolve_class_fully_maybe_cached(
                        ctx.current_class,
                        ctx.class_loader,
                        ctx.resolved_class_cache,
                    );
                    if let Some(merged_method) =
                        merged.methods.iter().find(|m| m.name == method_name)
                    {
                        // Find the matching parameter by name.
                        // ParameterInfo.name includes the `$` prefix.
                        if let Some(merged_param) = merged_method
                            .parameters
                            .iter()
                            .find(|p| p.name == ctx.var_name)
                            && let Some(ref hint) = merged_param.type_hint
                        {
                            let resolved =
                                crate::completion::type_resolution::type_hint_to_classes_typed(
                                    hint,
                                    &ctx.current_class.name,
                                    ctx.all_classes,
                                    ctx.class_loader,
                                );
                            if !resolved.is_empty() {
                                param_results =
                                    ResolvedType::from_classes_with_hint(resolved, hint.clone());
                                break;
                            }
                            // The merged type hint is richer than the
                            // native hint (e.g. `list<Pen>` vs `array`)
                            // but didn't resolve to a class. Remember
                            // it so the type-string-only fallback below
                            // uses it instead of the bare native hint.
                            merged_type_hint = Some(hint.clone());
                        }
                    }

                    // All class-resolution attempts failed.  Emit a
                    // type-string-only entry so that consumers like hover
                    // and diagnostics can see the parameter's type even
                    // when it's a scalar or PHPDoc pseudo-type.
                    //
                    // Prefer the docblock type (e.g. `class-string<BackedEnum>`)
                    // over the native type (e.g. `string`) when the
                    // docblock provides a more specific annotation.
                    // When the merged class provides a richer type from
                    // parent/interface inheritance (e.g. `list<Pen>` from
                    // a parent's `@param`), prefer that over the bare
                    // native hint.
                    let best_type = if let Some(ref rdt) = raw_docblock_type {
                        Some(rdt.clone())
                    } else if let Some(ref mth) = merged_type_hint {
                        Some(mth.clone())
                    } else {
                        type_for_resolution.cloned()
                    };
                    if let Some(mut parsed) = best_type {
                        // ── Substitute method-level template params
                        // in `class-string<T>` with their bounds ────────
                        // When the parameter type is `class-string<T>` and
                        // `T` is a method-level template with an upper bound
                        // (e.g. `@template T of CustomerModel`), replace `T`
                        // with `CustomerModel` so that static member access
                        // (`$class::KEY`, `$class::from(...)`) resolves
                        // against the bound type.
                        parsed = substitute_class_string_template_bounds(
                            parsed,
                            ctx.content,
                            method.span().start.offset as usize,
                        );

                        param_results = vec![ResolvedType::from_type_string(parsed)];
                    }
                }
            }

            // ── Variadic parameter wrapping ─────────────────────────
            // When the matched parameter is variadic (e.g.
            // `HtmlString|int|string ...$placeholders`), the native
            // type hint describes the *element* type, but the variable
            // itself holds `list<ElementType>`.  Wrap the resolved
            // types so that foreach iteration can extract the element
            // type via `PhpType::extract_value_type`.
            if matched_param_is_variadic && !param_results.is_empty() {
                for rt in &mut param_results {
                    rt.type_string = PhpType::list(rt.type_string.clone());
                    // The variable is now an array, not a class instance,
                    // so clear the class_info.
                    rt.class_info = None;
                }
            }

            if let MethodBody::Concrete(block) = &method.body {
                let blk_start = block.left_brace.start.offset;
                let blk_end = block.right_brace.end.offset;
                if ctx.cursor_offset >= blk_start && ctx.cursor_offset <= blk_end {
                    // Extract the enclosing method's @return type for
                    // generator yield inference inside the body.
                    // Use blk_start + 1 (just past the opening `{`)
                    // so the backward brace scan in
                    // find_enclosing_return_type immediately finds
                    // the method's own `{` and does NOT get confused
                    // by intermediate `{`/`}` from nested control-
                    // flow (if, while, foreach, etc.) that would sit
                    // between the cursor and the method brace when
                    // cursor_offset is used.
                    let enclosing_ret = crate::docblock::find_enclosing_return_type(
                        ctx.content,
                        (blk_start + 1) as usize,
                    );
                    let body_ctx = ctx.with_enclosing_return_type(enclosing_ret);
                    // Seed the result set with the parameter type hint
                    // (if any) so that instanceof narrowing and
                    // unconditional reassignments can refine it.
                    let mut results = param_results.clone();
                    walk_statements_for_assignments(
                        block.statements.iter(),
                        &body_ctx,
                        &mut results,
                        false,
                    );
                    if !results.is_empty() {
                        return results;
                    }

                    // Fall back to a standalone `@var` docblock scan
                    // when parameter resolution and assignment walking
                    // yielded no type.
                    super::closure_resolution::try_standalone_var_docblock(&body_ctx, &mut results);
                    if !results.is_empty() {
                        return results;
                    }

                    // ── Generator yield reverse inference ──
                    // If no type was found through normal resolution
                    // and the enclosing method returns a Generator,
                    // check whether our variable appears as the
                    // operand of a `yield` statement and infer its
                    // type from the Generator's TValue parameter.
                    if let Some(ref ret_type) = body_ctx.enclosing_return_type {
                        let yield_results =
                            super::raw_type_inference::try_infer_from_generator_yield(
                                ret_type, &body_ctx,
                            );
                        if !yield_results.is_empty() {
                            return ResolvedType::from_classes(yield_results);
                        }
                    }

                    // The concrete body was walked but produced no
                    // results.  This can happen when instanceof
                    // narrowing targeted an unresolvable class (e.g.
                    // from a phar) and cleared the parameter type.
                    // Do NOT fall through to the abstract-method
                    // param fallback below — returning the un-narrowed
                    // parameter type would cause false-positive
                    // "unknown member" diagnostics for members that
                    // only exist on the narrowed (unresolvable) class.
                    return vec![];
                } else {
                    // Cursor is not inside this method's body —
                    // skip to the next method so we don't
                    // accidentally return parameter types from
                    // a different method that happens to share
                    // the same parameter name.
                    continue;
                }
            }

            // Abstract method (no concrete body) — return the
            // parameter type hint only when the cursor falls
            // within the method's overall span (signature region).
            let method_start = method.span().start.offset;
            let method_end = method.span().end.offset;
            if !param_results.is_empty()
                && ctx.cursor_offset >= method_start
                && ctx.cursor_offset <= method_end
            {
                return param_results;
            }
        }
    }
    vec![]
}

/// Substitute method/function-level template parameter names with their
/// upper bounds from `@template T of Bound` annotations.
///
/// This handles the general case where a parameter type IS a template
/// parameter (e.g. `@param T $query` where `@template T of Builder`).
/// Without this substitution, `T` remains an unresolvable named type
/// and member access on `$query` fails with "subject type 'T' could not
/// be resolved".
///
/// Works on any `PhpType` structure — bare names, unions, intersections,
/// nullable wrappers, generics, etc. — via `PhpType::substitute`.
fn substitute_template_param_bounds(
    ty: PhpType,
    content: &str,
    method_start_offset: usize,
) -> PhpType {
    // Quick check: only act when the type contains at least one bare
    // identifier that could be a template parameter.  This avoids the
    // docblock parse for the common case where the type is a concrete
    // class name or scalar.
    if !type_may_contain_template_param(&ty) {
        return ty;
    }

    let before = &content[..method_start_offset];
    let docblock = extract_preceding_docblock(before);

    let Some(docblock) = docblock else {
        return ty;
    };

    let bounds = docblock::extract_template_params_with_bounds(docblock);
    if bounds.is_empty() {
        return ty;
    }

    let mut subs = std::collections::HashMap::new();
    for (name, bound) in bounds {
        if let Some(bound_type) = bound {
            subs.insert(name, bound_type);
        }
    }

    if subs.is_empty() {
        return ty;
    }

    ty.substitute(&subs)
}

/// Check whether a `PhpType` tree may contain a bare template parameter
/// name — i.e. a `Named` variant whose value is not a well-known scalar
/// or pseudo-type.  This is a cheap pre-filter so that we only parse the
/// docblock when there is a realistic chance of finding a substitution.
fn type_may_contain_template_param(ty: &PhpType) -> bool {
    match ty {
        PhpType::Named(name) => {
            // Well-known scalars/pseudo-types are never template params.
            !is_keyword_type(name)
        }
        PhpType::Union(members) | PhpType::Intersection(members) => {
            members.iter().any(type_may_contain_template_param)
        }
        PhpType::Nullable(inner) => type_may_contain_template_param(inner),
        PhpType::Generic(base, args) => {
            !crate::php_type::is_keyword_type(base)
                || args.iter().any(type_may_contain_template_param)
        }
        _ => false,
    }
}

/// Substitute method-level template parameters inside `class-string<T>`
/// types with their upper bounds from `@template T of Bound` annotations.
///
/// This enables `$class::` static member access resolution when the
/// parameter is typed as `class-string<T>` and `T` is bounded by a
/// concrete class.  Without this substitution, `T` remains an
/// unresolvable named type and `$class::` yields no completions.
fn substitute_class_string_template_bounds(
    ty: PhpType,
    content: &str,
    method_start_offset: usize,
) -> PhpType {
    // Only act on class-string<T> where the inner type is a simple name
    // (i.e. a potential template parameter).
    let inner_name = match &ty {
        PhpType::ClassString(Some(inner)) => match inner.as_ref() {
            PhpType::Named(name) => Some(name.clone()),
            _ => None,
        },
        _ => None,
    };

    let Some(tpl_name) = inner_name else {
        return ty;
    };

    // Extract the method's docblock to find template parameter bounds.
    // The docblock sits immediately before the method declaration, so
    // we search backward from the method's start offset.
    let before = &content[..method_start_offset];
    let docblock = extract_preceding_docblock(before);

    let Some(docblock) = docblock else {
        return ty;
    };

    let bounds = docblock::extract_template_params_with_bounds(docblock);
    for (name, bound) in bounds {
        if name == tpl_name
            && let Some(bound_type) = bound
        {
            return PhpType::ClassString(Some(Box::new(bound_type)));
        }
    }

    ty
}

/// Extract the docblock comment immediately preceding a given offset.
///
/// Scans backward from `before` (the source text up to the method start)
/// to find the closest `/** ... */` block.  Returns `None` when no
/// docblock is found or when there is non-whitespace between the
/// docblock and the method declaration.
fn extract_preceding_docblock(before: &str) -> Option<&str> {
    let trimmed = before.trim_end();
    if !trimmed.ends_with("*/") {
        return None;
    }
    let close_pos = trimmed.len();
    let open_pos = trimmed.rfind("/**")?;
    Some(&trimmed[open_pos..close_pos])
}

pub(in crate::completion) fn walk_statements_for_assignments<'b>(
    statements: impl Iterator<Item = &'b Statement<'b>>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) {
    /// Return the sorted set of class names in `results`.
    fn result_names(results: &[ResolvedType]) -> Vec<String> {
        let mut names: Vec<String> = results
            .iter()
            .filter_map(|rt| rt.class_info.as_ref().map(|c| c.name.clone()))
            .collect();
        names.sort();
        names
    }

    // Accumulator for sequential `assert($x instanceof ...)` calls.
    // Each assert narrows to a single type; this vec collects them
    // so that two asserts in a row produce a union (intersection type).
    let mut assert_narrowed_types: Vec<ResolvedType> = Vec::new();

    for stmt in statements {
        // ── Closure / arrow-function scope ──
        // If the cursor falls *inside* this statement, check whether
        // it is (or contains) a closure / arrow function whose body
        // encloses the cursor.  Closures introduce a new variable
        // scope, so we resolve entirely within that scope and stop.
        let stmt_span = stmt.span();
        if ctx.cursor_offset >= stmt_span.start.offset
            && ctx.cursor_offset <= stmt_span.end.offset
            && super::closure_resolution::try_resolve_in_closure_stmt(stmt, ctx, results)
        {
            return;
        }

        // Only consider statements whose start is before the cursor
        if stmt.span().start.offset >= ctx.cursor_offset {
            continue;
        }

        match stmt {
            Statement::Expression(expr_stmt) => {
                // Try inline `/** @var Type */` override first.
                // If the docblock resolves successfully (and passes
                // the same override check we apply to @return), use
                // it and skip normal resolution for this statement.
                let pre_assign_names = result_names(results);
                if !try_inline_var_override(
                    expr_stmt.expression,
                    stmt.span().start.offset as usize,
                    ctx,
                    results,
                    conditional,
                ) {
                    check_expression_for_assignment(
                        expr_stmt.expression,
                        ctx,
                        results,
                        conditional,
                    );
                }
                // If an assignment (or @var override) changed the
                // results, the variable was reassigned — any prior
                // assert-narrowed types are no longer valid.
                if result_names(results) != pre_assign_names {
                    assert_narrowed_types.clear();
                }

                // ── Pass-by-reference parameter type inference ──
                // When a function call passes our variable to a
                // parameter declared as `Type &$param`, the variable
                // acquires that type after the call.
                try_apply_pass_by_reference_type(expr_stmt.expression, ctx, results, conditional);

                // ── assert($var instanceof ClassName) narrowing ──
                // When `assert($var instanceof Foo)` appears before
                // the cursor, narrow the variable to `Foo` for the
                // remainder of the current scope.
                //
                // Sequential asserts accumulate an intersection type:
                //   assert($x instanceof A);
                //   assert($x instanceof B);
                // → results contains members from both A and B.
                //
                // Save the pre-assert state so we can detect when
                // the assert actually narrowed, and merge with any
                // prior assert-narrowed types.
                let pre_assert_names = result_names(results);
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_instanceof_narrowing(
                        expr_stmt.expression,
                        ctx,
                        classes,
                    );
                });
                let changed = result_names(results) != pre_assert_names;
                // If the assert changed results AND we had prior
                // assert-narrowed types, merge the old narrowed
                // types back in (accumulate the intersection).
                if changed && !assert_narrowed_types.is_empty() {
                    for rt in &assert_narrowed_types {
                        if !results
                            .iter()
                            .any(|existing| existing.type_string == rt.type_string)
                        {
                            results.push(rt.clone());
                        }
                    }
                }
                // Track types that came from assert narrowing.
                if changed {
                    assert_narrowed_types.clone_from(results);
                }

                // ── @phpstan-assert / @psalm-assert narrowing ──
                // When a function with `@phpstan-assert Type $param`
                // is called as a standalone statement, narrow the
                // corresponding argument variable unconditionally.
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_custom_assert_narrowing(
                        expr_stmt.expression,
                        ctx,
                        classes,
                    );
                });

                // ── match(true) { $var instanceof Foo => … } narrowing ──
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_match_true_narrowing(expr_stmt.expression, ctx, classes);
                });

                // ── ternary instanceof narrowing ──
                // `$var instanceof Foo ? $var->method() : …`
                // When the cursor is inside a ternary whose condition
                // checks instanceof, narrow accordingly.
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_ternary_instanceof_narrowing(
                        expr_stmt.expression,
                        ctx,
                        classes,
                    );
                });

                // ── inline && narrowing ──
                // `$var instanceof Foo && $var->method()`
                // When the cursor is inside the RHS of `&&` whose
                // LHS checks instanceof, narrow accordingly.
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_inline_and_narrowing(expr_stmt.expression, ctx, classes);
                });
                // ── inline && null narrowing ──
                // `$var !== null && $var->method()`
                // When the cursor is inside the RHS of `&&` whose
                // LHS checks for non-null, strip null from resolved types.
                narrowing::try_apply_inline_and_null_narrowing(expr_stmt.expression, ctx, results);
            }
            // ── Return statements ──
            // The return value expression can contain narrowing
            // constructs like `return $x instanceof Foo && $x->bar()`
            // or `return $x instanceof Foo ? $x->method() : null`.
            // Apply the same expression-level narrowing that we
            // apply to standalone expression statements.
            Statement::Return(ret) => {
                if let Some(val) = ret.value {
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_match_true_narrowing(val, ctx, classes);
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_ternary_instanceof_narrowing(val, ctx, classes);
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_inline_and_narrowing(val, ctx, classes);
                    });
                    narrowing::try_apply_inline_and_null_narrowing(val, ctx, results);
                }
            }
            // Recurse into blocks — these are just `{ … }` groupings,
            // not conditional, so preserve the current `conditional` flag.
            Statement::Block(block) => {
                walk_statements_for_assignments(block.statements.iter(), ctx, results, conditional);
            }
            Statement::If(if_stmt) => {
                walk_if_statement(if_stmt, stmt, ctx, results);
            }
            Statement::Foreach(foreach) => {
                walk_foreach_statement(foreach, ctx, results, conditional);
            }
            Statement::While(while_stmt) => {
                walk_while_statement(while_stmt, ctx, results);
            }
            Statement::For(for_stmt) => {
                // ── Pre-scan for loop-carried assignments ──
                let for_body_span = for_stmt.body.span();
                let for_header_start = for_stmt.r#for.span().start.offset;
                let cursor_inside_for = ctx.cursor_offset >= for_header_start
                    && ctx.cursor_offset <= for_body_span.end.offset;
                if cursor_inside_for {
                    match &for_stmt.body {
                        ForBody::Statement(inner) => {
                            prescan_loop_body_for_assignments(
                                std::iter::once(*inner),
                                for_body_span.end.offset,
                                ctx,
                                results,
                            );
                        }
                        ForBody::ColonDelimited(body) => {
                            prescan_loop_body_for_assignments(
                                body.statements.iter(),
                                for_body_span.end.offset,
                                ctx,
                                results,
                            );
                        }
                    }
                }
                match &for_stmt.body {
                    ForBody::Statement(inner) => {
                        check_statement_for_assignments(inner, ctx, results, true);
                    }
                    ForBody::ColonDelimited(body) => {
                        walk_statements_for_assignments(body.statements.iter(), ctx, results, true);
                    }
                }
            }
            Statement::DoWhile(dw) => {
                // ── Pre-scan for loop-carried assignments ──
                let dw_body_span = dw.statement.span();
                let dw_header_start = dw.r#do.span().start.offset;
                let cursor_inside_dw = ctx.cursor_offset >= dw_header_start
                    && ctx.cursor_offset <= dw_body_span.end.offset;
                if cursor_inside_dw {
                    prescan_loop_body_for_assignments(
                        std::iter::once(dw.statement),
                        dw_body_span.end.offset,
                        ctx,
                        results,
                    );
                }
                check_statement_for_assignments(dw.statement, ctx, results, true);
            }
            Statement::Try(try_stmt) => {
                walk_try_statement(try_stmt, ctx, results);
            }
            Statement::Switch(switch) => {
                for case in switch.body.cases().iter() {
                    walk_statements_for_assignments(case.statements().iter(), ctx, results, true);
                }
            }
            // ── unset($var) tracking ──
            // When `unset($var)` appears unconditionally before the
            // cursor, the variable no longer has a type.  Clear all
            // previously accumulated results so that `$var->` does
            // not resolve to the type it had before the unset.
            //
            // Inside conditional branches (`conditional == true`)
            // the variable *might* still exist, so we leave the
            // results untouched.
            Statement::Unset(unset_stmt) => {
                if !conditional {
                    for val in unset_stmt.values.iter() {
                        if let Expression::Variable(Variable::Direct(dv)) = val
                            && dv.name == ctx.var_name
                        {
                            results.clear();
                        }
                    }
                }
            }
            // Recurse into namespace blocks so that assignments and
            // closures inside `namespace Foo { … }` or after
            // `namespace Foo;` are visible to the walker.
            Statement::Namespace(ns) => {
                walk_statements_for_assignments(ns.statements().iter(), ctx, results, conditional);
            }
            _ => {}
        }
    }
}

/// Handle `if` / `elseif` / `else` statements during variable
/// assignment walking.
///
/// Applies instanceof and `@phpstan-assert-if-true/false` narrowing
/// for each branch, recurses into the branch bodies with
/// `conditional = true`, and applies guard-clause narrowing when the
/// cursor is after the if-statement.
fn walk_if_statement<'b>(
    if_stmt: &'b If<'b>,
    enclosing_stmt: &'b Statement<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) {
    // ── Branch-aware mode ──
    // When `ctx.branch_aware` is true and the cursor is inside a
    // specific branch body, only that branch's assignments contribute
    // to the result.  This produces the single type visible at the
    // cursor position (what hover needs).  If the cursor is not inside
    // any branch body (i.e. it is after the if/else), fall through to
    // the normal union-all-branches logic.
    if ctx.branch_aware
        && let Some(()) = walk_if_branch_aware(if_stmt, enclosing_stmt, ctx, results)
    {
        return;
    }

    // ── Inline && narrowing inside the condition expression ──
    // When the cursor is inside the RHS of `&&` in the condition,
    // apply instanceof narrowing from the LHS so that e.g.
    // `if ($x instanceof Foo && $x->bar())` narrows `$x` to `Foo`
    // at the `$x->bar()` call site.
    ResolvedType::apply_narrowing(results, |classes| {
        narrowing::try_apply_inline_and_narrowing(if_stmt.condition, ctx, classes);
    });
    narrowing::try_apply_inline_and_null_narrowing(if_stmt.condition, ctx, results);

    // ── Assignment in condition ──
    // `if ($x = expr())` — register the assignment so `$x` is typed
    // inside the then-body and subsequent code.
    check_condition_for_assignment(if_stmt.condition, ctx, results);

    match &if_stmt.body {
        IfBody::Statement(body) => {
            // ── instanceof narrowing for then-body ──
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_instanceof_narrowing(
                    if_stmt.condition,
                    body.statement.span(),
                    ctx,
                    classes,
                );
            });
            // ── @phpstan-assert-if-true/false narrowing for then-body ──
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_assert_condition_narrowing(
                    if_stmt.condition,
                    body.statement.span(),
                    ctx,
                    classes,
                    false, // not inverted — this is the then-body
                );
            });
            // ── in_array strict-mode narrowing for then-body ──
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_in_array_narrowing(
                    if_stmt.condition,
                    body.statement.span(),
                    ctx,
                    classes,
                );
            });
            // ── null narrowing for then-body ──
            // Must run after check_condition_for_assignment so the
            // type is registered before we try to strip null from it.
            narrowing::try_apply_if_body_null_narrowing(
                if_stmt.condition,
                body.statement.span(),
                ctx,
                results,
            );
            // ── type-guard narrowing for then-body ──
            // `is_array($var)`, `is_string($var)`, etc.
            narrowing::try_apply_type_guard_narrowing(
                if_stmt.condition,
                body.statement.span(),
                ctx,
                results,
            );
            check_statement_for_assignments(body.statement, ctx, results, true);

            for else_if in body.else_if_clauses.iter() {
                // ── inline && narrowing for elseif condition ──
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_inline_and_narrowing(else_if.condition, ctx, classes);
                });
                narrowing::try_apply_inline_and_null_narrowing(else_if.condition, ctx, results);
                // ── Assignment in elseif condition ──
                check_condition_for_assignment(else_if.condition, ctx, results);
                // ── null narrowing for elseif-body ──
                narrowing::try_apply_if_body_null_narrowing(
                    else_if.condition,
                    else_if.statement.span(),
                    ctx,
                    results,
                );
                // ── instanceof narrowing for elseif-body ──
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing(
                        else_if.condition,
                        else_if.statement.span(),
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        else_if.condition,
                        else_if.statement.span(),
                        ctx,
                        classes,
                        false,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing(
                        else_if.condition,
                        else_if.statement.span(),
                        ctx,
                        classes,
                    );
                });
                // ── type-guard narrowing for elseif-body ──
                narrowing::try_apply_type_guard_narrowing(
                    else_if.condition,
                    else_if.statement.span(),
                    ctx,
                    results,
                );
                check_statement_for_assignments(else_if.statement, ctx, results, true);
            }
            if let Some(else_clause) = &body.else_clause {
                // ── inverse instanceof narrowing for else-body ──
                // `if ($v instanceof Foo) { … } else { ← here }`
                // means $v is NOT Foo in the else branch.
                let else_span = else_clause.statement.span();
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                        true, // inverted — this is the else-body
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                    );
                });
                // ── inverse null narrowing for else-body ──
                narrowing::try_apply_if_body_null_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                // ── inverse type-guard narrowing for else-body ──
                narrowing::try_apply_type_guard_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                // Also apply inverse narrowing for every elseif condition.
                // In the else branch, all preceding conditions were false,
                // so each elseif's condition is also inverted.
                for else_if in body.else_if_clauses.iter() {
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing_inverse(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                            true,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing_inverse(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_type_guard_narrowing_inverse(
                        else_if.condition,
                        else_span,
                        ctx,
                        results,
                    );
                }
                check_statement_for_assignments(else_clause.statement, ctx, results, true);
            }
        }
        IfBody::ColonDelimited(body) => {
            // Determine the then-body span: from the colon to
            // the first elseif / else / endif keyword.
            let then_end = if !body.else_if_clauses.is_empty() {
                body.else_if_clauses
                    .first()
                    .unwrap()
                    .elseif
                    .span()
                    .start
                    .offset
            } else if let Some(ref ec) = body.else_clause {
                ec.r#else.span().start.offset
            } else {
                body.endif.span().start.offset
            };
            let then_span = mago_span::Span::new(
                body.colon.file_id,
                body.colon.start,
                mago_span::Position::new(then_end),
            );
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_instanceof_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    classes,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_assert_condition_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    classes,
                    false,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_in_array_narrowing(if_stmt.condition, then_span, ctx, classes);
            });
            // ── null narrowing for then-body ──
            narrowing::try_apply_if_body_null_narrowing(if_stmt.condition, then_span, ctx, results);
            // ── type-guard narrowing for then-body ──
            narrowing::try_apply_type_guard_narrowing(if_stmt.condition, then_span, ctx, results);
            walk_statements_for_assignments(body.statements.iter(), ctx, results, true);
            for else_if in body.else_if_clauses.iter() {
                // ── inline && narrowing for elseif condition ──
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_inline_and_narrowing(else_if.condition, ctx, classes);
                });
                narrowing::try_apply_inline_and_null_narrowing(else_if.condition, ctx, results);
                // ── Assignment in elseif condition ──
                check_condition_for_assignment(else_if.condition, ctx, results);
                // ── null narrowing for elseif (must be after condition assignment) ──
                // Note: we need the span for body narrowing, computed below,
                // but truthiness narrowing from the condition itself can use
                // the condition expression directly via try_extract_null_check
                // which doesn't need body_span (it's checked inside the fn).
                let ei_span = mago_span::Span::new(
                    else_if.colon.file_id,
                    else_if.colon.start,
                    mago_span::Position::new(
                        else_if
                            .statements
                            .span(else_if.colon.file_id, else_if.colon.end)
                            .end
                            .offset,
                    ),
                );
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        classes,
                        false,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        classes,
                    );
                });
                narrowing::try_apply_if_body_null_narrowing(
                    else_if.condition,
                    ei_span,
                    ctx,
                    results,
                );
                // ── type-guard narrowing for elseif-body ──
                narrowing::try_apply_type_guard_narrowing(else_if.condition, ei_span, ctx, results);
                walk_statements_for_assignments(else_if.statements.iter(), ctx, results, true);
            }
            if let Some(else_clause) = &body.else_clause {
                // ── inverse instanceof narrowing for else-body ──
                let else_span = mago_span::Span::new(
                    else_clause.colon.file_id,
                    else_clause.colon.start,
                    mago_span::Position::new(
                        else_clause
                            .statements
                            .span(else_clause.colon.file_id, else_clause.colon.end)
                            .end
                            .offset,
                    ),
                );
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                        true, // inverted — else-body
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        classes,
                    );
                });
                // ── inverse null narrowing for else-body ──
                narrowing::try_apply_if_body_null_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                // ── inverse type-guard narrowing for else-body ──
                narrowing::try_apply_type_guard_narrowing_inverse(
                    if_stmt.condition,
                    else_span,
                    ctx,
                    results,
                );
                // Also apply inverse narrowing for every elseif condition.
                for else_if in body.else_if_clauses.iter() {
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing_inverse(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                            true,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing_inverse(
                            else_if.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_type_guard_narrowing_inverse(
                        else_if.condition,
                        else_span,
                        ctx,
                        results,
                    );
                }
                walk_statements_for_assignments(else_clause.statements.iter(), ctx, results, true);
            }
        }
    }

    // ── Guard clause narrowing (early return / throw) ──
    // When the cursor is *after* a guard clause (an `if`
    // whose then-body unconditionally exits via return /
    // throw / continue / break, with no else / elseif),
    // apply the inverse narrowing so subsequent code sees
    // the narrowed type.
    //
    // Example:
    //   if (!$var instanceof Foo) { return; }
    //   $var-> // narrowed to Foo here
    if enclosing_stmt.span().end.offset < ctx.cursor_offset {
        ResolvedType::apply_narrowing(results, |classes| {
            narrowing::apply_guard_clause_narrowing(if_stmt, ctx, classes);
        });
        ResolvedType::apply_narrowing(results, |classes| {
            narrowing::apply_guard_clause_in_array_narrowing(if_stmt, ctx, classes);
        });
        // ── Null / falsy guard clause narrowing ──
        // `if (!$var) { return; }` or `if ($var === null) { continue; }`
        // → remove `null` from the resolved types after the guard.
        // This operates on `ResolvedType` directly because `null` is
        // not a class and would be missed by class-level narrowing.
        narrowing::apply_guard_clause_null_narrowing(if_stmt, ctx, results);
        // ── Type-guard guard clause narrowing ──
        // `if (is_array($x)) { return; }` → after if, $x is NOT array.
        narrowing::apply_guard_clause_type_guard_narrowing(if_stmt, ctx, results);
    }
}

/// Branch-aware if/else walking for hover.
///
/// When the cursor is inside a specific branch body, only that branch's
/// assignments are walked (with `conditional = false` since we know
/// we're in that branch).  The appropriate narrowing for the branch is
/// applied before walking.
///
/// Returns `Some(())` if the cursor was inside a branch body and the
/// branch was handled.  Returns `None` if the cursor is not inside any
/// branch (i.e. after the if/else), in which case the caller should
/// fall through to the normal union-all-branches logic.
fn walk_if_branch_aware<'b>(
    if_stmt: &'b If<'b>,
    _enclosing_stmt: &'b Statement<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) -> Option<()> {
    match &if_stmt.body {
        IfBody::Statement(body) => {
            let then_span = body.statement.span();
            if ctx.cursor_offset >= then_span.start.offset
                && ctx.cursor_offset <= then_span.end.offset
            {
                // Cursor is inside the then-branch.
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                        false,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                    );
                });
                // ── Assignment in condition ──
                check_condition_for_assignment(if_stmt.condition, ctx, results);
                narrowing::try_apply_if_body_null_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    results,
                );
                // ── type-guard narrowing for then-body ──
                narrowing::try_apply_type_guard_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    results,
                );
                check_statement_for_assignments(body.statement, ctx, results, false);
                return Some(());
            }

            for else_if in body.else_if_clauses.iter() {
                let ei_span = else_if.statement.span();
                if ctx.cursor_offset >= ei_span.start.offset
                    && ctx.cursor_offset <= ei_span.end.offset
                {
                    // Cursor is inside this elseif-branch.
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                            false,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_if_body_null_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    // ── type-guard narrowing for elseif-body ──
                    narrowing::try_apply_type_guard_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    // ── Assignment in elseif condition ──
                    check_condition_for_assignment(else_if.condition, ctx, results);
                    narrowing::try_apply_if_body_null_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    check_statement_for_assignments(else_if.statement, ctx, results, false);
                    return Some(());
                }
            }

            if let Some(else_clause) = &body.else_clause {
                let el_span = else_clause.statement.span();
                if ctx.cursor_offset >= el_span.start.offset
                    && ctx.cursor_offset <= el_span.end.offset
                {
                    // Cursor is inside the else-branch.
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing_inverse(
                            if_stmt.condition,
                            el_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            if_stmt.condition,
                            el_span,
                            ctx,
                            classes,
                            true,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing_inverse(
                            if_stmt.condition,
                            el_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_if_body_null_narrowing_inverse(
                        if_stmt.condition,
                        el_span,
                        ctx,
                        results,
                    );
                    // ── inverse type-guard narrowing for else-body ──
                    narrowing::try_apply_type_guard_narrowing_inverse(
                        if_stmt.condition,
                        el_span,
                        ctx,
                        results,
                    );
                    // Also apply inverse narrowing for every elseif condition.
                    for else_if in body.else_if_clauses.iter() {
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_instanceof_narrowing_inverse(
                                else_if.condition,
                                el_span,
                                ctx,
                                classes,
                            );
                        });
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_assert_condition_narrowing(
                                else_if.condition,
                                el_span,
                                ctx,
                                classes,
                                true,
                            );
                        });
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_in_array_narrowing_inverse(
                                else_if.condition,
                                el_span,
                                ctx,
                                classes,
                            );
                        });
                        narrowing::try_apply_type_guard_narrowing_inverse(
                            else_if.condition,
                            el_span,
                            ctx,
                            results,
                        );
                    }
                    check_statement_for_assignments(else_clause.statement, ctx, results, false);
                    return Some(());
                }
            }
        }
        IfBody::ColonDelimited(body) => {
            // Approximate the span of each branch using colon/keyword
            // boundaries (same logic as the raw-type pipeline's
            // `accumulate_if_branch_at_cursor`).
            let then_start = body.colon.start.offset;
            let then_end = body
                .else_if_clauses
                .first()
                .map(|ei| ei.elseif.span().start.offset)
                .or_else(|| {
                    body.else_clause
                        .as_ref()
                        .map(|ec| ec.r#else.span().start.offset)
                })
                .unwrap_or(body.endif.span().start.offset);

            if ctx.cursor_offset >= then_start && ctx.cursor_offset < then_end {
                // Cursor is inside the then-branch.
                let then_span = mago_span::Span::new(
                    body.colon.file_id,
                    body.colon.start,
                    mago_span::Position::new(then_end),
                );
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_instanceof_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_assert_condition_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                        false,
                    );
                });
                ResolvedType::apply_narrowing(results, |classes| {
                    narrowing::try_apply_in_array_narrowing(
                        if_stmt.condition,
                        then_span,
                        ctx,
                        classes,
                    );
                });
                // ── Assignment in condition ──
                check_condition_for_assignment(if_stmt.condition, ctx, results);
                narrowing::try_apply_if_body_null_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    results,
                );
                // ── type-guard narrowing for then-body ──
                narrowing::try_apply_type_guard_narrowing(
                    if_stmt.condition,
                    then_span,
                    ctx,
                    results,
                );
                walk_statements_for_assignments(body.statements.iter(), ctx, results, false);
                return Some(());
            }

            for (i, else_if) in body.else_if_clauses.iter().enumerate() {
                let ei_start = else_if.colon.start.offset;
                let ei_end = body
                    .else_if_clauses
                    .get(i + 1)
                    .map(|next| next.elseif.span().start.offset)
                    .or_else(|| {
                        body.else_clause
                            .as_ref()
                            .map(|ec| ec.r#else.span().start.offset)
                    })
                    .unwrap_or(body.endif.span().start.offset);

                if ctx.cursor_offset >= ei_start && ctx.cursor_offset < ei_end {
                    // Cursor is inside this elseif-branch.
                    let ei_span = mago_span::Span::new(
                        else_if.colon.file_id,
                        else_if.colon.start,
                        mago_span::Position::new(ei_end),
                    );
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                            false,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing(
                            else_if.condition,
                            ei_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_if_body_null_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    // ── type-guard narrowing for elseif-body ──
                    narrowing::try_apply_type_guard_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    // ── Assignment in elseif condition ──
                    check_condition_for_assignment(else_if.condition, ctx, results);
                    narrowing::try_apply_if_body_null_narrowing(
                        else_if.condition,
                        ei_span,
                        ctx,
                        results,
                    );
                    walk_statements_for_assignments(else_if.statements.iter(), ctx, results, false);
                    return Some(());
                }
            }

            if let Some(ref else_clause) = body.else_clause {
                let el_start = else_clause.colon.start.offset;
                let el_end = body.endif.span().start.offset;

                if ctx.cursor_offset >= el_start && ctx.cursor_offset < el_end {
                    // Cursor is inside the else-branch.
                    let else_span = mago_span::Span::new(
                        else_clause.colon.file_id,
                        else_clause.colon.start,
                        mago_span::Position::new(el_end),
                    );
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_instanceof_narrowing_inverse(
                            if_stmt.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_assert_condition_narrowing(
                            if_stmt.condition,
                            else_span,
                            ctx,
                            classes,
                            true,
                        );
                    });
                    ResolvedType::apply_narrowing(results, |classes| {
                        narrowing::try_apply_in_array_narrowing_inverse(
                            if_stmt.condition,
                            else_span,
                            ctx,
                            classes,
                        );
                    });
                    narrowing::try_apply_if_body_null_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        results,
                    );
                    // ── inverse type-guard narrowing for else-body ──
                    narrowing::try_apply_type_guard_narrowing_inverse(
                        if_stmt.condition,
                        else_span,
                        ctx,
                        results,
                    );
                    // Also apply inverse narrowing for every elseif condition.
                    for else_if in body.else_if_clauses.iter() {
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_instanceof_narrowing_inverse(
                                else_if.condition,
                                else_span,
                                ctx,
                                classes,
                            );
                        });
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_assert_condition_narrowing(
                                else_if.condition,
                                else_span,
                                ctx,
                                classes,
                                true,
                            );
                        });
                        ResolvedType::apply_narrowing(results, |classes| {
                            narrowing::try_apply_in_array_narrowing_inverse(
                                else_if.condition,
                                else_span,
                                ctx,
                                classes,
                            );
                        });
                        narrowing::try_apply_type_guard_narrowing_inverse(
                            else_if.condition,
                            else_span,
                            ctx,
                            results,
                        );
                    }
                    walk_statements_for_assignments(
                        else_clause.statements.iter(),
                        ctx,
                        results,
                        false,
                    );
                    return Some(());
                }
            }
        }
    }

    // Cursor is not inside any branch body — fall through to the
    // normal union-all-branches logic in `walk_if_statement`.
    None
}

/// Pre-scan a loop body for assignments to the target variable.
///
/// In a loop, an assignment that appears textually *after* the cursor
/// can still be live on subsequent iterations.  This helper walks the
/// loop body with `cursor_offset` set to `body_end` so that all
/// assignments are visible, and merges any discovered types into
/// `results` as conditional.  The caller should invoke this **before**
/// the normal positional walk so that narrowing (e.g. `!== null`)
/// applied during the normal walk can strip types contributed by the
/// pre-scan.
///
/// Only types that are not already present in `results` are added,
/// avoiding duplicates with assignments that the normal walk will
/// also discover.
fn prescan_loop_body_for_assignments<'b>(
    statements: impl Iterator<Item = &'b Statement<'b>>,
    body_end: u32,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) {
    // Only pre-scan when the cursor is actually inside the loop body.
    // The caller is responsible for checking this, but as a safety
    // measure we verify that the cursor is before the body end.
    if ctx.cursor_offset >= body_end {
        return;
    }

    let prescan_ctx = ctx.with_cursor_offset(body_end);
    let mut prescan_results: Vec<ResolvedType> = Vec::new();
    walk_statements_for_assignments(statements, &prescan_ctx, &mut prescan_results, true);

    // Merge pre-scanned types into results as conditional additions.
    ResolvedType::extend_unique(results, prescan_results);
}

/// Handle `foreach` statements during variable assignment walking.
///
/// Resolves the foreach value/key variable and recurses into the body
/// when the cursor is inside the loop body **or** on the foreach header
/// (the `foreach ($expr as $val)` part).  The header check is needed so
/// that hover on the binding variable at its definition site can resolve
/// the iteration type.
fn walk_foreach_statement<'b>(
    foreach: &'b Foreach<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) {
    let body_span = foreach.body.span();
    let header_start = foreach.foreach.span().start.offset;
    let cursor_inside =
        ctx.cursor_offset >= header_start && ctx.cursor_offset <= body_span.end.offset;

    if cursor_inside {
        // ── Foreach value/key type from generic iterables ──
        // When the variable we're resolving is the foreach
        // *value* variable, try to infer its type from the
        // iterated expression's generic type annotation.
        //
        // Example:
        //   /** @var list<User> $users */
        //   foreach ($users as $user) { $user-> }
        //
        // Here `$user` is resolved to `User`.
        //
        // Similarly, when the variable is the foreach *key*
        // variable, try to infer its type from the key
        // position of a two-parameter generic annotation.
        //
        // Example:
        //   /** @var SplObjectStorage<Request, Response> $storage */
        //   foreach ($storage as $req => $res) { $req-> }
        //
        // Here `$req` is resolved to `Request`.
        super::foreach_resolution::try_resolve_foreach_value_type(
            foreach,
            ctx,
            results,
            conditional,
        );
        super::foreach_resolution::try_resolve_foreach_key_type(foreach, ctx, results, conditional);
    }

    // ── Pre-scan for loop-carried assignments ──
    // When the cursor is inside the loop body, assignments that appear
    // textually after the cursor are live on subsequent iterations.
    // Pre-scan the body to pick them up as conditional types before the
    // normal positional walk (which skips statements after the cursor).
    if cursor_inside {
        match &foreach.body {
            ForeachBody::Statement(inner) => {
                prescan_loop_body_for_assignments(
                    std::iter::once(*inner),
                    body_span.end.offset,
                    ctx,
                    results,
                );
            }
            ForeachBody::ColonDelimited(body) => {
                prescan_loop_body_for_assignments(
                    body.statements.iter(),
                    body_span.end.offset,
                    ctx,
                    results,
                );
            }
        }
    }

    // Always walk the foreach body for variable assignments, even when
    // the cursor is after the foreach.  A foreach body may execute zero
    // or more times, so any assignment inside is conditional.
    //
    // Without this, `$x = null; foreach (...) { $x = new Foo(); }
    // $x->method();` would lose the `Foo` assignment because the body
    // was only walked when the cursor was inside the foreach.
    match &foreach.body {
        ForeachBody::Statement(inner) => {
            check_statement_for_assignments(inner, ctx, results, true);
        }
        ForeachBody::ColonDelimited(body) => {
            walk_statements_for_assignments(body.statements.iter(), ctx, results, true);
        }
    }
}

/// Handle `while` statements during variable assignment walking.
///
/// Applies instanceof and `@phpstan-assert` narrowing based on the
/// while condition and recurses into the loop body.
fn walk_while_statement<'b>(
    while_stmt: &'b While<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) {
    // ── Inline && narrowing inside the while condition ──
    ResolvedType::apply_narrowing(results, |classes| {
        narrowing::try_apply_inline_and_narrowing(while_stmt.condition, ctx, classes);
    });
    narrowing::try_apply_inline_and_null_narrowing(while_stmt.condition, ctx, results);

    // ── Assignment in condition ──
    // `while ($line = fgets($fp))` — register the assignment.
    check_condition_for_assignment(while_stmt.condition, ctx, results);

    // Determine whether the cursor is inside this while loop for the
    // pre-scan.  We check both body variants.
    let while_body_span = while_stmt.body.span();
    let while_header_start = while_stmt.r#while.span().start.offset;
    let cursor_inside_while =
        ctx.cursor_offset >= while_header_start && ctx.cursor_offset <= while_body_span.end.offset;

    // ── Pre-scan for loop-carried assignments ──
    if cursor_inside_while {
        match &while_stmt.body {
            WhileBody::Statement(inner) => {
                prescan_loop_body_for_assignments(
                    std::iter::once(*inner),
                    while_body_span.end.offset,
                    ctx,
                    results,
                );
            }
            WhileBody::ColonDelimited(body) => {
                prescan_loop_body_for_assignments(
                    body.statements.iter(),
                    while_body_span.end.offset,
                    ctx,
                    results,
                );
            }
        }
    }

    match &while_stmt.body {
        WhileBody::Statement(inner) => {
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_instanceof_narrowing(
                    while_stmt.condition,
                    inner.span(),
                    ctx,
                    classes,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_assert_condition_narrowing(
                    while_stmt.condition,
                    inner.span(),
                    ctx,
                    classes,
                    false,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_in_array_narrowing(
                    while_stmt.condition,
                    inner.span(),
                    ctx,
                    classes,
                );
            });
            // ── null narrowing for while-body ──
            // Runs after check_condition_for_assignment so `$row`
            // from `while ($row = nextRow())` is typed before we
            // strip null.
            narrowing::try_apply_if_body_null_narrowing(
                while_stmt.condition,
                inner.span(),
                ctx,
                results,
            );
            check_statement_for_assignments(inner, ctx, results, true);
        }
        WhileBody::ColonDelimited(body) => {
            let body_span = mago_span::Span::new(
                body.colon.file_id,
                body.colon.start,
                mago_span::Position::new(body.end_while.span().start.offset),
            );
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_instanceof_narrowing(
                    while_stmt.condition,
                    body_span,
                    ctx,
                    classes,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_assert_condition_narrowing(
                    while_stmt.condition,
                    body_span,
                    ctx,
                    classes,
                    false,
                );
            });
            ResolvedType::apply_narrowing(results, |classes| {
                narrowing::try_apply_in_array_narrowing(
                    while_stmt.condition,
                    body_span,
                    ctx,
                    classes,
                );
            });
            // ── null narrowing for while-body ──
            // Must run after check_condition_for_assignment (called above
            // before the match) so the type is registered first.
            narrowing::try_apply_if_body_null_narrowing(
                while_stmt.condition,
                body_span,
                ctx,
                results,
            );
            walk_statements_for_assignments(body.statements.iter(), ctx, results, true);
        }
    }
}

/// Handle `try` / `catch` / `finally` statements during variable
/// assignment walking.
///
/// Recurses into the try block, seeds the catch variable's type from
/// the catch clause's type hint(s), recurses into each catch block,
/// and recurses into the finally block if present.
fn walk_try_statement<'b>(
    try_stmt: &'b Try<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) {
    // When the cursor is inside the try block body, assignments that
    // precede the cursor have executed sequentially — use
    // `conditional: false` so reassignments replace the previous type
    // instead of forming a union with it.  When the cursor is outside
    // (after the try statement), we don't know whether the try body
    // ran to completion, so keep `conditional: true`.
    let try_span = try_stmt.block.span();
    let cursor_in_try =
        ctx.cursor_offset >= try_span.start.offset && ctx.cursor_offset <= try_span.end.offset;
    walk_statements_for_assignments(
        try_stmt.block.statements.iter(),
        ctx,
        results,
        !cursor_in_try,
    );

    for catch in try_stmt.catch_clauses.iter() {
        // Seed the catch variable's type from the catch
        // clause's type hint(s) before recursing into the
        // block.  Handles single types like
        // `catch (ValidationException $e)` and multi-catch
        // like `catch (TypeA | TypeB $e)`.
        if let Some(ref var) = catch.variable
            && var.name == ctx.var_name
        {
            let parsed_hint = extract_hint_type(&catch.hint);
            let resolved = crate::completion::type_resolution::type_hint_to_classes_typed(
                &parsed_hint,
                &ctx.current_class.name,
                ctx.all_classes,
                ctx.class_loader,
            );
            ResolvedType::extend_unique(
                results,
                ResolvedType::from_classes_with_hint(resolved, parsed_hint),
            );
        }
        // Same logic: when the cursor is inside this catch block,
        // treat preceding assignments as unconditional.
        let catch_span = catch.block.span();
        let cursor_in_catch = ctx.cursor_offset >= catch_span.start.offset
            && ctx.cursor_offset <= catch_span.end.offset;
        walk_statements_for_assignments(
            catch.block.statements.iter(),
            ctx,
            results,
            !cursor_in_catch,
        );
    }
    if let Some(finally) = &try_stmt.finally_clause {
        let finally_span = finally.block.span();
        let cursor_in_finally = ctx.cursor_offset >= finally_span.start.offset
            && ctx.cursor_offset <= finally_span.end.offset;
        walk_statements_for_assignments(
            finally.block.statements.iter(),
            ctx,
            results,
            !cursor_in_finally,
        );
    }
}

/// Convenience wrapper that walks a single statement for assignments
/// to the target variable, delegating to `walk_statements_for_assignments`.
pub(in crate::completion) fn check_statement_for_assignments<'b>(
    stmt: &'b Statement<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) {
    walk_statements_for_assignments(std::iter::once(stmt), ctx, results, conditional);
}

/// Try to resolve a variable's type from an inline `/** @var … */`
/// docblock that immediately precedes the assignment statement.
///
/// Supports both formats:
///   - `/** @var TheType */`
///   - `/** @var TheType $var */`
///
/// When a variable name is present in the annotation, it must match
/// the variable being resolved.
///
/// The same override check used for `@return` is applied: the docblock
/// type only wins when `resolve_effective_type(native, docblock)` picks
/// the docblock.  If the native (RHS) type is a concrete scalar and the
/// docblock type is a class name, the override is rejected and the
/// method returns `false` so the caller falls through to normal
/// resolution.
///
/// Returns `true` when the override was applied (results updated) and
/// `false` when there is no applicable `@var` annotation.
pub(in crate::completion) fn try_inline_var_override<'b>(
    expr: &'b Expression<'b>,
    stmt_start: usize,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) -> bool {
    // Must be an assignment to our target variable.
    let assignment = match expr {
        Expression::Assignment(a) if a.operator.is_assign() => a,
        _ => return false,
    };
    let lhs_name = match assignment.lhs {
        Expression::Variable(Variable::Direct(dv)) => dv.name.to_string(),
        _ => return false,
    };
    if lhs_name != ctx.var_name {
        return false;
    }

    // ── Skip when cursor is inside the RHS ─────────
    // When the cursor falls within the RHS of this assignment
    // (e.g. `/** @var array<string, mixed> */ $data = $data->toArray()`),
    // the `@var` cast should only apply *after* the assignment
    // completes.  The RHS `$data` still has its previous type.
    let rhs_start = assignment.rhs.span().start.offset;
    let assign_end = assignment.span().end.offset;
    if ctx.cursor_offset >= rhs_start && ctx.cursor_offset <= assign_end {
        return false;
    }

    // Look for a `/** @var … */` docblock right before this statement.
    let (var_type, var_name) = match docblock::find_inline_var_docblock(ctx.content, stmt_start) {
        Some(pair) => pair,
        None => return false,
    };

    // If the annotation includes a variable name, it must match.
    if let Some(ref vn) = var_name
        && vn != ctx.var_name
    {
        return false;
    }

    // Determine the "native" return-type string from the RHS so we can
    // apply the same override check used for `@return` annotations.
    let native_type = extract_native_type_from_rhs(assignment.rhs, ctx);
    let native_parsed = native_type.as_ref().cloned();
    let effective = docblock::resolve_effective_type_typed(native_parsed.as_ref(), Some(&var_type));

    let eff_type = match effective {
        Some(t) => t,
        None => return false,
    };

    let resolved = crate::completion::type_resolution::type_hint_to_classes_typed(
        &eff_type,
        &ctx.current_class.name,
        ctx.all_classes,
        ctx.class_loader,
    );

    if resolved.is_empty() {
        // When `type_hint_to_classes_typed` can't resolve the type (e.g.
        // `list<User>`, `array{name: string}`, `int[]`), emit a
        // type-string-only entry so that downstream consumers like
        // foreach resolution can still extract element types via
        // `PhpType::extract_value_type`.  Skip non-informative types
        // (`array`, `mixed`, etc.) so normal resolution can provide
        // more precise information.
        if eff_type.is_informative() {
            let resolved_types = vec![ResolvedType::from_type_string(eff_type.clone())];
            if !conditional {
                results.clear();
            }
            ResolvedType::extend_unique(results, resolved_types);
            return true;
        }
        return false;
    }

    let resolved_types = ResolvedType::from_classes_with_hint(resolved, eff_type.clone());

    // Apply the resolved type(s) with the same conditional semantics
    // used by `check_expression_for_assignment`.
    if !conditional {
        results.clear();
    }
    ResolvedType::extend_unique(results, resolved_types);
    true
}

/// Extract the "native" return-type string from the RHS of an assignment
/// expression, without resolving it to `ClassInfo`.
///
/// This is used by [`try_inline_var_override`] to feed
/// [`docblock::resolve_effective_type`] with the same kind of parsed
/// `PhpType` that `@return` override checking uses.
///
/// Returns `None` when the native type cannot be determined (the
/// caller should treat this as "unknown", which lets the docblock type
/// win unconditionally).
fn extract_native_type_from_rhs<'b>(
    rhs: &'b Expression<'b>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<PhpType> {
    match rhs {
        // `new ClassName(…)` → the class name.
        Expression::Instantiation(inst) => match inst.class {
            Expression::Identifier(ident) => Some(PhpType::Named(ident.value().to_string())),
            Expression::Self_(_) => Some(PhpType::Named(ctx.current_class.name.clone())),
            Expression::Static(_) => Some(PhpType::Named(ctx.current_class.name.clone())),
            _ => None,
        },
        // Function / method calls → look up the return type.
        Expression::Call(call) => match call {
            Call::Function(func_call) => {
                let func_name = match func_call.function {
                    Expression::Identifier(ident) => Some(ident.value().to_string()),
                    _ => None,
                };
                func_name.and_then(|name| {
                    ctx.function_loader()
                        .and_then(|fl| fl(&name))
                        .and_then(|fi| fi.return_type.clone())
                })
            }
            Call::Method(method_call) => {
                if let Expression::Variable(Variable::Direct(dv)) = method_call.object
                    && dv.name == "$this"
                    && let ClassLikeMemberSelector::Identifier(ident) = &method_call.method
                {
                    let method_name = ident.value.to_string();
                    ctx.all_classes
                        .iter()
                        .find(|c| c.name == ctx.current_class.name)
                        .and_then(|cls| {
                            cls.methods
                                .iter()
                                .find(|m| m.name == method_name)
                                .and_then(|m| m.return_type.clone())
                        })
                } else {
                    None
                }
            }
            Call::StaticMethod(static_call) => {
                let class_name = match static_call.class {
                    Expression::Self_(_) | Expression::Static(_) => {
                        Some(ctx.current_class.name.clone())
                    }
                    Expression::Identifier(ident) => Some(ident.value().to_string()),
                    _ => None,
                };
                if let Some(cls_name) = class_name
                    && let ClassLikeMemberSelector::Identifier(ident) = &static_call.method
                {
                    let method_name = ident.value.to_string();
                    let owner = ctx
                        .all_classes
                        .iter()
                        .find(|c| c.name == cls_name)
                        .map(|c| ClassInfo::clone(c))
                        .or_else(|| (ctx.class_loader)(&cls_name).map(Arc::unwrap_or_clone));
                    owner.and_then(|o| {
                        o.methods
                            .iter()
                            .find(|m| m.name == method_name)
                            .and_then(|m| m.return_type.clone())
                    })
                } else {
                    None
                }
            }
            _ => None,
        },
        // First-class callable syntax, closure literals, and arrow
        // functions always produce a Closure.
        Expression::PartialApplication(_)
        | Expression::Closure(_)
        | Expression::ArrowFunction(_) => Some(PhpType::closure()),
        _ => None,
    }
}

/// Extract and apply an assignment embedded in an `if` / `while`
/// condition expression.
///
/// Handles:
///   - `if ($x = expr())` — condition is a bare assignment
///   - `if (($x = expr()) !== null)` — assignment inside a comparison
///   - `if ($x = expr()) { … }` — truthiness check (truthy narrowing
///     is handled separately by the null-narrowing pass)
///
/// The assignment is always treated as conditional (the variable
/// *might* have this type), because the condition may be false.
/// The caller is responsible for applying truthiness narrowing
/// inside the then-body.
pub(in crate::completion) fn check_condition_for_assignment<'b>(
    condition: &'b Expression<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
) {
    // Unwrap parentheses.
    let inner = match condition {
        Expression::Parenthesized(p) => p.expression,
        other => other,
    };

    // Direct assignment: `if ($x = expr())`
    if let Expression::Assignment(_) = inner {
        check_expression_for_assignment(inner, ctx, results, true);
        return;
    }

    // Assignment inside a comparison: `if (($x = expr()) !== null)`
    // or `if (null !== ($x = expr()))`.
    if let Expression::Binary(bin) = inner {
        if let Expression::Assignment(_) = bin.lhs {
            check_expression_for_assignment(bin.lhs, ctx, results, true);
            return;
        }
        if let Expression::Assignment(_) = bin.rhs {
            check_expression_for_assignment(bin.rhs, ctx, results, true);
            return;
        }
        // Unwrap one layer of parens on each side.
        if let Expression::Parenthesized(p) = bin.lhs
            && let Expression::Assignment(_) = p.expression
        {
            check_expression_for_assignment(p.expression, ctx, results, true);
            return;
        }
        if let Expression::Parenthesized(p) = bin.rhs
            && let Expression::Assignment(_) = p.expression
        {
            check_expression_for_assignment(p.expression, ctx, results, true);
        }
    }
}

/// If `expr` is an assignment whose LHS matches `$var_name` and whose
/// RHS is a `new …` instantiation or a function/method call with a
/// known return type, resolve the class and add it to `results`.
///
/// When `conditional` is `false` (unconditional assignment), previous
/// candidates are cleared before adding the new type.  When `true`,
/// the new type is appended (the variable *might* be this type).
///
/// Duplicate class names are suppressed automatically.
pub(in crate::completion) fn check_expression_for_assignment<'b>(
    expr: &'b Expression<'b>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) {
    let var_name = ctx.var_name;

    /// Push one or more resolved types into `results`.
    ///
    /// * `conditional == false` → unconditional assignment: **clear**
    ///   previous candidates first, then add all new ones (handles
    ///   union return types like `A|B` from a single assignment).
    /// * `conditional == true` → conditional branch: **append**
    ///   without clearing (the variable *might* be these types).
    ///
    /// Duplicates (same type string) are always suppressed.
    fn push_results(results: &mut Vec<ResolvedType>, new: Vec<ResolvedType>, conditional: bool) {
        if new.is_empty() {
            return;
        }
        if !conditional {
            results.clear();
        }
        ResolvedType::extend_unique(results, new);
    }

    if let Expression::Assignment(assignment) = expr {
        if !assignment.operator.is_assign() {
            return;
        }

        // ── Array destructuring: `[$a, $b] = …` / `list($a, $b) = …` ──
        // When the LHS is an Array or List expression, check whether
        // our target variable appears among its elements.  If so,
        // resolve the RHS's iterable element type.
        if matches!(assignment.lhs, Expression::Array(_) | Expression::List(_)) {
            super::foreach_resolution::try_resolve_destructured_type(
                assignment,
                ctx,
                results,
                conditional,
            );
            return;
        }

        // ── Incremental key assignment: `$var['key'] = expr;` ──
        // Track string-keyed assignments and merge them into the
        // base type's array shape.  This produces type strings like
        // `array{name: string, age: int}` which downstream consumers
        // use for shape-aware completion and hover.
        if let Expression::ArrayAccess(array_access) = assignment.lhs
            && let Expression::Variable(Variable::Direct(dv)) = array_access.array
            && dv.name == var_name
        {
            // ── Skip when cursor is inside the RHS ────────
            // Same guard as the base-assignment path below.
            // Without this, `$var['key'] = $var['key']->method()`
            // would infinitely recurse: resolving the RHS triggers
            // resolution of `$var`, which re-discovers the same
            // assignment and resolves its RHS again.
            let rhs_start = assignment.rhs.span().start.offset;
            let assign_end = assignment.span().end.offset;
            if ctx.cursor_offset >= rhs_start && ctx.cursor_offset <= assign_end {
                return;
            }

            let key = extract_array_key_for_shape(array_access.index);
            if let Some(key) = key {
                // ── String-literal key: merge into array shape ──
                let rhs_ctx = ctx.with_cursor_offset(assignment.span().start.offset);
                let resolved =
                    super::rhs_resolution::resolve_rhs_expression(assignment.rhs, &rhs_ctx);
                let value_php_type = if !resolved.is_empty() {
                    ResolvedType::types_joined(&resolved)
                } else {
                    PhpType::mixed()
                };
                // Read the current base type from results (if any)
                // and merge the new key into its shape.
                let base = results
                    .last()
                    .map(|rt| &rt.type_string)
                    .cloned()
                    .unwrap_or_else(PhpType::array);
                let merged = merge_shape_key(&base, &key, &value_php_type);
                // Replace results with the enriched shape type.
                // Use extend_unique so this works in conditional
                // branches (appends) as well as unconditional
                // (results cleared first by push_results via the
                // base assignment that preceded this).
                // We always push here without clearing — shape keys
                // accumulate on top of the existing base.
                let new_rt = ResolvedType::from_type_string(merged);
                results.clear();
                results.push(new_rt);
            } else {
                // ── Non-literal key (variable, numeric, expression) ──
                // Track the RHS type as the array's value type so that
                // subsequent `foreach` iteration and bracket access
                // resolve element members.  This handles patterns like
                // `$arr[$id] = $orderLine` inside a loop.
                let rhs_ctx = ctx.with_cursor_offset(assignment.span().start.offset);
                let resolved =
                    super::rhs_resolution::resolve_rhs_expression(assignment.rhs, &rhs_ctx);
                let value_php_type = if !resolved.is_empty() {
                    ResolvedType::types_joined(&resolved)
                } else {
                    PhpType::mixed()
                };
                let base_type = results
                    .last()
                    .map(|rt| &rt.type_string)
                    .cloned()
                    .unwrap_or_else(PhpType::array);
                // When the base already has a shape type from prior
                // string-keyed assignments, do not overwrite it with
                // a generic element type — shapes take precedence.
                if base_type.is_array_shape() {
                    return;
                }
                // Infer the key type from the index expression.
                let key_php_type = infer_array_key_type(array_access.index, &rhs_ctx);
                let merged = merge_keyed_type(&base_type, &key_php_type, &value_php_type);
                let new_rt = ResolvedType::from_type_string(merged);
                results.clear();
                results.push(new_rt);
            }
            return;
        }

        // ── Push assignment: `$var[] = expr;` ──
        // Track push-style assignments and merge them into the base
        // type's list element type.  This produces type strings like
        // `list<User>` or `list<User|Admin>`.
        if let Expression::ArrayAppend(array_append) = assignment.lhs
            && let Expression::Variable(Variable::Direct(dv)) = array_append.array
            && dv.name == var_name
        {
            // ── Skip when cursor is inside the RHS ────────
            let rhs_start = assignment.rhs.span().start.offset;
            let assign_end = assignment.span().end.offset;
            if ctx.cursor_offset >= rhs_start && ctx.cursor_offset <= assign_end {
                return;
            }

            let rhs_ctx = ctx.with_cursor_offset(assignment.span().start.offset);
            let resolved = super::rhs_resolution::resolve_rhs_expression(assignment.rhs, &rhs_ctx);
            let value_php_type = if !resolved.is_empty() {
                ResolvedType::types_joined(&resolved)
            } else {
                PhpType::mixed()
            };
            // Read the current base type from results (if any)
            // and merge the push element type into it.
            //
            // When the base is already an array shape (from prior
            // `$var['key'] = expr` assignments), skip the push merge.
            // String-keyed entries take precedence over positional
            // pushes, matching the old AssignmentAccumulator's
            // finalize() behaviour.
            let base_type = results
                .last()
                .map(|rt| &rt.type_string)
                .cloned()
                .unwrap_or_else(PhpType::array);
            if base_type.is_array_shape() {
                return;
            }
            let merged = merge_push_type(&base_type, &value_php_type);
            let new_rt = ResolvedType::from_type_string(merged);
            results.clear();
            results.push(new_rt);
            return;
        }

        // Check LHS is our variable
        let lhs_name = match assignment.lhs {
            Expression::Variable(Variable::Direct(dv)) => dv.name.to_string(),
            _ => return,
        };
        if lhs_name != var_name {
            return;
        }

        // ── Skip when cursor is inside the RHS ────────────
        // When the cursor falls within the RHS of this assignment
        // (e.g. `$request = new Bar(arg: $request->…)`), the
        // variable reference on the RHS still sees the *previous*
        // definition — PHP evaluates all RHS arguments before
        // performing the assignment.  Do not apply this assignment.
        let rhs_start = assignment.rhs.span().start.offset;
        let assign_end = assignment.span().end.offset;
        if ctx.cursor_offset >= rhs_start && ctx.cursor_offset <= assign_end {
            return;
        }

        // Delegate all RHS resolution to the shared helper.
        //
        // Use the assignment's own start offset as cursor_offset so
        // that any recursive variable resolution only considers
        // assignments *before* this one.  Without this, a
        // self-referential assignment like `$value = $value->value`
        // would infinitely recurse: resolving the RHS `$value`
        // would re-discover the same assignment, resolve its RHS
        // again, and so on until a stack overflow crashes the
        // process.
        let rhs_ctx = ctx.with_cursor_offset(assignment.span().start.offset);
        let resolved = super::rhs_resolution::resolve_rhs_expression(assignment.rhs, &rhs_ctx);
        push_results(results, resolved, conditional);
    }
}

// ── Shape mutation helpers ───────────────────────────────────────────

/// Extract a string key from an array access index expression.
///
/// Returns `Some(key)` for string-literal keys like `'name'` or `"age"`.
/// Returns `None` for numeric keys, variable indices, and other
/// non-string-literal expressions — these are not tracked as shape
/// entries.
fn extract_array_key_for_shape(index: &Expression<'_>) -> Option<String> {
    if let Expression::Literal(Literal::String(s)) = index {
        let key = s.value.map(|v| v.to_string()).unwrap_or_else(|| {
            crate::util::unquote_php_string(s.raw)
                .unwrap_or(s.raw)
                .to_string()
        });
        // Skip numeric-only keys — they are positional, not shape entries.
        if key.chars().all(|c| c.is_ascii_digit()) {
            return None;
        }
        Some(key)
    } else {
        None
    }
}

/// Merge a `(key, value_type)` pair into an existing `PhpType` to
/// produce an `ArrayShape`.
///
/// If `base` is already an `ArrayShape`, the key is added or updated.
/// Otherwise a new shape is created with just the given key.
///
/// Returns `PhpType::ArrayShape(entries)` with the merged entries.
fn merge_shape_key(base: &PhpType, key: &str, value_type: &PhpType) -> PhpType {
    let mut entries: Vec<ShapeEntry> = Vec::new();

    // Copy existing shape entries from the base type, skipping the
    // key we are about to upsert.
    if let Some(shape_entries) = base.shape_entries() {
        for entry in shape_entries {
            if entry.key.as_deref() != Some(key) {
                entries.push(entry.clone());
            }
        }
    }

    // Add/upsert the new key.
    entries.push(ShapeEntry {
        key: Some(key.to_string()),
        value_type: value_type.clone(),
        optional: false,
    });

    PhpType::ArrayShape(entries)
}

/// Merge a push element type into an existing `PhpType` to produce
/// a `Generic("list", …)` type.
///
/// If `base` already has a generic value type (e.g. `list<User>`),
/// the new type is unioned with it (e.g. `list<User|Admin>`).
/// Otherwise, produces `list<value_type>`.
///
/// Returns `PhpType::list(elem_type)` or
/// `PhpType::Named("array")` when no element types are available.
fn merge_push_type(base: &PhpType, value_type: &PhpType) -> PhpType {
    let mut elem_types: Vec<PhpType> = Vec::new();

    // Extract existing element types from the base.
    if let Some(existing_elem) = base.extract_element_type() {
        for member in existing_elem.union_members() {
            if !member.is_empty() {
                elem_types.push(member.clone());
            }
        }
    }

    // Add new value type members (union-aware).
    for member in value_type.union_members() {
        if !member.is_empty() && !elem_types.iter().any(|e| e.equivalent(member)) {
            elem_types.push(member.clone());
        }
    }

    if elem_types.is_empty() {
        return PhpType::array();
    }

    let elem_type = if elem_types.len() == 1 {
        elem_types.into_iter().next().unwrap()
    } else {
        PhpType::Union(elem_types)
    };

    PhpType::list(elem_type)
}

/// Merge a keyed element type into an existing `PhpType` to produce
/// a `Generic("array", …)` type.
///
/// Similar to [`merge_push_type`] but preserves the key type from the
/// index expression instead of assuming sequential integer keys.
///
/// When the base already has a generic value type (e.g.
/// `array<string, User>`), the new value type is unioned with it and
/// key types are unioned as well.
///
/// Returns `PhpType::generic_array(key, val)`,
/// `PhpType::generic_array_val(val)` when no key types are
/// available, or `PhpType::Named("array")` when no element types
/// are available.
fn merge_keyed_type(base: &PhpType, key_type: &PhpType, value_type: &PhpType) -> PhpType {
    // Collect existing key types from the base.
    let mut key_types: Vec<PhpType> = Vec::new();
    if let Some(existing_key) = base.extract_key_type(false)
        && !existing_key.is_empty()
    {
        key_types.push(existing_key.clone());
    }
    // Add new key type members.
    for member in key_type.union_members() {
        if !member.is_empty() && !key_types.iter().any(|e| e.equivalent(member)) {
            key_types.push(member.clone());
        }
    }

    // Collect existing value types from the base.
    let mut elem_types: Vec<PhpType> = Vec::new();
    if let Some(existing_elem) = base.extract_element_type() {
        for member in existing_elem.union_members() {
            if !member.is_empty() {
                elem_types.push(member.clone());
            }
        }
    }
    // Add new value type members.
    for member in value_type.union_members() {
        if !member.is_empty() && !elem_types.iter().any(|e| e.equivalent(member)) {
            elem_types.push(member.clone());
        }
    }

    if elem_types.is_empty() {
        return PhpType::array();
    }

    let val_type = if elem_types.len() == 1 {
        elem_types.into_iter().next().unwrap()
    } else {
        PhpType::Union(elem_types)
    };

    if key_types.is_empty() {
        // No key type information — use a single-param generic.
        PhpType::generic_array_val(val_type)
    } else {
        let k_type = if key_types.len() == 1 {
            key_types.into_iter().next().unwrap()
        } else {
            PhpType::Union(key_types)
        };
        PhpType::generic_array(k_type, val_type)
    }
}

/// Infer the key type of an array-access index expression.
///
/// Returns `"string"` for expressions that are known to produce
/// strings (string literals, method calls returning `string`, string
/// variables), `"int"` for integer expressions, and `"int|string"`
/// when the type cannot be determined.
fn infer_array_key_type(index: &Expression<'_>, ctx: &VarResolutionCtx<'_>) -> PhpType {
    // Fast path: literal values.
    match index {
        Expression::Literal(Literal::Integer(_)) => return PhpType::int(),
        Expression::Literal(Literal::String(_)) => return PhpType::string(),
        _ => {}
    }

    // Resolve the expression type through the standard pipeline.
    let resolved = super::rhs_resolution::resolve_rhs_expression(index, ctx);
    if !resolved.is_empty() {
        let joined = ResolvedType::types_joined(&resolved);
        // Normalise the resolved type to a valid array key type.
        // PHP array keys are always int or string; bool and null are
        // coerced to int, float is truncated to int.
        if is_int_like_key_typed(&joined) {
            return PhpType::int();
        }
        if is_string_like_key(&joined) {
            return PhpType::string();
        }
        if joined.is_mixed() || is_array_key_type(&joined) {
            return PhpType::Union(vec![PhpType::int(), PhpType::string()]);
        }
        // For anything else (e.g. a class-string<T>, or a union),
        // return as-is if it is composed entirely of int/string
        // subtypes; otherwise fall back.
        return joined;
    }

    PhpType::Union(vec![PhpType::int(), PhpType::string()])
}

/// Returns `true` when the [`PhpType`] represents a PHP type that
/// is always coerced to `int` when used as an array key.
fn is_int_like_key_typed(ty: &PhpType) -> bool {
    ty.is_int_coercible_key()
}

/// Returns `true` when the [`PhpType`] represents a string-like
/// array key type.
fn is_string_like_key(ty: &PhpType) -> bool {
    ty.is_string_subtype()
}

/// Returns `true` when the [`PhpType`] is `array-key` or the
/// equivalent `int|string` union.
fn is_array_key_type(ty: &PhpType) -> bool {
    if ty.is_array_key() {
        return true;
    }
    match ty {
        PhpType::Union(members) if members.len() == 2 => {
            let has_int = members.iter().any(|m| m.is_int());
            let has_string = members.iter().any(|m| m.is_string_type());
            has_int && has_string
        }
        _ => false,
    }
}

// ── Array function type preservation helpers ─────────────────────────

/// Extract the first positional argument expression from an
/// argument list.
pub(in crate::completion) fn first_arg_expr<'b>(
    args: &'b ArgumentList<'b>,
) -> Option<&'b Expression<'b>> {
    args.arguments.first().map(|arg| match arg {
        Argument::Positional(pos) => pos.value,
        Argument::Named(named) => named.value,
    })
}

/// Extract the nth positional argument expression (0-based).
pub(in crate::completion) fn nth_arg_expr<'b>(
    args: &'b ArgumentList<'b>,
    n: usize,
) -> Option<&'b Expression<'b>> {
    args.arguments.iter().nth(n).map(|arg| match arg {
        Argument::Positional(pos) => pos.value,
        Argument::Named(named) => named.value,
    })
}

/// Resolve the raw iterable type of an argument expression.
///
/// Handles `$variable` (via docblock scanning) and delegates to
/// `resolve_expression_type` for method calls, property access,
/// etc.
pub(in crate::completion) fn resolve_arg_raw_type<'b>(
    arg_expr: &'b Expression<'b>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<PhpType> {
    // Direct variable — scan for @var / @param annotation.
    if let Expression::Variable(Variable::Direct(dv)) = arg_expr {
        let var_text = dv.name.to_string();
        let offset = arg_expr.span().start.offset as usize;
        let from_docblock =
            docblock::find_iterable_raw_type_in_source(ctx.content, offset, &var_text);
        if let Some(raw) = from_docblock {
            return Some(raw);
        }

        // No docblock — walk the AST for the variable's assignment
        // to extract the raw iterable type.  This handles cases like
        // `$users = $this->getUsers(); array_pop($users)` where
        // `$users` has no `@var` annotation but was assigned from a
        // method returning `list<User>`.
        let resolved = resolve_variable_types(
            &var_text,
            ctx.current_class,
            ctx.all_classes,
            ctx.content,
            offset as u32,
            ctx.class_loader,
            Loaders::with_function(ctx.function_loader()),
        );
        if !resolved.is_empty() {
            let joined = crate::types::ResolvedType::types_joined(&resolved);
            if joined.extract_value_type(true).is_some() {
                return Some(joined);
            }
        }
    }
    // Fall back to the unified pipeline (method calls, etc.)
    super::foreach_resolution::resolve_expression_type(arg_expr, ctx)
}

/// Check whether a call expression passes the target variable to a
/// pass-by-reference parameter with a type hint, and if so, push the
/// resolved type into `results`.
///
/// For example, given `function foo(Baz &$bar): void {}` and the call
/// `foo($bar)`, this function detects that `$bar` is passed to a `&`
/// parameter typed as `Baz` and resolves `$bar` to `Baz`.
///
/// Currently handles standalone function calls (via `function_loader`).
/// Handles standalone function calls, instance method calls, static
/// method calls, and constructor calls.
fn try_apply_pass_by_reference_type(
    expr: &Expression<'_>,
    ctx: &VarResolutionCtx<'_>,
    results: &mut Vec<ResolvedType>,
    conditional: bool,
) {
    let (argument_list, parameters) = match expr {
        Expression::Call(Call::Function(func_call)) => {
            let func_name = match func_call.function {
                Expression::Identifier(ident) => ident.value().to_string(),
                _ => return,
            };
            let fl = match ctx.function_loader() {
                Some(fl) => fl,
                None => return,
            };
            let func_info = match fl(&func_name) {
                Some(fi) => fi,
                None => return,
            };
            // Borrow the argument list and clone the parameters so we
            // can iterate them together.
            (&func_call.argument_list, func_info.parameters)
        }
        Expression::Call(Call::Method(method_call)) => {
            match try_resolve_method_params(method_call.object, &method_call.method, ctx) {
                Some((params,)) => (&method_call.argument_list, params),
                None => return,
            }
        }
        Expression::Call(Call::NullSafeMethod(method_call)) => {
            match try_resolve_method_params(method_call.object, &method_call.method, ctx) {
                Some((params,)) => (&method_call.argument_list, params),
                None => return,
            }
        }
        Expression::Call(Call::StaticMethod(static_call)) => {
            match try_resolve_static_method_params(static_call, ctx) {
                Some((params, arg_list)) => (arg_list, params),
                None => return,
            }
        }
        Expression::Instantiation(inst) => match try_resolve_constructor_params(inst, ctx) {
            Some((params, arg_list)) => (arg_list, params),
            None => return,
        },
        _ => return,
    };

    for (i, arg) in argument_list.arguments.iter().enumerate() {
        let arg_expr = match arg {
            Argument::Positional(pos) => pos.value,
            Argument::Named(named) => named.value,
        };

        // Check if this argument is our target variable.
        let is_our_var = match arg_expr {
            Expression::Variable(Variable::Direct(dv)) => dv.name == ctx.var_name,
            _ => false,
        };
        if !is_our_var {
            continue;
        }

        // Check if the corresponding parameter is pass-by-reference
        // with a type hint.
        if let Some(param) = parameters.get(i)
            && param.is_reference
            && let Some(type_hint) = &param.type_hint
        {
            let resolved = crate::completion::type_resolution::type_hint_to_classes_typed(
                type_hint,
                &ctx.current_class.name,
                ctx.all_classes,
                ctx.class_loader,
            );
            if !resolved.is_empty() {
                if !conditional {
                    results.clear();
                }
                ResolvedType::extend_unique(
                    results,
                    ResolvedType::from_classes_with_hint(resolved, type_hint.clone()),
                );
            }
        }
    }
}

/// Resolve parameters for an instance method call.
///
/// Currently only handles `$this->method()` where the current class
/// is known.  General variable receiver resolution is deferred to the
/// forward-walking scope model (T25) to avoid re-entrant variable
/// resolution.
fn try_resolve_method_params(
    object: &Expression<'_>,
    method: &ClassLikeMemberSelector<'_>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<(Vec<ParameterInfo>,)> {
    let method_name = match method {
        ClassLikeMemberSelector::Identifier(ident) => ident.value,
        _ => return None,
    };

    // Only handle `$this->method()` — we know the current class.
    match object {
        Expression::Variable(Variable::Direct(dv)) if dv.name == "$this" => {}
        _ => return None,
    }

    let method_info = ctx
        .current_class
        .methods
        .iter()
        .find(|m| m.name == method_name)?;
    Some((method_info.parameters.clone(),))
}

/// Resolve parameters for a static method call.
fn try_resolve_static_method_params<'a>(
    static_call: &'a StaticMethodCall<'a>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<(Vec<ParameterInfo>, &'a ArgumentList<'a>)> {
    let method_name = match &static_call.method {
        ClassLikeMemberSelector::Identifier(ident) => ident.value,
        _ => return None,
    };

    let class_name = match static_call.class {
        Expression::Self_(_) | Expression::Static(_) => ctx.current_class.name.clone(),
        Expression::Parent(_) => ctx.current_class.parent_class.clone()?,
        Expression::Identifier(ident) => ident.value().to_string(),
        _ => return None,
    };

    let cls = (ctx.class_loader)(&class_name)?;
    let method_info = cls.methods.iter().find(|m| m.name == method_name)?;
    Some((method_info.parameters.clone(), &static_call.argument_list))
}

/// Resolve parameters for a constructor call (`new Cls(...)`).
fn try_resolve_constructor_params<'a>(
    inst: &'a Instantiation<'a>,
    ctx: &VarResolutionCtx<'_>,
) -> Option<(Vec<ParameterInfo>, &'a ArgumentList<'a>)> {
    let class_name = match inst.class {
        Expression::Identifier(ident) => ident.value().to_string(),
        Expression::Self_(_) | Expression::Static(_) => ctx.current_class.name.clone(),
        Expression::Parent(_) => ctx.current_class.parent_class.clone()?,
        _ => return None,
    };

    let args = inst.argument_list.as_ref()?;
    let cls = (ctx.class_loader)(&class_name)?;
    let ctor = cls.methods.iter().find(|m| m.name == "__construct")?;
    Some((ctor.parameters.clone(), args))
}

#[cfg(test)]
#[path = "resolution_tests.rs"]
mod tests;