mir-analyzer 0.51.0

Analysis engine for the mir PHP static analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
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
/// Type narrowing — refines variable types based on conditional expressions.
///
/// Given a condition expression and a branch direction (true/false), this
/// module updates the `FlowState` to narrow variable types accordingly.
use php_ast::ast::{AssignOp, BinaryOp, UnaryPrefixOp};
use php_ast::owned::ExprKind;

use mir_codebase::storage::AssertionKind;
use mir_types::{Atomic, Type};

use crate::db::MirDatabase;
use crate::flow_state::FlowState;

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Narrow the types in `ctx` as if `expr` evaluates to `is_true`.
pub fn narrow_from_condition(
    expr: &php_ast::owned::Expr,
    ctx: &mut FlowState,
    is_true: bool,
    db: &dyn MirDatabase,
    file: &str,
) {
    match &expr.kind {
        // Parenthesized — unwrap and narrow the inner expression
        ExprKind::Parenthesized(inner) => {
            narrow_from_condition(inner, ctx, is_true, db, file);
        }

        // !expr  →  narrow as if expr is !is_true
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::BooleanNot => {
            narrow_from_condition(&u.operand, ctx, !is_true, db, file);
        }

        // $a && $b  →  if true: narrow both; if false: no constraint
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanAnd || b.op == BinaryOp::LogicalAnd => {
            if is_true {
                narrow_from_condition(&b.left, ctx, true, db, file);
                narrow_from_condition(&b.right, ctx, true, db, file);
                // When A && B is true, both sides were evaluated.
                // Promote variables from possibly_assigned to assigned for side effects in each.
                promote_assignment_effects(&b.left, ctx, db, file);
                promote_assignment_effects(&b.right, ctx, db, file);
            }
        }

        // $a || $b  →  if false: narrow both; if true: try to narrow same-var instanceof union
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
            if !is_true {
                narrow_from_condition(&b.left, ctx, false, db, file);
                narrow_from_condition(&b.right, ctx, false, db, file);
                // When A || B is false, both sides were evaluated.
                // Promote variables from possibly_assigned to assigned for side effects in each.
                promote_assignment_effects(&b.left, ctx, db, file);
                promote_assignment_effects(&b.right, ctx, db, file);
            } else {
                // For `$x instanceof A || $x instanceof B` in true-branch: narrow $x to A|B
                narrow_or_instanceof_true(&b.left, &b.right, ctx, db, file);

                // For `!isset($x) || RHS` in true-branch: narrow RHS as if isset($x) is true
                narrow_or_isset_true(&b.left, &b.right, ctx, db, file);
            }
        }

        // $x === null / $x !== null
        ExprKind::Binary(b) if b.op == BinaryOp::Identical || b.op == BinaryOp::NotIdentical => {
            let is_identical = b.op == BinaryOp::Identical;
            let effective_true = if is_identical { is_true } else { !is_true };

            // `($x ?? FALLBACK) === FALLBACK` — on the false branch, $x was defined
            // Must be checked before literal comparisons because `b.right` matching a literal
            // would otherwise consume the arm before we check for NullCoalesce on `b.left`.
            if let Some(nc) = extract_null_coalesce(&b.left) {
                if let Some(var_name) = extract_var_name(&nc.left) {
                    if !effective_true && same_literal(&nc.right, &b.right) {
                        let current = ctx.get_var(&var_name);
                        ctx.set_var(&var_name, current.remove_null());
                    }
                }
            } else if let Some(nc) = extract_null_coalesce(&b.right) {
                if let Some(var_name) = extract_var_name(&nc.left) {
                    if !effective_true && same_literal(&nc.right, &b.left) {
                        let current = ctx.get_var(&var_name);
                        ctx.set_var(&var_name, current.remove_null());
                    }
                }
            }
            // `$x === null`
            else if matches!(b.right.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(&b.left) {
                    narrow_var_null(ctx, &name, effective_true);
                } else if let Some((obj, prop)) = extract_prop_access(&b.left) {
                    narrow_prop_null(ctx, &obj, &prop, db, file, effective_true);
                } else if let Some((fqcn, prop)) =
                    extract_static_prop_access(&b.left, ctx, db, file)
                {
                    narrow_static_prop_null(ctx, &fqcn, &prop, db, effective_true);
                }
            } else if matches!(b.left.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(&b.right) {
                    narrow_var_null(ctx, &name, effective_true);
                } else if let Some((obj, prop)) = extract_prop_access(&b.right) {
                    narrow_prop_null(ctx, &obj, &prop, db, file, effective_true);
                } else if let Some((fqcn, prop)) =
                    extract_static_prop_access(&b.right, ctx, db, file)
                {
                    narrow_static_prop_null(ctx, &fqcn, &prop, db, effective_true);
                }
            }
            // `$x === true` / `$x === false`
            else if matches!(b.right.kind, ExprKind::Bool(true)) {
                if let Some(name) = extract_var_name(&b.left) {
                    narrow_var_bool(ctx, &name, true, effective_true);
                }
            } else if matches!(b.right.kind, ExprKind::Bool(false)) {
                if let Some(name) = extract_var_name(&b.left) {
                    narrow_var_bool(ctx, &name, false, effective_true);
                }
            }
            // `true === $x` / `false === $x` — symmetric; extract_var_name looks through
            // assignment exprs, so this also handles `false === ($x = expr)`.
            else if matches!(b.left.kind, ExprKind::Bool(true)) {
                if let Some(name) = extract_var_name(&b.right) {
                    narrow_var_bool(ctx, &name, true, effective_true);
                }
            } else if matches!(b.left.kind, ExprKind::Bool(false)) {
                if let Some(name) = extract_var_name(&b.right) {
                    narrow_var_bool(ctx, &name, false, effective_true);
                }
            }
            // `get_class($x) === 'ClassName'` — check before literal strings so it takes precedence
            else if let ExprKind::String(class_name_str) = &b.right.kind {
                if let Some(obj_var_name) = extract_get_class_arg(&b.left) {
                    let fqcn = crate::db::resolve_name(db, file, class_name_str.as_ref());
                    narrow_var_to_specific_class(ctx, &obj_var_name, &fqcn, effective_true);
                } else if let Some(name) = extract_var_name(&b.left) {
                    // `$x === 'literal'`
                    narrow_var_literal_string(ctx, &name, class_name_str, effective_true);
                }
            } else if let ExprKind::String(class_name_str) = &b.left.kind {
                if let Some(obj_var_name) = extract_get_class_arg(&b.right) {
                    let fqcn = crate::db::resolve_name(db, file, class_name_str.as_ref());
                    narrow_var_to_specific_class(ctx, &obj_var_name, &fqcn, effective_true);
                } else if let Some(name) = extract_var_name(&b.right) {
                    // `$x === 'literal'`
                    narrow_var_literal_string(ctx, &name, class_name_str, effective_true);
                }
            }
            // `$x === 42`
            else if let ExprKind::Int(n) = &b.right.kind {
                if let Some(name) = extract_var_name(&b.left) {
                    narrow_var_literal_int(ctx, &name, *n, effective_true);
                }
            } else if let ExprKind::Int(n) = &b.left.kind {
                if let Some(name) = extract_var_name(&b.right) {
                    narrow_var_literal_int(ctx, &name, *n, effective_true);
                }
            }
            // `$x === EnumName::CaseName`
            else if let ExprKind::StaticPropertyAccess(_) = &b.right.kind {
                if let Some(var_name) = extract_var_name(&b.left) {
                    if let Some((enum_fqcn, case_name)) = extract_enum_case(
                        &b.right,
                        ctx.self_fqcn.as_deref(),
                        ctx.parent_fqcn.as_deref(),
                        db,
                        file,
                    ) {
                        narrow_var_to_literal_enum_case(
                            db,
                            ctx,
                            &var_name,
                            &enum_fqcn,
                            &case_name,
                            effective_true,
                        );
                    }
                }
            } else if let ExprKind::StaticPropertyAccess(_) = &b.left.kind {
                if let Some(var_name) = extract_var_name(&b.right) {
                    if let Some((enum_fqcn, case_name)) = extract_enum_case(
                        &b.left,
                        ctx.self_fqcn.as_deref(),
                        ctx.parent_fqcn.as_deref(),
                        db,
                        file,
                    ) {
                        narrow_var_to_literal_enum_case(
                            db,
                            ctx,
                            &var_name,
                            &enum_fqcn,
                            &case_name,
                            effective_true,
                        );
                    }
                }
            }
            // `$x === EnumName::CaseName` (real enum-case access parses as
            // ClassConstAccess, the same node `Foo::class` uses — try case
            // narrowing first, falling back to the class-string case below).
            else if let ExprKind::ClassConstAccess(_) = &b.right.kind {
                if let Some(var_name) = extract_var_name(&b.left) {
                    if let Some((enum_fqcn, case_name)) = extract_enum_case(
                        &b.right,
                        ctx.self_fqcn.as_deref(),
                        ctx.parent_fqcn.as_deref(),
                        db,
                        file,
                    ) {
                        narrow_var_to_literal_enum_case(
                            db,
                            ctx,
                            &var_name,
                            &enum_fqcn,
                            &case_name,
                            effective_true,
                        );
                    } else if let ExprKind::ClassConstAccess(cca) = &b.right.kind {
                        if let Some(fqcn) = extract_class_const_fqcn(
                            cca,
                            ctx.self_fqcn.as_deref(),
                            ctx.parent_fqcn.as_deref(),
                            db,
                            file,
                        ) {
                            narrow_var_to_class_string(ctx, &var_name, &fqcn, effective_true);
                        }
                    }
                }
                // `get_class($x) === Foo::class` — the far more idiomatic
                // counterpart of the `get_class($x) === 'Foo'` string-literal
                // case above; only reached once extract_var_name on the left
                // fails (i.e. the left side is the get_class(...) call itself).
                else if let Some(obj_var_name) = extract_get_class_arg(&b.left) {
                    if let ExprKind::ClassConstAccess(cca) = &b.right.kind {
                        if let Some(fqcn) = extract_class_const_fqcn(
                            cca,
                            ctx.self_fqcn.as_deref(),
                            ctx.parent_fqcn.as_deref(),
                            db,
                            file,
                        ) {
                            narrow_var_to_specific_class(ctx, &obj_var_name, &fqcn, effective_true);
                        }
                    }
                }
            } else if let ExprKind::ClassConstAccess(_) = &b.left.kind {
                if let Some(var_name) = extract_var_name(&b.right) {
                    if let Some((enum_fqcn, case_name)) = extract_enum_case(
                        &b.left,
                        ctx.self_fqcn.as_deref(),
                        ctx.parent_fqcn.as_deref(),
                        db,
                        file,
                    ) {
                        narrow_var_to_literal_enum_case(
                            db,
                            ctx,
                            &var_name,
                            &enum_fqcn,
                            &case_name,
                            effective_true,
                        );
                    } else if let ExprKind::ClassConstAccess(cca) = &b.left.kind {
                        if let Some(fqcn) = extract_class_const_fqcn(
                            cca,
                            ctx.self_fqcn.as_deref(),
                            ctx.parent_fqcn.as_deref(),
                            db,
                            file,
                        ) {
                            narrow_var_to_class_string(ctx, &var_name, &fqcn, effective_true);
                        }
                    }
                }
                // `Foo::class === get_class($x)` — symmetric counterpart.
                else if let Some(obj_var_name) = extract_get_class_arg(&b.right) {
                    if let ExprKind::ClassConstAccess(cca) = &b.left.kind {
                        if let Some(fqcn) = extract_class_const_fqcn(
                            cca,
                            ctx.self_fqcn.as_deref(),
                            ctx.parent_fqcn.as_deref(),
                            db,
                            file,
                        ) {
                            narrow_var_to_specific_class(ctx, &obj_var_name, &fqcn, effective_true);
                        }
                    }
                }
            }
            // `$arr === []` — false-branch (i.e. `$arr !== []`) narrows $arr to non-empty.
            else if let ExprKind::Array(elems) = &b.right.kind {
                if elems.is_empty() {
                    if let Some(var_name) = extract_var_name(&b.left) {
                        if !effective_true {
                            let current = ctx.get_var(&var_name);
                            let narrowed = current.narrow_to_non_empty_collection();
                            if !narrowed.is_empty() && narrowed != current {
                                ctx.set_var(&var_name, narrowed);
                            }
                        }
                    }
                }
            } else if let ExprKind::Array(elems) = &b.left.kind {
                if elems.is_empty() {
                    if let Some(var_name) = extract_var_name(&b.right) {
                        if !effective_true {
                            let current = ctx.get_var(&var_name);
                            let narrowed = current.narrow_to_non_empty_collection();
                            if !narrowed.is_empty() && narrowed != current {
                                ctx.set_var(&var_name, narrowed);
                            }
                        }
                    }
                }
            }
        }

        // $x < N, $x <= N, $x > N, $x >= N — comparison-driven integer range narrowing
        ExprKind::Binary(b)
            if matches!(
                b.op,
                BinaryOp::Less
                    | BinaryOp::LessOrEqual
                    | BinaryOp::Greater
                    | BinaryOp::GreaterOrEqual
            ) =>
        {
            // Normalize: variable on left, integer literal on right.
            // If the literal is on the left (`5 > $x`), swap and flip the operator.
            let (var_expr, cmp_op, lit_expr) = if extract_var_name(&b.left).is_some() {
                (&b.left, b.op, &b.right)
            } else {
                (&b.right, flip_comparison_op(b.op), &b.left)
            };

            if let (Some(var_name), Some(n)) =
                (extract_var_name(var_expr), extract_int_literal(lit_expr))
            {
                narrow_var_int_comparison(ctx, &var_name, cmp_op, n, is_true);
            }
            // count($arr) op N  /  N op count($arr) — normalize so count call is on left.
            let (count_expr, count_cmp_op, count_lit) = if extract_count_of_var(&b.left).is_some() {
                (&b.left, b.op, &b.right)
            } else {
                (&b.right, flip_comparison_op(b.op), &b.left)
            };
            if let (Some(arr_var), Some(n)) = (
                extract_count_of_var(count_expr),
                extract_int_literal(count_lit),
            ) {
                narrow_array_count_comparison(ctx, &arr_var, count_cmp_op, n, is_true);
            }
            // strlen($str) op N  /  N op strlen($str) — same normalization.
            let (strlen_expr, strlen_cmp_op, strlen_lit) =
                if extract_strlen_of_var(&b.left).is_some() {
                    (&b.left, b.op, &b.right)
                } else {
                    (&b.right, flip_comparison_op(b.op), &b.left)
                };
            if let (Some(str_var), Some(n)) = (
                extract_strlen_of_var(strlen_expr),
                extract_int_literal(strlen_lit),
            ) {
                narrow_string_strlen_comparison(ctx, &str_var, strlen_cmp_op, n, is_true);
            }
        }

        // $x == null  (loose equality)
        ExprKind::Binary(b) if b.op == BinaryOp::Equal || b.op == BinaryOp::NotEqual => {
            let is_equal = b.op == BinaryOp::Equal;
            let effective_true = if is_equal { is_true } else { !is_true };
            if matches!(b.right.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(&b.left) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            } else if matches!(b.left.kind, ExprKind::Null) {
                if let Some(name) = extract_var_name(&b.right) {
                    narrow_var_null(ctx, &name, effective_true);
                }
            }
        }

        // $x instanceof ClassName  /  $this->prop instanceof ClassName
        ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
            if let Some(var_name) = extract_var_name(&b.left) {
                if let Some(raw_name) = extract_class_name(
                    &b.right,
                    ctx.self_fqcn.as_deref(),
                    ctx.parent_fqcn.as_deref(),
                ) {
                    // Resolve the short name to its FQCN using file imports
                    let class_name = crate::db::resolve_name(db, file, &raw_name);
                    let current = ctx.get_var(&var_name);
                    let narrowed = if is_true {
                        narrow_instanceof_preserving_subtypes(
                            &current,
                            &class_name,
                            db,
                            &ctx.template_param_names,
                        )
                    } else {
                        filter_out_instanceof_match(&current, &class_name, db)
                    };
                    set_narrowed(ctx, &var_name, &current, narrowed, true);
                }
            } else if let Some((obj, prop)) = extract_prop_access(&b.left) {
                if let Some(raw_name) = extract_class_name(
                    &b.right,
                    ctx.self_fqcn.as_deref(),
                    ctx.parent_fqcn.as_deref(),
                ) {
                    let class_name = crate::db::resolve_name(db, file, &raw_name);
                    narrow_prop_instanceof(ctx, &obj, &prop, &class_name, db, file, is_true);
                }
            }
        }

        // is_string($x), is_int($x), is_null($x), is_array($x), etc.
        // Also handles assert($x instanceof Y) — narrows like a bare condition.
        ExprKind::FunctionCall(call) => {
            let fn_name_opt: Option<&str> = match &call.name.kind {
                ExprKind::Identifier(name) => Some(name.as_ref()),
                ExprKind::Variable(name) => Some(name.as_ref()),
                _ => None,
            };
            if let Some(fn_name) = fn_name_opt {
                let bare = fn_name.trim_start_matches('\\');
                if matches!(bare, "class_exists" | "interface_exists" | "trait_exists") {
                    // `if (class_exists(\Foo\Bar::class)) { ... }` — record \Foo\Bar as
                    // proven-to-exist in the true branch so that UndefinedClass is
                    // suppressed for all usages within the guarded block.
                    // Variable form: `if (class_exists($var)) { ... }` — narrow $var to
                    // class-string so it satisfies class-string-typed parameters.
                    // `interface_exists($var)` narrows to the more precise interface-string.
                    if is_true {
                        if let Some(arg_expr) = call.args.first() {
                            if let Some(fqcn) =
                                extract_class_fqcn_from_expr(&arg_expr.value, db, file)
                            {
                                ctx.class_exists_guards.insert(fqcn);
                            } else if let Some(var_name) = extract_var_name(&arg_expr.value) {
                                let current = ctx.get_var(&var_name);
                                let narrowed = if bare == "interface_exists" {
                                    current.narrow_to_interface_string()
                                } else {
                                    current.narrow_to_class_string()
                                };
                                set_narrowed(ctx, &var_name, &current, narrowed, true);
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("defined") {
                    // `if (defined('NAME')) { ... NAME ... }` — record NAME as
                    // proven-defined in the true branch to suppress
                    // UndefinedConstant within the guarded block.
                    if is_true {
                        if let Some(arg) = call.args.first() {
                            if let ExprKind::String(name) = &arg.value.kind {
                                let name = name.as_ref().trim_start_matches('\\');
                                if !name.is_empty() {
                                    ctx.defined_guards.insert(std::sync::Arc::from(name));
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("function_exists") {
                    // `if (function_exists('fn')) { ... fn() ... }` — record fn
                    // as proven-to-exist in the true branch to suppress
                    // UndefinedFunction within the guarded block. Combined with
                    // negation + divergence (`if (!function_exists('fn')) throw;`)
                    // this also covers the early-exit pattern.
                    if is_true {
                        if let Some(arg) = call.args.first() {
                            if let ExprKind::String(name) = &arg.value.kind {
                                let name = name.as_ref().trim_start_matches('\\');
                                if !name.is_empty() {
                                    ctx.function_exists_guards
                                        .insert(std::sync::Arc::from(name));
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("extension_loaded") {
                    // `if (extension_loaded('ext')) { ... }` — record the extension
                    // name so that `UndefinedClass` is suppressed for any class used
                    // inside the guarded block (the caller verified the extension is
                    // present). The false-branch / early-exit pattern also works via
                    // the normal divergence+narrowing mechanism.
                    if is_true {
                        if let Some(arg) = call.args.first() {
                            if let ExprKind::String(ext) = &arg.value.kind {
                                if !ext.is_empty() {
                                    ctx.extension_loaded_guards
                                        .insert(std::sync::Arc::from(ext.as_ref()));
                                }
                            }
                        }
                    }
                } else if fn_name.eq_ignore_ascii_case("assert") {
                    // assert($condition) — narrow as if the condition is is_true
                    if let Some(arg_expr) = call.args.first() {
                        narrow_from_condition(&arg_expr.value, ctx, is_true, db, file);
                    }
                } else if fn_name.eq_ignore_ascii_case("method_exists")
                    || fn_name.eq_ignore_ascii_case("property_exists")
                {
                    // Narrow the first arg to TObject for simple variables (existing behaviour).
                    // Additionally record `(expr_key, method_name)` in method_exists_guards for
                    // property-access first args where variable narrowing can't reach.
                    if let Some(arg_expr) = call.args.first() {
                        if let Some(var_name) = extract_var_name(&arg_expr.value) {
                            narrow_from_type_fn(ctx, fn_name, &var_name, is_true);
                        }
                        if is_true {
                            if let Some(expr_key) = extract_expr_guard_key(&arg_expr.value) {
                                if let Some(method_arg) = call.args.get(1) {
                                    if let ExprKind::String(method_name) = &method_arg.value.kind {
                                        let method_lc = std::sync::Arc::from(
                                            crate::util::php_ident_lowercase(method_name).as_str(),
                                        );
                                        ctx.method_exists_guards.insert((expr_key, method_lc));
                                    }
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("array_key_exists") && is_true {
                    // array_key_exists('k', $arr) in true-branch: prove the key
                    // exists in the array's sealed shape so that $arr['k'] does
                    // not trigger NonExistentArrayOffset afterwards.
                    if let (Some(key_arg), Some(arr_arg)) = (call.args.first(), call.args.get(1)) {
                        let literal_key = match &key_arg.value.kind {
                            ExprKind::String(s) => Some(mir_types::atomic::ArrayKey::String(
                                std::sync::Arc::from(s.as_ref()),
                            )),
                            ExprKind::Int(i) => Some(mir_types::atomic::ArrayKey::Int(*i)),
                            _ => None,
                        };
                        if let Some(key) = literal_key {
                            if let Some(var_name) = extract_var_name(&arr_arg.value) {
                                let current = ctx.get_var(&var_name);
                                let narrowed = add_key_to_sealed_shapes(&current, &key);
                                if narrowed != current {
                                    ctx.set_var(&var_name, narrowed);
                                }
                            } else if let Some((obj, prop)) = extract_prop_access(&arr_arg.value) {
                                narrow_prop_array_key_exists(ctx, &obj, &prop, &key, db, file);
                            }
                        }
                    }
                } else if matches!(
                    bare.to_ascii_lowercase().as_str(),
                    "str_contains" | "str_starts_with" | "str_ends_with"
                ) {
                    // str_contains($haystack, 'x') true → $haystack is non-empty-string
                    // (when the needle is a non-empty literal — a non-empty needle can
                    // only be found in a non-empty haystack).
                    if is_true {
                        if let (Some(haystack_arg), Some(needle_arg)) =
                            (call.args.first(), call.args.get(1))
                        {
                            let needle_non_empty = match &needle_arg.value.kind {
                                ExprKind::String(s) => !s.is_empty(),
                                _ => false,
                            };
                            if needle_non_empty {
                                if let Some(var_name) = extract_var_name(&haystack_arg.value) {
                                    let current = ctx.get_var(&var_name);
                                    if !current.is_mixed() {
                                        let narrowed = narrow_string_to_non_empty(&current);
                                        if narrowed != current {
                                            ctx.set_var(&var_name, narrowed);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("in_array") {
                    // in_array($needle, ['a', 'b', 'c']) true →
                    // narrow $needle to 'a'|'b'|'c'.
                    if let (Some(needle_arg), Some(haystack_arg)) =
                        (call.args.first(), call.args.get(1))
                    {
                        if let Some(var_name) = extract_var_name(&needle_arg.value) {
                            if let Some(haystack_ty) =
                                extract_haystack_type(&haystack_arg.value, ctx)
                            {
                                let current = ctx.get_var(&var_name);
                                if !current.is_mixed() && is_true {
                                    // intersect: keep only types that could match a haystack value
                                    let narrowed =
                                        narrow_to_haystack_values(&current, &haystack_ty);
                                    if !narrowed.is_empty() && narrowed != current {
                                        ctx.set_var(&var_name, narrowed);
                                    }
                                } else if !current.is_mixed() && !is_true {
                                    // False branch: safe only when the current type is a
                                    // finite literal union — remove the matched haystack values.
                                    let all_literals = !current.types.is_empty()
                                        && current.types.iter().all(|a| {
                                            matches!(
                                                a,
                                                Atomic::TLiteralString(_) | Atomic::TLiteralInt(_)
                                            )
                                        });
                                    if all_literals {
                                        let narrowed = current
                                            .filter(|a| !haystack_ty.types.iter().any(|h| h == a));
                                        if !narrowed.is_empty() && narrowed != current {
                                            ctx.set_var(&var_name, narrowed);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("is_a") {
                    // is_a($obj, 'ClassName') → instanceof semantics (includes exact class).
                    // When $allow_string (3rd arg) is truthy, the first arg may be a class-string
                    // — preserve string/class-string atoms so the true branch stays reachable
                    // and no false diverge is set in the false branch.
                    if let (Some(obj_arg), Some(class_arg)) = (call.args.first(), call.args.get(1))
                    {
                        if let Some(var_name) = extract_var_name(&obj_arg.value) {
                            if let Some(class_name) =
                                extract_class_fqcn_from_expr(&class_arg.value, db, file)
                            {
                                let allow_string = call
                                    .args
                                    .get(2)
                                    .map(|a| is_truthy_bool_literal(&a.value))
                                    .unwrap_or(false);
                                let current = ctx.get_var(&var_name);
                                if allow_string {
                                    // When allow_string is true, string/class-string atoms are
                                    // valid is_a() true-branch values — preserve them so the
                                    // true branch stays reachable and type is not wrongly erased.
                                    let narrowed = if is_true {
                                        // Partition into string-like (kept as-is) and object-like
                                        // (narrowed via instanceof) so `narrow_instanceof_preserving_subtypes`
                                        // fallback doesn't inject a spurious named-object atom when
                                        // the current type is purely string/class-string.
                                        let mut result = Type::empty();
                                        result.possibly_undefined = current.possibly_undefined;
                                        result.from_docblock = current.from_docblock;
                                        let mut obj_part = Type::empty();
                                        for atom in &current.types {
                                            if atom.is_string()
                                                || matches!(atom, Atomic::TClassString(_))
                                            {
                                                result.add_type(atom.clone());
                                            } else {
                                                obj_part.add_type(atom.clone());
                                            }
                                        }
                                        if !obj_part.is_empty() || current.is_mixed() {
                                            let obj_src = if obj_part.is_empty() {
                                                &current
                                            } else {
                                                &obj_part
                                            };
                                            let obj_narrowed =
                                                narrow_instanceof_preserving_subtypes(
                                                    obj_src,
                                                    &class_name,
                                                    db,
                                                    &ctx.template_param_names,
                                                );
                                            for atom in obj_narrowed.types.iter() {
                                                result.add_type(atom.clone());
                                            }
                                        }
                                        result
                                    } else {
                                        filter_out_instanceof_match(&current, &class_name, db)
                                    };
                                    // Don't mark diverges when allow_string is set: a
                                    // class-string variable may still be a valid non-object
                                    // value that passes the test.
                                    set_narrowed(ctx, &var_name, &current, narrowed, false);
                                } else {
                                    let narrowed = if is_true {
                                        narrow_instanceof_preserving_subtypes(
                                            &current,
                                            &class_name,
                                            db,
                                            &ctx.template_param_names,
                                        )
                                    } else {
                                        filter_out_instanceof_match(&current, &class_name, db)
                                    };
                                    set_narrowed(ctx, &var_name, &current, narrowed, true);
                                }
                            }
                        }
                    }
                } else if bare.eq_ignore_ascii_case("is_subclass_of") {
                    // is_subclass_of($obj, 'ClassName') → strict-subclass check: the exact
                    // class itself is NOT a subclass of itself.
                    // True branch: keep only atoms that are known strict subclasses.
                    // False branch: no narrowing — is_subclass_of being false doesn't tell us
                    // the variable isn't Foo; Foo is not a subclass of itself, so Foo atoms
                    // must be kept (removing them would make a later `Foo` use diverge).
                    if let (Some(obj_arg), Some(class_arg)) = (call.args.first(), call.args.get(1))
                    {
                        if let Some(var_name) = extract_var_name(&obj_arg.value) {
                            if let Some(class_name) =
                                extract_class_fqcn_from_expr(&class_arg.value, db, file)
                            {
                                let current = ctx.get_var(&var_name);
                                if is_true {
                                    let narrowed = narrow_strict_subclass_of(
                                        &current,
                                        &class_name,
                                        db,
                                        &ctx.template_param_names,
                                    );
                                    // mark_diverges=false: the exact class being absent from
                                    // strict-subclass narrowing doesn't make the branch dead.
                                    set_narrowed(ctx, &var_name, &current, narrowed, false);
                                }
                                // False branch: leave current type unchanged.
                            }
                        }
                    }
                } else if apply_docblock_assertions(call, ctx, is_true, db, file, fn_name) {
                    // User-defined assertion applied.
                } else if let Some(arg_expr) = call.args.first() {
                    if let Some(var_name) = extract_var_name(&arg_expr.value) {
                        narrow_from_type_fn(ctx, fn_name, &var_name, is_true);
                    }
                }
            }
        }

        // isset($x)
        ExprKind::Isset(vars) => {
            for var_expr in vars.iter() {
                if let Some(var_name) = extract_var_name(var_expr) {
                    if is_true {
                        // remove null; mark as definitely assigned
                        let current = ctx.get_var(&var_name);
                        ctx.set_var(&var_name, current.remove_null());
                        std::sync::Arc::make_mut(&mut ctx.assigned_vars)
                            .insert(mir_types::Name::from(var_name.as_str()));
                    }
                } else if is_true {
                    // `isset($base[$k])` implies `$base` is a non-null, indexable
                    // value — remove null/false from the base variable so a
                    // guarded access (`preg_split()` returns array|false) does
                    // not report PossiblyInvalidArrayAccess.
                    if let Some(base) = array_access_base_var(var_expr) {
                        let current = ctx.get_var(&base);
                        ctx.set_var(&base, current.remove_null().remove_false());
                    }
                    // For a single-level `isset($arr['key'])` on a shape-typed
                    // base, also narrow that key's OWN value type: remove null
                    // and mark it no longer optional, so a later `$arr['key']`
                    // read inside the guard isn't reported as possibly-null (the
                    // isset check just proved the key is present and non-null).
                    narrow_isset_shape_key(var_expr, ctx);
                }
            }
        }

        // empty($x)
        ExprKind::Empty(var_expr) => {
            if let Some(var_name) = extract_var_name(var_expr) {
                let current = ctx.get_var(&var_name);
                let narrowed = if is_true {
                    // empty($x) is true: x is falsy
                    current.narrow_to_falsy()
                } else {
                    // empty($x) is false: x is truthy
                    current.narrow_to_truthy()
                };
                if !narrowed.is_empty() {
                    ctx.set_var(&var_name, narrowed);
                }
            }
        }

        // ($x = expr) / ($x ??= expr) used as a condition
        // The assignment has already been evaluated (ctx holds the post-assignment type).
        // Narrow the target variable based on the truthiness of the expression result.
        ExprKind::Assign(a) if matches!(a.op, AssignOp::Assign | AssignOp::Coalesce) => {
            if let Some(var_name) = extract_var_name(&a.target) {
                let current = ctx.get_var(&var_name);
                let mut narrowed = if is_true {
                    current.narrow_to_truthy()
                } else {
                    current.narrow_to_falsy()
                };
                // In the true-branch the assignment definitely executed, so
                // the variable is always defined here — clear possibly_undefined.
                if is_true {
                    narrowed.possibly_undefined = false;
                }
                if !narrowed.is_empty() {
                    ctx.set_var(&var_name, narrowed);
                } else if !current.is_empty() && !current.is_mixed() {
                    ctx.diverges = true;
                }
            }
        }

        // if ($x)  — truthy/falsy narrowing
        _ => {
            if let Some(var_name) = extract_var_name(expr) {
                let current = ctx.get_var(&var_name);
                let narrowed = if is_true {
                    current.narrow_to_truthy()
                } else {
                    current.narrow_to_falsy()
                };
                if !narrowed.is_empty() {
                    ctx.set_var(&var_name, narrowed);
                } else if !current.is_empty()
                    && !current.is_mixed()
                    && ctx.var_is_defined(&var_name)
                {
                    // The variable's type can never satisfy this truthiness
                    // constraint → this branch is statically unreachable.
                    // Possibly-undefined variables are exempt: an unset
                    // variable reads as null (falsy), so the branch stays
                    // reachable at runtime.
                    ctx.diverges = true;
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn apply_docblock_assertions(
    call: &php_ast::owned::FunctionCallExpr,
    ctx: &mut FlowState,
    is_true: bool,
    db: &dyn MirDatabase,
    file: &str,
    fn_name: &str,
) -> bool {
    let fn_name = fn_name
        .strip_prefix('\\')
        .map(|s| s.to_string())
        .unwrap_or_else(|| fn_name.to_string());
    let fn_active = |name: &str| -> bool {
        let here = crate::db::Fqcn::from_str(db, name);
        crate::db::find_function(db, here).is_some()
    };
    let resolved_fn_name = {
        let qualified = crate::db::resolve_name(db, file, &fn_name);
        if fn_active(qualified.as_str()) {
            qualified
        } else if fn_active(fn_name.as_str()) {
            fn_name.clone()
        } else {
            qualified
        }
    };

    let here = crate::db::Fqcn::from_str(db, resolved_fn_name.as_str());
    let Some(f) = crate::db::find_function(db, here) else {
        return false;
    };
    let expected_kind = if is_true {
        AssertionKind::AssertIfTrue
    } else {
        AssertionKind::AssertIfFalse
    };

    let assertions = &f.assertions;
    let params = &f.params;

    // An assertion type written in terms of the function's own `@template`s
    // (e.g. `@psalm-assert-if-true T $value` alongside `@param
    // class-string<T> $class`) must resolve T from this call's actual
    // arguments before narrowing — otherwise the variable narrows to the
    // bare, unresolved template atom instead of the concrete type.
    let template_bindings = if f.template_params.is_empty() {
        None
    } else {
        let arg_types: Vec<Type> = params
            .iter()
            .enumerate()
            .map(|(i, _)| {
                call.args
                    .get(i)
                    .map(|arg| assertion_arg_type(&arg.value, ctx, db, file))
                    .unwrap_or_else(Type::mixed)
            })
            .collect();
        Some(crate::generic::infer_template_bindings(db, &f.template_params, params, &arg_types).0)
    };

    let mut applied = false;
    for assertion in assertions
        .iter()
        .filter(|a| a.kind == expected_kind || (is_true && a.kind == AssertionKind::Assert))
    {
        if let Some(index) = params.iter().position(|p| p.name == assertion.param) {
            if let Some(arg) = call.args.get(index) {
                if let Some(var_name) = extract_var_name(&arg.value) {
                    let ty = match &template_bindings {
                        Some(b) => assertion.ty.substitute_templates(b),
                        None => assertion.ty.clone(),
                    };
                    ctx.set_var(&var_name, ty);
                    applied = true;
                }
            }
        }
    }

    applied
}

/// Best-effort type of a call argument for inferring `@template` bindings on
/// an assert-if-true/-false narrowing call — not a full expression
/// evaluator, just enough to resolve the common `class-string<T>`/`T
/// $x`-typed guard-function shapes (e.g. `isInstanceOf($value,
/// Foo::class)`). Anything else falls back to `mixed`, which leaves the
/// template unbound rather than mis-bound.
fn assertion_arg_type(
    expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Type {
    if let Some(var_name) = extract_var_name(expr) {
        return ctx.get_var(&var_name);
    }
    if let Some(fqcn) = extract_class_fqcn_from_expr(expr, db, file) {
        return Type::single(Atomic::TClassString(Some(mir_types::Name::from(
            fqcn.as_ref(),
        ))));
    }
    Type::mixed()
}

/// Collect class names from `instanceof` checks on the SAME variable across
/// an arbitrary expression — recursing through `||`/`or` and parens. Returns
/// `false` as soon as something doesn't fit the shape (a non-instanceof leaf,
/// or an instanceof on a different variable), signaling the caller should not
/// treat the whole set as one OR-chain over a single variable.
#[allow(clippy::too_many_arguments)]
fn collect_instanceof(
    expr: &php_ast::owned::Expr,
    var_name: &mut Option<String>,
    class_names: &mut Vec<String>,
    db: &dyn MirDatabase,
    file: &str,
    self_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
) -> bool {
    match &expr.kind {
        ExprKind::Binary(b) if b.op == BinaryOp::Instanceof => {
            if let (Some(vn), Some(cn)) = (
                extract_var_name(&b.left),
                extract_class_name(&b.right, self_fqcn, parent_fqcn),
            ) {
                let resolved = crate::db::resolve_name(db, file, &cn);
                match var_name {
                    None => {
                        *var_name = Some(vn);
                        class_names.push(resolved);
                        true
                    }
                    Some(existing) if existing == &vn => {
                        class_names.push(resolved);
                        true
                    }
                    _ => false, // different variable — bail out
                }
            } else {
                false
            }
        }
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
            collect_instanceof(
                &b.left,
                var_name,
                class_names,
                db,
                file,
                self_fqcn,
                parent_fqcn,
            ) && collect_instanceof(
                &b.right,
                var_name,
                class_names,
                db,
                file,
                self_fqcn,
                parent_fqcn,
            )
        }
        ExprKind::Parenthesized(inner) => collect_instanceof(
            inner,
            var_name,
            class_names,
            db,
            file,
            self_fqcn,
            parent_fqcn,
        ),
        _ => false,
    }
}

/// Narrow `$x` to the union of every `instanceof` class collected from
/// `conditions`, when EVERY condition is an `instanceof` (or OR-chain/parens
/// thereof) on the SAME variable — e.g. `$x instanceof A, $x instanceof B`
/// comma-separated `match(true)` arm conditions, or the two sides of an
/// `if ($x instanceof A || $x instanceof B)`.
///
/// Returns `true` when it fully narrowed (every condition fit the shape and
/// shared one variable) — the caller should then skip narrowing those
/// conditions again individually, since re-applying each `instanceof` in
/// sequence would AND-compose them and collapse the result to the last
/// disjunct (no value can be simultaneously exactly-A and exactly-B).
/// Returns `false` when the shape doesn't apply (mixed condition kinds, or
/// instanceof checks on different variables) — the caller should fall back
/// to narrowing each condition normally.
/// Returns the discovered variable name on success (the caller may want to
/// know which variable was narrowed, e.g. to re-apply the result on top of a
/// different context — see `analyze_switch_stmt`'s fallthrough handling).
pub(crate) fn narrow_instanceof_disjuncts(
    conditions: &[&php_ast::owned::Expr],
    ctx: &mut FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<String> {
    if conditions.len() < 2 {
        return None;
    }
    let self_fqcn = ctx.self_fqcn.as_deref();
    let parent_fqcn = ctx.parent_fqcn.as_deref();

    let mut var_name: Option<String> = None;
    let mut class_names: Vec<String> = vec![];
    let all_ok = conditions.iter().all(|cond| {
        collect_instanceof(
            cond,
            &mut var_name,
            &mut class_names,
            db,
            file,
            self_fqcn,
            parent_fqcn,
        )
    });

    if !all_ok || class_names.len() < 2 {
        return None;
    }
    let vn = var_name?;

    let current = ctx.get_var(&vn);
    // Narrow to the union of all instanceof types, classifying each union
    // member against every disjunct at once (see narrow_or_instanceof_union's
    // doc comment for why this can't be done by narrowing per-class and
    // merging afterward).
    let narrowed =
        narrow_or_instanceof_union(&current, &class_names, db, &ctx.template_param_names);
    // Fall back to current if narrowed is empty (e.g. mixed)
    let result = if narrowed.is_empty() {
        current.clone()
    } else {
        narrowed
    };
    if !result.is_empty() {
        ctx.set_var(&vn, result);
    }
    Some(vn)
}

/// Recognized single-argument type-check functions whose truthy narrowing
/// `narrow_from_type_fn` implements. Matches its match arms (excluding
/// `method_exists`/`property_exists`, which take two arguments and are
/// unrelated to the single-variable-disjunct shape this supports).
const NARROWING_TYPE_FNS: &[&str] = &[
    "is_string",
    "is_int",
    "is_integer",
    "is_long",
    "is_float",
    "is_double",
    "is_real",
    "is_bool",
    "is_null",
    "is_array",
    "array_is_list",
    "is_object",
    "is_callable",
    "is_scalar",
    "is_iterable",
    "is_countable",
    "is_resource",
    "is_numeric",
];

/// Extract `(fn_name, var_name)` from a single-argument type-check call
/// (`is_int($x)`) recognized by [`NARROWING_TYPE_FNS`]. Returns `None` for
/// anything else — a different function, more than one argument, or an
/// argument that isn't a plain variable.
fn extract_type_fn_check(expr: &php_ast::owned::Expr) -> Option<(&str, String)> {
    let ExprKind::FunctionCall(call) = &expr.kind else {
        return None;
    };
    let ExprKind::Identifier(name) = &call.name.kind else {
        return None;
    };
    let bare = name.as_ref().trim_start_matches('\\');
    let canonical = NARROWING_TYPE_FNS
        .iter()
        .find(|f| f.eq_ignore_ascii_case(bare))?;
    if call.args.len() != 1 {
        return None;
    }
    let var_name = extract_var_name(&call.args[0].value)?;
    Some((canonical, var_name))
}

/// Narrow `$x` to the union of every `is_TYPE($x)` truthy-narrowing
/// collected from `conditions`, when EVERY condition is a recognized
/// single-argument type-check call on the SAME variable — the scalar-type
/// counterpart to [`narrow_instanceof_disjuncts`], used for the same
/// `match(true)`/`switch(true)` fallthrough shape (`is_int($x)`,
/// `is_string($x)`, …) that instanceof-only narrowing doesn't cover.
///
/// Returns the narrowed variable name on success; `None` when the shape
/// doesn't apply (mixed condition kinds, or checks on different variables) —
/// the caller should fall back to narrowing each condition individually.
pub(crate) fn narrow_type_fn_disjuncts(
    conditions: &[&php_ast::owned::Expr],
    ctx: &mut FlowState,
) -> Option<String> {
    if conditions.len() < 2 {
        return None;
    }
    let mut var_name: Option<String> = None;
    let mut fn_names: Vec<&str> = Vec::with_capacity(conditions.len());
    for cond in conditions {
        let (fn_name, vn) = extract_type_fn_check(cond)?;
        match &var_name {
            None => var_name = Some(vn),
            Some(existing) if *existing == vn => {}
            _ => return None, // different variable — bail out
        }
        fn_names.push(fn_name);
    }
    let vn = var_name?;
    let original = ctx.get_var(&vn);
    let mut union_ty = Type::empty();
    for fn_name in &fn_names {
        let mut scratch = ctx.branch();
        scratch.set_var(&vn, original.clone());
        narrow_from_type_fn(&mut scratch, fn_name, &vn, true);
        union_ty.merge_with(&scratch.get_var(&vn));
    }
    if !union_ty.is_empty() {
        ctx.set_var(&vn, union_ty);
    }
    Some(vn)
}

/// For `$x instanceof A || $x instanceof B` (true branch): narrow $x to A|B.
/// Handles OR chains recursively, e.g. `$x instanceof A || $x instanceof B || $x instanceof C`.
/// Also handles the scalar-type-check counterpart (`is_int($x) || is_string($x)`)
/// via [`narrow_type_fn_disjuncts`] when the instanceof shape doesn't apply.
fn narrow_or_instanceof_true(
    left: &php_ast::owned::Expr,
    right: &php_ast::owned::Expr,
    ctx: &mut FlowState,
    db: &dyn MirDatabase,
    file: &str,
) {
    if narrow_instanceof_disjuncts(&[left, right], ctx, db, file).is_none() {
        narrow_type_fn_disjuncts(&[left, right], ctx);
    }
}

/// Apply short-circuit narrowing for isset() in || expressions (true branch).
///
/// Handles the PHP idiom: `!isset($x) || use($x)`
///
/// When the || operator's RHS is evaluated:
/// - If LHS is `!isset($x)`, then isset($x) must be TRUE in RHS
///   (because short-circuit: RHS only executes when LHS is false)
///
/// The narrowing is scoped to RHS analysis only and is restored afterward.
/// This ensures the if-body context isn't incorrectly narrowed.
fn narrow_or_isset_true(
    left: &php_ast::owned::Expr,
    right: &php_ast::owned::Expr,
    ctx: &mut FlowState,
    db: &dyn MirDatabase,
    file: &str,
) {
    // Pattern: !isset($x) || RHS
    // When RHS is evaluated via short-circuit, !isset($x) is false, so isset($x) is true
    if let ExprKind::UnaryPrefix(u) = &left.kind {
        if u.op == UnaryPrefixOp::BooleanNot {
            if let ExprKind::Isset(vars) = &u.operand.kind {
                // Save original variable states so narrowing only affects RHS analysis
                let original_vars: Vec<_> = vars
                    .iter()
                    .filter_map(|var_expr| {
                        extract_var_name(var_expr).map(|name| {
                            let was_assigned = ctx.var_is_defined(&name);
                            (name.clone(), ctx.get_var(&name), was_assigned)
                        })
                    })
                    .collect();

                // Apply isset narrowing: remove null and mark as definitely assigned
                for var_expr in vars.iter() {
                    if let Some(var_name) = extract_var_name(var_expr) {
                        let current = ctx.get_var(&var_name);
                        ctx.set_var(&var_name, current.remove_null());
                        std::sync::Arc::make_mut(&mut ctx.assigned_vars)
                            .insert(mir_types::Name::from(var_name.as_str()));
                    }
                }

                // Evaluate RHS with narrowed context
                narrow_from_condition(right, ctx, true, db, file);

                // Restore original variable states for if-body context
                for (var_name, original_type, was_assigned) in original_vars {
                    let sym = mir_types::Name::from(var_name.as_str());
                    std::sync::Arc::make_mut(&mut ctx.vars)
                        .insert(sym, mir_codebase::storage::wrap_var_type(original_type));
                    if !was_assigned {
                        std::sync::Arc::make_mut(&mut ctx.assigned_vars).remove(&sym);
                    }
                }
            }
        }
    }
}

fn narrow_instanceof_preserving_subtypes(
    current: &Type,
    class_name: &str,
    db: &dyn MirDatabase,
    template_param_names: &rustc_hash::FxHashSet<mir_types::Name>,
) -> Type {
    let narrowed_ty = Atomic::TNamedObject {
        fqcn: class_name.into(),
        type_params: mir_types::union::empty_type_params(),
    };

    if current.is_empty() || current.is_mixed_not_template() {
        return Type::single(narrowed_ty);
    }

    let mut result = Type::empty();
    result.possibly_undefined = current.possibly_undefined;
    result.from_docblock = current.from_docblock;

    for atomic in &current.types {
        match atomic {
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if named_object_matches_instanceof(fqcn, class_name, db) =>
            {
                result.add_type(atomic.clone());
            }
            // Handle template parameters: if a bare unqualified name matches a template param,
            // intersect it with the checked class rather than replacing it — the value is
            // still guaranteed to be a T (e.g. for a later `@return T`), just now also
            // known to be an instance of `class_name`.
            Atomic::TNamedObject { fqcn, type_params }
                if type_params.is_empty()
                    && !fqcn.contains('\\')
                    && template_param_names.contains(fqcn) =>
            {
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![
                        Type::single(atomic.clone()),
                        Type::single(narrowed_ty.clone()),
                    ]),
                });
            }
            // Handle TTemplateParam: intersect it with the instanceof check class instead
            // of discarding the template binding (see comment above).
            Atomic::TTemplateParam { .. } => {
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![
                        Type::single(atomic.clone()),
                        Type::single(narrowed_ty.clone()),
                    ]),
                });
            }
            Atomic::TObject | Atomic::TMixed => result.add_type(narrowed_ty.clone()),
            // `$x instanceof C` on an `A&B`-typed value adds C to the
            // intersection rather than replacing it — the value is still
            // guaranteed to be an A and a B, so dropping them here would
            // falsely reject valid uses of the original intersection.
            Atomic::TIntersection { parts } => {
                let already_covered = parts.iter().any(|p| {
                    p.types.iter().any(|a| {
                        matches!(a, Atomic::TNamedObject { fqcn, .. }
                            if named_object_matches_instanceof(fqcn, class_name, db))
                    })
                });
                if already_covered {
                    result.add_type(atomic.clone());
                } else {
                    let mut new_parts: Vec<Type> = parts.iter().cloned().collect();
                    new_parts.push(Type::single(narrowed_ty.clone()));
                    result.add_type(Atomic::TIntersection {
                        parts: std::sync::Arc::from(new_parts),
                    });
                }
            }
            // `class_name` is a (possibly indirect) subtype of the atom's own class
            // — e.g. atom is the `Foo` interface and class_name is `A implements
            // Foo` — so the instanceof check's result subsumes and is strictly
            // more specific than what's already known; replace outright rather
            // than forming a redundant `Foo&A` intersection.
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if named_object_matches_instanceof(class_name, fqcn, db) =>
            {
                result.add_type(narrowed_ty.clone());
            }
            // A named object unrelated to `class_name` by inheritance in either
            // direction (e.g. two interfaces neither of which extends the other,
            // as in `$x instanceof A && $x instanceof B`) must not be silently
            // discarded — the instanceof check proved the value ALSO satisfies
            // class_name. Form an intersection when that's actually possible
            // (at least one side is an interface, so a single object can
            // implement both); otherwise the atom's own class and class_name are
            // both concrete classes, which PHP's single inheritance makes
            // mutually exclusive, so the atom is provably impossible here and is
            // correctly dropped.
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if classes_can_coexist(fqcn, class_name, db) =>
            {
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![
                        Type::single(atomic.clone()),
                        Type::single(narrowed_ty.clone()),
                    ]),
                });
            }
            // A `Closure(...): R`-typed atom (its own dedicated atomic, not a
            // TNamedObject) genuinely IS an instance of `Closure` at runtime —
            // keep it as-is rather than falling through to the catch-all drop,
            // which would make `$x instanceof Closure` on a `Closure(): T`-typed
            // value look provably impossible.
            Atomic::TClosure { .. } if class_name.eq_ignore_ascii_case("Closure") => {
                result.add_type(atomic.clone());
            }
            _ => {}
        }
    }

    // Unlike the early-return above (truly unconstrained `mixed`/empty `current`),
    // reaching here with an empty `result` means `current` had at least one real
    // atom and NONE of them survived narrowing — every atom was proven
    // incompatible with `class_name` (e.g. two unrelated `final` classes).
    // Propagate the emptiness instead of resetting to a bare `narrowed_ty`, so
    // the caller's `mark_diverges` can correctly flag the branch as unreachable
    // instead of silently treating a provably-impossible instanceof as if
    // nothing were known about the value.
    result
}

/// Like [`narrow_instanceof_preserving_subtypes`], but for an OR-chain of
/// `instanceof` checks against several classes at once (`$x instanceof A ||
/// $x instanceof B`) — narrowing per-class-then-merging (as opposed to
/// per-atom-across-all-classes) double-counts `TIntersection` union members
/// unrelated to any single disjunct: `(A&B)|C|D` narrowed by `instanceof C ||
/// instanceof D` would otherwise produce two separate `A&B&C`/`A&B&D`
/// members instead of one `A&B&(C|D)` member, bloating the displayed type
/// and hiding it from later, more precise checks.
fn narrow_or_instanceof_union(
    current: &Type,
    class_names: &[String],
    db: &dyn MirDatabase,
    template_param_names: &rustc_hash::FxHashSet<mir_types::Name>,
) -> Type {
    let class_atom = |cn: &str| Atomic::TNamedObject {
        fqcn: cn.into(),
        type_params: mir_types::union::empty_type_params(),
    };

    if current.is_empty() || current.is_mixed_not_template() {
        let mut out = Type::empty();
        for cn in class_names {
            out.add_type(class_atom(cn));
        }
        return out;
    }

    let mut result = Type::empty();
    result.possibly_undefined = current.possibly_undefined;
    result.from_docblock = current.from_docblock;

    for atomic in &current.types {
        match atomic {
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if class_names
                    .iter()
                    .any(|cn| named_object_matches_instanceof(fqcn, cn, db)) =>
            {
                result.add_type(atomic.clone());
            }
            // As in narrow_instanceof_preserving_subtypes, keep the template atom by
            // intersecting it with the union of checked classes rather than replacing it.
            Atomic::TNamedObject { fqcn, type_params }
                if type_params.is_empty()
                    && !fqcn.contains('\\')
                    && template_param_names.contains(fqcn) =>
            {
                let mut classes = Type::empty();
                for cn in class_names {
                    classes.add_type(class_atom(cn));
                }
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![Type::single(atomic.clone()), classes]),
                });
            }
            Atomic::TTemplateParam { .. } => {
                let mut classes = Type::empty();
                for cn in class_names {
                    classes.add_type(class_atom(cn));
                }
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![Type::single(atomic.clone()), classes]),
                });
            }
            Atomic::TObject | Atomic::TMixed => {
                for cn in class_names {
                    result.add_type(class_atom(cn));
                }
            }
            Atomic::TIntersection { parts } => {
                let mut remaining = Type::empty();
                for cn in class_names {
                    let already_covered = parts.iter().any(|p| {
                        p.types.iter().any(|a| {
                            matches!(a, Atomic::TNamedObject { fqcn, .. }
                                if named_object_matches_instanceof(fqcn, cn, db))
                        })
                    });
                    if !already_covered {
                        remaining.add_type(class_atom(cn));
                    }
                }
                if remaining.is_empty() {
                    result.add_type(atomic.clone());
                } else {
                    let mut new_parts: Vec<Type> = parts.iter().cloned().collect();
                    new_parts.push(remaining);
                    result.add_type(Atomic::TIntersection {
                        parts: std::sync::Arc::from(new_parts),
                    });
                }
            }
            // Some disjunct(s) are a (possibly indirect) subtype of the atom's own
            // class — e.g. atom is `Foo` and one label checks `instanceof A` where
            // `A implements Foo` — so the instanceof result subsumes and is
            // strictly more specific; narrow to just the subsuming disjunct(s)
            // rather than forming a redundant `Foo&A` intersection.
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if class_names
                    .iter()
                    .any(|cn| named_object_matches_instanceof(cn, fqcn, db)) =>
            {
                for cn in class_names {
                    if named_object_matches_instanceof(cn, fqcn, db) {
                        result.add_type(class_atom(cn));
                    }
                }
            }
            // A named object matching none of the disjuncts by inheritance in
            // either direction must not be silently discarded — the
            // (already-true) instanceof check proved the value ALSO satisfies
            // one of class_names. Intersect with only the disjuncts that could
            // actually coexist with this atom (at least one side an interface);
            // a disjunct that's a concrete class unrelated to this atom's own
            // concrete class is impossible under PHP's single inheritance and is
            // dropped instead. Mirrors the equivalent fix in
            // narrow_instanceof_preserving_subtypes for the single-class case.
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn } => {
                let mut classes = Type::empty();
                for cn in class_names {
                    if classes_can_coexist(fqcn, cn, db) {
                        classes.add_type(class_atom(cn));
                    }
                }
                if !classes.is_empty() {
                    result.add_type(Atomic::TIntersection {
                        parts: std::sync::Arc::from(vec![Type::single(atomic.clone()), classes]),
                    });
                }
            }
            _ => {}
        }
    }

    if result.is_empty() {
        // No atomic in `current` extends/implements any disjunct (e.g.
        // `current` is an interface the disjuncts implement, not vice versa)
        // — mirrors narrow_instanceof_preserving_subtypes's fallback: assume
        // the instanceof check(s) narrow to the union of the checked classes
        // rather than silently keeping the pre-narrowing type.
        let mut out = Type::empty();
        for cn in class_names {
            out.add_type(class_atom(cn));
        }
        out
    } else {
        result
    }
}

/// Whether a value could simultaneously be (a subtype of) both `a` and `b` —
/// true when either is an interface (a class can implement any number of
/// interfaces), false when both are concrete classes, which PHP's single
/// inheritance makes mutually exclusive unless one already extends the other
/// (checked separately by the caller via `named_object_matches_instanceof`).
fn classes_can_coexist(a: &str, b: &str, db: &dyn MirDatabase) -> bool {
    crate::db::class_kind(db, a).is_some_and(|k| k.is_interface)
        || crate::db::class_kind(db, b).is_some_and(|k| k.is_interface)
}

fn filter_out_instanceof_match(current: &Type, class_name: &str, db: &dyn MirDatabase) -> Type {
    current.filter(|t| match t {
        Atomic::TNamedObject { fqcn, .. }
        | Atomic::TSelf { fqcn }
        | Atomic::TStaticObject { fqcn }
        | Atomic::TParent { fqcn } => !named_object_matches_instanceof(fqcn, class_name, db),
        // A&B is provably excluded by `!($x instanceof C)` when EITHER part
        // alone would satisfy it — a value that's simultaneously an A and a B
        // is also a C the moment either A or B extends/implements C, so the
        // whole intersection can't survive the negation, not just its own
        // (nonexistent) direct name.
        Atomic::TIntersection { parts } => !parts.iter().any(|part| {
            part.types.iter().any(|inner| match inner {
                Atomic::TNamedObject { fqcn, .. }
                | Atomic::TSelf { fqcn }
                | Atomic::TStaticObject { fqcn }
                | Atomic::TParent { fqcn } => named_object_matches_instanceof(fqcn, class_name, db),
                _ => false,
            })
        }),
        _ => true,
    })
}

fn named_object_matches_instanceof(fqcn: &str, class_name: &str, db: &dyn MirDatabase) -> bool {
    fqcn == class_name || crate::db::extends_or_implements(db, fqcn, class_name)
}

/// Narrow `current` for the true branch of `is_subclass_of($obj, 'ClassName')`.
///
/// Unlike `instanceof` / `is_a`, `is_subclass_of` requires a *strict* subclass:
/// the exact class itself is excluded. Atoms that are only the named class (not a
/// descendant) are dropped. Mixed/TObject are narrowed to the named class as the
/// best approximation (a value satisfying `is_subclass_of` must be some subclass,
/// and the named class is the tightest bound we can express).
fn narrow_strict_subclass_of(
    current: &Type,
    class_name: &str,
    db: &dyn MirDatabase,
    template_param_names: &rustc_hash::FxHashSet<mir_types::Name>,
) -> Type {
    let narrowed_ty = Atomic::TNamedObject {
        fqcn: class_name.into(),
        type_params: mir_types::union::empty_type_params(),
    };

    if current.is_empty() || current.is_mixed_not_template() {
        return Type::single(narrowed_ty);
    }

    let mut result = Type::empty();
    result.possibly_undefined = current.possibly_undefined;
    result.from_docblock = current.from_docblock;

    for atomic in &current.types {
        match atomic {
            // Strict subclass: keep only atoms that extend/implement without being the class itself.
            Atomic::TNamedObject { fqcn, .. }
            | Atomic::TSelf { fqcn }
            | Atomic::TStaticObject { fqcn }
            | Atomic::TParent { fqcn }
                if crate::db::extends_or_implements(db, fqcn.as_ref(), class_name)
                    && fqcn.as_ref() != class_name =>
            {
                result.add_type(atomic.clone());
            }
            // Template parameter — intersect with the named class rather than replacing it,
            // so the value is still known to be a T as well as a strict subclass of it.
            Atomic::TNamedObject { fqcn, type_params }
                if type_params.is_empty()
                    && !fqcn.contains('\\')
                    && template_param_names.contains(fqcn) =>
            {
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![
                        Type::single(atomic.clone()),
                        Type::single(narrowed_ty.clone()),
                    ]),
                });
            }
            Atomic::TTemplateParam { .. } => {
                result.add_type(Atomic::TIntersection {
                    parts: std::sync::Arc::from(vec![
                        Type::single(atomic.clone()),
                        Type::single(narrowed_ty.clone()),
                    ]),
                });
            }
            Atomic::TObject | Atomic::TMixed => result.add_type(narrowed_ty.clone()),
            _ => {}
        }
    }

    result
    // Note: no fallback to Type::single(narrowed_ty) when result is empty — if the
    // current type contains no known subclasses of the named class, the narrowing
    // returns empty and the caller should NOT mark diverges (is_subclass_of may still
    // be false at runtime for the exact class, which is valid).
}

/// Returns true if `expr` is the boolean literal `true`.
fn is_truthy_bool_literal(expr: &php_ast::owned::Expr) -> bool {
    matches!(expr.kind, php_ast::owned::ExprKind::Bool(true))
}

/// Apply a pre-computed narrowed type to a variable.
///
/// If `mark_diverges` is true and the narrowed type is empty (the current type
/// can never satisfy the constraint), the branch is marked unreachable.
fn set_narrowed(
    ctx: &mut FlowState,
    name: &str,
    current: &Type,
    narrowed: Type,
    mark_diverges: bool,
) {
    if !narrowed.is_empty() {
        ctx.set_var(name, narrowed);
    } else if mark_diverges && !current.is_empty() && !current.is_mixed() {
        ctx.diverges = true;
    }
}

/// Narrow a property access `$obj->prop` by a null check.
/// Looks up the declared property type through the database and stores the
/// narrowed result in `ctx.prop_refined`.
fn narrow_prop_null(
    ctx: &mut FlowState,
    obj_var: &str,
    prop: &str,
    db: &dyn MirDatabase,
    file: &str,
    is_null: bool,
) {
    // Get the current type: use an existing refinement if present, else look up
    // the declared type through the object variable's type.
    let current = if let Some(refined) = ctx.get_prop_refined(obj_var, prop) {
        refined.clone()
    } else {
        // Resolve through the object variable's type
        let obj_ty = ctx.get_var(obj_var);
        let mut prop_ty = mir_types::Type::mixed();
        'outer: for atomic in &obj_ty.types {
            if let mir_types::Atomic::TNamedObject { fqcn, .. } = atomic {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                // Try to find the property in the class chain
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                        break 'outer;
                    }
                }
            } else if let mir_types::Atomic::TSelf { fqcn }
            | mir_types::Atomic::TStaticObject { fqcn } = atomic
            {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                        break 'outer;
                    }
                }
            }
        }
        // Also try self_fqcn if obj_var is "this"
        if prop_ty.is_mixed() && obj_var == "this" {
            if let Some(fqcn) = ctx.self_fqcn.as_ref() {
                let resolved = crate::db::resolve_name(db, file, fqcn.as_ref());
                let here = crate::db::Fqcn::from_str(db, &resolved);
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                    }
                }
            }
        }
        prop_ty
    };

    if current.is_mixed() {
        return;
    }
    let narrowed = if is_null {
        current.narrow_to_null()
    } else {
        current.remove_null()
    };
    if narrowed != current {
        ctx.set_prop_refined(obj_var, prop, narrowed);
    }
}

/// Narrow a static property access `self::$prop`/`Class::$prop` by a null
/// check. `prop_refined` is keyed by FQCN here instead of a receiver
/// variable name — a FQCN string can never collide with a real PHP variable.
fn narrow_static_prop_null(
    ctx: &mut FlowState,
    fqcn: &str,
    prop: &str,
    db: &dyn MirDatabase,
    is_null: bool,
) {
    let current = if let Some(refined) = ctx.get_prop_refined(fqcn, prop) {
        refined.clone()
    } else {
        let here = crate::db::Fqcn::from_str(db, fqcn);
        crate::db::find_property_in_chain(db, here, prop)
            .and_then(|(_, p)| p.ty.as_deref().cloned())
            .unwrap_or_else(mir_types::Type::mixed)
    };

    if current.is_mixed() {
        return;
    }
    let narrowed = if is_null {
        current.narrow_to_null()
    } else {
        current.remove_null()
    };
    if narrowed != current {
        ctx.set_prop_refined(fqcn, prop, narrowed);
    }
}

fn narrow_prop_instanceof(
    ctx: &mut FlowState,
    obj_var: &str,
    prop: &str,
    class_name: &str,
    db: &dyn MirDatabase,
    file: &str,
    is_true: bool,
) {
    let current = if let Some(refined) = ctx.get_prop_refined(obj_var, prop) {
        refined.clone()
    } else {
        let obj_ty = ctx.get_var(obj_var);
        let mut prop_ty = mir_types::Type::mixed();
        'outer: for atomic in &obj_ty.types {
            if let mir_types::Atomic::TNamedObject { fqcn, .. } = atomic {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                        break 'outer;
                    }
                }
            } else if let mir_types::Atomic::TSelf { fqcn }
            | mir_types::Atomic::TStaticObject { fqcn } = atomic
            {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                        break 'outer;
                    }
                }
            }
        }
        if prop_ty.is_mixed() && obj_var == "this" {
            if let Some(fqcn) = ctx.self_fqcn.as_ref() {
                let resolved = crate::db::resolve_name(db, file, fqcn.as_ref());
                let here = crate::db::Fqcn::from_str(db, &resolved);
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                    }
                }
            }
        }
        prop_ty
    };

    if current.is_mixed_not_template() {
        return;
    }
    let narrowed = if is_true {
        narrow_instanceof_preserving_subtypes(&current, class_name, db, &ctx.template_param_names)
    } else {
        filter_out_instanceof_match(&current, class_name, db)
    };
    if narrowed != current {
        ctx.set_prop_refined(obj_var, prop, narrowed);
    }
}

/// Narrow a property's type when `array_key_exists('k', $this->prop)` is proven true.
fn narrow_prop_array_key_exists(
    ctx: &mut FlowState,
    obj_var: &str,
    prop: &str,
    key: &mir_types::atomic::ArrayKey,
    db: &dyn MirDatabase,
    file: &str,
) {
    let current = if let Some(refined) = ctx.get_prop_refined(obj_var, prop) {
        refined.clone()
    } else {
        let obj_ty = ctx.get_var(obj_var);
        let mut prop_ty = mir_types::Type::mixed();
        'outer: for atomic in &obj_ty.types {
            if let mir_types::Atomic::TNamedObject { fqcn, .. }
            | mir_types::Atomic::TSelf { fqcn }
            | mir_types::Atomic::TStaticObject { fqcn } = atomic
            {
                let here = crate::db::Fqcn::from_str(db, fqcn.as_ref());
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                        break 'outer;
                    }
                }
            }
        }
        if prop_ty.is_mixed() && obj_var == "this" {
            if let Some(fqcn) = ctx.self_fqcn.as_ref() {
                let resolved = crate::db::resolve_name(db, file, fqcn.as_ref());
                let here = crate::db::Fqcn::from_str(db, &resolved);
                if let Some((_, p_def)) = crate::db::find_property_in_chain(db, here, prop) {
                    if let Some(ty) = p_def.ty.as_deref() {
                        prop_ty = ty.clone();
                    }
                }
            }
        }
        prop_ty
    };
    if current.is_mixed() {
        return;
    }
    let narrowed = add_key_to_sealed_shapes(&current, key);
    if narrowed != current {
        ctx.set_prop_refined(obj_var, prop, narrowed);
    }
}

/// For each `TKeyedArray` in `ty` that does not already contain `key`: if
/// it's open, add `key` as non-optional `mixed` (an open shape might
/// genuinely carry it at runtime).
///
/// If it's sealed (`is_open == false`) AND `ty` is a real union of more than
/// one shape, exclude that member entirely instead — among a known finite
/// set of shape *alternatives*, one lacking the key can never satisfy
/// `array_key_exists()`, so keeping it let an impossible arm survive into
/// the true branch and widen later reads of that key to `mixed`.
///
/// A single (non-union) sealed shape lacking the key still falls back to
/// adding it as `mixed`, same as an open shape: a lone `@var array{a: T}`
/// docblock is a hint, not proof the underlying array can hold no other
/// key, so treating `array_key_exists` on an undeclared key as definitely
/// impossible would be a real false positive on ordinary runtime arrays.
fn add_key_to_sealed_shapes(
    ty: &mir_types::Type,
    key: &mir_types::atomic::ArrayKey,
) -> mir_types::Type {
    use mir_types::atomic::KeyedProperty;
    let is_real_union = ty.types.len() > 1;
    let mut changed = false;
    let mut result = mir_types::Type::empty();
    for a in &ty.types {
        if let Atomic::TKeyedArray {
            properties,
            is_open,
            is_list,
        } = a
        {
            if !properties.contains_key(key) {
                changed = true;
                if *is_open || !is_real_union {
                    let mut new_props = properties.clone();
                    new_props.insert(
                        key.clone(),
                        KeyedProperty {
                            ty: mir_types::Type::mixed(),
                            optional: false,
                        },
                    );
                    result.add_type(Atomic::TKeyedArray {
                        properties: new_props,
                        is_open: *is_open,
                        is_list: *is_list,
                    });
                }
                continue;
            }
        }
        result.add_type(a.clone());
    }
    if !changed {
        return ty.clone();
    }
    // Every union member turned out to be an impossible closed shape — keep
    // the original type rather than narrowing to an empty union.
    if result.types.is_empty() {
        return ty.clone();
    }
    result.from_docblock = ty.from_docblock;
    result
}

/// Extract a signed integer literal from an expression, handling negation.
fn extract_int_literal(expr: &php_ast::owned::Expr) -> Option<i64> {
    let e = peel_parens(expr);
    match &e.kind {
        ExprKind::Int(n) => Some(*n),
        ExprKind::UnaryPrefix(u) if u.op == UnaryPrefixOp::Negate => {
            if let ExprKind::Int(n) = &u.operand.kind {
                n.checked_neg()
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Flip a comparison operator for when operands are swapped (`5 > $x` → `$x < 5`).
fn flip_comparison_op(op: BinaryOp) -> BinaryOp {
    match op {
        BinaryOp::Less => BinaryOp::Greater,
        BinaryOp::LessOrEqual => BinaryOp::GreaterOrEqual,
        BinaryOp::Greater => BinaryOp::Less,
        BinaryOp::GreaterOrEqual => BinaryOp::LessOrEqual,
        other => other,
    }
}

/// Narrow a variable by a comparison `$var op n` being `is_true`.
fn narrow_var_int_comparison(ctx: &mut FlowState, name: &str, op: BinaryOp, n: i64, is_true: bool) {
    // Determine the range constraint when the condition holds.
    // Negation (`!is_true`) flips the constraint (e.g. NOT `< N` becomes `>= N`).
    let (min, max): (Option<i64>, Option<i64>) = match (op, is_true) {
        (BinaryOp::Less, true) | (BinaryOp::GreaterOrEqual, false) => (None, n.checked_sub(1)),
        (BinaryOp::LessOrEqual, true) | (BinaryOp::Greater, false) => (None, Some(n)),
        (BinaryOp::Greater, true) | (BinaryOp::LessOrEqual, false) => (n.checked_add(1), None),
        (BinaryOp::GreaterOrEqual, true) | (BinaryOp::Less, false) => (Some(n), None),
        _ => return,
    };
    let current = ctx.get_var(name);
    let narrowed = narrow_type_to_int_range(&current, min, max);
    // Mark the branch unreachable only when the current type is "closed precise"
    // (a bounded int range, named int subtype, or literal union) — these only arise
    // from docblocks/inference, so an empty intersection is a real contradiction.
    // A plain `int` narrowed to an empty range is just conservative widening, not a bug.
    let mark_diverges = crate::contradiction::is_closed_precise(&current);
    set_narrowed(ctx, name, &current, narrowed, mark_diverges);
}

/// Apply integer bounds `[min, max]` to all integer components of a type.
///
/// Integer atoms (`int`, `int<a,b>`, literal ints) that fall within the bounds
/// are kept (possibly tightened); those that provably fall outside are removed.
/// Non-integer atoms pass through unchanged so the narrowing is always safe.
fn narrow_type_to_int_range(ty: &Type, min: Option<i64>, max: Option<i64>) -> Type {
    let in_bounds = |v: i64| min.is_none_or(|lo| v >= lo) && max.is_none_or(|hi| v <= hi);
    let mut result = Type::empty();
    result.from_docblock = ty.from_docblock;
    for atomic in &ty.types {
        match atomic {
            Atomic::TInt => {
                result.add_type(Atomic::TIntRange { min, max });
            }
            // Named int subtypes carry implicit bounds; intersect rather than replace.
            Atomic::TPositiveInt => {
                intersect_int_range_into(&mut result, Some(1), None, min, max);
            }
            Atomic::TNonNegativeInt => {
                intersect_int_range_into(&mut result, Some(0), None, min, max);
            }
            Atomic::TNegativeInt => {
                intersect_int_range_into(&mut result, None, Some(-1), min, max);
            }
            Atomic::TIntRange {
                min: cur_min,
                max: cur_max,
            } => {
                intersect_int_range_into(&mut result, *cur_min, *cur_max, min, max);
            }
            Atomic::TLiteralInt(v) => {
                if in_bounds(*v) {
                    result.add_type(atomic.clone());
                }
            }
            _ => {
                result.add_type(atomic.clone());
            }
        }
    }
    result
}

/// Intersect `(existing_min, existing_max)` with `(narrow_min, narrow_max)` and push
/// the result into `out`, skipping the intersection if it is provably empty.
fn intersect_int_range_into(
    out: &mut Type,
    existing_min: Option<i64>,
    existing_max: Option<i64>,
    narrow_min: Option<i64>,
    narrow_max: Option<i64>,
) {
    let new_min = match (existing_min, narrow_min) {
        (Some(a), Some(b)) => Some(a.max(b)),
        (None, v) | (v, None) => v,
    };
    let new_max = match (existing_max, narrow_max) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (None, v) | (v, None) => v,
    };
    if let (Some(lo), Some(hi)) = (new_min, new_max) {
        if lo > hi {
            return; // Empty intersection — this arm is unreachable
        }
    }
    out.add_type(Atomic::TIntRange {
        min: new_min,
        max: new_max,
    });
}

/// Narrow all `TString` atoms to `TNonEmptyString`, preserving other atoms.
/// Used when a condition proves the string is non-empty.
fn narrow_string_to_non_empty(ty: &Type) -> Type {
    let mut result = Type::empty();
    result.from_docblock = ty.from_docblock;
    for t in &ty.types {
        match t {
            Atomic::TString => result.add_type(Atomic::TNonEmptyString),
            _ => result.add_type(t.clone()),
        }
    }
    result
}

fn narrow_var_null(ctx: &mut FlowState, name: &str, is_null: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_null {
        current.narrow_to_null()
    } else {
        current.remove_null()
    };
    set_narrowed(ctx, name, &current, narrowed, true);
}

fn narrow_var_bool(ctx: &mut FlowState, name: &str, value: bool, is_value: bool) {
    let current = ctx.get_var(name);
    // `TBool` (PHP `bool`) must be split into TTrue/TFalse rather than kept wholesale.
    // e.g. `$x: bool; if ($x === false)` → true-branch should be `false`, not `bool`.
    let mut narrowed = Type::empty();
    narrowed.from_docblock = current.from_docblock;
    for t in &current.types {
        let keep = match t {
            Atomic::TBool => {
                // Split: narrow TBool to the specific literal being tested.
                if is_value {
                    let lit = if value { Atomic::TTrue } else { Atomic::TFalse };
                    narrowed.add_type(lit);
                } else {
                    let lit = if value { Atomic::TFalse } else { Atomic::TTrue };
                    narrowed.add_type(lit);
                }
                false // handled above — don't fall through
            }
            Atomic::TTrue => is_value == value,
            Atomic::TFalse => is_value != value,
            Atomic::TMixed => true,
            _ => !is_value, // non-bool atoms: keep only when narrowing away
        };
        if keep {
            narrowed.add_type(t.clone());
        }
    }
    set_narrowed(ctx, name, &current, narrowed, false);
}

fn narrow_from_type_fn(ctx: &mut FlowState, fn_name: &str, var_name: &str, is_true: bool) {
    let current = ctx.get_var(var_name);
    let narrowed = match crate::util::php_ident_lowercase(fn_name).as_str() {
        "is_string" => {
            if is_true {
                current.narrow_to_string()
            } else {
                current.filter(|t| !t.is_string())
            }
        }
        "is_int" | "is_integer" | "is_long" => {
            if is_true {
                current.narrow_to_int()
            } else {
                current.filter(|t| !t.is_int())
            }
        }
        "is_float" | "is_double" | "is_real" => {
            if is_true {
                current.narrow_to_float()
            } else {
                current.filter(|t| !matches!(t, Atomic::TFloat | Atomic::TLiteralFloat(..)))
            }
        }
        "is_bool" => {
            if is_true {
                current.narrow_to_bool()
            } else {
                current.filter(|t| !matches!(t, Atomic::TBool | Atomic::TTrue | Atomic::TFalse))
            }
        }
        "is_null" => {
            if is_true {
                current.narrow_to_null()
            } else {
                current.remove_null()
            }
        }
        "is_array" => {
            if is_true {
                current.narrow_to_array()
            } else {
                current.filter(|t| !t.is_array())
            }
        }
        "array_is_list" => {
            if is_true {
                current.narrow_to_list()
            } else {
                current
                    .filter(|t| !matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
            }
        }
        "is_object" => {
            if is_true {
                current.narrow_to_object()
            } else {
                current.filter(|t| !t.is_object())
            }
        }
        "is_callable" => {
            if is_true {
                current.narrow_to_callable()
            } else {
                current.filter(|t| !t.is_callable())
            }
        }
        "is_scalar" => {
            if is_true {
                current.narrow_to_scalar()
            } else {
                current.filter(|t| {
                    !t.is_string()
                        && !t.is_int()
                        && !matches!(
                            t,
                            Atomic::TFloat
                                | Atomic::TIntegralFloat
                                | Atomic::TLiteralFloat(..)
                                | Atomic::TBool
                                | Atomic::TTrue
                                | Atomic::TFalse
                                | Atomic::TScalar
                                | Atomic::TNumeric
                        )
                })
            }
        }
        "is_iterable" => {
            if is_true {
                current.narrow_to_iterable()
            } else {
                current.filter(|t| !t.is_array() && !t.is_object())
            }
        }
        "is_countable" => {
            if is_true {
                current.narrow_to_countable()
            } else {
                current.filter(|t| !t.is_array() && !t.is_object())
            }
        }
        "is_resource" => {
            if is_true {
                current.narrow_to_resource()
            } else {
                // Exclude nothing (no resource type exists); return unchanged
                current.clone()
            }
        }
        "is_numeric" => {
            if is_true {
                // In the truthy branch: keep numeric types and string types that
                // *could* be numeric. TString / TNonEmptyString narrow to TNumericString
                // (a string proven to be numeric-valued). All int and float variants are
                // always numeric. TMixed is kept as-is.
                let mut narrowed_parts = Type::empty();
                for t in &current.types {
                    match t {
                        // All int and float variants are unconditionally numeric.
                        Atomic::TInt
                        | Atomic::TIntRange { .. }
                        | Atomic::TPositiveInt
                        | Atomic::TNonNegativeInt
                        | Atomic::TNegativeInt
                        | Atomic::TLiteralInt(_)
                        | Atomic::TFloat
                        | Atomic::TIntegralFloat
                        | Atomic::TLiteralFloat(..)
                        | Atomic::TNumeric
                        | Atomic::TNumericString => {
                            narrowed_parts.add_type(t.clone());
                        }
                        // A generic string could be numeric; narrow to numeric-string.
                        Atomic::TString | Atomic::TNonEmptyString => {
                            narrowed_parts.add_type(Atomic::TNumericString);
                        }
                        // A literal string is numeric only if it parses as a number.
                        Atomic::TLiteralString(s) if is_numeric_string(s) => {
                            narrowed_parts.add_type(t.clone());
                        }
                        Atomic::TScalar | Atomic::TMixed => {
                            narrowed_parts.add_type(t.clone());
                        }
                        _ => {} // non-numeric types are excluded
                    }
                }
                narrowed_parts
            } else {
                current.filter(|t| {
                    !matches!(
                        t,
                        Atomic::TInt
                            | Atomic::TIntRange { .. }
                            | Atomic::TPositiveInt
                            | Atomic::TNonNegativeInt
                            | Atomic::TNegativeInt
                            | Atomic::TFloat
                            | Atomic::TIntegralFloat
                            | Atomic::TNumeric
                            | Atomic::TNumericString
                            | Atomic::TLiteralInt(_)
                            | Atomic::TLiteralFloat(..)
                    ) && !matches!(t, Atomic::TLiteralString(s) if is_numeric_string(s))
                })
            }
        }
        // method_exists($obj, 'method') — if true, narrow to TObject (suppresses
        // UndefinedMethod; the concrete type is unresolvable without knowing the method arg)
        "method_exists" | "property_exists" => {
            if is_true {
                Type::single(Atomic::TObject)
            } else {
                current.clone()
            }
        }
        _ => return,
    };
    set_narrowed(ctx, var_name, &current, narrowed, true);
}

fn narrow_var_literal_string(ctx: &mut FlowState, name: &str, value: &str, is_value: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_value {
        let lit: std::sync::Arc<str> = std::sync::Arc::from(value);
        let mut result = Type::empty();
        result.from_docblock = current.from_docblock;
        for t in &current.types {
            match t {
                Atomic::TLiteralString(s) if s.as_ref() == value => {
                    result.add_type(t.clone());
                }
                // Generic/wide string types: keep as-is (we can't narrow further without
                // knowing the literal's place in a union)
                Atomic::TString | Atomic::TScalar | Atomic::TMixed => {
                    result.add_type(t.clone());
                }
                // String subtypes: the literal could satisfy them — narrow to the literal.
                Atomic::TNonEmptyString if !value.is_empty() => {
                    result.add_type(Atomic::TLiteralString(lit.clone()));
                }
                Atomic::TNumericString if is_numeric_string(value) => {
                    result.add_type(Atomic::TLiteralString(lit.clone()));
                }
                Atomic::TCallableString
                | Atomic::TClassString(_)
                | Atomic::TInterfaceString(_)
                | Atomic::TEnumString
                | Atomic::TTraitString => {
                    result.add_type(Atomic::TLiteralString(lit.clone()));
                }
                _ => {} // non-string or non-matching literal — filtered out
            }
        }
        result
    } else {
        current.filter(|t| !matches!(t, Atomic::TLiteralString(s) if s.as_ref() == value))
    };
    set_narrowed(ctx, name, &current, narrowed, false);
}

fn narrow_var_literal_int(ctx: &mut FlowState, name: &str, value: i64, is_value: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_value {
        let int_contains = |min: Option<i64>, max: Option<i64>| {
            min.is_none_or(|lo| value >= lo) && max.is_none_or(|hi| value <= hi)
        };
        let mut result = Type::empty();
        result.from_docblock = current.from_docblock;
        for t in &current.types {
            match t {
                Atomic::TLiteralInt(n) if *n == value => {
                    result.add_type(t.clone());
                }
                Atomic::TInt | Atomic::TScalar | Atomic::TNumeric | Atomic::TMixed => {
                    result.add_type(t.clone());
                }
                Atomic::TIntRange { min, max } if int_contains(*min, *max) => {
                    result.add_type(Atomic::TLiteralInt(value));
                }
                Atomic::TPositiveInt if int_contains(Some(1), None) => {
                    result.add_type(Atomic::TLiteralInt(value));
                }
                Atomic::TNonNegativeInt if int_contains(Some(0), None) => {
                    result.add_type(Atomic::TLiteralInt(value));
                }
                Atomic::TNegativeInt if int_contains(None, Some(-1)) => {
                    result.add_type(Atomic::TLiteralInt(value));
                }
                _ => {}
            }
        }
        result
    } else {
        // Remove the excluded literal from the type.  For named int subtypes and
        // int ranges, also tighten the bound when the excluded value sits exactly
        // at the lower or upper edge.
        let tighten = |min: Option<i64>, max: Option<i64>| {
            let (new_min, new_max) = if min == Some(value) {
                (value.checked_add(1), max)
            } else if max == Some(value) {
                (min, value.checked_sub(1))
            } else {
                return None; // excluded value is not on an edge — keep as-is
            };
            // Canonicalise tightened ranges back to named subtypes.
            let atom = match (new_min, new_max) {
                (Some(1), None) => Atomic::TPositiveInt,
                (Some(0), None) => Atomic::TNonNegativeInt,
                (None, Some(-1)) => Atomic::TNegativeInt,
                (None, None) => Atomic::TInt,
                (min, max) => Atomic::TIntRange { min, max },
            };
            Some(atom)
        };
        let mut result = Type::empty();
        result.from_docblock = current.from_docblock;
        for t in &current.types {
            match t {
                Atomic::TLiteralInt(n) if *n == value => {} // excluded
                Atomic::TIntRange { min, max } => {
                    if let Some(tightened) = tighten(*min, *max) {
                        // Skip the atom entirely when tightening produced an empty
                        // range (lo > hi). This correctly empties the result for
                        // single-point ranges like `int<1,1>` when excluding 1.
                        let is_empty_range = matches!(
                            &tightened,
                            Atomic::TIntRange { min: Some(lo), max: Some(hi) } if lo > hi
                        );
                        if !is_empty_range {
                            result.add_type(tightened);
                        }
                    } else {
                        result.add_type(t.clone());
                    }
                }
                Atomic::TPositiveInt => {
                    if let Some(tightened) = tighten(Some(1), None) {
                        result.add_type(tightened);
                    } else {
                        result.add_type(t.clone());
                    }
                }
                Atomic::TNonNegativeInt => {
                    if let Some(tightened) = tighten(Some(0), None) {
                        result.add_type(tightened);
                    } else {
                        result.add_type(t.clone());
                    }
                }
                Atomic::TNegativeInt => {
                    if let Some(tightened) = tighten(None, Some(-1)) {
                        result.add_type(tightened);
                    } else {
                        result.add_type(t.clone());
                    }
                }
                _ => result.add_type(t.clone()),
            }
        }
        result
    };
    // For closed-precise types (bounded ranges, named int subtypes, literal unions),
    // an empty result means the exclusion is a genuine contradiction — mark divergence.
    let mark_diverges = crate::contradiction::is_closed_precise(&current);
    set_narrowed(ctx, name, &current, narrowed, mark_diverges);
}

/// If `ty` contains an atomic referring to the WHOLE enum `enum_fqcn` (a
/// plain `TNamedObject` — e.g. a `Status $s` parameter that was never
/// narrowed to individual cases), replace that atomic with a union of
/// `TLiteralEnumCase` for every case the enum declares. Atoms that already
/// are per-case literals, or refer to something else entirely, pass through
/// unchanged. Falls back to `ty` unchanged if the enum can't be resolved or
/// nothing needed expanding.
fn expand_enum_to_cases(db: &dyn MirDatabase, ty: &Type, enum_fqcn: &str) -> Type {
    if !ty
        .types
        .iter()
        .any(|a| matches!(a, Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == enum_fqcn))
    {
        return ty.clone();
    }
    let Some(crate::db::ClassLike::Enum(e)) =
        crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, enum_fqcn))
    else {
        return ty.clone();
    };
    let mut result = Type::empty();
    result.possibly_undefined = ty.possibly_undefined;
    result.from_docblock = ty.from_docblock;
    for atomic in &ty.types {
        match atomic {
            Atomic::TNamedObject { fqcn, .. } if fqcn.as_ref() == enum_fqcn => {
                for case_name in e.cases.keys() {
                    result.add_type(Atomic::TLiteralEnumCase {
                        enum_fqcn: enum_fqcn.into(),
                        case_name: case_name.as_ref().into(),
                    });
                }
            }
            other => result.add_type(other.clone()),
        }
    }
    result
}

fn narrow_var_to_literal_enum_case(
    db: &dyn MirDatabase,
    ctx: &mut FlowState,
    name: &str,
    enum_fqcn: &str,
    case_name: &str,
    is_case: bool,
) {
    let current = ctx.get_var(name);
    let narrowed = if is_case {
        Type::single(Atomic::TLiteralEnumCase {
            enum_fqcn: enum_fqcn.into(),
            case_name: case_name.into(),
        })
    } else {
        // For !== comparison with enum case, remove that specific case from
        // the union. `current` may not already be decomposed into per-case
        // TLiteralEnumCase atoms (e.g. a plain `Status $s` parameter typed
        // as the whole enum) — expand it first, or the filter below matches
        // nothing and the exclusion silently does nothing.
        expand_enum_to_cases(db, &current, enum_fqcn).filter(|t| {
            !matches!(t, Atomic::TLiteralEnumCase { enum_fqcn: fqcn, case_name: c }
                if fqcn.as_ref() == enum_fqcn && c.as_ref() == case_name)
        })
    };
    set_narrowed(ctx, name, &current, narrowed, true);
}

fn narrow_var_to_class_string(ctx: &mut FlowState, name: &str, fqcn: &str, is_class: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_class {
        Type::single(Atomic::TClassString(Some(mir_types::Name::from(fqcn))))
    } else {
        current.filter(|t| !matches!(t, Atomic::TClassString(Some(f)) if f.as_ref() == fqcn))
    };
    set_narrowed(ctx, name, &current, narrowed, true);
}

fn narrow_var_to_specific_class(ctx: &mut FlowState, name: &str, fqcn: &str, is_exact_class: bool) {
    let current = ctx.get_var(name);
    let narrowed = if is_exact_class {
        Type::single(Atomic::TNamedObject {
            fqcn: fqcn.into(),
            type_params: mir_types::union::empty_type_params(),
        })
    } else {
        current.filter(|t| match t {
            Atomic::TNamedObject { fqcn: obj_fqcn, .. } => obj_fqcn.as_ref() != fqcn,
            _ => true,
        })
    };
    set_narrowed(ctx, name, &current, narrowed, true);
}

/// Extract a fully-qualified class name from the first argument of
/// `class_exists()` / `interface_exists()` / `trait_exists()`.
///
/// Recognised forms:
/// - `\Foo\Bar::class` or `Foo\Bar::class` — resolved via `crate::db::resolve_name`
/// - `'Foo\Bar'` or `'Foo\\Bar'` — string literals
pub(crate) fn extract_class_fqcn_from_expr(
    expr: &php_ast::owned::Expr,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<std::sync::Arc<str>> {
    let expr = peel_parens(expr);
    match &expr.kind {
        // \Foo\Bar::class  or  Foo\Bar::class
        ExprKind::ClassConstAccess(cca) => {
            if let ExprKind::Identifier(id) = &cca.class.kind {
                let member = match &cca.member.kind {
                    ExprKind::Identifier(s) => s.as_ref(),
                    _ => return None,
                };
                if member.eq_ignore_ascii_case("class") {
                    let resolved = crate::db::resolve_name(db, file, id.as_ref());
                    if !matches!(resolved.as_str(), "self" | "static" | "parent") {
                        return Some(std::sync::Arc::from(resolved.as_str()));
                    }
                }
            }
            None
        }
        // 'Foo\Bar'  or  'Foo\\Bar'  or  'Foo'
        ExprKind::String(s) => {
            let name = s.as_ref().trim_start_matches('\\');
            if !name.is_empty() {
                Some(std::sync::Arc::from(name))
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Extract `(obj_var, prop_name)` from a simple `$var->prop` expression.
fn extract_prop_access(expr: &php_ast::owned::Expr) -> Option<(String, String)> {
    match &expr.kind {
        ExprKind::PropertyAccess(pa) => {
            let obj = extract_var_name(&pa.object)?;
            let prop = match &pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref().to_string(),
                _ => return None,
            };
            Some((obj, prop))
        }
        ExprKind::Parenthesized(inner) => extract_prop_access(inner),
        _ => None,
    }
}

/// Extract `(fqcn, prop_name)` from a `self::$prop` / `static::$prop` /
/// `parent::$prop` / `ClassName::$prop` expression, resolving relative
/// keywords through the current `FlowState`.
fn extract_static_prop_access(
    expr: &php_ast::owned::Expr,
    ctx: &FlowState,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<(std::sync::Arc<str>, String)> {
    match &expr.kind {
        ExprKind::StaticPropertyAccess(spa) => {
            let id = match &spa.class.kind {
                ExprKind::Identifier(id) => id,
                _ => return None,
            };
            let resolved = crate::db::resolve_name(db, file, id.as_ref());
            let fqcn = match resolved.as_str() {
                "self" | "static" => ctx.self_fqcn.clone().or_else(|| ctx.static_fqcn.clone())?,
                "parent" => ctx.parent_fqcn.clone()?,
                s => std::sync::Arc::from(s),
            };
            let prop = match &spa.member.kind {
                ExprKind::Variable(name) | ExprKind::Identifier(name) => {
                    name.trim_start_matches('$').to_string()
                }
                _ => return None,
            };
            Some((fqcn, prop))
        }
        ExprKind::Parenthesized(inner) => extract_static_prop_access(inner, ctx, db, file),
        _ => None,
    }
}

fn extract_var_name(expr: &php_ast::owned::Expr) -> Option<String> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(name.trim_start_matches('$').to_string()),
        ExprKind::Parenthesized(inner) => extract_var_name(inner),
        // is_null($x = expr) — narrow the assigned variable, not the RHS
        ExprKind::Assign(a) if matches!(a.op, AssignOp::Assign) => extract_var_name(&a.target),
        _ => None,
    }
}

/// Extract a compact key for simple expressions used as the first arg of
/// `method_exists`/`property_exists`. Supports `$var` → `"var"` and
/// `$var->prop` → `"var->prop"` (depth-1 only). Returns `None` for anything
/// more complex so we don't risk false-positive suppression.
pub(crate) fn extract_expr_guard_key(expr: &php_ast::owned::Expr) -> Option<std::sync::Arc<str>> {
    match &expr.kind {
        ExprKind::Variable(name) => Some(std::sync::Arc::from(name.trim_start_matches('$'))),
        ExprKind::Parenthesized(inner) => extract_expr_guard_key(inner),
        ExprKind::PropertyAccess(pa) => {
            let base = extract_var_name(&pa.object)?;
            let prop = match &pa.property.kind {
                ExprKind::Identifier(s) => s.as_ref(),
                ExprKind::Variable(s) => s.trim_start_matches('$'),
                _ => return None,
            };
            Some(std::sync::Arc::from(format!("{base}->{prop}").as_str()))
        }
        _ => None,
    }
}

/// The base variable name of a (possibly nested) array-access expression:
/// `$a[1][2]` → `a`. Returns `None` if the base is not a plain variable.
fn array_access_base_var(expr: &php_ast::owned::Expr) -> Option<String> {
    match &expr.kind {
        ExprKind::ArrayAccess(aa) => array_access_base_var(&aa.array),
        ExprKind::Variable(name) => Some(name.trim_start_matches('$').to_string()),
        ExprKind::Parenthesized(inner) => array_access_base_var(inner),
        _ => None,
    }
}

/// For a single-level `isset($base['key'])` where `$base` is (partly) a known
/// shape, narrow that key's own property: remove `null` from its value type
/// and mark it no longer optional. Multi-level access (`isset($a['b']['c'])`)
/// and non-literal keys are left alone — not worth the added complexity here.
fn narrow_isset_shape_key(var_expr: &php_ast::owned::Expr, ctx: &mut FlowState) {
    let ExprKind::ArrayAccess(aa) = &var_expr.kind else {
        return;
    };
    let Some(base) = extract_var_name(&aa.array) else {
        return;
    };
    let Some(idx) = &aa.index else {
        return;
    };
    let key = match &idx.kind {
        ExprKind::String(s) => {
            mir_types::atomic::ArrayKey::String(std::sync::Arc::from(s.as_ref()))
        }
        ExprKind::Int(i) => mir_types::atomic::ArrayKey::Int(*i),
        _ => return,
    };

    let current = ctx.get_var(&base);
    let mut changed = false;
    let mut result = Type::empty();
    for atomic in &current.types {
        match atomic {
            Atomic::TKeyedArray {
                properties,
                is_open,
                is_list,
            } => {
                if properties.contains_key(&key) {
                    let mut new_props = properties.clone();
                    if let Some(prop) = new_props.get_mut(&key) {
                        let narrowed_ty = prop.ty.remove_null();
                        if !narrowed_ty.is_empty() {
                            prop.ty = narrowed_ty;
                        }
                        prop.optional = false;
                    }
                    changed = true;
                    result.add_type(Atomic::TKeyedArray {
                        properties: new_props,
                        is_open: *is_open,
                        is_list: *is_list,
                    });
                } else if *is_open {
                    // An open shape might still carry the key at runtime —
                    // keep it (unnarrowed) rather than dropping it.
                    result.add_type(atomic.clone());
                } else {
                    // A closed shape without this key can never satisfy
                    // isset() — this union member is impossible in the true
                    // branch, so exclude it instead of leaving it to be
                    // treated as if the key existed.
                    changed = true;
                }
            }
            _ => result.add_type(atomic.clone()),
        }
    }
    // If every union member turned out to be an impossible closed shape, keep
    // the original type rather than narrowing to an empty union — proving
    // the branch itself unreachable is a separate concern from key narrowing.
    if changed && !result.types.is_empty() {
        ctx.set_var(&base, result);
    }
}

fn extract_null_coalesce(expr: &php_ast::owned::Expr) -> Option<&php_ast::owned::NullCoalesceExpr> {
    match &expr.kind {
        ExprKind::NullCoalesce(nc) => Some(nc),
        ExprKind::Parenthesized(inner) => extract_null_coalesce(inner),
        _ => None,
    }
}

fn same_literal(a: &php_ast::owned::Expr, b: &php_ast::owned::Expr) -> bool {
    let a = peel_parens(a);
    let b = peel_parens(b);
    match (&a.kind, &b.kind) {
        (ExprKind::Null, ExprKind::Null) => true,
        (ExprKind::Bool(a), ExprKind::Bool(b)) => a == b,
        (ExprKind::Int(a), ExprKind::Int(b)) => a == b,
        (ExprKind::String(a), ExprKind::String(b)) => a == b,
        _ => false,
    }
}

fn peel_parens(expr: &php_ast::owned::Expr) -> &php_ast::owned::Expr {
    match &expr.kind {
        ExprKind::Parenthesized(inner) => peel_parens(inner),
        _ => expr,
    }
}

/// `self`/`static`/`parent` are bare keywords, not real class names —
/// `db::resolve_name` deliberately returns them unresolved (it has no class
/// context), so they must be resolved to a concrete FQCN here, where the
/// surrounding class context (`self_fqcn`/`parent_fqcn`) is available.
/// `static` resolves to `self_fqcn` too: it's late-static-binding, so the
/// exact runtime class is unknown, but `self_fqcn` is its precise lower
/// bound — the same approximation `Atomic::TStaticObject` uses elsewhere.
fn extract_class_name(
    expr: &php_ast::owned::Expr,
    self_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
) -> Option<String> {
    match &expr.kind {
        ExprKind::Identifier(name) => match name.to_ascii_lowercase().as_str() {
            "self" | "static" => self_fqcn.map(|s| s.to_string()),
            "parent" => parent_fqcn.map(|s| s.to_string()),
            _ => Some(name.to_string()),
        },
        ExprKind::Variable(name) if name.trim_start_matches('$') == "this" => {
            self_fqcn.map(|s| s.to_string())
        }
        ExprKind::Variable(_) => None, // dynamic class — can't narrow
        _ => None,
    }
}

fn extract_enum_case(
    expr: &php_ast::owned::Expr,
    self_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<(String, String)> {
    // Real `EnumName::CaseName` syntax parses as `ClassConstAccess` (the same
    // node shape used for `Foo::class` and plain class constants) — not
    // `StaticPropertyAccess`, which is reserved for `Foo::$prop` (the `$`
    // sigil enum-case access never has). Accept both node kinds structurally
    // and disambiguate by confirming the target actually is a declared case
    // of a real enum, so `Foo::BAR` (a plain class constant) and `Foo::class`
    // aren't misread as case narrowing.
    let spa = match &expr.kind {
        ExprKind::StaticPropertyAccess(spa) => spa,
        ExprKind::ClassConstAccess(cca) => cca,
        _ => return None,
    };
    let enum_short_name = extract_class_name(&spa.class, self_fqcn, parent_fqcn)?;
    let enum_fqcn = crate::db::resolve_name(db, file, &enum_short_name);
    let ExprKind::Identifier(case_name) = &spa.member.kind else {
        return None;
    };
    let is_declared_case = matches!(
        crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, &enum_fqcn)),
        Some(crate::db::ClassLike::Enum(e)) if e.cases.contains_key(case_name.as_ref())
    );
    if !is_declared_case {
        return None;
    }
    Some((enum_fqcn, case_name.to_string()))
}

fn extract_class_const_fqcn(
    cca: &php_ast::owned::StaticAccessExpr,
    self_fqcn: Option<&str>,
    parent_fqcn: Option<&str>,
    db: &dyn MirDatabase,
    file: &str,
) -> Option<String> {
    let is_class = matches!(&cca.member.kind, ExprKind::Identifier(n) if n.as_ref() == "class");
    if !is_class {
        return None;
    }
    let short = extract_class_name(&cca.class, self_fqcn, parent_fqcn)?;
    Some(crate::db::resolve_name(db, file, &short))
}

/// Promote variables that were assigned as side effects of evaluating `expr`.
///
/// Called when we know `expr` was definitely evaluated (e.g., from the true-branch
/// of `&&` or the false-branch of `||`). Promotes variables that are in
/// `possibly_assigned_vars` up to `assigned_vars` if they appear as assignment
/// targets inside `expr`.
///
/// Conservative for internal short-circuit operators: only recurses into the
/// guaranteed-evaluated side (LHS) of nested `&&`/`||` sub-expressions, since
/// we cannot know whether the RHS of those was reached.
fn promote_assignment_effects(
    expr: &php_ast::owned::Expr,
    ctx: &mut FlowState,
    db: &dyn crate::db::MirDatabase,
    file: &str,
) {
    match &expr.kind {
        ExprKind::Assign(a) => {
            if let Some(var_name) = extract_var_name(&a.target) {
                let sym = mir_types::Name::from(var_name.as_str());
                if ctx.possibly_assigned_vars.contains(&sym) {
                    let ty = ctx.get_var(&var_name);
                    ctx.set_var(&var_name, ty);
                    std::sync::Arc::make_mut(&mut ctx.possibly_assigned_vars).remove(&sym);
                }
            }
            promote_assignment_effects(&a.value, ctx, db, file);
        }
        ExprKind::UnaryPrefix(u) => {
            promote_assignment_effects(&u.operand, ctx, db, file);
        }
        ExprKind::FunctionCall(call) => {
            // Promote variables that were assigned via by-ref parameters
            if let ExprKind::Identifier(fn_name) = &call.name.kind {
                let resolved = crate::db::resolve_name(db, file, fn_name.as_ref());
                let here = crate::db::Fqcn::from_str(db, &resolved);
                if let Some(func) = crate::db::find_function(db, here) {
                    for (i, param) in func.params.iter().enumerate() {
                        if param.is_byref {
                            let arg = call.args.get(i);
                            if let Some(arg) = arg {
                                if let ExprKind::Variable(name) = &arg.value.kind {
                                    let var_name = name.as_ref().trim_start_matches('$');
                                    let sym = mir_types::Name::from(var_name);
                                    if ctx.possibly_assigned_vars.contains(&sym) {
                                        let ty = ctx.get_var(var_name);
                                        ctx.set_var(var_name, ty);
                                        std::sync::Arc::make_mut(&mut ctx.possibly_assigned_vars)
                                            .remove(&sym);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for arg in call.args.iter() {
                promote_assignment_effects(&arg.value, ctx, db, file);
            }
        }
        ExprKind::MethodCall(mc) | ExprKind::NullsafeMethodCall(mc) => {
            promote_assignment_effects(&mc.object, ctx, db, file);
            for arg in mc.args.iter() {
                promote_assignment_effects(&arg.value, ctx, db, file);
            }
        }
        ExprKind::StaticMethodCall(smc) => {
            for arg in smc.args.iter() {
                promote_assignment_effects(&arg.value, ctx, db, file);
            }
        }
        // For nested &&: LHS is always evaluated; RHS might short-circuit — only recurse LHS.
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanAnd || b.op == BinaryOp::LogicalAnd => {
            promote_assignment_effects(&b.left, ctx, db, file);
        }
        // For nested ||: LHS is always evaluated; RHS might short-circuit — only recurse LHS.
        ExprKind::Binary(b) if b.op == BinaryOp::BooleanOr || b.op == BinaryOp::LogicalOr => {
            promote_assignment_effects(&b.left, ctx, db, file);
        }
        // For all other binary operators (===, !==, instanceof, +, etc.) both sides are evaluated.
        ExprKind::Binary(b) => {
            promote_assignment_effects(&b.left, ctx, db, file);
            promote_assignment_effects(&b.right, ctx, db, file);
        }
        ExprKind::Parenthesized(inner) => {
            promote_assignment_effects(inner, ctx, db, file);
        }
        // Array access: both base and index are evaluated; assignments inside either matter.
        ExprKind::ArrayAccess(aa) => {
            promote_assignment_effects(&aa.array, ctx, db, file);
            if let Some(idx) = &aa.index {
                promote_assignment_effects(idx, ctx, db, file);
            }
        }
        _ => {}
    }
}

fn extract_get_class_arg(expr: &php_ast::owned::Expr) -> Option<String> {
    if let ExprKind::FunctionCall(call) = &expr.kind {
        if let ExprKind::Identifier(name) = &call.name.kind {
            if name.eq_ignore_ascii_case("get_class") {
                if let Some(arg) = call.args.first() {
                    return extract_var_name(&arg.value);
                }
            }
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Extension methods on Type used only in narrowing
// ---------------------------------------------------------------------------

trait UnionNarrowExt {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type;
}

impl UnionNarrowExt for Type {
    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
        let mut result = Type::empty();
        result.possibly_undefined = self.possibly_undefined;
        result.from_docblock = self.from_docblock;
        for atomic in &self.types {
            if f(atomic) {
                result.types.push(atomic.clone());
            }
        }
        result
    }
}

fn is_numeric_string(s: &str) -> bool {
    let t = s.trim();
    !t.is_empty() && (t.parse::<i64>().is_ok() || t.parse::<f64>().is_ok())
}

/// Extract the variable name from `count($var)` / `sizeof($var)`.
fn extract_count_of_var(expr: &php_ast::owned::Expr) -> Option<String> {
    if let ExprKind::FunctionCall(call) = &expr.kind {
        let name = match &call.name.kind {
            ExprKind::Identifier(n) => n.as_ref(),
            _ => return None,
        };
        let bare = name.trim_start_matches('\\');
        if bare.eq_ignore_ascii_case("count") || bare.eq_ignore_ascii_case("sizeof") {
            if let Some(arg) = call.args.first() {
                return extract_var_name(&arg.value);
            }
        }
    }
    None
}

/// Extract the variable name from `strlen($var)` / `mb_strlen($var, ...)`.
fn extract_strlen_of_var(expr: &php_ast::owned::Expr) -> Option<String> {
    if let ExprKind::FunctionCall(call) = &expr.kind {
        let name = match &call.name.kind {
            ExprKind::Identifier(n) => n.as_ref(),
            _ => return None,
        };
        let bare = name.trim_start_matches('\\');
        if bare.eq_ignore_ascii_case("strlen") || bare.eq_ignore_ascii_case("mb_strlen") {
            if let Some(arg) = call.args.first() {
                return extract_var_name(&arg.value);
            }
        }
    }
    None
}

/// Narrow an array variable based on `count($arr) op n` being `is_true`.
/// Promotes `array` / `list` to their non-empty variants when the comparison
/// proves the count is >= 1.
fn narrow_array_count_comparison(
    ctx: &mut FlowState,
    arr_var: &str,
    op: BinaryOp,
    n: i64,
    is_true: bool,
) {
    // Determine whether the comparison proves count >= 1 (i.e., non-empty).
    let non_empty = match (op, is_true) {
        (BinaryOp::Greater, true) if n >= 0 => true, // count > 0 (or > n>=0)
        (BinaryOp::GreaterOrEqual, true) if n >= 1 => true, // count >= 1
        (BinaryOp::Less, false) if n >= 1 => true,   // NOT (count < 1)
        (BinaryOp::LessOrEqual, false) if n >= 0 => true, // NOT (count <= 0)
        _ => false,
    };
    if !non_empty {
        return;
    }
    let current = ctx.get_var(arr_var);
    if current.is_mixed() {
        return;
    }
    let narrowed = current.narrow_to_non_empty_collection();
    if narrowed != current {
        ctx.set_var(arr_var, narrowed);
    }
}

/// Narrow a string variable based on `strlen($str) op n` being `is_true`.
/// Promotes `string` to `non-empty-string` when the comparison proves length >= 1.
fn narrow_string_strlen_comparison(
    ctx: &mut FlowState,
    str_var: &str,
    op: BinaryOp,
    n: i64,
    is_true: bool,
) {
    let non_empty = match (op, is_true) {
        (BinaryOp::Greater, true) if n >= 0 => true,
        (BinaryOp::GreaterOrEqual, true) if n >= 1 => true,
        (BinaryOp::Less, false) if n >= 1 => true,
        (BinaryOp::LessOrEqual, false) if n >= 0 => true,
        _ => false,
    };
    if !non_empty {
        return;
    }
    let current = ctx.get_var(str_var);
    if current.is_mixed() {
        return;
    }
    let narrowed = narrow_string_to_non_empty(&current);
    if narrowed != current {
        ctx.set_var(str_var, narrowed);
    }
}

/// Extract a union Type from an `in_array` haystack argument.
/// Supports:
/// - Literal arrays: `['a', 'b', 1]` → union of `TLiteralString` / `TLiteralInt`
/// - Variables: look up from ctx and collect the TLiteralString/TLiteralInt values
///   inside the TKeyedArray's properties.
fn extract_haystack_type(expr: &php_ast::owned::Expr, ctx: &FlowState) -> Option<Type> {
    match &expr.kind {
        ExprKind::Array(elements) => {
            let mut ty = Type::empty();
            for item in elements.iter() {
                match &item.value.kind {
                    ExprKind::String(s) => {
                        ty.add_type(Atomic::TLiteralString(std::sync::Arc::from(s.as_ref())))
                    }
                    ExprKind::Int(n) => ty.add_type(Atomic::TLiteralInt(*n)),
                    _ => return None, // non-literal element — bail out
                }
            }
            if ty.is_empty() {
                None
            } else {
                Some(ty)
            }
        }
        ExprKind::Variable(name) => {
            let var_name = name.trim_start_matches('$');
            let var_ty = ctx.get_var(var_name);
            if var_ty.is_mixed() || var_ty.is_empty() {
                return None;
            }
            let mut ty = Type::empty();
            for atomic in &var_ty.types {
                match atomic {
                    Atomic::TKeyedArray { properties, .. } => {
                        for prop in properties.values() {
                            match &prop.ty.types[..] {
                                [Atomic::TLiteralString(_)] | [Atomic::TLiteralInt(_)] => {
                                    for a in &prop.ty.types {
                                        ty.add_type(a.clone());
                                    }
                                }
                                _ => return None, // non-literal value
                            }
                        }
                    }
                    _ => return None,
                }
            }
            if ty.is_empty() {
                None
            } else {
                Some(ty)
            }
        }
        ExprKind::Parenthesized(inner) => extract_haystack_type(inner, ctx),
        _ => None,
    }
}

/// Narrow `current` to only the atomic types that overlap with `haystack` literals.
/// For each literal atom in `haystack` (TLiteralString / TLiteralInt): keep it in
/// the output if `current` could hold that value — i.e., the literal is a subtype
/// of at least one atom in `current`.
fn narrow_to_haystack_values(current: &Type, haystack: &Type) -> Type {
    let mut out = Type::empty();
    for hay_atom in &haystack.types {
        let lit_ty = Type::single(hay_atom.clone());
        if lit_ty.is_subtype_structural(current) {
            out.add_type(hay_atom.clone());
        }
    }
    out
}