gdscript-hir 0.5.1

Semantic layer: name resolution, gradual type inference, and GDScript warning checks — gdscript-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
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
//! Gradual type inference (Playbook §3.3–§3.6 + §5): a single forward, bottom-up,
//! bidirectional walk over a lowered [`Body`]. No unification variables — types flow forward
//! from annotations, literals, and the engine API (rust-analyzer's *structure*, Pyright's
//! gradual *semantics*).
//!
//! The walk memoizes every expression's [`Ty`] in [`InferenceResult::expr_ty`] (the source of
//! hover + inlay), does flow-scoped `is`/`as` narrowing over the lexical guarded sub-tree, and
//! raises the §5 type diagnostics. The load-bearing invariant: a `Variant`/`Unknown`/`Error`
//! receiver is *uninformative* — it never fires `UNSAFE_*`, never cascades — so cross-file code
//! (which lands on `Unknown` via the seam) produces zero false diagnostics.

use gdscript_api::{EngineApi, MemberRef, TyRef};
use gdscript_base::{Diagnostic, DiagnosticSource, FileId, Severity, TextRange};
use gdscript_db::Db;
use gdscript_scene::{SceneModel, SceneNode};
use gdscript_syntax::GdNode;
use rustc_hash::{FxHashMap, FxHashSet};
use smol_str::SmolStr;

use std::sync::Arc;

use crate::body::{self, BinOp, Body, Expr, ExprId, Literal, ParamBinding, Stmt, UnOp};
use crate::cst::{self, AstPtr};
use crate::flow::{self, FlowAnalysis, NarrowedTy, Place};
use crate::item_tree::{InnerClassItem, ItemTree, Member, has_annotation, item_tree};
use crate::resolve::{self, ClassItem, ClassScope, GlobalDef};
use crate::ty::{self, Assign, EnumRef, ScriptRefId, Ty};
use crate::warnings::{RawWarning, WarningCode};

// ---- diagnostic codes + message templates (Playbook §5, engine-matching) -----------------

/// `:=` / inferred binding from a statically-`Variant` value.
pub const INFERENCE_ON_VARIANT: &str = "INFERENCE_ON_VARIANT";
/// Incompatible hard types (our umbrella for the engine's `push_error`).
pub const TYPE_MISMATCH: &str = "TYPE_MISMATCH";
/// `float` stored into an `int` slot.
pub const NARROWING_CONVERSION: &str = "NARROWING_CONVERSION";
/// `int / int`.
pub const INTEGER_DIVISION: &str = "INTEGER_DIVISION";
/// A property missing on a statically-known base.
pub const UNSAFE_PROPERTY_ACCESS: &str = "UNSAFE_PROPERTY_ACCESS";
/// A method missing on a statically-known base.
pub const UNSAFE_METHOD_ACCESS: &str = "UNSAFE_METHOD_ACCESS";
/// An argument whose static type needs an unsafe implicit cast (`Variant` / a downcast) into the
/// resolved parameter type — Godot's per-argument value-prop warning.
pub const UNSAFE_CALL_ARGUMENT: &str = "UNSAFE_CALL_ARGUMENT";
/// A `$Path`/`%Unique`/`get_node("…")` whose literal path is genuinely absent in the owning scene
/// (only raised when the script attaches to exactly one scene — never on an `..`/absolute path or a
/// path that descends into an instanced sub-scene we don't see).
pub const INVALID_NODE_PATH: &str = "INVALID_NODE_PATH";
/// A declared `class_name` that shadows another global identifier — a duplicate user `class_name`,
/// an engine/native class, a builtin/utility, a global enum/const, or a `*`-autoload singleton.
/// Godot's `gdscript_analyzer.cpp` raises this (as an error) so the global namespace stays unique.
pub const SHADOWED_GLOBAL_IDENTIFIER: &str = "SHADOWED_GLOBAL_IDENTIFIER";
/// A genuine `extends` cycle: a file's base chain transitively returns to itself (`A extends B`,
/// `B extends A`). Illegal in Godot (`gdscript_analyzer.cpp` raises it). Only the `extends`
/// inheritance chain cycles — a `preload`/`load` cycle is legal at runtime and is NOT reported.
pub const CYCLIC_INHERITANCE: &str = "CYCLIC_INHERITANCE";

/// What kind of binding a [`Binding`] describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingKind {
    /// A local `var` / `const`.
    Var,
    /// A function / lambda parameter.
    Param,
    /// A `for` loop variable.
    ForVar,
    /// A `var x` capture in a `match` pattern (typed `Variant`; arm-scoped).
    MatchBind,
}

/// A typed local binding — the unit hover + inlay hints read for `var`/param/`for` names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
    /// The binding name (for unused-binding analysis, find-references).
    pub name: SmolStr,
    /// The name token's range.
    pub name_range: TextRange,
    /// The binding's resolved type. For an untyped `var x = e` this is the gradual `Variant`;
    /// the precise initializer type (for an "add type annotation" action) is [`Binding::init`].
    pub ty: Ty,
    /// The initializer expression, when the binding has one (a `var`/`const` with `= e`).
    pub init: Option<ExprId>,
    /// Whether the source carried an explicit `: T` annotation.
    pub annotated: bool,
    /// Whether the source used `:=` (inferred-but-hard).
    pub inferred_colon_eq: bool,
    /// Whether this is a `const` (vs a `var`) — distinguishes `UNUSED_LOCAL_CONSTANT` from
    /// `UNUSED_VARIABLE`.
    pub is_const: bool,
    /// What kind of binding this is.
    pub kind: BindingKind,
}

/// The result of inferring one body.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InferenceResult {
    /// Every expression's inferred type (feeds hover + inlay).
    pub expr_ty: FxHashMap<ExprId, Ty>,
    /// The local bindings introduced by the body (params, `var`/`const`, `for` vars).
    pub bindings: Vec<Binding>,
    /// The §5 type diagnostics raised directly (the ungated analyzer-native codes:
    /// `TYPE_MISMATCH`, `INVALID_NODE_PATH` — these have no Godot warning-setting key).
    pub diagnostics: Vec<Diagnostic>,
    /// The gateable Godot warnings, recorded severity-free. Resolved into final diagnostics by
    /// [`crate::warnings::gate`] downstream of the cached `analyze_file` query (Workstream 1).
    pub raw_warnings: Vec<RawWarning>,
}

impl InferenceResult {
    /// The inferred type of an expression, if it was visited.
    #[must_use]
    pub fn type_of(&self, id: ExprId) -> Option<&Ty> {
        self.expr_ty.get(&id)
    }

    /// The binding whose name token contains `offset`, if any.
    #[must_use]
    pub fn binding_at(&self, offset: u32) -> Option<&Binding> {
        self.bindings
            .iter()
            .find(|b| b.name_range.start <= offset && offset < b.name_range.end)
    }
}

/// Infer a lowered `body` (its `tail` initializer expression and/or its statement block).
/// `return_ty` is the function's declared return type (`Variant` if none / for an
/// initializer body).
/// Every assignment-LHS `ExprId` in a body (`x = …` / `x += …`, all lowered to `BinOp::Assign`) —
/// a *write* site, excluded from the `UNASSIGNED_VARIABLE` read-before-assign check.
fn collect_assign_lhs(body: &Body) -> FxHashSet<ExprId> {
    body.exprs
        .iter()
        .filter_map(|e| match e {
            Expr::Bin {
                op: BinOp::Assign,
                lhs,
                ..
            } => Some(*lhs),
            _ => None,
        })
        .collect()
}

/// Infer one function/initializer body against a class scope: walks the lowered [`body::Body`],
/// resolving each expression's [`Ty`] (engine + cross-file members, scene-node paths, flow
/// narrowing) and recording the bindings, diagnostics, and severity-free gateable warnings.
/// Returns the [`InferenceResult`] the IDE features and the warning gate read.
#[must_use]
#[allow(
    clippy::too_many_lines,
    reason = "the per-body inference orchestration reads best whole"
)]
pub fn infer(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    class: &ClassScope,
    body: &Body,
    return_ty: Ty,
    is_func_body: bool,
) -> InferenceResult {
    let self_ty = class.self_ty.clone();
    let mut cx = Cx {
        db,
        api,
        root,
        body,
        class,
        self_ty,
        return_ty,
        expr_ty: FxHashMap::default(),
        bindings: Vec::new(),
        diagnostics: Vec::new(),
        raw_warnings: Vec::new(),
        locals: FxHashMap::default(),
        used_locals: FxHashSet::default(),
        narrowing: FxHashMap::default(),
        flow: flow::analyze(body),
        is_func_body,
        assigned: flow::analyze_assigned(
            body,
            &body
                .params
                .iter()
                .map(|p| p.name.clone())
                .collect::<Vec<_>>(),
        ),
        cur_stmt: None,
        needs_assignment: FxHashSet::default(),
        assign_lhs: collect_assign_lhs(body),
    };
    // Parameters bind first (their defaults can reference earlier params).
    let params = body.params.clone();
    for p in &params {
        let ty = cx.param_ty(p);
        cx.bindings.push(Binding {
            name: p.name.clone(),
            name_range: p.name_range,
            ty: ty.clone(),
            init: None,
            annotated: p.type_ref.is_some(),
            inferred_colon_eq: false,
            is_const: false,
            kind: BindingKind::Param,
        });
        cx.locals.insert(p.name.clone(), ty);
    }
    if let Some(tail) = body.tail {
        cx.infer_expr(tail, &Expectation::None);
    }
    let block = body.block.clone();
    cx.infer_block(&block);

    // UNUSED_* — a declared local/param/const never read. Only for a *function* body: a class-field
    // initializer body would otherwise false-flag every field (the member is read in other methods,
    // not in its own initializer). `_`-prefixed names + loop/match captures are excluded.
    if is_func_body {
        let unused: Vec<(TextRange, WarningCode, String)> = cx
            .bindings
            .iter()
            .filter_map(|b| {
                if b.name.starts_with('_') || cx.used_locals.contains(&b.name) {
                    return None;
                }
                let (code, what) = match b.kind {
                    BindingKind::Param => (WarningCode::UnusedParameter, "parameter"),
                    BindingKind::Var if b.is_const => {
                        (WarningCode::UnusedLocalConstant, "local constant")
                    }
                    BindingKind::Var => (WarningCode::UnusedVariable, "local variable"),
                    BindingKind::ForVar | BindingKind::MatchBind => return None,
                };
                Some((
                    b.name_range,
                    code,
                    format!("The {what} \"{}\" is declared but never used.", b.name),
                ))
            })
            .collect();
        for (range, code, msg) in unused {
            cx.warn(range, code, msg);
        }
    }

    // SHADOWED_GLOBAL_IDENTIFIER — a parameter / local / `for` / pattern-bind whose name collides
    // with a project/engine global (built-in type/function, native class, engine singleton, project
    // `class_name`, or autoload). Godot's `is_shadowing` fires for every local-scope binding. A local
    // `var`/`const` that *also* shadows a param/member emits THIS instead of `SHADOWED_VARIABLE` (the
    // global check wins in `gdscript_analyzer.cpp`; `infer_local_var` suppresses the variable-shadow
    // when a global one applies, so the two never double-fire on one declaration).
    if is_func_body {
        let global_shadows: Vec<(TextRange, String)> = cx
            .bindings
            .iter()
            .filter_map(|b| {
                let kind = shadowed_global_kind(db, api, &b.name)?;
                let what = match b.kind {
                    BindingKind::Param => "parameter",
                    BindingKind::Var if b.is_const => "constant",
                    BindingKind::Var => "variable",
                    BindingKind::ForVar => "for loop variable",
                    BindingKind::MatchBind => "pattern bind",
                };
                Some((
                    b.name_range,
                    format!("The {what} \"{}\" has the same name as a {kind}.", b.name),
                ))
            })
            .collect();
        for (range, msg) in global_shadows {
            cx.warn(range, WarningCode::ShadowedGlobalIdentifier, msg);
        }
    }

    // UNTYPED_DECLARATION / INFERRED_DECLARATION — the opt-in declaration-strictness codes (default
    // IGNORE; promoted to WARN under a strict / standalone run). Driven directly by the binding flags:
    // a `var` declared with `:=` is INFERRED_DECLARATION; a `var` / parameter with neither a `: T`
    // annotation nor `:=` is UNTYPED_DECLARATION. `const` (its value type is always statically known),
    // `for` vars, and pattern binds (fixed by the iterable / scrutinee, not user-typeable) are excluded
    // — they can't carry the static type Godot's strict check expects.
    if is_func_body {
        let decl_strictness: Vec<(TextRange, WarningCode, String)> = cx
            .bindings
            .iter()
            .filter_map(|b| match b.kind {
                BindingKind::Param if !b.annotated => Some((
                    b.name_range,
                    WarningCode::UntypedDeclaration,
                    format!("The parameter \"{}\" has no static type.", b.name),
                )),
                BindingKind::Var if !b.is_const && b.inferred_colon_eq => Some((
                    b.name_range,
                    WarningCode::InferredDeclaration,
                    format!(
                        "The variable \"{}\" uses inferred typing (`:=`); consider declaring its type explicitly.",
                        b.name
                    ),
                )),
                BindingKind::Var if !b.is_const && !b.annotated => Some((
                    b.name_range,
                    WarningCode::UntypedDeclaration,
                    format!("The variable \"{}\" has no static type.", b.name),
                )),
                _ => None,
            })
            .collect();
        for (range, code, msg) in decl_strictness {
            cx.warn(range, code, msg);
        }
    }

    // CONFUSABLE_IDENTIFIER — a parameter / local binding whose name mixes scripts in a spoofable
    // way (the same UTS #39 check used for member names; ASCII names fast-path out).
    let confusable_bindings: Vec<TextRange> = cx
        .bindings
        .iter()
        .filter(|b| is_confusable_identifier(&b.name))
        .map(|b| b.name_range)
        .collect();
    for range in confusable_bindings {
        cx.warn(
            range,
            WarningCode::ConfusableIdentifier,
            "This identifier uses confusable characters (mixed scripts).".to_owned(),
        );
    }

    // UNREACHABLE_CODE — statements after a return/break/continue / exhaustive branch (Workstream 2).
    let unreachable = cx.flow.unreachable_ranges(body);
    for range in unreachable {
        cx.warn(
            range,
            WarningCode::UnreachableCode,
            "Unreachable code (statement after a return, break, continue, or an exhaustive match)."
                .to_owned(),
        );
    }

    // UNREACHABLE_PATTERN — a `match` arm after an unconditional catch-all (Workstream 2).
    let unreachable_patterns = cx.flow.unreachable_pattern_ranges().to_vec();
    for range in unreachable_patterns {
        cx.warn(
            range,
            WarningCode::UnreachablePattern,
            "Unreachable pattern: an earlier arm's wildcard (`_`) or `var` binding always matches."
                .to_owned(),
        );
    }

    InferenceResult {
        expr_ty: cx.expr_ty,
        bindings: cx.bindings,
        diagnostics: cx.diagnostics,
        raw_warnings: cx.raw_warnings,
    }
}

/// Convenience: recover a function node from its [`AstPtr`], lower its body, resolve its
/// declared return type, and infer it.
#[must_use]
pub fn infer_func(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    class: &ClassScope,
    ptr: AstPtr,
) -> InferenceResult {
    let Some(node) = ptr.to_node(root) else {
        return InferenceResult::default();
    };
    let body = body::body_of_func(&node);
    // The return-type annotation is the FuncDecl's direct `TypeRef` child (params' type refs
    // are nested inside the ParamList, so they are not direct children).
    let return_ty = cst::first_child(&node, |k| k == gdscript_syntax::SyntaxKind::TypeRef)
        .map_or(Ty::Variant, |t| resolve::resolve_type_ref(db, api, &t));
    infer(db, api, root, class, &body, return_ty, true)
}

/// One inferred unit of a file: a function body or a class field's initializer, with its
/// lowered [`Body`] and [`InferenceResult`] (kept so position-based features — hover, inlay,
/// member completion — can map a cursor back through the source map).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit {
    /// The source range this unit covers (the function decl or the field decl).
    pub range: TextRange,
    /// The lowered body.
    pub body: Body,
    /// The inference result.
    pub result: InferenceResult,
}

/// The full single-file inference: the item tree, every inferred unit, and the merged §5
/// diagnostics. The whole-file entry point the IDE layer consumes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FileInference {
    /// The lowered item tree.
    pub tree: Arc<ItemTree>,
    /// The inferred function/field units.
    pub units: Vec<Unit>,
    /// The ungated analyzer-native diagnostics, merged across units (`TYPE_MISMATCH`,
    /// `INVALID_NODE_PATH`) plus the file-level `SHADOWED_GLOBAL_IDENTIFIER` / `CYCLIC_INHERITANCE`.
    pub diagnostics: Vec<Diagnostic>,
    /// The severity-free gateable Godot warnings, merged across units. The IDE layer resolves
    /// these via [`crate::warnings::gate`] against the project's settings (Workstream 1).
    pub raw_warnings: Vec<RawWarning>,
}

impl FileInference {
    /// The innermost unit whose range contains `offset`.
    #[must_use]
    pub fn unit_at(&self, offset: u32) -> Option<&Unit> {
        self.units
            .iter()
            .filter(|u| u.range.start <= offset && offset < u.range.end)
            .min_by_key(|u| u.range.end - u.range.start)
    }
}

/// Infer an entire file: lower its item tree, then infer every function body and every
/// class-field initializer against a shared [`ClassScope`]. The single entry point for the
/// IDE features (Playbook §6 — a pure `(api, parsed file) -> result` function).
#[must_use]
#[allow(clippy::too_many_lines)] // the two-pass field-fixpoint + function walk reads best whole
pub fn analyze_file(db: &dyn Db, api: &EngineApi, root: &GdNode, file_id: FileId) -> FileInference {
    let tree = item_tree(root);
    let mut units = Vec::new();
    let mut diagnostics = Vec::new();
    let mut raw_warnings: Vec<RawWarning> = Vec::new();

    // EMPTY_FILE — a script with no members, no `class_name`, and no `extends` (Workstream 1).
    if tree.members.is_empty() && tree.class_name.is_none() && tree.extends.is_none() {
        raw_warnings.push(RawWarning {
            range: TextRange::new(0, 0),
            code: WarningCode::EmptyFile,
            message: "Empty script file.".to_owned(),
        });
    }
    let mut member_types: FxHashMap<SmolStr, Ty> = FxHashMap::default();
    // `self` is the script's OWN class (a self-`ScriptRef`), not just its engine base — so member
    // access on an aliased `self` resolves the file's own members (see `ClassScope::self_ty`).
    let self_ref = Ty::ScriptRef(ScriptRefId(file_id.0));
    // The file's own `res://` path, for anchoring relative `preload`/`extends` to its directory.
    let res_path = db.file_text(file_id).and_then(|ft| ft.res_path(db));

    // A declared `class_name` that collides with another global identifier (W2). Mirrors Godot's
    // `gdscript_analyzer.cpp` uniqueness check over the global namespace, projected through the
    // cross-file firewall (`class_name_collisions`) and the offset-free global resolvers — so it
    // fires only when genuinely shadowing, never on the seam. Emitted once, at the decl's NAME.
    if let Some(name) = tree.class_name.clone() {
        let collides = collisions_contains(db, &name)
            || resolve::resolve_global(api, &name).is_some()
            || is_autoload_singleton(db, &name);
        if collides && let Some(range) = class_name_decl_range(root) {
            diagnostics.push(Diagnostic {
                range,
                severity: Severity::Warning,
                code: SHADOWED_GLOBAL_IDENTIFIER.to_owned(),
                message: format!(
                    "The global class \"{name}\" hides a built-in/native/global/autoload."
                ),
                source: DiagnosticSource::Type,
                fixes: Vec::new(),
            });
        }
        // CONFUSABLE_IDENTIFIER on the `class_name` itself (gated, unlike the hides-global check).
        if is_confusable_identifier(&name)
            && let Some(range) = class_name_decl_range(root)
        {
            raw_warnings.push(RawWarning {
                range,
                code: WarningCode::ConfusableIdentifier,
                message: format!(
                    "The identifier \"{name}\" uses confusable characters (mixed scripts)."
                ),
            });
        }
    }

    // A genuine `extends` cycle (D7): walk THIS file's base chain by `FileId`; if it returns to the
    // start, the inheritance is cyclic (illegal in Godot). Reported once, at the file's own `extends`
    // decl range. Only `extends` cycles are walked here (member lookup is the only thing that loops);
    // `preload`/`load` cycles are legal at runtime and never reach this resolver. We start by stepping
    // ONTO the user base — if the very first base is the start file (`extends "res://self.gd"`, or two
    // files A↔B), the revisit-of-start check fires; a deep but ACYCLIC chain bottoms out at an engine
    // `Object`/`Unknown` and never revisits, so it does not false-fire.
    if extends_chain_is_cyclic(db, file_id)
        && let Some(range) = extends_decl_range(root)
    {
        diagnostics.push(Diagnostic {
            range,
            severity: Severity::Warning,
            code: CYCLIC_INHERITANCE.to_owned(),
            message: "Cyclic class hierarchy: this class's `extends` chain returns to itself."
                .to_owned(),
            source: DiagnosticSource::Type,
            fixes: Vec::new(),
        });
    }

    // File-level (member) warnings that need the whole item-tree, not a single body.
    raw_warnings.extend(member_level_warnings(
        db,
        api,
        root,
        &tree,
        res_path.as_deref(),
    ));

    // Pass 1 — class fields. Inferring each `var`/`const` seeds `member_types` so the function
    // pass sees the *inferred* field type (`var n := 0` → `int`), not just the annotation.
    //
    // A field initializer may reference an *earlier* field (`var a := 1` then `var b := a + 1`),
    // so a single shallow round sees the referent as `Variant`/seam. We run a BOUNDED fixpoint:
    // each round re-infers every field against the prior round's `member_types`, until the map
    // stops changing or we hit the round cap. Cheap (fields are few, types settle in a round or
    // two) and deterministic. Only the final round's units/diagnostics are kept — earlier rounds
    // are throwaway probes feeding the seed.
    {
        // Bound the iteration: a linear `a -> b -> c -> …` chain settles in O(n) rounds, but a
        // small constant is enough in practice (the corpus settles in ≤2) and guarantees
        // termination even if a type oscillated.
        const MAX_ROUNDS: usize = 4;
        let mut final_units: Vec<Unit> = Vec::new();
        let mut final_diagnostics: Vec<Diagnostic> = Vec::new();
        let mut final_raw_warnings: Vec<RawWarning> = Vec::new();
        for _ in 0..MAX_ROUNDS {
            let mut class = ClassScope::new(db, api, &tree, res_path.as_deref());
            class.self_ty = self_ref.clone();
            class.member_types.clone_from(&member_types);
            let mut next_member_types: FxHashMap<SmolStr, Ty> = FxHashMap::default();
            final_units = Vec::new();
            final_diagnostics = Vec::new();
            final_raw_warnings = Vec::new();
            for m in &tree.members {
                let (ptr, range) = match m {
                    Member::Var(v) => (v.ptr, v.range),
                    Member::Const(c) => (c.ptr, c.range),
                    _ => continue,
                };
                if let Some(unit) = unit_from_decl(db, api, root, &class, ptr, range) {
                    if let (Some(name), Some(b)) = (m.name(), unit.result.bindings.first()) {
                        next_member_types.insert(SmolStr::new(name), b.ty.clone());
                    }
                    final_diagnostics.extend(unit.result.diagnostics.iter().cloned());
                    final_raw_warnings.extend(unit.result.raw_warnings.iter().cloned());
                    final_units.push(unit);
                }
            }
            if next_member_types == member_types {
                break;
            }
            member_types = next_member_types;
        }
        diagnostics.extend(final_diagnostics);
        raw_warnings.extend(final_raw_warnings);
        units.extend(final_units);
    }

    // Pass 2 — functions, against a scope carrying the seeded field types.
    {
        let mut class = ClassScope::new(db, api, &tree, res_path.as_deref());
        class.member_types = member_types;
        class.self_ty = self_ref.clone();
        for m in &tree.members {
            let Member::Func(f) = m else { continue };
            let Some(node) = f.ptr.to_node(root) else {
                continue;
            };
            let body = body::body_of_func(&node);
            let return_ty = cst::first_child(&node, |k| k == gdscript_syntax::SyntaxKind::TypeRef)
                .map_or(Ty::Variant, |t| resolve::resolve_type_ref(db, api, &t));
            let result = infer(db, api, root, &class, &body, return_ty, true);
            diagnostics.extend(result.diagnostics.iter().cloned());
            raw_warnings.extend(result.raw_warnings.iter().cloned());
            units.push(Unit {
                range: f.range,
                body,
                result,
            });
        }
    }

    // Pass 2b — inner-class method bodies. The top-level pass skips `Member::Class`, so inner `class
    // Name:` methods were never inferred (no units / diagnostics / resolvable refs). Analyze them with
    // `self` typed as the inner class, so `self.member` / bare member refs resolve against the inner
    // item-tree + its `extends` chain; anything unresolved stays the seam (no false positive).
    infer_inner_class_bodies(
        db,
        api,
        root,
        &tree,
        file_id,
        "",
        res_path.as_deref(),
        &mut units,
        &mut diagnostics,
        &mut raw_warnings,
        0,
    );

    FileInference {
        tree,
        units,
        diagnostics,
        raw_warnings,
    }
}

/// Infer the method bodies of every inner `class Name:` in `tree` (recursively), with `self` typed as
/// the inner class. `path_prefix` is the dotted path to `tree`'s class (`""` at the top level), used
/// to build each inner class's [`crate::ty::InnerClassRef`] path. Depth-bounded against pathological
/// nesting. Inner-class *field* fixpoint pre-pass is intentionally skipped (an inner field types by
/// annotation only — lossy, like the cross-file path).
#[allow(
    clippy::too_many_arguments,
    reason = "threads the same analyze_file accumulators a free helper can't capture from a closure"
)]
fn infer_inner_class_bodies(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    tree: &ItemTree,
    file_id: FileId,
    path_prefix: &str,
    res_path: Option<&str>,
    units: &mut Vec<Unit>,
    diagnostics: &mut Vec<Diagnostic>,
    raw_warnings: &mut Vec<RawWarning>,
    depth: u32,
) {
    if depth > 16 {
        return;
    }
    for m in &tree.members {
        let Member::Class(c) = m else { continue };
        let inner_path = if path_prefix.is_empty() {
            c.name.to_string()
        } else {
            format!("{path_prefix}.{}", c.name)
        };
        let mut class = ClassScope::new(db, api, &c.tree, res_path);
        class.self_ty = Ty::InnerClass(crate::ty::InnerClassRef {
            file: file_id.0,
            path: SmolStr::new(&inner_path),
        });
        for im in &c.tree.members {
            let Member::Func(f) = im else { continue };
            let Some(node) = f.ptr.to_node(root) else {
                continue;
            };
            let body = body::body_of_func(&node);
            let return_ty = cst::first_child(&node, |k| k == gdscript_syntax::SyntaxKind::TypeRef)
                .map_or(Ty::Variant, |t| resolve::resolve_type_ref(db, api, &t));
            let result = infer(db, api, root, &class, &body, return_ty, true);
            diagnostics.extend(result.diagnostics.iter().cloned());
            raw_warnings.extend(result.raw_warnings.iter().cloned());
            units.push(Unit {
                range: f.range,
                body,
                result,
            });
        }
        infer_inner_class_bodies(
            db,
            api,
            root,
            &c.tree,
            file_id,
            &inner_path,
            res_path,
            units,
            diagnostics,
            raw_warnings,
            depth + 1,
        );
    }
}

/// Class-level annotation checks (W1), unblocked by first-class item-tree annotations:
/// `REDUNDANT_STATIC_UNLOAD` (`@static_unload` with no `static var`) and `MISSING_TOOL` (a non-`@tool`
/// class extending a `@tool` user-script base).
fn class_annotation_warnings(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    tree: &ItemTree,
    res_path: Option<&str>,
) -> Vec<RawWarning> {
    let mut out = Vec::new();
    // REDUNDANT_STATIC_UNLOAD — `@static_unload` on a class that declares no `static var`.
    if let Some(unload) = tree.annotations.iter().find(|a| a.name == "static_unload")
        && !tree
            .members
            .iter()
            .any(|m| matches!(m, Member::Var(v) if v.is_static))
    {
        out.push(RawWarning {
            range: unload.range,
            code: WarningCode::RedundantStaticUnload,
            message: "`@static_unload` is redundant on a class with no static variables."
                .to_owned(),
        });
    }
    // MISSING_TOOL — this class is not `@tool` but its (user-script) base is, so it will NOT run in
    // the editor. Only the resolvable user-script base is checked (an engine base is never `@tool`).
    if !has_annotation(&tree.annotations, "tool")
        && user_base_is_tool(db, api, tree, res_path)
        && let Some(range) = extends_decl_range(root)
    {
        out.push(RawWarning {
            range,
            code: WarningCode::MissingTool,
            message: "This class extends a `@tool` script but is not itself `@tool` (it will not run in the editor)."
                .to_owned(),
        });
    }
    out
}

/// File-level (member) warnings that need the whole item-tree, not a single body (W1):
/// `ENUM_VARIABLE_WITHOUT_DEFAULT`, `UNUSED_SIGNAL`, `UNUSED_PRIVATE_CLASS_VARIABLE`,
/// `SHADOWED_GLOBAL_IDENTIFIER`, `CONFUSABLE_IDENTIFIER`, the annotation-lifecycle checks, and
/// `NATIVE_METHOD_OVERRIDE` — each independent + conservative.
#[allow(
    clippy::too_many_lines,
    reason = "a flat sequence of independent per-member warning checks; reads best as one walk"
)]
fn member_level_warnings(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    tree: &ItemTree,
    res_path: Option<&str>,
) -> Vec<RawWarning> {
    let mut out = Vec::new();
    let has_signal = tree.members.iter().any(|m| matches!(m, Member::Signal(_)));
    // A `_`-prefixed, non-exported member var is an UNUSED_PRIVATE_CLASS_VARIABLE candidate.
    let has_private_var = tree
        .members
        .iter()
        .any(|m| matches!(m, Member::Var(v) if v.name.starts_with('_') && !v.is_exported));
    // Only pay for the whole-file name scan when there is a signal or a private var to judge.
    let uses = (has_signal || has_private_var).then(|| NameUses::collect(root));
    // The resolved ENGINE base, for NATIVE_METHOD_OVERRIDE (an unresolved/user base ⇒ no check).
    let engine_base = match resolve::resolve_base(db, api, tree, res_path) {
        Ty::Object(c) => Some(c),
        _ => None,
    };

    out.extend(class_annotation_warnings(db, api, root, tree, res_path));

    for m in &tree.members {
        // UNUSED_PRIVATE_CLASS_VARIABLE — a `_`-prefixed, non-exported member var never referenced
        // anywhere in the file (same-file scan, like UNUSED_SIGNAL). Exported vars are set externally
        // (inspector / scene), so they are excluded to keep the contract no-false-positive.
        if let Member::Var(v) = m
            && v.name.starts_with('_')
            && !v.is_exported
            && let Some(uses) = &uses
            && !uses.is_referenced(&v.name)
        {
            out.push(RawWarning {
                range: v.name_range,
                code: WarningCode::UnusedPrivateClassVariable,
                message: format!(
                    "The class variable \"{}\" is never used in this file.",
                    v.name
                ),
            });
        }
        // ONREADY_WITH_EXPORT — `@onready` and `@export` on the same member (Godot raises this).
        if let Member::Var(v) = m
            && has_annotation(&v.annotations, "onready")
            && v.is_exported
        {
            out.push(RawWarning {
                range: v.name_range,
                code: WarningCode::OnreadyWithExport,
                message: format!(
                    "The member \"{}\" has both `@onready` and `@export`; they conflict.",
                    v.name
                ),
            });
        }
        // SHADOWED_GLOBAL_IDENTIFIER — a value member (`var`/`const`/`signal`) whose name collides
        // with a project/engine global. Godot's `is_shadowing` fires for member declarations too.
        if let Some((name, range, what)) = member_value_decl(m)
            && let Some(kind) = shadowed_global_kind(db, api, name)
        {
            out.push(RawWarning {
                range,
                code: WarningCode::ShadowedGlobalIdentifier,
                message: format!("The {what} \"{name}\" has the same name as a {kind}."),
            });
        }
        // CONFUSABLE_IDENTIFIER — any member name that mixes scripts in a spoofable way.
        if let Some((name, range)) = member_decl_name(m)
            && is_confusable_identifier(name)
        {
            out.push(RawWarning {
                range,
                code: WarningCode::ConfusableIdentifier,
                message: format!(
                    "The identifier \"{name}\" uses confusable characters (mixed scripts)."
                ),
            });
        }
        match m {
            // An enum-typed field with no initializer (the local case is in `infer_local_var`).
            Member::Var(v) if !v.has_init => {
                if let Some(tref) = &v.type_ref
                    && matches!(resolve::resolve_type_name(db, api, tref), Ty::Enum(_))
                {
                    out.push(RawWarning {
                        range: v.name_range,
                        code: WarningCode::EnumVariableWithoutDefault,
                        message: format!(
                            "The enum variable \"{}\" has no default value (it defaults to 0, which may not be a valid enum value).",
                            v.name
                        ),
                    });
                }
            }
            // A signal never referenced in this file (emit/connect/string). Same-file only, like
            // Godot — a signal connected purely from a scene/other file is invisible (the known
            // limitation); the conservative scan only warns when the name appears nowhere else.
            Member::Signal(s) => {
                if let Some(uses) = &uses
                    && !uses.is_referenced(&s.name)
                {
                    out.push(RawWarning {
                        range: s.name_range,
                        code: WarningCode::UnusedSignal,
                        message: format!(
                            "The signal \"{}\" is never emitted or connected in this file.",
                            s.name
                        ),
                    });
                }
            }
            // NATIVE_METHOD_OVERRIDE (ERROR-default) — an override of an engine VIRTUAL whose
            // signature is clearly incompatible. Conservative to the extreme (a false positive is a
            // loud error): warn ONLY on a *definite type clash* at an overlapping typed parameter —
            // both the override's annotation and the virtual's param resolve to known engine types
            // that are mutually NON-assignable. Arity, defaults/vararg, and variance subtleties are
            // deliberately left to under-warn (see `TECH_DEBT.md`).
            Member::Func(f) => {
                if let Some(base) = engine_base
                    && let Some(MemberRef::Method(vsig)) = api.lookup_member(base, &f.name)
                    && vsig.is_virtual
                {
                    for (p, vp) in f.params.iter().zip(vsig.params.iter()) {
                        let Some(ann) = &p.type_ref else { continue };
                        let pty = resolve::resolve_type_name(db, api, ann);
                        let vty = ty::resolve_tyref(api, &vp.ty);
                        if types_definitely_clash(api, &pty, &vty) {
                            out.push(RawWarning {
                                range: f.name_range,
                                code: WarningCode::NativeMethodOverride,
                                message: format!(
                                    "The override of the native virtual method \"{}\" has an incompatible type for parameter \"{}\".",
                                    f.name, p.name
                                ),
                            });
                            break; // one warning per overriding function
                        }
                    }
                }
            }
            _ => {}
        }
    }
    out
}

/// Whether two **known** engine types are mutually non-assignable — a *definite* clash. An
/// uninformative type (`Variant`/`Unknown`) never clashes (gradual), and any assignable relation in
/// either direction (subtype, widening, enum/int, …) is treated as "related" (not a clash), so the
/// conservative `NATIVE_METHOD_OVERRIDE` only fires on genuinely unrelated types.
fn types_definitely_clash(api: &EngineApi, a: &Ty, b: &Ty) -> bool {
    if a.is_uninformative() || b.is_uninformative() {
        return false;
    }
    // Enums are int-backed and their qualified name resolves differently on the annotation side
    // (`resolve_type_name` → `Class.Enum`) than on the engine-model side (`resolve_tyref`), so an
    // enum "clash" is unreliable — never clash on an enum. (Fixes a false NATIVE_METHOD_OVERRIDE on
    // a valid dotted-enum-typed override param, e.g. `p_mode: MultiplayerPeer.TransferMode`.)
    if matches!(a, Ty::Enum(_)) || matches!(b, Ty::Enum(_)) {
        return false;
    }
    matches!(ty::is_assignable(api, a, b), Assign::No)
        && matches!(ty::is_assignable(api, b, a), Assign::No)
}

/// Identifier-occurrence counts + string-literal contents across a file's CST — the file-wide
/// "is this name referenced anywhere?" check (drives `UNUSED_SIGNAL`).
struct NameUses {
    ident_counts: FxHashMap<SmolStr, u32>,
    strings: FxHashSet<SmolStr>,
}

impl NameUses {
    fn collect(root: &GdNode) -> Self {
        let mut ident_counts: FxHashMap<SmolStr, u32> = FxHashMap::default();
        let mut strings: FxHashSet<SmolStr> = FxHashSet::default();
        for node in gdscript_syntax::ast::descendants(root) {
            for el in node.children_with_tokens() {
                let Some(tok) = el.into_token() else { continue };
                match tok.kind() {
                    gdscript_syntax::SyntaxKind::Ident => {
                        *ident_counts.entry(SmolStr::new(tok.text())).or_insert(0) += 1;
                    }
                    gdscript_syntax::SyntaxKind::String => {
                        strings.insert(SmolStr::new(tok.text().trim_matches(['"', '\''])));
                    }
                    _ => {}
                }
            }
        }
        Self {
            ident_counts,
            strings,
        }
    }

    /// Whether `name` is referenced beyond its single declaration — a 2nd identifier occurrence, or
    /// any string literal naming it (covering `emit_signal("name")` / `connect("name", …)`).
    fn is_referenced(&self, name: &str) -> bool {
        self.ident_counts.get(name).copied().unwrap_or(0) > 1 || self.strings.contains(name)
    }
}

/// Whether `name` is declared as a `class_name` by more than one file in the project (W2). Reads
/// the cross-file `class_name_collisions` firewall; `false` (no warning) when no source root is set
/// — single-file analysis cannot observe a duplicate.
fn collisions_contains(db: &dyn Db, name: &SmolStr) -> bool {
    db.source_root()
        .is_some_and(|root| crate::queries::class_name_collisions(db, root).contains(name))
}

/// Whether `name` is a `*`-flagged autoload singleton (a bare global). `false` when no
/// `project.godot` is loaded — the seam, no warning.
fn is_autoload_singleton(db: &dyn Db, name: &str) -> bool {
    db.project_config().is_some_and(|config| {
        crate::queries::autoload_registry(db, config)
            .resolve_path(name)
            .is_some()
    })
}

/// Whether the file's resolved **user-script** base carries the `@tool` annotation (for
/// `MISSING_TOOL`). An engine base or an unresolved base is never `@tool`. Firewall-safe: reads the
/// base's `item_tree` (signature-level — a base *body* edit leaves the annotation set unchanged).
fn user_base_is_tool(
    db: &dyn Db,
    api: &EngineApi,
    tree: &ItemTree,
    res_path: Option<&str>,
) -> bool {
    let Ty::ScriptRef(sref) = resolve::resolve_base(db, api, tree, res_path) else {
        return false;
    };
    let Some(ft) = db.file_text(FileId(sref.0)) else {
        return false;
    };
    has_annotation(&crate::queries::item_tree(db, ft).annotations, "tool")
}

/// Whether `name` is registered as a global `class_name` by some file in the project. `false` when
/// no source root is set (single-file analysis can't observe the registry). Reads the firewalled
/// [`crate::queries::global_registry`].
fn is_registered_global_class(db: &dyn Db, name: &str) -> bool {
    db.source_root().is_some_and(|root| {
        crate::queries::global_registry(db, root)
            .resolve(name)
            .is_some()
    })
}

/// Whether a declared identifier `name` shadows a project/engine **global**, returning Godot's
/// category label for the `SHADOWED_GLOBAL_IDENTIFIER` message, else `None`. Mirrors
/// `gdscript_analyzer.cpp`'s `is_shadowing` global checks: a built-in function, a built-in (Variant)
/// type, a native class, an engine singleton, a project `class_name` global, or a `*`-autoload
/// singleton. **Conservative:** bare global pseudo-constants (`PI`/`TAU`) and global enum namespaces
/// (`Error`/`Key`) are deliberately excluded — they are rare as user identifiers (and the tokenizer
/// treats the math constants as literals), so this only ever *under*-warns vs. Godot, never a false
/// positive. With no source root / `project.godot`, the cross-file/autoload arms are silent (seam).
fn shadowed_global_kind(db: &dyn Db, api: &EngineApi, name: &str) -> Option<&'static str> {
    match resolve::resolve_global(api, name) {
        Some(GlobalDef::Builtin | GlobalDef::Utility) => return Some("built-in function"),
        Some(GlobalDef::BuiltinType(_)) => return Some("built-in type"),
        Some(GlobalDef::ClassType(_)) => return Some("native class"),
        Some(GlobalDef::Singleton(_)) => return Some("engine singleton"),
        // Bare pseudo-constants / global enums: intentionally not flagged (see doc above).
        Some(GlobalDef::Const(_) | GlobalDef::GlobalEnum) | None => {}
    }
    if is_registered_global_class(db, name) {
        return Some("global class");
    }
    if is_autoload_singleton(db, name) {
        return Some("autoload");
    }
    None
}

/// The `(name, name range, kind noun)` of a *value-declaring* member (`var`/`const`/`signal`) — the
/// members that `SHADOWED_GLOBAL_IDENTIFIER` checks at the class level. `None` for funcs / enums /
/// inner classes (where the "shadow" framing is weaker, matching Godot's `is_shadowing` callers).
fn member_value_decl(m: &Member) -> Option<(&SmolStr, TextRange, &'static str)> {
    match m {
        Member::Var(v) => Some((&v.name, v.name_range, "variable")),
        Member::Const(c) => Some((&c.name, c.name_range, "constant")),
        Member::Signal(s) => Some((&s.name, s.name_range, "signal")),
        _ => None,
    }
}

/// The declared `(name, name range)` of any named member (`func`/`var`/`const`/`signal`/named
/// `enum`/inner `class`), for the `CONFUSABLE_IDENTIFIER` scan. An anonymous `enum { … }` has no
/// name → `None`.
fn member_decl_name(m: &Member) -> Option<(&SmolStr, TextRange)> {
    match m {
        Member::Func(f) => Some((&f.name, f.name_range)),
        Member::Var(v) => Some((&v.name, v.name_range)),
        Member::Const(c) => Some((&c.name, c.name_range)),
        Member::Signal(s) => Some((&s.name, s.name_range)),
        Member::Class(c) => Some((&c.name, c.name_range)),
        Member::Enum(e) => e.name.as_ref().map(|n| (n, e.name_range)),
    }
}

/// Whether `name` is a `CONFUSABLE_IDENTIFIER` — a non-ASCII identifier that mixes scripts in a
/// spoofable way (UTS #39 restriction level ≥ `MinimallyRestrictive`, e.g. a Latin identifier with a
/// Cyrillic/Greek homoglyph like `pаypal`). Pure-ASCII (the overwhelming majority) and legitimate
/// single-script / CJK-plus-Latin identifiers are never flagged. Mirrors the intent of Godot's
/// `TextServer` confusable check with zero false positives on ordinary code.
fn is_confusable_identifier(name: &str) -> bool {
    use unicode_security::RestrictionLevel as RL;
    use unicode_security::RestrictionLevelDetection;
    if name.is_ascii() {
        return false; // the fast path for ~all real identifiers
    }
    name.detect_restriction_level() >= RL::MinimallyRestrictive
}

/// The NAME range of the file's `class_name` declaration, trimmed to the bare identifier (the
/// `Name` CST node absorbs leading inter-token trivia). `None` if the file declares no `class_name`
/// or the decl has no name token. Mirrors `item_tree::trimmed_name_range` / navigation's
/// `class_decl_target` (which lives in the IDE crate, hence this local CST scan).
fn class_name_decl_range(root: &GdNode) -> Option<TextRange> {
    use gdscript_syntax::SyntaxKind;
    let decl = gdscript_syntax::ast::descendants(root)
        .into_iter()
        .find(|n| n.kind() == SyntaxKind::ClassNameDecl)?;
    let name_node = decl.children().find(|c| c.kind() == SyntaxKind::Name)?;
    let r = cst::text_range_of(name_node);
    let text = name_node.text().to_string();
    let lead = u32::try_from(text.len() - text.trim_start().len()).unwrap_or(0);
    let len = u32::try_from(text.trim().len()).unwrap_or(0);
    Some(TextRange::new(r.start + lead, r.start + lead + len))
}

/// The byte range of the file's top-level `extends` declaration — the anchor for `CYCLIC_INHERITANCE`.
/// Two surface forms: a standalone `extends Target` (an [`ExtendsClause`] child of the `SourceFile`),
/// or the inline `class_name Name extends Target` (the `extends` keyword + target inside the
/// [`ClassNameDecl`]). Scans only the `SourceFile`'s DIRECT children, so an inner class's `extends`
/// (nested under `Class`/`ClassBody`) is never mistaken for the file's own. `None` if the file has no
/// top-level `extends`.
fn extends_decl_range(root: &GdNode) -> Option<TextRange> {
    use gdscript_syntax::SyntaxKind;
    for child in root.children() {
        match child.kind() {
            // Standalone `extends Target` — the whole clause is the anchor.
            SyntaxKind::ExtendsClause => return Some(cst::text_range_of(child)),
            // Inline `class_name Name extends Target` — anchor the `extends` keyword onward.
            SyntaxKind::ClassNameDecl => {
                if let Some(kw) = child.children().find(|c| c.kind() == SyntaxKind::ExtendsKw) {
                    let start = cst::text_range_of(kw).start;
                    let end = cst::text_range_of(child).end;
                    return Some(TextRange::new(start, end));
                }
            }
            _ => {}
        }
    }
    None
}

/// Whether the file's `extends` inheritance chain transitively returns to itself (a genuine cycle).
/// Walks base-by-base by `FileId` from `start`, stepping only across user `ScriptRef` bases (an
/// engine `Object`/`Unknown` base ends the chain). A `FileId` revisit means a cycle. We stop as soon
/// as we either revisit a file (cycle) or hit a non-script base (acyclic) — a deep but acyclic chain
/// terminates without a revisit and is NOT flagged. Depth is also hard-capped as belt-and-suspenders
/// (the visited set already guarantees termination).
fn extends_chain_is_cyclic(db: &dyn Db, start: FileId) -> bool {
    use std::collections::HashSet;
    let mut visited: HashSet<FileId> = HashSet::new();
    visited.insert(start);
    let mut current = start;
    for _ in 0..=64 {
        let Some(file) = db.file_text(current) else {
            return false;
        };
        let base = crate::queries::script_class(db, file).base().clone();
        let Ty::ScriptRef(next) = base else {
            return false; // engine `Object` / `Unknown` base — chain ends, no cycle.
        };
        let next_id = FileId(next.0);
        if !visited.insert(next_id) {
            // Revisiting an already-seen file closes a cycle. We report the cycle for every file ON
            // it (each file's own `extends` is genuinely cyclic), so no need to special-case `start`.
            return true;
        }
        current = next_id;
    }
    false
}

/// Infer a class field declaration as a single local-var statement (full annotation checks).
fn unit_from_decl(
    db: &dyn Db,
    api: &EngineApi,
    root: &GdNode,
    class: &ClassScope,
    ptr: AstPtr,
    range: TextRange,
) -> Option<Unit> {
    let node = ptr.to_node(root)?;
    let body = body::body_of_decl_stmt(&node);
    let result = infer(db, api, root, class, &body, Ty::Variant, false);
    Some(Unit {
        range,
        body,
        result,
    })
}

/// What type is expected of an expression (bidirectional checking).
enum Expectation {
    /// No expectation — pure synthesis.
    None,
    /// The expression is checked against this declared type.
    Has(Ty),
}

/// Navigate a dotted inner-class path (`Inner` / `Outer.Inner`) from a file's top item-tree to the
/// target [`InnerClassItem`]. `None` if any segment isn't an inner class.
fn find_inner_class<'a>(tree: &'a ItemTree, path: &str) -> Option<&'a InnerClassItem> {
    let mut members: &'a [Member] = &tree.members;
    let mut found: Option<&'a InnerClassItem> = None;
    for seg in path.split('.') {
        found = members.iter().find_map(|m| match m {
            Member::Class(c) if c.name == seg => Some(c),
            _ => None,
        });
        members = &found?.tree.members;
    }
    found
}

struct Cx<'a> {
    db: &'a dyn Db,
    api: &'a EngineApi,
    root: &'a GdNode,
    body: &'a Body,
    class: &'a ClassScope<'a>,
    self_ty: Ty,
    return_ty: Ty,
    expr_ty: FxHashMap<ExprId, Ty>,
    bindings: Vec<Binding>,
    diagnostics: Vec<Diagnostic>,
    /// Severity-free gateable warnings (Workstream 1), resolved by `gate()` downstream.
    raw_warnings: Vec<RawWarning>,
    /// Function-scoped local bindings (GDScript locals are function-, not block-, scoped).
    locals: FxHashMap<SmolStr, Ty>,
    /// The names of locals/params that were *read* during the walk — drives the `UNUSED_*` family (a
    /// declared binding whose name never appears here is unused). A bare assignment LHS (`x = …`) is a
    /// write, NOT a read, and is excluded (so an assigned-but-never-read local is correctly unused);
    /// a compound `x += …` still reads via its RHS, and a receiver / index target reads the base.
    used_locals: FxHashSet<SmolStr>,
    /// The active narrowing env for the current statement, keyed by a dotted access path. Rebuilt
    /// per statement from [`Cx::flow`] (Workstream 2) — not mutated ad-hoc anymore.
    narrowing: FxHashMap<String, Ty>,
    /// The precomputed per-body control-flow narrowing facts (Workstream 2). The checker consults
    /// `facts_before(stmt)` to build [`Cx::narrowing`]; it survives `else`/early-return/`and`-`or`.
    flow: FlowAnalysis,
    /// Whether this is a real function body (vs a class-field initializer body). Gates the
    /// body-only checks (`UNUSED_*`, `SHADOWED_VARIABLE`) so a field initializer doesn't, e.g.,
    /// "shadow itself" against its own member entry.
    is_func_body: bool,
    /// Definite-assignment facts (Workstream 2) — the locals assigned before each statement, for
    /// `UNASSIGNED_VARIABLE`. Consulted at a read via [`Cx::cur_stmt`].
    assigned: flow::AssignedAnalysis,
    /// The statement currently being inferred (set in `infer_stmt`), so a read can look up
    /// [`Cx::assigned`].
    cur_stmt: Option<body::StmtId>,
    /// Typed locals declared **without** an initializer — the only locals `UNASSIGNED_VARIABLE`
    /// considers (an untyped/`:=`/initialized local is never read-before-assign). Grows as the walk
    /// passes each declaration.
    needs_assignment: FxHashSet<SmolStr>,
    /// Names that are the direct LHS of an assignment (`x = …`/`x += …`) — a *write*, not a read, so
    /// excluded from the `UNASSIGNED_VARIABLE` check even though inference resolves the LHS.
    assign_lhs: FxHashSet<ExprId>,
}

impl Cx<'_> {
    // ---- small type constructors ----

    fn builtin(&self, name: &str) -> Ty {
        self.api
            .builtin_by_name(name)
            .map_or(Ty::Variant, Ty::Builtin)
    }
    fn int_ty(&self) -> Ty {
        self.builtin("int")
    }
    fn float_ty(&self) -> Ty {
        self.builtin("float")
    }
    fn bool_ty(&self) -> Ty {
        self.builtin("bool")
    }
    fn is_int(&self, ty: &Ty) -> bool {
        matches!(ty, Ty::Builtin(b) if self.api.builtin(*b).name == "int")
    }
    fn is_float(&self, ty: &Ty) -> bool {
        matches!(ty, Ty::Builtin(b) if self.api.builtin(*b).name == "float")
    }
    fn is_numeric(&self, ty: &Ty) -> bool {
        self.is_int(ty) || self.is_float(ty)
    }

    // ---- diagnostics ----

    fn emit(&mut self, range: TextRange, severity: Severity, code: &str, message: String) {
        self.diagnostics.push(Diagnostic {
            range,
            severity,
            code: code.to_owned(),
            message,
            source: DiagnosticSource::Type,
            fixes: Vec::new(),
        });
    }

    /// Record a gateable Godot warning, severity-free. The resolved severity (and whether it fires
    /// at all) is decided later by [`crate::warnings::gate`], keyed on the project's warning
    /// settings — so a settings edit never re-runs inference (Workstream 1, the salsa firewall).
    fn warn(&mut self, range: TextRange, code: WarningCode, message: String) {
        self.raw_warnings.push(RawWarning {
            range,
            code,
            message,
        });
    }

    fn range_of(&self, id: ExprId) -> TextRange {
        self.body.source_map.expr_range(id)
    }

    /// Run `is_assignable(from, to)` and raise the matching diagnostic. Safe to call
    /// unconditionally: `to` being `Variant`/`Unknown` yields `Ok`/no diagnostic.
    fn check_assign(&mut self, from: &Ty, to: &Ty, range: TextRange) {
        match ty::is_assignable(self.api, from, to) {
            Assign::Narrowing => self.warn(
                range,
                WarningCode::NarrowingConversion,
                "Narrowing conversion (float is converted to int and loses precision).".to_owned(),
            ),
            Assign::No => {
                let to_label = to.label(self.api).unwrap_or_else(|| "?".to_owned());
                let from_label = from.label(self.api).unwrap_or_else(|| "?".to_owned());
                self.emit(
                    range,
                    Severity::Error,
                    TYPE_MISMATCH,
                    format!(
                        "Cannot assign a value of type \"{from_label}\" to a target of type \"{to_label}\"."
                    ),
                );
            }
            // `int` assigned to an enum slot without an explicit cast (the previously-dead arm).
            Assign::IntAsEnum => self.warn(
                range,
                WarningCode::IntAsEnumWithoutCast,
                "Integer used when an enum value is expected. Cast the value to the enum type."
                    .to_owned(),
            ),
            Assign::Ok | Assign::OkUnsafe => {}
        }
    }

    /// Flag a statement whose expression has no effect: a bare value (`STANDALONE_EXPRESSION`) or a
    /// ternary used as a statement (`STANDALONE_TERNARY`). A call / await / assignment / `preload`
    /// has an effect and is never flagged.
    fn check_standalone(&mut self, e: ExprId) {
        if self.expr_has_side_effect(e) {
            return;
        }
        match self.body.expr(e) {
            Expr::Ternary { .. } => self.warn(
                self.range_of(e),
                WarningCode::StandaloneTernary,
                "Standalone ternary conditional: the return value is discarded.".to_owned(),
            ),
            // Not value-like statements / forms with subtle effects — never flag.
            Expr::Missing | Expr::Lambda { .. } | Expr::GetNode { .. } | Expr::Preload { .. } => {}
            _ => self.warn(
                self.range_of(e),
                WarningCode::StandaloneExpression,
                "Standalone expression (the line has no effect).".to_owned(),
            ),
        }
    }

    /// Whether evaluating an expression may have a side effect — a call, an `await`, a `preload`,
    /// or an assignment anywhere in the subtree. Used to suppress `STANDALONE_*` on effectful lines.
    fn expr_has_side_effect(&self, e: ExprId) -> bool {
        match self.body.expr(e) {
            Expr::Call { .. }
            | Expr::Await(_)
            | Expr::Preload { .. }
            | Expr::Bin {
                op: BinOp::Assign, ..
            } => true,
            Expr::Bin { lhs, rhs, .. }
            | Expr::In { lhs, rhs, .. }
            | Expr::Index {
                base: lhs,
                index: rhs,
            } => self.expr_has_side_effect(*lhs) || self.expr_has_side_effect(*rhs),
            Expr::Unary { operand, .. }
            | Expr::Paren(operand)
            | Expr::Cast { operand, .. }
            | Expr::Is { operand, .. } => self.expr_has_side_effect(*operand),
            Expr::Field { receiver, .. } => self.expr_has_side_effect(*receiver),
            Expr::Ternary {
                cond,
                then_branch,
                else_branch,
            } => {
                self.expr_has_side_effect(*cond)
                    || self.expr_has_side_effect(*then_branch)
                    || self.expr_has_side_effect(*else_branch)
            }
            Expr::Array(items) => items.iter().any(|&i| self.expr_has_side_effect(i)),
            Expr::Dict(entries) => entries.iter().any(|(k, v)| {
                self.expr_has_side_effect(*k) || v.is_some_and(|e| self.expr_has_side_effect(e))
            }),
            _ => false,
        }
    }

    // ---- statements ----

    fn infer_block(&mut self, block: &[body::StmtId]) {
        for &stmt in block {
            self.infer_stmt(stmt);
        }
    }

    fn infer_stmt(&mut self, id: body::StmtId) {
        // Install the narrowing in force *before* this statement (Workstream 2). Recomputed per
        // statement from the precomputed flow facts — replaces the old ad-hoc `in_branch` frames.
        self.narrowing = self.facts_to_narrowing(id);
        self.cur_stmt = Some(id); // for the read-before-assign (UNASSIGNED_VARIABLE) check
        match self.body.stmt(id).clone() {
            Stmt::Expr(e) => {
                self.infer_expr(e, &Expectation::None);
                self.check_standalone(e);
            }
            Stmt::Var(v) => self.infer_local_var(&v),
            Stmt::Return(e) => {
                if let Some(e) = e {
                    let expected = if self.return_ty.is_uninformative() {
                        Expectation::None
                    } else {
                        Expectation::Has(self.return_ty.clone())
                    };
                    let t = self.infer_expr(e, &expected);
                    if let Expectation::Has(ret) = expected {
                        self.check_assign(&t, &ret, self.range_of(e));
                    }
                }
            }
            Stmt::If {
                cond,
                then_branch,
                elifs,
                else_branch,
            } => {
                // The branch narrowing now lives in the flow facts, so each sub-statement installs
                // its own via `infer_stmt`. Restore the if-level facts before each guard (a block
                // walk overwrites `self.narrowing`).
                let at_if = self.narrowing.clone();
                self.infer_expr(cond, &Expectation::None);
                self.infer_block(&then_branch);
                for (econd, eblock) in elifs {
                    self.narrowing.clone_from(&at_if);
                    self.infer_expr(econd, &Expectation::None);
                    self.infer_block(&eblock);
                }
                if let Some(eb) = else_branch {
                    self.infer_block(&eb);
                }
            }
            Stmt::While { cond, body } => {
                self.infer_expr(cond, &Expectation::None);
                self.infer_block(&body);
            }
            Stmt::For(f) => {
                let iter_ty = self.infer_expr(f.iter, &Expectation::None);
                let var_ty = f.var_type.as_ref().map_or_else(
                    || self.loop_var_ty(&iter_ty),
                    |ptr| self.resolve_ptr_ty(*ptr),
                );
                self.bindings.push(Binding {
                    name: f.var.clone(),
                    name_range: f.var_range,
                    ty: var_ty.clone(),
                    init: None,
                    annotated: f.var_type.is_some(),
                    inferred_colon_eq: false,
                    is_const: false,
                    kind: BindingKind::ForVar,
                });
                self.locals.insert(f.var.clone(), var_ty);
                self.infer_block(&f.body);
            }
            Stmt::Match { scrutinee, arms } => {
                let at_match = self.narrowing.clone();
                self.infer_expr(scrutinee, &Expectation::None);
                for arm in arms {
                    // Restore the match-level facts before each arm's guard (a prior arm's body
                    // walk overwrote `self.narrowing`).
                    self.narrowing.clone_from(&at_match);
                    for b in &arm.binds {
                        // Record the capture as a binding so navigation (find-refs / rename) sees
                        // it as a local that shadows a same-named member; the type is the Phase-2
                        // `Variant`.
                        self.bindings.push(Binding {
                            name: b.name.clone(),
                            name_range: b.range,
                            ty: Ty::Variant,
                            init: None,
                            annotated: false,
                            inferred_colon_eq: false,
                            is_const: false,
                            kind: BindingKind::MatchBind,
                        });
                        self.locals.insert(b.name.clone(), Ty::Variant);
                    }
                    if let Some(g) = arm.guard {
                        self.infer_expr(g, &Expectation::None);
                    }
                    self.infer_block(&arm.body);
                }
            }
            Stmt::Break | Stmt::Continue | Stmt::Pass => {}
            Stmt::Assert(cond) => {
                if let Some(cond) = cond {
                    self.infer_expr(cond, &Expectation::None);
                    self.check_assert_constant(cond);
                }
            }
        }
    }

    /// `ASSERT_ALWAYS_TRUE` / `ASSERT_ALWAYS_FALSE` — fire when the assert condition is a constant
    /// with a known boolean value (Godot `resolve_assert`: a constant condition is booleanized and
    /// warned). Sound subset via [`Cx::const_bool_of`]: a literal `true`/`false`, or `null` (false).
    fn check_assert_constant(&mut self, cond: ExprId) {
        let Some(always) = self.const_bool_of(cond) else {
            return;
        };
        let (code, msg) = if always {
            (
                WarningCode::AssertAlwaysTrue,
                "The assert condition is always true, so this assert has no effect.",
            )
        } else {
            (
                WarningCode::AssertAlwaysFalse,
                "The assert condition is always false, so this assert will always fail.",
            )
        };
        self.warn(self.range_of(cond), code, msg.to_owned());
    }

    /// The constant boolean value of `expr`, when it is a literal whose booleanization is known — a
    /// bool literal, or `null` (false). `None` for any other / non-constant expression (the sound
    /// default: no false `ASSERT_ALWAYS_*`). Mirrors Godot's `reduced_value.booleanize()` restricted
    /// to the literal forms (named-constant / arithmetic folding is deliberately not attempted).
    fn const_bool_of(&self, expr: ExprId) -> Option<bool> {
        match self.body.expr(expr) {
            Expr::Literal(Literal::Bool(b)) => Some(*b),
            Expr::Literal(Literal::Null) => Some(false),
            _ => None,
        }
    }

    fn infer_local_var(&mut self, v: &body::LocalVar) {
        let annotated = v.type_ref.map(|p| self.resolve_ptr_ty(p));
        let init_ty = v.init.map(|e| {
            let expected = annotated
                .as_ref()
                .map_or(Expectation::None, |t| Expectation::Has(t.clone()));
            self.infer_expr(e, &expected)
        });
        let range = v.init.map_or(v.name_range, |e| self.range_of(e));

        let binding_ty = match (&annotated, &init_ty) {
            // `var x: T = e` — hard slot; check the initializer against it.
            (Some(t), Some(init)) => {
                self.check_assign(init, t, range);
                t.clone()
            }
            // `var x: T` (no init).
            (Some(t), None) => t.clone(),
            // `var x := e` — inferred (hard); guard the Variant / null cases.
            (None, Some(init)) if v.is_inferred => {
                if init.is_variant() {
                    self.warn(
                        range,
                        WarningCode::InferenceOnVariant,
                        inference_on_variant_msg(if v.is_const { "constant" } else { "variable" }),
                    );
                    Ty::Variant
                } else {
                    // `Unknown` (the seam) stays `Unknown` with no warning.
                    init.clone()
                }
            }
            // `var x = e` — untyped, soft → Variant. `const X = e` keeps the inferred type.
            (None, Some(init)) => {
                if v.is_const {
                    init.clone()
                } else {
                    Ty::Variant
                }
            }
            (None, None) => Ty::Variant,
        };
        // SHADOWED_VARIABLE — a local `var`/`const` whose name shadows a parameter or an own class
        // member (a redeclared *local* is a Godot error, not handled here). Sound: only fires on a
        // genuine outer-scope shadow. The binding isn't pushed yet, so the `Param` scan can't see it.
        // Gated to a real function body — a class-field initializer's own `var n` is not a shadow.
        let shadows_param = self
            .bindings
            .iter()
            .any(|b| b.kind == BindingKind::Param && b.name == v.name);
        // Only a *value* member (var/const/signal, or an anon-enum constant) — not a method or a
        // type name, where the "shadow" framing is weaker — counts, to stay conservative.
        let shadows_member = match self.class.lookup(&v.name) {
            Some(ClassItem::EnumVariant) => true,
            Some(item) => matches!(
                self.class.member(item),
                Some(Member::Var(_) | Member::Const(_) | Member::Signal(_))
            ),
            None => false,
        };
        if self.is_func_body {
            let what = if v.is_const { "constant" } else { "variable" };
            // A global-identifier shadow takes precedence over a variable/base-class shadow (Godot's
            // `is_shadowing` checks globals first and returns), so the variable-shadow is emitted only
            // when the name does NOT shadow a global — the global one is emitted by the binding
            // post-pass in `infer`, keeping a single warning per declaration.
            if shadowed_global_kind(self.db, self.api, &v.name).is_none() {
                if shadows_param || shadows_member {
                    let outer = if shadows_param {
                        "parameter"
                    } else {
                        "class member"
                    };
                    self.warn(
                        v.name_range,
                        WarningCode::ShadowedVariable,
                        format!(
                            "The local {what} \"{}\" shadows a {outer} of the same name.",
                            v.name
                        ),
                    );
                } else if self.engine_base_has_value_member(&v.name) {
                    // An own-member shadow already won above; only a *base*-member shadow reaches here.
                    self.warn(
                        v.name_range,
                        WarningCode::ShadowedVariableBaseClass,
                        format!(
                            "The local {what} \"{}\" shadows a member of a base class.",
                            v.name
                        ),
                    );
                }
            }
            // ENUM_VARIABLE_WITHOUT_DEFAULT — a local typed as an enum with no initializer (the
            // implicit `0` may not name a valid enum value). Only an explicit `Ty::Enum` annotation.
            if v.init.is_none() && matches!(annotated.as_ref(), Some(Ty::Enum(_))) {
                self.warn(
                    v.name_range,
                    WarningCode::EnumVariableWithoutDefault,
                    format!(
                        "The enum variable \"{}\" has no default value (it defaults to 0, which may not be a valid enum value).",
                        v.name
                    ),
                );
            }
            // A typed local declared WITHOUT an initializer is the only `UNASSIGNED_VARIABLE`
            // candidate (an untyped / `:=` / initialized local is never read-before-assign).
            if v.type_ref.is_some() && v.init.is_none() {
                self.needs_assignment.insert(v.name.clone());
            }
        }
        self.bindings.push(Binding {
            name: v.name.clone(),
            name_range: v.name_range,
            ty: binding_ty.clone(),
            init: v.init,
            annotated: v.type_ref.is_some(),
            inferred_colon_eq: v.is_inferred,
            is_const: v.is_const,
            kind: BindingKind::Var,
        });
        // A (re-)declaration's narrowing invalidation is handled by the flow analysis (Workstream 2).
        self.locals.insert(v.name.clone(), binding_ty);
    }

    // ---- expressions ----

    fn infer_expr(&mut self, id: ExprId, expected: &Expectation) -> Ty {
        let ty = self.synth_expr(id, expected);
        self.expr_ty.insert(id, ty.clone());
        ty
    }

    #[allow(clippy::too_many_lines)]
    fn synth_expr(&mut self, id: ExprId, expected: &Expectation) -> Ty {
        match self.body.expr(id).clone() {
            Expr::Missing => Ty::Error,
            Expr::Literal(lit) => self.literal_ty(lit),
            Expr::Name(name) => self.resolve_name(id, &name),
            Expr::SelfExpr => self.self_ty.clone(),
            Expr::Super => self.class.base.clone(),
            Expr::Paren(inner) => self.infer_expr(inner, expected),
            Expr::Bin { op, lhs, rhs } => self.infer_bin(id, op, lhs, rhs),
            Expr::Unary { op, operand } => {
                let t = self.infer_expr(operand, &Expectation::None);
                match op {
                    UnOp::Not => self.bool_ty(),
                    UnOp::BitNot => self.int_ty(),
                    UnOp::Neg | UnOp::Pos => {
                        if t.is_uninformative() || self.is_numeric(&t) {
                            t
                        } else {
                            Ty::Variant
                        }
                    }
                }
            }
            Expr::Ternary {
                cond,
                then_branch,
                else_branch,
            } => {
                self.infer_expr(cond, &Expectation::None);
                let a = self.infer_expr(then_branch, expected);
                let b = self.infer_expr(else_branch, expected);
                // A `null` branch does not poison the other: `x if c else null` is nullable-`x`.
                if self.is_null(else_branch) {
                    a
                } else if self.is_null(then_branch) {
                    b
                } else {
                    let r = self.join(&a, &b);
                    // Both arms informative but with no common type (the join widened to Variant) —
                    // the ternary's two values are mutually incompatible.
                    if r.is_variant() && !a.is_uninformative() && !b.is_uninformative() {
                        self.warn(
                            self.range_of(id),
                            WarningCode::IncompatibleTernary,
                            "The values of the ternary conditional are not mutually compatible."
                                .to_owned(),
                        );
                    }
                    r
                }
            }
            Expr::Call { callee, args } => self.infer_call(callee, &args),
            Expr::Field {
                receiver,
                name,
                name_range,
            } => {
                self.infer_field(receiver, &name, name_range, /*as_method=*/ false)
            }
            Expr::Index { base, index } => {
                let base_ty = self.infer_expr(base, &Expectation::None);
                self.infer_expr(index, &Expectation::None);
                self.index_ty(&base_ty)
            }
            Expr::Is { operand, .. } => {
                self.infer_expr(operand, &Expectation::None);
                self.bool_ty()
            }
            Expr::Cast { operand, ty } => {
                self.infer_expr(operand, &Expectation::None);
                ty.map_or(Ty::Variant, |p| self.resolve_ptr_ty(p))
            }
            Expr::In { lhs, rhs, .. } => {
                self.infer_expr(lhs, &Expectation::None);
                self.infer_expr(rhs, &Expectation::None);
                self.bool_ty()
            }
            Expr::Await(operand) => {
                let operand_ty = self.infer_expr(operand, &Expectation::None);
                // `await coroutine()` yields the call's value, so await is **identity** on the operand
                // type (`await f()` for `func f() -> int` is `int`) — recovered here. `await signal`
                // instead yields the signal's emitted payload, which needs the Phase-3+ signal-signature
                // table; until then it's the seam (never `Variant`, so `var x := await sig` never warns).
                if matches!(operand_ty, Ty::Signal(_)) {
                    Ty::Unknown
                } else {
                    operand_ty
                }
            }
            Expr::Array(elems) => {
                // Checking mode: an expected `Array[T]` is pushed down onto the literal (so
                // `var a: Array[String] = []` / `[...]` is accepted). Otherwise the engine does
                // not infer a literal's element type past `Variant`.
                let pushed = match expected {
                    Expectation::Has(Ty::Array(e)) => Some((**e).clone()),
                    _ => None,
                };
                let elem_exp = pushed.clone().map_or(Expectation::None, Expectation::Has);
                for e in elems {
                    self.infer_expr(e, &elem_exp);
                }
                pushed.map_or_else(Ty::array_of_variant, |e| Ty::Array(Box::new(e)))
            }
            Expr::Dict(entries) => {
                let pushed = match expected {
                    Expectation::Has(Ty::Dict(k, v)) => Some(((**k).clone(), (**v).clone())),
                    _ => None,
                };
                let (kx, vx) = pushed
                    .clone()
                    .map_or((Expectation::None, Expectation::None), |(k, v)| {
                        (Expectation::Has(k), Expectation::Has(v))
                    });
                for (k, v) in entries {
                    self.infer_expr(k, &kx);
                    if let Some(v) = v {
                        self.infer_expr(v, &vx);
                    }
                }
                pushed.map_or_else(Ty::dict_of_variant, |(k, v)| {
                    Ty::Dict(Box::new(k), Box::new(v))
                })
            }
            Expr::Lambda { params, body } => {
                self.infer_lambda(&params, &body);
                Ty::Callable
            }
            Expr::Preload { arg, path } => {
                if let Some(arg) = arg {
                    self.infer_expr(arg, &Expectation::None);
                }
                // A constant string-literal path resolves to the declaring file's `ScriptRef`
                // (M3 — a SCRIPT meta-type in Godot; `X.new()`/`X.member` then resolve via the
                // usual `ScriptRef` walk). A non-constant argument (`preload(var)`) — which Godot
                // itself rejects — stays the seam, never a false diagnostic.
                match path {
                    // Anchor a relative `preload("sibling.gd")` to the importing file's directory
                    // before resolving (Godot anchors relative resource paths); absolute paths pass
                    // through, and a relative path with no anchor stays the seam.
                    Some(p) => {
                        match resolve::anchor_res_path(self.self_res_path().as_deref(), &p) {
                            Some(abs) => resolve::resolve_external(
                                self.db,
                                &resolve::ExternalRef::Preload(abs),
                            ),
                            None => Ty::Unknown,
                        }
                    }
                    None => Ty::Unknown,
                }
            }
            // `$Path`/`%Unique` — resolve the literal path against the owning scene to the node's
            // concrete type (Phase-4 M1); a computed/unresolvable path stays `Object(Node)`.
            Expr::GetNode { path, unique } => self.resolve_node_path(id, path.as_deref(), unique),
        }
    }

    /// Whether `id` is the `null` literal.
    fn is_null(&self, id: ExprId) -> bool {
        matches!(self.body.expr(id), Expr::Literal(Literal::Null))
    }

    fn literal_ty(&self, lit: Literal) -> Ty {
        match lit {
            Literal::Int => self.int_ty(),
            Literal::Float | Literal::MathConst => self.float_ty(),
            Literal::Bool(_) => self.bool_ty(),
            Literal::Str => self.builtin("String"),
            Literal::StringName => self.builtin("StringName"),
            Literal::NodePath => self.builtin("NodePath"),
            // `null` is compatible everywhere; typing it `Variant` avoids false mismatches.
            Literal::Null => Ty::Variant,
        }
    }

    fn node_ty(&self) -> Ty {
        self.api
            .class_by_name("Node")
            .map_or(Ty::Unknown, Ty::Object)
    }

    // ---- scene-aware node-path typing (Phase-4 M1) ----

    /// Resolve a `$Path`/`%Unique`/`get_node("…")` literal node path against the owning scene to the
    /// node's concrete type. A computed (`None`) path, no owning scene, an `..`/absolute escape, or a
    /// path that descends into an instanced sub-scene all degrade to `Object(Node)` — never a false
    /// positive. A *genuinely* absent in-scene node raises `INVALID_NODE_PATH` (M2), but only when
    /// the script attaches to exactly one scene (an ambiguous multi-scene attachment stays silent).
    fn resolve_node_path(&mut self, id: ExprId, path: Option<&str>, unique: bool) -> Ty {
        use gdscript_scene::NodePathResolution as R;
        let fallback = self.node_ty();
        let Some(path) = path else {
            return fallback; // computed `get_node(var)` — stays `Node`
        };
        // An absolute `/root/<Autoload>` access resolves to the autoload's type — singleton OR
        // loaded-but-not-global (both live at `/root/Name`). Independent of any owning scene. A deeper
        // tail (`/root/Name/Child`) would need to walk the autoload's own scene; left as the seam.
        if !unique && let Some(ty) = self.resolve_root_autoload_path(path) {
            return ty;
        }
        let Some(ctx) = self.owning_scene() else {
            return fallback; // no scene attaches this script (dynamic UI / single-file)
        };
        // Multi-scene attachment (M2 §6.3): a `$Path` may resolve to a different node type in each
        // attaching scene, so type it as the COMMON BASE across all of them (never the first-scene
        // type, which could be wrong for another scene). If any scene can't resolve it identically,
        // degrade to `Node` — never a false positive and never a false `INVALID_NODE_PATH`.
        if ctx.ambiguous {
            return self.union_node_ty(path, unique).unwrap_or(fallback);
        }
        let resolution = if unique {
            ctx.model.classify_unique(path)
        } else {
            ctx.model.classify_path_from(ctx.attach, path)
        };
        match resolution {
            R::Resolved(idx) => ctx
                .model
                .node(idx)
                .and_then(|n| self.scene_node_ty(&ctx.model, n, 0))
                .unwrap_or(fallback),
            R::Missing => {
                let what = if unique { "unique name" } else { "node path" };
                let sigil = if unique { "%" } else { "$" };
                self.emit(
                    self.range_of(id),
                    Severity::Warning,
                    INVALID_NODE_PATH,
                    format!("no {what} `{sigil}{path}` in the owning scene"),
                );
                fallback
            }
            // The path descends into an instanced sub-scene (`$Enemy/Sprite`): resolve the tail in
            // the sub-scene's own tree (`Sprite` typed by `enemy.tscn`). Any failure → `Node`.
            R::IntoInstance => {
                let walked = if unique {
                    ctx.model.resolve_unique_into_instance(path)
                } else {
                    ctx.model.resolve_into_instance(ctx.attach, path)
                };
                walked
                    .and_then(|(inst, tail)| {
                        let inst_node = ctx.model.node(inst)?;
                        self.resolve_into_instance_ty(&ctx.model, inst_node, &tail, 0)
                    })
                    .unwrap_or(fallback)
            }
            // An `..`/absolute escape out of the slice → `Node`, never a false warning.
            R::Escaped => fallback,
        }
    }

    /// Union-type a `$Path`/`%Unique` across **every** scene that attaches this script (the rare
    /// multi-scene case): resolve the path in each scene, then take the COMMON BASE of the per-scene
    /// node types. `None` (→ caller degrades to `Node`) if any scene fails to resolve the path the
    /// same way — keeping the no-false-positive contract on an ambiguous attachment.
    fn union_node_ty(&self, path: &str, unique: bool) -> Option<Ty> {
        use gdscript_scene::NodePathResolution as R;
        let res_path = self.self_res_path()?;
        let root = self.db.source_root()?;
        let attaches = crate::queries::script_scene_attachments(self.db, root)
            .get(res_path.as_str())
            .cloned()?;
        let mut acc: Option<Ty> = None;
        for (scene_file, attach) in &attaches {
            let ft = self.db.file_text(*scene_file)?;
            let model = crate::queries::scene_model(self.db, ft);
            let resolution = if unique {
                model.classify_unique(path)
            } else {
                model.classify_path_from(*attach, path)
            };
            let R::Resolved(idx) = resolution else {
                return None; // a miss / escape / into-instance in some scene → bail to `Node`
            };
            let ty = model
                .node(idx)
                .and_then(|n| self.scene_node_ty(&model, n, 0))?;
            acc = Some(match acc {
                None => ty,
                Some(prev) => self.common_base(&prev, &ty),
            });
        }
        acc
    }

    /// The common base of two scene-node types — the lowest engine class both descend from (walk
    /// `a`'s ancestor chain, return the first that `b` is a subclass of). Identical types collapse to
    /// themselves; a `ScriptRef` or any mixed pair degrades to the `Node` floor (the engine base for
    /// every scene node), which is always a sound supertype.
    fn common_base(&self, a: &Ty, b: &Ty) -> Ty {
        if a == b {
            return a.clone();
        }
        if let (Ty::Object(ca), Ty::Object(cb)) = (a, b) {
            let mut cur = Some(*ca);
            while let Some(c) = cur {
                if self.api.is_subclass(*cb, c) {
                    return Ty::Object(c);
                }
                cur = self.api.class(c).base;
            }
        }
        self.node_ty()
    }

    /// Resolve an absolute `/root/<Autoload>` node path to the autoload's type (singleton or
    /// loaded-but-not-global — both are children of the scene-tree root). `None` for any other path,
    /// including a deeper tail (`/root/Name/Child`, which would need the autoload's own scene) — those
    /// degrade to the `Node` seam with no false positive.
    fn resolve_root_autoload_path(&self, path: &str) -> Option<Ty> {
        let name = path.strip_prefix("/root/")?;
        // Only the autoload node itself (no trailing segment) for now.
        if name.is_empty() || name.contains('/') {
            return None;
        }
        let ty = resolve::resolve_autoload_any(self.db, name);
        (!ty.is_uninformative()).then_some(ty)
    }

    /// The owning-scene context for the current file (scene + attach node + multi-scene ambiguity).
    /// Recovered from `self_ty`, which `analyze_file` sets to the file's own `ScriptRef` (so no extra
    /// `FileId` threading).
    fn owning_scene(&self) -> Option<crate::queries::SceneContext> {
        let Ty::ScriptRef(sref) = &self.self_ty else {
            return None;
        };
        let ft = self.db.file_text(FileId(sref.0))?;
        crate::queries::scene_context(self.db, ft)
    }

    /// The importing file's own `res://` path (from `self_ty`), for anchoring relative
    /// `preload`/`extends` paths to its directory. `None` when the file has no resource path.
    fn self_res_path(&self) -> Option<SmolStr> {
        let Ty::ScriptRef(sref) = &self.self_ty else {
            return None;
        };
        self.db.file_text(FileId(sref.0))?.res_path(self.db)
    }

    /// The concrete `Ty` of a scene node, by precedence: an attached script's own class (most
    /// specific) wins; else the declared `type=` (native class or `class_name`); else — an instanced
    /// node (`instance=`, no own `type=`/script) — the **instanced sub-scene's root** type (M3,
    /// recursive). `None` for a node we can't sharpen (the caller degrades to `Node`).
    fn scene_node_ty(&self, scene: &SceneModel, node: &SceneNode, depth: u32) -> Option<Ty> {
        if let Some(script_ty) = self.node_script_ref(scene, node) {
            return Some(script_ty);
        }
        if let Some(decl) = node.decl_type.as_ref() {
            let ty = resolve::resolve_type_name(self.db, self.api, decl);
            if !ty.is_uninformative() {
                return Some(ty);
            }
        }
        self.instance_root_ty(scene, node, depth)
            .or_else(|| self.override_child_ty(scene, node, depth))
    }

    /// An **override child** *under* an instance: a node added/overridden in the outer scene beneath
    /// an `instance=` boundary (`[node name="Sprite" parent="Enemy"]` over an instanced `enemy.tscn`),
    /// carrying no own `type=`/`script`/`instance=` — so its real type lives in the instanced
    /// sub-scene. Walk up to the nearest instance-boundary ancestor, then type the node by its same
    /// path *inside* that sub-scene (so the outer override of `enemy.tscn`'s `Sprite` types as the
    /// sub-scene's `Sprite`, not bare `Node`). `None` if the node is not under an instance (the
    /// caller then floors to `Node`, unchanged). Depth-bounded against an instancing cycle.
    fn override_child_ty(&self, scene: &SceneModel, node: &SceneNode, depth: u32) -> Option<Ty> {
        if depth >= 16 {
            return None;
        }
        let mut segs_rev: Vec<String> = vec![node.name.to_string()];
        let mut parent_idx = node.parent_idx?;
        let mut guard = 0u32;
        loop {
            let parent = scene.node(parent_idx)?;
            if parent.instance.is_some() {
                segs_rev.reverse();
                let rel = segs_rev.join("/");
                return self.resolve_into_instance_ty(scene, parent, &rel, depth + 1);
            }
            segs_rev.push(parent.name.to_string());
            parent_idx = parent.parent_idx?;
            guard += 1;
            if guard > 4096 {
                return None;
            }
        }
    }

    /// An instanced node (`instance=ExtResource(id)`) takes the type of the instanced sub-scene's
    /// ROOT node — resolved recursively, so the root's own script / `type=` / nested instance all
    /// flow through (so `$Enemy` types as `enemy.tscn`'s root class, not bare `Node`). Depth-bounded
    /// against an instancing cycle (scene A instances B instances A).
    fn instance_root_ty(&self, scene: &SceneModel, node: &SceneNode, depth: u32) -> Option<Ty> {
        if depth >= 16 {
            return None;
        }
        let (sub, sub_root) = self.instance_subscene(scene, node)?;
        let root_node = sub.node(sub_root)?;
        self.scene_node_ty(&sub, root_node, depth + 1)
    }

    /// The instanced sub-scene's model + its root index, for an instance node (`instance=ExtResource`
    /// → `res://` path → `FileId` → `scene_model`). The shared resolution step for both
    /// [`instance_root_ty`](Self::instance_root_ty) (the node's own type) and
    /// [`resolve_into_instance_ty`](Self::resolve_into_instance_ty) (paths that go *into* it).
    fn instance_subscene(
        &self,
        scene: &SceneModel,
        node: &SceneNode,
    ) -> Option<(Arc<SceneModel>, gdscript_scene::NodeIdx)> {
        let inst = node.instance.as_ref()?;
        let path = scene.ext_resources.get(inst)?.path.as_ref()?;
        let root = self.db.source_root()?;
        let file = crate::queries::res_path_registry(self.db, root)
            .get(path.as_str())
            .copied()?;
        let ft = self.db.file_text(file)?;
        let sub = crate::queries::scene_model(self.db, ft);
        let sub_root = sub.root?;
        Some((sub, sub_root))
    }

    /// Type a node path that descends INTO an instanced sub-scene: `instance_node` is the boundary
    /// (an `instance=` node) and `tail` is the remaining path. Resolve `tail` from the sub-scene's
    /// root, recursing through further instance boundaries inside it. Depth-bounded against an
    /// instancing cycle. `None` (→ `Node`, no false warning) if the tail genuinely can't be typed.
    fn resolve_into_instance_ty(
        &self,
        scene: &SceneModel,
        instance_node: &SceneNode,
        tail: &str,
        depth: u32,
    ) -> Option<Ty> {
        if depth >= 16 {
            return None;
        }
        let (sub, sub_root) = self.instance_subscene(scene, instance_node)?;
        if let Some(idx) = sub.resolve_path_from(sub_root, tail) {
            let n = sub.node(idx)?;
            return self.scene_node_ty(&sub, n, depth + 1);
        }
        // The tail crosses a further instance boundary *inside* the sub-scene — keep descending.
        let (inner, inner_tail) = sub.resolve_into_instance(sub_root, tail)?;
        let inner_node = sub.node(inner)?;
        self.resolve_into_instance_ty(&sub, inner_node, &inner_tail, depth + 1)
    }

    /// The `ScriptRef` of a node's attached `.gd` script (`script = ExtResource(id)` → its `res://`
    /// path → `FileId`), or `None` if it has no resolvable external script.
    fn node_script_ref(&self, scene: &SceneModel, node: &SceneNode) -> Option<Ty> {
        let path = scene
            .ext_resources
            .get(node.script.as_ref()?)?
            .path
            .as_ref()?;
        let root = self.db.source_root()?;
        let file = crate::queries::res_path_registry(self.db, root)
            .get(path.as_str())
            .copied()?;
        Some(Ty::ScriptRef(ScriptRefId(file.0)))
    }

    fn infer_bin(&mut self, id: ExprId, op: BinOp, lhs: ExprId, rhs: ExprId) -> Ty {
        if op == BinOp::Assign {
            return self.infer_assign(lhs, rhs);
        }
        // Short-circuit narrowing (Workstream 2): the RHS of `a and b` is typed under `a`'s
        // then-facts; `a or b`'s RHS under `a`'s else-facts. Restore the env afterward.
        if matches!(op, BinOp::And | BinOp::Or) {
            self.infer_expr(lhs, &Expectation::None);
            let saved = self.narrowing.clone();
            self.apply_condition_facts(lhs, op == BinOp::And);
            self.infer_expr(rhs, &Expectation::None);
            self.narrowing = saved;
            return self.bool_ty();
        }
        let lt = self.infer_expr(lhs, &Expectation::None);
        let rt = self.infer_expr(rhs, &Expectation::None);
        if op.is_boolean() {
            return self.bool_ty();
        }
        // `int / int` discards the fractional part.
        if op == BinOp::Div && self.is_int(&lt) && self.is_int(&rt) {
            self.warn(
                self.range_of(id),
                WarningCode::IntegerDivision,
                "Integer division. Decimal part will be discarded.".to_owned(),
            );
            return self.int_ty();
        }
        self.bin_result(op, &lt, &rt)
    }

    fn infer_assign(&mut self, lhs: ExprId, rhs: ExprId) -> Ty {
        let slot = self.infer_expr(lhs, &Expectation::None);
        let expected = if slot.is_uninformative() {
            Expectation::None
        } else {
            Expectation::Has(slot.clone())
        };
        let value = self.infer_expr(rhs, &expected);
        if !slot.is_uninformative() {
            self.check_assign(&value, &slot, self.range_of(rhs));
        }
        // Assignment *invalidates* the place's narrowing (handled by the flow analysis, Workstream
        // 2); re-narrowing from the assigned value's type is a post-1.0 precision item.
        slot
    }

    /// Resolve a binary operator's result type via the builtin operator table, with a numeric
    /// fallback. Comparison/logical operators are handled by the caller.
    fn bin_result(&self, op: BinOp, lt: &Ty, rt: &Ty) -> Ty {
        if let (Ty::Builtin(b), Some(sym)) = (lt, op_symbol(op)) {
            for o in self.api.builtin_operators(*b) {
                if o.op == sym
                    && let Some(right) = &o.right
                    && self.tyref_matches(right, rt)
                {
                    return ty::resolve_tyref(self.api, &o.result);
                }
            }
        }
        if self.is_numeric(lt) && self.is_numeric(rt) {
            return if self.is_float(lt) || self.is_float(rt) {
                self.float_ty()
            } else {
                self.int_ty()
            };
        }
        // A seam operand keeps the result on the seam (`a + unknown` is `Unknown`, not the
        // gradual `Variant`, so `var x := a + unknown` never warns).
        if lt.is_unknown() || rt.is_unknown() || lt.is_error() || rt.is_error() {
            return Ty::Unknown;
        }
        Ty::Variant
    }

    fn tyref_matches(&self, tyref: &TyRef, ty: &Ty) -> bool {
        let resolved = ty::resolve_tyref(self.api, tyref);
        resolved.is_variant() || &resolved == ty
    }

    fn infer_call(&mut self, callee: ExprId, args: &[ExprId]) -> Ty {
        // Argument expressions are always inferred (their own diagnostics + hover).
        for &a in args {
            self.infer_expr(a, &Expectation::None);
        }
        let ret = match self.body.expr(callee).clone() {
            Expr::Field {
                receiver,
                name,
                name_range,
            } => {
                self.infer_field(receiver, &name, name_range, /*as_method=*/ true)
            }
            Expr::Name(name) => {
                let ret = self.resolve_call_name(&name);
                self.expr_ty.insert(callee, Ty::Callable);
                ret
            }
            // Calling an arbitrary expression — a `Callable` value or an immediately-invoked
            // lambda (`(func(): …).call()`): the callee's return type isn't tracked, so the
            // result is the seam (not `Variant`), and `var x := f()()` never warns.
            _ => {
                self.infer_expr(callee, &Expectation::None);
                Ty::Unknown
            }
        };
        // UNSAFE_CALL_ARGUMENT (Phase-2 §5): args + receiver are now inferred (in `expr_ty`), so
        // check each argument against the statically-resolved callee's parameter types.
        self.check_call_args(callee, args);
        ret
    }

    /// Raise `UNSAFE_CALL_ARGUMENT` for each argument whose static type needs an unsafe implicit
    /// cast (`Variant` / a downcast) into the resolved parameter type — Godot's per-argument
    /// value-prop warning. Only fires when the callee resolves to a concrete signature here; an
    /// uninformative argument (the cross-file seam) is `Assign::Ok` and correctly silent, and an
    /// untyped parameter accepts anything.
    fn check_call_args(&mut self, callee: ExprId, args: &[ExprId]) {
        let Some(params) = self.call_param_tys(callee) else {
            return;
        };
        for (i, &arg) in args.iter().enumerate() {
            let Some(param_ty) = params.get(i) else {
                break; // a vararg tail or an arity mismatch — not an argument-type concern
            };
            if param_ty.is_uninformative() || param_ty.is_variant() {
                continue; // an untyped parameter accepts anything safely
            }
            // A missing arg type defaults to the seam (never warns), not `Variant` (would warn).
            let arg_ty = self.expr_ty.get(&arg).cloned().unwrap_or(Ty::Unknown);
            if ty::is_assignable(self.api, &arg_ty, param_ty) == Assign::OkUnsafe {
                let pl = param_ty.label(self.api).unwrap_or_else(|| "?".to_owned());
                let al = arg_ty.label(self.api).unwrap_or_else(|| "?".to_owned());
                self.warn(
                    self.range_of(arg),
                    WarningCode::UnsafeCallArgument,
                    format!(
                        "The argument {} requires a value of type \"{pl}\" but is passed \"{al}\", which is unsafe.",
                        i + 1
                    ),
                );
            }
        }
    }

    /// Parameter types of a statically-resolved callee, for [`Self::check_call_args`]. `None` when
    /// the callee isn't concretely resolvable here (a cross-file script method — params aren't
    /// modeled —, a builtin/utility, a `Callable` value): those raise no argument warning.
    fn call_param_tys(&self, callee: ExprId) -> Option<Vec<Ty>> {
        match self.body.expr(callee) {
            Expr::Name(name) => self.name_call_param_tys(name),
            Expr::Field { receiver, name, .. } => match self.expr_ty.get(receiver)? {
                Ty::Object(class) => match self.api.lookup_member(*class, name)? {
                    MemberRef::Method(sig) => Some(
                        sig.params
                            .iter()
                            .map(|p| ty::resolve_tyref(self.api, &p.ty))
                            .collect(),
                    ),
                    _ => None,
                },
                // ScriptRef / builtin / seam receivers: params not uniformly modeled — skip.
                _ => None,
            },
            _ => None,
        }
    }

    /// Parameter types for a bare-name call (`foo(...)` / an inherited `method(...)`): an own `func`
    /// first, then the `self` engine base's method. Utilities/builtins are skipped (looser, often
    /// variadic typing — out of the conservative MVP slice).
    fn name_call_param_tys(&self, name: &str) -> Option<Vec<Ty>> {
        if let Some(item) = self.class.lookup(name)
            && let Some(Member::Func(f)) = self.class.member(item)
        {
            return Some(
                f.params
                    .iter()
                    .map(|p| {
                        p.type_ref.as_deref().map_or(Ty::Variant, |t| {
                            resolve::resolve_type_name(self.db, self.api, t)
                        })
                    })
                    .collect(),
            );
        }
        if let Ty::Object(base) = self.class.base
            && let Some(MemberRef::Method(sig)) = self.api.lookup_member(base, name)
        {
            return Some(
                sig.params
                    .iter()
                    .map(|p| ty::resolve_tyref(self.api, &p.ty))
                    .collect(),
            );
        }
        None
    }

    /// Resolve a bare-name call (`foo(...)`): own method → utility/builtin fn → constructor.
    fn resolve_call_name(&self, name: &str) -> Ty {
        if let Some(item) = self.class.lookup(name)
            && let Some(Member::Func(f)) = self.class.member(item)
        {
            return self.func_return_ty(f.return_type.as_deref());
        }
        // A bare call inside the class is `self.name(...)` — resolve against the inherited base.
        if let Ty::Object(base) = self.class.base
            && let Some(MemberRef::Method(sig)) = self.api.lookup_member(base, name)
        {
            return ty::resolve_tyref(self.api, &sig.return_ty);
        }
        if let Some(u) = self.api.utility(name) {
            return ty::resolve_tyref(self.api, &u.return_ty);
        }
        if let Some(f) = self.api.gdscript_builtin(name) {
            return resolve::layer_to_ty(self.api, f.ret);
        }
        // A builtin / class name used as a constructor: `Vector2(...)` / `Array(...)`.
        // Normalize via `resolve_tyref` so `Array`/`Dictionary`/`Callable`/`Signal` land on
        // their dedicated `Ty` variants rather than `Builtin(...)`.
        if let Some(b) = self.api.builtin_by_name(name) {
            return ty::resolve_tyref(self.api, &TyRef::Builtin(b));
        }
        // Otherwise unresolved — most likely a cross-file global / autoload / a method on a
        // `class_name` base we can't see. Treat as the seam so `var x := foo()` never warns.
        Ty::Unknown
    }

    fn func_return_ty(&self, annotation: Option<&str>) -> Ty {
        annotation.map_or(Ty::Variant, |t| {
            resolve::resolve_type_name(self.db, self.api, t)
        })
    }

    /// Member access `receiver.name`. When `as_method`, resolve a method (and use its return
    /// type); otherwise resolve a property/const/etc. Raises `UNSAFE_*` only on a statically
    /// **known** receiver.
    fn infer_field(
        &mut self,
        receiver: ExprId,
        name: &str,
        name_range: TextRange,
        as_method: bool,
    ) -> Ty {
        let is_self = matches!(self.body.expr(receiver), Expr::SelfExpr);
        let recv_ty = self.infer_expr(receiver, &Expectation::None);

        // `self.member` consults this file's own members first (Playbook §3.2).
        if is_self && let Some(item) = self.class.lookup(name) {
            return self.own_member_ty(item, as_method);
        }

        match &recv_ty {
            // Uninformative receivers are unchecked and **propagate the seam**: a member of an
            // `Unknown` (cross-file) value is itself `Unknown` (never warns), a member of a
            // `Variant` is `Variant`, of an `Error` is `Error`. Collapsing `Unknown` to
            // `Variant` here would wrongly fire `INFERENCE_ON_VARIANT` on `var x := other.field`.
            t if t.is_uninformative() => recv_ty.clone(),
            Ty::Object(class) => {
                if name == "new" {
                    // `Class.new(...)` always constructs an instance of the class (some classes,
                    // e.g. GDScript, also carry a modeled `new` member — the constructor wins).
                    recv_ty.clone()
                } else if let Some(m) = self.api.lookup_member(*class, name) {
                    self.check_member_kind_misuse(&m, as_method, name, name_range);
                    self.check_static_on_instance(receiver, &m, as_method, name_range);
                    self.member_ref_ty(&m, as_method)
                } else if let Some(t) = self.class_enum_value(*class, name) {
                    // A statically-accessed enum value (`Control.PRESET_FULL_RECT`).
                    t
                } else {
                    // Self with an Object base already checked own members above.
                    self.emit_unsafe(name, &recv_ty, name_range, as_method);
                    Ty::Variant
                }
            }
            Ty::Builtin(_) | Ty::Array(_) | Ty::Dict(..) | Ty::Callable | Ty::Signal(_) => {
                self.builtin_member_ty(&recv_ty, name, name_range, as_method)
            }
            // Accessing a member of an enum namespace (`State.IDLE`) yields the enum type itself —
            // an enum value (freely int-assignable via `ty::is_assignable`). Was `int`, which lost
            // the enum type and false-`INFERENCE_ON_VARIANT`'d a same-file `var x := State.IDLE`.
            Ty::Enum(er) => Ty::Enum(er.clone()),
            // A cross-file script reference: resolve the member against its (own) member table.
            Ty::ScriptRef(sref) => self.script_member_ty(*sref, name, as_method),
            // An inner-class value/instance: resolve against its own item-tree + `extends` chain.
            Ty::InnerClass(iref) => self.inner_class_member_ty(iref, name, as_method),
            _ => Ty::Variant,
        }
    }

    /// Resolve `name` on an inner-class value/instance (`Ty::InnerClass`). `Inner.new()` constructs an
    /// instance (the same `InnerClass`); otherwise the inner class's own members (typed by their
    /// annotation — lossy, like the cross-file `ScriptRef` path: an inferred/unannotated member seams)
    /// then its `extends` chain. The seam (`Unknown`) for an unresolved member — never a false
    /// `UNSAFE_*`.
    fn inner_class_member_ty(
        &self,
        iref: &crate::ty::InnerClassRef,
        name: &str,
        as_method: bool,
    ) -> Ty {
        if name == "new" && as_method {
            return Ty::InnerClass(iref.clone());
        }
        self.inner_member_walk(iref, name, as_method, 0)
            .unwrap_or(Ty::Unknown)
    }

    /// Walk an inner class's own members, then its `extends` base (an engine class, a `class_name`, or
    /// another inner/script class), for `name`. Depth-bounded like [`script_member_walk`].
    fn inner_member_walk(
        &self,
        iref: &crate::ty::InnerClassRef,
        name: &str,
        as_method: bool,
        depth: u32,
    ) -> Option<Ty> {
        if depth > 32 {
            return None;
        }
        let ft = self.db.file_text(FileId(iref.file))?;
        let tree = crate::queries::item_tree(self.db, ft);
        let inner = find_inner_class(&tree, &iref.path)?;
        if let Some(m) = inner.tree.member(name) {
            return self.inner_member_item_ty(m, as_method, iref);
        }
        // Not an own member — walk the inner class's `extends` base.
        let res_path = self.self_res_path();
        match resolve::resolve_base(self.db, self.api, &inner.tree, res_path.as_deref()) {
            Ty::Object(class) => self
                .api
                .lookup_member(class, name)
                .map(|m| self.member_ref_ty(&m, as_method)),
            Ty::ScriptRef(base) => self.script_member_walk(base, name, as_method, depth + 1),
            Ty::InnerClass(base) => self.inner_member_walk(&base, name, as_method, depth + 1),
            _ => None,
        }
    }

    /// Type an inner class's own member by its written **annotation** (the inner body isn't inferred
    /// here — Increment 2 adds that). An unannotated `var`/`const` or an untyped `func` return seams.
    fn inner_member_item_ty(
        &self,
        m: &Member,
        as_method: bool,
        iref: &crate::ty::InnerClassRef,
    ) -> Option<Ty> {
        Some(match m {
            Member::Func(f) => {
                if as_method {
                    f.return_type.as_deref().map_or(Ty::Variant, |t| {
                        resolve::resolve_type_name(self.db, self.api, t)
                    })
                } else {
                    Ty::Callable
                }
            }
            Member::Var(v) => resolve::resolve_type_name(self.db, self.api, v.type_ref.as_deref()?),
            Member::Const(c) => {
                resolve::resolve_type_name(self.db, self.api, c.type_ref.as_deref()?)
            }
            Member::Signal(_) => Ty::Signal(None),
            Member::Enum(e) => Ty::Enum(EnumRef {
                qualified: e.name.clone()?,
                bitfield: false,
            }),
            // A nested inner class → `Ty::InnerClass` with the extended dotted path.
            Member::Class(c) => Ty::InnerClass(crate::ty::InnerClassRef {
                file: iref.file,
                path: SmolStr::new(format!("{}.{}", iref.path, c.name)),
            }),
        })
    }

    /// A member of a cross-file script (`ScriptRef`): looked up in the script's own member table
    /// (M1). A member we don't model — e.g. one inherited from a base we don't resolve until M2 —
    /// yields the seam (`Unknown`), **never** an `UNSAFE_*` warning. `Class.new(...)` constructs
    /// an instance of the class.
    fn script_member_ty(&self, sref: ScriptRefId, name: &str, as_method: bool) -> Ty {
        if name == "new" {
            return Ty::ScriptRef(sref);
        }
        self.script_member_walk(sref, name, as_method, 0)
            .unwrap_or(Ty::Unknown)
    }

    /// Walk a script class's `extends` chain for `name`: own members first, then a user base
    /// (another `ScriptRef`), then an engine base (the API table). Depth-bounded so a cyclic
    /// `extends` cannot loop. `None` = not found anywhere in the chain (the seam).
    fn script_member_walk(
        &self,
        sref: ScriptRefId,
        name: &str,
        as_method: bool,
        depth: u32,
    ) -> Option<Ty> {
        if depth > 32 {
            return None;
        }
        let file = self.db.file_text(FileId(sref.0))?;
        let sc = crate::queries::script_class(self.db, file);
        if let Some(m) = sc.member(name) {
            return Some(match m {
                crate::queries::MemberSig::Method(ret) => {
                    if as_method {
                        ret.clone()
                    } else {
                        Ty::Callable
                    }
                }
                crate::queries::MemberSig::Field(t) => t.clone(),
                crate::queries::MemberSig::Signal => Ty::Signal(None),
            });
        }
        // Not an own member — continue up the inheritance chain.
        match sc.base() {
            Ty::ScriptRef(base) => self.script_member_walk(*base, name, as_method, depth + 1),
            Ty::Object(class) => self
                .api
                .lookup_member(*class, name)
                .map(|m| self.member_ref_ty(&m, as_method)),
            _ => None,
        }
    }

    /// Whether a value of type `sub` is statically a subtype of `sup` — composing user `ScriptRef`
    /// `extends` chains with the engine class table (M4, for `is`/`as` widen-only narrowing). A
    /// `ScriptRef` IS-A its native base (so `script_value is Node` holds), but Godot's asymmetry is
    /// honored: a native/script value is **not** a subtype of an *unrelated* user script.
    fn is_subtype(&self, sub: &Ty, sup: &Ty) -> bool {
        match (sub, sup) {
            (Ty::Object(a), Ty::Object(b)) => self.api.is_subclass(*a, *b),
            (Ty::ScriptRef(a), Ty::ScriptRef(b)) => self.script_is_subtype(*a, *b, 0),
            (Ty::ScriptRef(a), Ty::Object(b)) => self.script_extends_engine(*a, *b, 0),
            _ => false,
        }
    }

    /// Whether script `sub` is `sup` or transitively extends it — walk the `extends` base chain by
    /// script identity (depth-bounded, like [`script_member_walk`](Self::script_member_walk)).
    fn script_is_subtype(&self, sub: ScriptRefId, sup: ScriptRefId, depth: u32) -> bool {
        if depth > 32 {
            return false;
        }
        if sub == sup {
            return true;
        }
        let Some(file) = self.db.file_text(FileId(sub.0)) else {
            return false;
        };
        match crate::queries::script_class(self.db, file).base() {
            Ty::ScriptRef(base) => self.script_is_subtype(*base, sup, depth + 1),
            _ => false,
        }
    }

    /// Whether script `sub`'s `extends` chain reaches engine class `sup_native` at its native base.
    fn script_extends_engine(
        &self,
        sub: ScriptRefId,
        sup_native: gdscript_api::ClassId,
        depth: u32,
    ) -> bool {
        if depth > 32 {
            return false;
        }
        let Some(file) = self.db.file_text(FileId(sub.0)) else {
            return false;
        };
        match crate::queries::script_class(self.db, file).base() {
            Ty::ScriptRef(base) => self.script_extends_engine(*base, sup_native, depth + 1),
            Ty::Object(native) => self.api.is_subclass(*native, sup_native),
            _ => false,
        }
    }

    fn emit_unsafe(&mut self, name: &str, recv: &Ty, range: TextRange, as_method: bool) {
        let recv_label = recv.label(self.api).unwrap_or_else(|| "?".to_owned());
        let (code, message) = if as_method {
            (
                WarningCode::UnsafeMethodAccess,
                format!(
                    "The method \"{name}()\" is not present on the inferred type \"{recv_label}\" (but may be present on a subtype)."
                ),
            )
        } else {
            (
                WarningCode::UnsafePropertyAccess,
                format!(
                    "The property \"{name}\" is not present on the inferred type \"{recv_label}\" (but may be present on a subtype)."
                ),
            )
        };
        self.warn(range, code, message);
    }

    /// Whether the class's RESOLVED **engine** base declares a *value* member (var/const/signal)
    /// named `name` — the sound floor for `SHADOWED_VARIABLE_BASE_CLASS`. Only the engine base is
    /// consulted: an unresolved base (the cross-file seam) returns `false` (no warning), and the
    /// cross-file *user*-base `MemberSig` is lossy (no kind detail) so user-base shadowing stays
    /// deferred (see `TECH_DEBT.md`). Methods are excluded (matches the own-member shadow rule).
    fn engine_base_has_value_member(&self, name: &str) -> bool {
        let Ty::Object(base) = &self.class.base else {
            return false;
        };
        matches!(
            self.api.lookup_member(*base, name),
            Some(MemberRef::Property(_) | MemberRef::Const(_) | MemberRef::Signal(_))
        )
    }

    /// Flag a deprecated member-kind misuse on a statically-resolved engine member:
    /// `PROPERTY_USED_AS_FUNCTION` / `CONSTANT_USED_AS_FUNCTION` when a property/const is *called*.
    /// Guarded against a Callable/Signal/uninformative-typed member (those can legitimately be
    /// invoked). `FUNCTION_USED_AS_PROPERTY` is intentionally NOT emitted — a bare `obj.method` is an
    /// idiomatic `Callable` reference (every signal `.connect`), indistinguishable from a misuse
    /// without call-context, so it would false-positive everywhere (see `TECH_DEBT.md`).
    fn check_member_kind_misuse(
        &mut self,
        m: &MemberRef,
        as_method: bool,
        name: &str,
        range: TextRange,
    ) {
        if !as_method {
            return;
        }
        let (code, kind, ty) = match m {
            MemberRef::Property(p) => (
                WarningCode::PropertyUsedAsFunction,
                "property",
                ty::resolve_tyref(self.api, &p.ty),
            ),
            MemberRef::Const(c) => (
                WarningCode::ConstantUsedAsFunction,
                "constant",
                ty::resolve_tyref(self.api, &c.ty),
            ),
            _ => return,
        };
        // A Callable/Signal-typed (or uninformative) member can be invoked — never flag it.
        if ty.is_uninformative() || matches!(ty, Ty::Callable | Ty::Signal(_)) {
            return;
        }
        self.warn(
            range,
            code,
            format!("The {kind} \"{name}\" is being called as if it were a function."),
        );
    }

    /// Flag `STATIC_CALLED_ON_INSTANCE`: an engine static method called through an instance value
    /// rather than the type. Conservative + sound — fires only when the receiver is a **typed local
    /// instance** (a `Name` bound in `locals`), never a bare class name (`Class.static()` is
    /// correct) nor an expression we can't classify. Under-warns by design; zero false positives.
    fn check_static_on_instance(
        &mut self,
        receiver: ExprId,
        m: &MemberRef,
        as_method: bool,
        range: TextRange,
    ) {
        if !as_method {
            return;
        }
        let MemberRef::Method(sig) = m else {
            return;
        };
        if !sig.is_static {
            return;
        }
        let Expr::Name(rname) = self.body.expr(receiver) else {
            return;
        };
        if !self.locals.contains_key(rname) {
            return;
        }
        // A local that ALIASES a type/var (`var t := JSON; t.stringify()`) is not an instance —
        // calling a static method through it is valid (`t` holds the type, not an object). A bare
        // `Name` initializer marks such an alias; only a constructor/call init (or a param/field
        // with no init) is a true instance. Skipping the alias case fixes a false positive.
        if let Some(b) = self.bindings.iter().rev().find(|b| &b.name == rname)
            && let Some(init) = b.init
            && matches!(self.body.expr(init), Expr::Name(_))
        {
            return;
        }
        self.warn(
            range,
            WarningCode::StaticCalledOnInstance,
            "A static method is being called on an instance; call it on the type instead."
                .to_owned(),
        );
    }

    fn member_ref_ty(&self, m: &MemberRef, as_method: bool) -> Ty {
        match m {
            MemberRef::Method(sig) => {
                if as_method {
                    ty::resolve_tyref(self.api, &sig.return_ty)
                } else {
                    Ty::Callable
                }
            }
            MemberRef::Property(p) => p.enum_of.as_ref().map_or_else(
                || ty::resolve_tyref(self.api, &p.ty),
                |q| {
                    Ty::Enum(EnumRef {
                        qualified: SmolStr::new(q),
                        bitfield: false,
                    })
                },
            ),
            MemberRef::Const(c) => ty::resolve_tyref(self.api, &c.ty),
            MemberRef::Signal(_) => Ty::Signal(None),
            MemberRef::Enum(_) => Ty::Variant,
        }
    }

    fn builtin_member_ty(
        &mut self,
        recv: &Ty,
        name: &str,
        range: TextRange,
        as_method: bool,
    ) -> Ty {
        let Some(bid) = self.builtin_id_of(recv) else {
            return Ty::Variant;
        };
        if as_method {
            return if let Some(sig) = self.api.builtin_method(bid, name) {
                ty::resolve_tyref(self.api, &sig.return_ty)
            } else {
                self.emit_unsafe(name, recv, range, true);
                Ty::Variant
            };
        }
        if let Some(member) = self.api.builtin_member(bid, name) {
            return ty::resolve_tyref(self.api, &member.ty);
        }
        // Static constants (`Vector2.ZERO`, `Color.WHITE`) and enum values (`Variant.Type.*`).
        let data = self.api.builtin(bid);
        if let Some(c) = data.constants.iter().find(|c| c.name == name) {
            return ty::resolve_tyref(self.api, &c.ty);
        }
        if data
            .enums
            .iter()
            .any(|e| e.values.iter().any(|v| v.name == name))
        {
            return self.int_ty();
        }
        if self.api.builtin_method(bid, name).is_some() {
            return Ty::Callable;
        }
        self.emit_unsafe(name, recv, range, false);
        Ty::Variant
    }

    /// The type of a class enum **value** accessed statically (`Control.PRESET_FULL_RECT`):
    /// the engine exposes enum values as class members, so search every (inherited) enum's
    /// values. Returns the value's **declaring enum type** (`Ty::Enum`) — mirroring how a
    /// `Class.Enum` *annotation* resolves (`resolve::resolve_named`), so an enum member assigned
    /// to a slot of that same enum is `Assign::Ok`, not a false `INT_AS_ENUM_WITHOUT_CAST`. (An
    /// enum value is still freely assignable to `int` — see `ty::is_assignable`.)
    fn class_enum_value(&self, class: gdscript_api::ClassId, name: &str) -> Option<Ty> {
        let mut cur = Some(class);
        while let Some(cid) = cur {
            let c = self.api.class(cid);
            if let Some(e) = c
                .enums
                .iter()
                .find(|e| e.values.iter().any(|v| v.name == name))
            {
                return Some(Ty::Enum(EnumRef {
                    qualified: SmolStr::new(format!("{}.{}", c.name, e.name)),
                    bitfield: e.is_bitfield,
                }));
            }
            cur = c.base;
        }
        None
    }

    /// The builtin id backing a builtin / `Array` / `Dictionary` receiver.
    fn builtin_id_of(&self, ty: &Ty) -> Option<gdscript_api::BuiltinId> {
        match ty {
            Ty::Builtin(b) => Some(*b),
            Ty::Array(_) => self.api.builtin_by_name("Array"),
            Ty::Dict(..) => self.api.builtin_by_name("Dictionary"),
            Ty::Callable => self.api.builtin_by_name("Callable"),
            Ty::Signal(_) => self.api.builtin_by_name("Signal"),
            _ => None,
        }
    }

    /// The element type of an indexing expression (Playbook §2 switch).
    fn index_ty(&self, base: &Ty) -> Ty {
        match base {
            Ty::Array(elem) => (**elem).clone(),
            Ty::Builtin(b) => self
                .api
                .builtin(*b)
                .indexing_return
                .as_ref()
                .map_or(Ty::Variant, |r| ty::resolve_tyref(self.api, r)),
            // Indexing through the seam stays on the seam (never warns).
            Ty::Unknown => Ty::Unknown,
            Ty::Error => Ty::Error,
            _ => Ty::Variant,
        }
    }

    /// The loop variable's type for `for v in iter:` (Playbook §2 switch).
    fn loop_var_ty(&self, iter: &Ty) -> Ty {
        match iter {
            Ty::Array(elem) => (**elem).clone(),
            Ty::Builtin(b) => {
                let data = self.api.builtin(*b);
                if data.name == "int" {
                    // `for i in 5` / `for i in range(...)` → int.
                    self.int_ty()
                } else if let Some(r) = &data.indexing_return {
                    // `for c in "abc"` → String; `for s in packed_string_array` → String; …
                    ty::resolve_tyref(self.api, r)
                } else {
                    Ty::Variant
                }
            }
            // Iterating a seam value keeps the loop var on the seam (never warns).
            Ty::Unknown => Ty::Unknown,
            Ty::Error => Ty::Error,
            _ => Ty::Variant,
        }
    }

    fn infer_lambda(&mut self, params: &[ParamBinding], body: &[body::StmtId]) {
        // Lambda params shadow within the body; restore the outer locals afterward. A `return`
        // inside the lambda is the *lambda's* return, not the enclosing function's — so disable
        // return checking (set the expected return to `Variant`) while walking the body.
        let saved_locals = self.locals.clone();
        let saved_ret = std::mem::replace(&mut self.return_ty, Ty::Variant);
        for p in params {
            let ty = self.param_ty(p);
            self.bindings.push(Binding {
                name: p.name.clone(),
                name_range: p.name_range,
                ty: ty.clone(),
                init: None,
                annotated: p.type_ref.is_some(),
                inferred_colon_eq: false,
                is_const: false,
                kind: BindingKind::Param,
            });
            self.locals.insert(p.name.clone(), ty);
        }
        self.infer_block(body);
        self.return_ty = saved_ret;
        self.locals = saved_locals;
    }

    fn param_ty(&mut self, p: &ParamBinding) -> Ty {
        if let Some(ptr) = p.type_ref {
            return self.resolve_ptr_ty(ptr);
        }
        // An unannotated param infers from its default, else `Variant`.
        p.default
            .map_or(Ty::Variant, |e| self.infer_expr(e, &Expectation::None))
    }

    // ---- name resolution (local → class member → inherited → global) ----

    /// The `Ty`-producing half of the bare-name lookup. Its precedence is the **canonical order**
    /// documented on [`crate::def::resolve_name_to_def`] (local → own member → inherited member →
    /// engine global → `class_name` global → autoload) — kept in lockstep with that identity-producing
    /// copy by the `classify_and_infer_agree_*` tests (gdscript-ide). Unlike that copy, this one is
    /// woven with flow-narrowing and the `UNUSED`/`UNASSIGNED` side-effects (it runs mid-inference),
    /// which is why the two are intentionally separate functions rather than one.
    fn resolve_name(&mut self, id: ExprId, name: &str) -> Ty {
        // Record a *read* of a local/param for the `UNUSED_*` analysis (before the narrowing check,
        // so a narrowed read still counts as used). The direct LHS of an assignment (`x = …`) is a
        // WRITE, not a read — excluding it lets `UNUSED_VARIABLE` catch an assigned-but-never-read
        // local (Godot's precise behaviour). A compound `x += …` still reads `x` via its RHS NameRef
        // (a distinct expr), and a receiver / index target (`x.f()`, `x[i] = …`) is a read of `x`.
        if self.locals.contains_key(name) && !self.assign_lhs.contains(&id) {
            self.used_locals.insert(SmolStr::new(name));
        }
        // UNASSIGNED_VARIABLE (Workstream 2) — a *read* of a typed-no-init local that is not
        // definitely assigned on every path reaching here. Excludes the LHS of an assignment (a
        // write) and reads inside a lambda body (which `assigned_before` leaves `None`, unchecked).
        if self.is_func_body
            && self.needs_assignment.contains(name)
            && !self.assign_lhs.contains(&id)
            && let Some(cur) = self.cur_stmt
            && self
                .assigned
                .assigned_before(cur)
                .is_some_and(|a| !a.contains(name))
        {
            self.warn(
                self.range_of(id),
                WarningCode::UnassignedVariable,
                format!("The variable \"{name}\" may be used before it is assigned a value."),
            );
        }
        // Flow narrowing wins over the binding's declared type.
        if let Some(key) = self.narrow_key(id)
            && let Some(t) = self.narrowing.get(&key)
        {
            return t.clone();
        }
        if let Some(t) = self.locals.get(name) {
            return t.clone();
        }
        if let Some(item) = self.class.lookup(name) {
            return self.own_member_ty(item, false);
        }
        // Inherited members: an engine `Object` base via the API table, or a user `ScriptRef`
        // base via the script member walk (M2 — so a class extending another class_name sees its
        // inherited members).
        match self.class.base.clone() {
            Ty::Object(base) => {
                if let Some(m) = self.api.lookup_member(base, name) {
                    return self.member_ref_ty(&m, false);
                }
            }
            Ty::ScriptRef(base) => {
                if let Some(t) = self.script_member_walk(base, name, false, 0) {
                    return t;
                }
            }
            _ => {}
        }
        if let Some(g) = resolve::resolve_global(self.api, name) {
            return global_ty(&g);
        }
        // A project-global `class_name` used as a value — the class itself, for static access
        // (`V.fc()`) or as a constructor (`Player.new()`). Resolves to a `ScriptRef` via the
        // registry. Precedence (Godot `reduce_identifier`): `class_name` global ≫ autoload
        // singleton. So try `class_name` first, then a `*`-autoload, then the seam.
        let by_class = resolve::resolve_external(
            self.db,
            &resolve::ExternalRef::ClassName(SmolStr::new(name)),
        );
        if !by_class.is_unknown() {
            return by_class;
        }
        resolve::resolve_external(self.db, &resolve::ExternalRef::Autoload(SmolStr::new(name)))
    }

    fn own_member_ty(&self, item: ClassItem, as_method: bool) -> Ty {
        match item {
            ClassItem::EnumVariant => self.int_ty(),
            ClassItem::Member(_) => match self.class.member(item) {
                Some(Member::Var(v)) => self.field_ty(&v.name, v.ptr),
                Some(Member::Const(c)) => self.field_ty(&c.name, c.ptr),
                Some(Member::Func(f)) => {
                    if as_method {
                        self.func_return_ty(f.return_type.as_deref())
                    } else {
                        Ty::Callable
                    }
                }
                Some(Member::Signal(_)) => Ty::Signal(None),
                // An inner `class Name:` used as a value → `Ty::InnerClass` (was the `Unknown` seam),
                // so `Inner.CONST` / `Inner.new()` / a typed instance's members resolve against its own
                // item-tree. The path is the inner class's name (resolved from the top-level scope;
                // nested inner classes get their dotted path once inner bodies are inferred).
                Some(Member::Class(c)) => match &self.self_ty {
                    Ty::ScriptRef(sref) => Ty::InnerClass(crate::ty::InnerClassRef {
                        file: sref.0,
                        path: c.name.clone(),
                    }),
                    _ => Ty::Unknown,
                },
                // A same-file named `enum State` used as a value/namespace → the enum type, so
                // `State.IDLE` (member access below) types as `State`, not a false-`INFERENCE_ON_
                // VARIANT` seam. An anonymous enum has no namespace name (its variants are direct
                // class constants), so it stays the seam.
                Some(Member::Enum(e)) => e.name.as_ref().map_or(Ty::Variant, |n| {
                    Ty::Enum(EnumRef {
                        qualified: n.clone(),
                        bitfield: false,
                    })
                }),
                None => Ty::Variant,
            },
        }
    }

    /// The type of an own field (`var`/`const`): the type seeded by the field pre-pass (which
    /// captures the inferred type of `var n := 0`), falling back to the written annotation.
    fn field_ty(&self, name: &str, ptr: AstPtr) -> Ty {
        if let Some(t) = self.class.member_types.get(name) {
            return t.clone();
        }
        self.resolve_decl_annotation(ptr)
    }

    /// Resolve a declaration's annotation (recovering its `TypeRef` node), else `Variant`.
    fn resolve_decl_annotation(&self, ptr: AstPtr) -> Ty {
        let Some(node) = ptr.to_node(self.root) else {
            return Ty::Variant;
        };
        cst::first_child(&node, |k| k == gdscript_syntax::SyntaxKind::TypeRef)
            .map_or(Ty::Variant, |t| {
                resolve::resolve_type_ref(self.db, self.api, &t)
            })
    }

    // ---- narrowing ----

    /// Build the narrowing env for a statement from the precomputed flow facts (Workstream 2).
    ///
    /// Only `Is` facts contribute a type (`NotNull`/`Not` are recorded by the flow pass but not yet
    /// consumed for typing — the 1.0 cut). The **widen-only + `is_uninformative`** soundness gate is
    /// preserved verbatim from the old `apply_narrowing`: `is`-narrowing is a deliberate divergence
    /// from upstream Godot (whose `is` does not flow-narrow), kept widen-only so it never produces a
    /// type Godot would reject — narrow only when the tested type is a downcast of the place's
    /// declared type, or the declared type is uninformative; never un-narrow a known subtype
    /// (`d: Derived; if d is Base` keeps `Derived`), never narrow to a type we couldn't resolve.
    fn facts_to_narrowing(&self, id: body::StmtId) -> FxHashMap<String, Ty> {
        let mut out = FxHashMap::default();
        if let Some(facts) = self.flow.facts_before(id) {
            for (place, nt) in facts.iter() {
                if let Some((key, ty)) = self.narrowing_entry(place, nt) {
                    out.insert(key, ty);
                }
            }
        }
        out
    }

    /// Resolve one flow fact into a `(dotted-key, narrowed-type)` narrowing entry, applying the
    /// widen-only + `is_uninformative` soundness gate. `None` if the fact doesn't narrow a type
    /// (a `NotNull`/`Not`, an unresolvable/uninformative type, or an un-narrowing of a known subtype).
    fn narrowing_entry(&self, place: &Place, nt: &NarrowedTy) -> Option<(String, Ty)> {
        let NarrowedTy::Is(ptr) = nt else {
            return None;
        };
        let narrowed = self.resolve_ptr_ty(*ptr);
        if narrowed.is_uninformative() {
            return None;
        }
        // Gate against a local/param's declared type; for `self`-members / field chains the
        // `is_uninformative` check above is the soundness floor.
        if let Place::Local(n) = place
            && let Some(cur) = self.locals.get(n)
            && !cur.is_uninformative()
            && !self.is_subtype(&narrowed, cur)
        {
            return None;
        }
        Some((place.dotted_key(), narrowed))
    }

    /// Apply a condition's short-circuit narrowing to the active env, for typing the RHS of an
    /// `and`/`or` (Workstream 2): `if x is T and x.method():` narrows `x` for `x.method()`.
    fn apply_condition_facts(&mut self, cond: ExprId, truthy: bool) {
        for (place, nt) in flow::condition_facts(self.body, cond, truthy) {
            if let Some((key, ty)) = self.narrowing_entry(&place, &nt) {
                self.narrowing.insert(key, ty);
            }
        }
    }

    /// A dotted access-path key for narrowing (`x`, `self.field`, `a.b.c`), or `None` for a
    /// non-path expression.
    fn narrow_key(&self, id: ExprId) -> Option<String> {
        match self.body.expr(id) {
            Expr::Name(n) => Some(n.to_string()),
            Expr::SelfExpr => Some("self".to_owned()),
            Expr::Paren(inner) => self.narrow_key(*inner),
            Expr::Field { receiver, name, .. } => {
                Some(format!("{}.{name}", self.narrow_key(*receiver)?))
            }
            _ => None,
        }
    }

    fn resolve_ptr_ty(&self, ptr: AstPtr) -> Ty {
        ptr.to_node(self.root).map_or(Ty::Variant, |n| {
            resolve::resolve_type_ref(self.db, self.api, &n)
        })
    }

    // ---- helpers ----

    /// The join (least upper bound) of two branch types — conservative: equal types collapse,
    /// a subtype widens to its supertype, else `Variant`.
    ///
    /// The three uninformative markers do NOT collapse to `Variant` — that would defeat the
    /// seam. They propagate by priority: `Error` (already diagnosed) → `Unknown` (the cross-file
    /// seam — must never warn or cascade) → `Variant` (the gradual top). So
    /// `x if c else <unknown>` stays `Unknown`, and `var y := (x if c else unknown)` does not
    /// fire a false `INFERENCE_ON_VARIANT`.
    fn join(&self, a: &Ty, b: &Ty) -> Ty {
        if a == b {
            return a.clone();
        }
        if a.is_error() || b.is_error() {
            return Ty::Error;
        }
        if a.is_unknown() || b.is_unknown() {
            return Ty::Unknown;
        }
        if a.is_variant() || b.is_variant() {
            return Ty::Variant;
        }
        if ty::is_assignable(self.api, a, b) == Assign::Ok {
            return b.clone();
        }
        if ty::is_assignable(self.api, b, a) == Assign::Ok {
            return a.clone();
        }
        Ty::Variant
    }
}

/// Map a resolved global definition to the type of a bare reference to it.
fn global_ty(g: &GlobalDef) -> Ty {
    match g {
        GlobalDef::Const(t) => t.clone(),
        GlobalDef::Singleton(c) | GlobalDef::ClassType(c) => Ty::Object(*c),
        GlobalDef::BuiltinType(b) => Ty::Builtin(*b),
        // A bare function referenced as a value is a `Callable`; an enum namespace is opaque.
        GlobalDef::Builtin | GlobalDef::Utility => Ty::Callable,
        GlobalDef::GlobalEnum => Ty::Variant,
    }
}

fn inference_on_variant_msg(kind: &str) -> String {
    format!(
        "The {kind} type is being inferred from a Variant value, so it will be typed as Variant."
    )
}

/// The `extension_api.json` operator spelling for a binary operator.
fn op_symbol(op: BinOp) -> Option<&'static str> {
    Some(match op {
        BinOp::Add => "+",
        BinOp::Sub => "-",
        BinOp::Mul => "*",
        BinOp::Div => "/",
        BinOp::Mod => "%",
        BinOp::Pow => "**",
        BinOp::BitAnd => "&",
        BinOp::BitOr => "|",
        BinOp::BitXor => "^",
        BinOp::Shl => "<<",
        BinOp::Shr => ">>",
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::item_tree::item_tree;
    use gdscript_syntax::{SyntaxKind, parse};

    struct Harness {
        result: InferenceResult,
        body: Body,
    }

    /// Infer the (first) function in `src` against a fresh class scope.
    fn infer_first_func(src: &str) -> Harness {
        let api = gdscript_api::bundled();
        let db = gdscript_db::RootDatabase::default();
        let root = parse(src).syntax_node();
        let tree = item_tree(&root);
        let class = ClassScope::new(&db, api, &tree, None);
        let func = gdscript_syntax::ast::descendants(&root)
            .into_iter()
            .find(|n| n.kind() == SyntaxKind::FuncDecl)
            .expect("a function");
        let body = body::body_of_func(&func);
        let return_ty = cst::first_child(&func, |k| k == SyntaxKind::TypeRef)
            .map_or(Ty::Variant, |t| resolve::resolve_type_ref(&db, api, &t));
        let result = infer(&db, api, &root, &class, &body, return_ty, true);
        Harness { result, body }
    }

    /// Every code inference produced — the ungated `diagnostics` plus the severity-free
    /// `raw_warnings` (the gateable Godot codes, post-W1-M0). Infer-level tests assert what the
    /// checker *records*; the gate-level resolution is tested in `crate::warnings`.
    /// The opt-in declaration-strictness codes — filtered out of [`codes`] / [`file_codes`] so they
    /// don't pollute the hundreds of focused fixtures (they fire on essentially every untyped /
    /// inferred local). A test that targets them reads the raw warnings directly (see
    /// `untyped_and_inferred_declarations_warn`).
    const DECLARATION_STRICTNESS: &[&str] = &["UNTYPED_DECLARATION", "INFERRED_DECLARATION"];

    fn codes(h: &Harness) -> Vec<&str> {
        h.result
            .diagnostics
            .iter()
            .map(|d| d.code.as_str())
            .chain(h.result.raw_warnings.iter().map(|w| w.code.as_str()))
            .filter(|c| !DECLARATION_STRICTNESS.contains(c))
            .collect()
    }

    /// Run the whole-file pass (Pass 1 field fixpoint + Pass 2 functions) and collect every
    /// diagnostic code (ungated diagnostics + raw gateable warnings). Drives `analyze_file`
    /// directly so the bounded member fixpoint runs.
    fn file_codes(src: &str) -> Vec<String> {
        let api = gdscript_api::bundled();
        let db = gdscript_db::RootDatabase::default();
        let root = parse(src).syntax_node();
        let fi = analyze_file(&db, api, &root, FileId(0));
        fi.diagnostics
            .iter()
            .map(|d| d.code.clone())
            .chain(fi.raw_warnings.iter().map(|w| w.code.as_str().to_owned()))
            .filter(|c| !DECLARATION_STRICTNESS.contains(&c.as_str()))
            .collect()
    }

    #[test]
    fn integer_division_warns() {
        let h = infer_first_func("func f():\n\tvar x = 5 / 2\n");
        assert!(codes(&h).contains(&INTEGER_DIVISION));
    }

    #[test]
    fn float_div_does_not_warn() {
        let h = infer_first_func("func f():\n\tvar x = 5.0 / 2\n");
        assert!(!codes(&h).contains(&INTEGER_DIVISION));
    }

    #[test]
    fn type_mismatch_on_hard_annotation() {
        let h = infer_first_func("func f():\n\tvar s: String = 5\n");
        assert!(codes(&h).contains(&TYPE_MISMATCH));
    }

    #[test]
    fn vector_scalar_compound_assign_is_not_a_mismatch() {
        // `v *= 0.5` desugars to `v = v * 0.5` : Vector2 — not the scalar float (the old collapse).
        let h = infer_first_func(
            "func f() -> Vector2:\n\tvar v := Vector2()\n\tv *= 0.5\n\treturn v\n",
        );
        assert!(!codes(&h).contains(&TYPE_MISMATCH), "{:?}", codes(&h));
    }

    #[test]
    fn array_literal_to_packed_array_is_allowed() {
        let h = infer_first_func("func f():\n\tvar p: PackedStringArray = [\"a\", \"b\"]\n");
        assert!(!codes(&h).contains(&TYPE_MISMATCH), "{:?}", codes(&h));
    }

    #[test]
    fn vector2i_to_vector2_is_allowed() {
        let h = infer_first_func("func f():\n\tvar v: Vector2 = Vector2i(1, 2)\n");
        assert!(!codes(&h).contains(&TYPE_MISMATCH), "{:?}", codes(&h));
    }

    #[test]
    fn local_enum_member_access_types_as_the_enum_not_variant() {
        // `var x := State.IDLE` (a same-file enum) infers the enum type, not a Variant seam — so no
        // false INFERENCE_ON_VARIANT.
        let h = infer_first_func(
            "enum State { IDLE, RUN }\nfunc f():\n\tvar x := State.IDLE\n\treturn x\n",
        );
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn lua_style_dict_key_is_not_an_assignment() {
        // `{ pos = "x" }` is a dict entry (key `pos`), not the statement `pos = "x"` — so it must not
        // check the value against the member `pos`'s type.
        let h = infer_first_func(
            "var pos: Vector2\nfunc f():\n\tvar d = { pos = \"x\" }\n\treturn d\n",
        );
        assert!(!codes(&h).contains(&TYPE_MISMATCH), "{:?}", codes(&h));
    }

    #[test]
    fn narrowing_conversion_float_to_int() {
        let h = infer_first_func("func f():\n\tvar n: int = 1.5\n");
        assert!(codes(&h).contains(&NARROWING_CONVERSION));
    }

    #[test]
    fn int_to_float_is_silent() {
        let h = infer_first_func("func f():\n\tvar x: float = 3\n\treturn x\n");
        assert!(codes(&h).is_empty(), "{:?}", codes(&h));
    }

    #[test]
    fn local_shadowing_a_param_warns_shadowed_variable() {
        let h = infer_first_func("func f(x):\n\tvar x = 1\n\treturn x\n");
        assert!(codes(&h).contains(&"SHADOWED_VARIABLE"), "{:?}", codes(&h));
    }

    #[test]
    fn local_shadowing_a_class_member_warns_shadowed_variable() {
        // The class scope (built from the whole file) sees the member `health`; the local shadows it.
        let h =
            infer_first_func("var health = 100\nfunc f():\n\tvar health = 1\n\treturn health\n");
        assert!(codes(&h).contains(&"SHADOWED_VARIABLE"), "{:?}", codes(&h));
    }

    #[test]
    fn non_shadowing_local_does_not_warn_shadowed_variable() {
        let h = infer_first_func("func f(x):\n\tvar y = 1\n\treturn x + y\n");
        assert!(!codes(&h).contains(&"SHADOWED_VARIABLE"), "{:?}", codes(&h));
    }

    #[test]
    fn local_shadowing_a_base_member_warns_base_class() {
        // `position` is a Node2D property; a local of that name shadows the base member.
        let h =
            infer_first_func("extends Node2D\nfunc f():\n\tvar position = 1\n\treturn position\n");
        assert!(
            codes(&h).contains(&"SHADOWED_VARIABLE_BASE_CLASS"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn shadowing_an_unresolved_base_is_silent() {
        // No false positive when the base can't be resolved (the cross-file seam).
        let h = infer_first_func(
            "extends SomeUnknownThirdPartyClass\nfunc f():\n\tvar position = 1\n\treturn position\n",
        );
        assert!(
            !codes(&h).contains(&"SHADOWED_VARIABLE_BASE_CLASS"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn local_named_after_a_native_class_warns_shadowed_global() {
        let h = infer_first_func("func f():\n\tvar Node = 1\n\treturn Node\n");
        assert!(
            codes(&h).contains(&SHADOWED_GLOBAL_IDENTIFIER),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn param_named_after_a_builtin_type_warns_shadowed_global() {
        let h = infer_first_func("func f(Vector2):\n\treturn Vector2\n");
        assert!(
            codes(&h).contains(&SHADOWED_GLOBAL_IDENTIFIER),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn member_named_after_a_native_class_warns_shadowed_global() {
        let cs = file_codes("var Timer = null\n");
        assert!(
            cs.iter().any(|c| c == "SHADOWED_GLOBAL_IDENTIFIER"),
            "{cs:?}"
        );
    }

    #[test]
    fn ordinary_local_does_not_warn_shadowed_global() {
        // A no-false-positive guard: a normal identifier is not a global.
        let h = infer_first_func("func f():\n\tvar count = 1\n\treturn count\n");
        assert!(
            !codes(&h).contains(&SHADOWED_GLOBAL_IDENTIFIER),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn global_shadow_takes_precedence_over_variable_shadow() {
        // A member named after a built-in type (`Color`), shadowed by a local of the same name:
        // Godot emits SHADOWED_GLOBAL_IDENTIFIER (global wins), NOT SHADOWED_VARIABLE on the local.
        let cs = file_codes("var Color = null\nfunc f():\n\tvar Color = 1\n\treturn Color\n");
        assert!(
            cs.iter().any(|c| c == "SHADOWED_GLOBAL_IDENTIFIER"),
            "{cs:?}"
        );
        assert!(
            !cs.iter().any(|c| c == "SHADOWED_VARIABLE"),
            "the local's variable-shadow must be suppressed in favor of the global one: {cs:?}"
        );
    }

    #[test]
    fn assert_true_warns_always_true() {
        let h = infer_first_func("func f():\n\tassert(true)\n");
        assert!(codes(&h).contains(&"ASSERT_ALWAYS_TRUE"), "{:?}", codes(&h));
    }

    #[test]
    fn assert_false_warns_always_false() {
        let h = infer_first_func("func f():\n\tassert(false, \"nope\")\n");
        assert!(
            codes(&h).contains(&"ASSERT_ALWAYS_FALSE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn assert_null_warns_always_false() {
        let h = infer_first_func("func f():\n\tassert(null)\n");
        assert!(
            codes(&h).contains(&"ASSERT_ALWAYS_FALSE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn assert_on_a_variable_is_silent() {
        // No false positive: a runtime condition is not a constant.
        let h = infer_first_func("func f(x):\n\tassert(x)\n");
        assert!(
            !codes(&h).iter().any(|c| c.starts_with("ASSERT_ALWAYS")),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn untyped_and_inferred_declarations_warn() {
        // The opt-in (default IGNORE) declaration-strictness codes, read from the raw warnings —
        // `codes()` filters them out so they don't pollute every other fixture.
        let h = infer_first_func("func f(p):\n\tvar a = 1\n\tvar b := 2\n\tvar c: int = 3\n");
        let raw: Vec<&str> = h
            .result
            .raw_warnings
            .iter()
            .map(|w| w.code.as_str())
            .collect();
        // The untyped param `p` and untyped `var a` — not the typed `var c` nor the inferred `var b`.
        let untyped = raw.iter().filter(|c| **c == "UNTYPED_DECLARATION").count();
        assert_eq!(untyped, 2, "only `p` and `a` are untyped: {raw:?}");
        let inferred = raw.iter().filter(|c| **c == "INFERRED_DECLARATION").count();
        assert_eq!(inferred, 1, "only `b` uses `:=`: {raw:?}");
    }

    #[test]
    fn confusable_identifier_warns_on_a_mixed_script_local() {
        // `p\u{0430}ypal` — Latin letters with a Cyrillic `а` (U+0430): a homoglyph of ASCII `paypal`.
        let h = infer_first_func("func f():\n\tvar p\u{0430}ypal = 1\n\treturn p\u{0430}ypal\n");
        assert!(
            codes(&h).contains(&"CONFUSABLE_IDENTIFIER"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn an_ordinary_ascii_identifier_is_not_confusable() {
        let h = infer_first_func("func f():\n\tvar paypal = 1\n\treturn paypal\n");
        assert!(
            !codes(&h).contains(&"CONFUSABLE_IDENTIFIER"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn a_member_with_a_confusable_name_warns() {
        // Cyrillic `а` inside `balance`.
        let cs = file_codes("var b\u{0430}lance = 0\n");
        assert!(cs.iter().any(|c| c == "CONFUSABLE_IDENTIFIER"), "{cs:?}");
    }

    #[test]
    fn an_assigned_but_never_read_local_is_unused() {
        // Precise read-vs-write: `x` is only assigned, never read → UNUSED_VARIABLE.
        let h = infer_first_func("func f():\n\tvar x = 1\n\tx = 2\n");
        assert!(codes(&h).contains(&"UNUSED_VARIABLE"), "{:?}", codes(&h));
    }

    #[test]
    fn a_read_local_is_not_unused() {
        let h = infer_first_func("func f() -> int:\n\tvar x = 1\n\tx = 2\n\treturn x\n");
        assert!(!codes(&h).contains(&"UNUSED_VARIABLE"), "{:?}", codes(&h));
    }

    #[test]
    fn unused_private_class_variable_warns() {
        let cs = file_codes("var _cache = 0\nfunc f():\n\tpass\n");
        assert!(
            cs.iter().any(|c| c == "UNUSED_PRIVATE_CLASS_VARIABLE"),
            "{cs:?}"
        );
    }

    #[test]
    fn a_read_private_class_variable_is_silent() {
        let cs = file_codes("var _cache = 0\nfunc f() -> int:\n\treturn _cache\n");
        assert!(
            !cs.iter().any(|c| c == "UNUSED_PRIVATE_CLASS_VARIABLE"),
            "{cs:?}"
        );
    }

    #[test]
    fn an_exported_private_var_is_not_unused_private() {
        // No false positive: an `@export`'d `_`-var is set externally (inspector / scene).
        let cs = file_codes("@export var _hidden = 0\n");
        assert!(
            !cs.iter().any(|c| c == "UNUSED_PRIVATE_CLASS_VARIABLE"),
            "{cs:?}"
        );
    }

    #[test]
    fn onready_with_export_warns() {
        let cs = file_codes("@onready @export var n = null\n");
        assert!(cs.iter().any(|c| c == "ONREADY_WITH_EXPORT"), "{cs:?}");
    }

    #[test]
    fn redundant_static_unload_warns_without_a_static_var() {
        let cs = file_codes("@static_unload\nclass_name Foo\nvar x = 1\n");
        assert!(cs.iter().any(|c| c == "REDUNDANT_STATIC_UNLOAD"), "{cs:?}");
    }

    #[test]
    fn static_unload_with_a_static_var_is_silent() {
        let cs = file_codes("@static_unload\nstatic var pool = []\n");
        assert!(!cs.iter().any(|c| c == "REDUNDANT_STATIC_UNLOAD"), "{cs:?}");
    }

    #[test]
    fn typed_local_read_before_assignment_warns() {
        let h = infer_first_func("func f() -> int:\n\tvar x: int\n\treturn x\n");
        assert!(
            codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn typed_local_assigned_then_read_does_not_warn() {
        let h = infer_first_func("func f() -> int:\n\tvar x: int\n\tx = 5\n\treturn x\n");
        assert!(
            !codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn typed_local_with_initializer_is_not_unassigned() {
        let h = infer_first_func("func f() -> int:\n\tvar x: int = 0\n\treturn x\n");
        assert!(
            !codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn untyped_local_is_not_unassigned_checked() {
        // An untyped `var x` is not an UNASSIGNED_VARIABLE candidate (no declared slot type).
        let h = infer_first_func("func f():\n\tvar x\n\tvar y = x\n\treturn y\n");
        assert!(
            !codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn typed_local_assigned_in_all_branches_then_read_does_not_warn() {
        // Both branches assign before the merge ⇒ definitely assigned ⇒ no warning (the join).
        let h = infer_first_func(
            "func f(c) -> int:\n\tvar x: int\n\tif c:\n\t\tx = 1\n\telse:\n\t\tx = 2\n\treturn x\n",
        );
        assert!(
            !codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn typed_local_assigned_in_one_branch_then_read_warns() {
        // Assigned only in the `then` branch ⇒ may be unassigned at the read ⇒ warns (matches Godot).
        let h =
            infer_first_func("func f(c) -> int:\n\tvar x: int\n\tif c:\n\t\tx = 1\n\treturn x\n");
        assert!(
            codes(&h).contains(&"UNASSIGNED_VARIABLE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn arm_after_wildcard_is_unreachable_pattern() {
        let h =
            infer_first_func("func f(x):\n\tmatch x:\n\t\t_:\n\t\t\tpass\n\t\t1:\n\t\t\tpass\n");
        assert!(
            codes(&h).contains(&"UNREACHABLE_PATTERN"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn arm_after_var_bind_is_unreachable_pattern() {
        let h = infer_first_func(
            "func f(x):\n\tmatch x:\n\t\tvar y:\n\t\t\treturn y\n\t\t1:\n\t\t\tpass\n",
        );
        assert!(
            codes(&h).contains(&"UNREACHABLE_PATTERN"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn arm_before_wildcard_is_not_unreachable() {
        let h =
            infer_first_func("func f(x):\n\tmatch x:\n\t\t1:\n\t\t\tpass\n\t\t_:\n\t\t\tpass\n");
        assert!(
            !codes(&h).contains(&"UNREACHABLE_PATTERN"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn guarded_wildcard_is_not_a_catch_all() {
        // `_ when c:` is conditional — a following arm is NOT unreachable.
        let h = infer_first_func(
            "func f(x, c):\n\tmatch x:\n\t\t_ when c:\n\t\t\tpass\n\t\t1:\n\t\t\tpass\n",
        );
        assert!(
            !codes(&h).contains(&"UNREACHABLE_PATTERN"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn multi_pattern_with_wildcard_is_conservatively_not_catch_all() {
        // `1, _:` IS a catch-all in Godot, but we conservatively under-warn (no false positive).
        let h =
            infer_first_func("func f(x):\n\tmatch x:\n\t\t1, _:\n\t\t\tpass\n\t\t2:\n\t\t\tpass\n");
        assert!(
            !codes(&h).contains(&"UNREACHABLE_PATTERN"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn enum_local_without_default_warns() {
        let h = infer_first_func("func f():\n\tvar m: Tween.TweenProcessMode\n");
        assert!(
            codes(&h).contains(&"ENUM_VARIABLE_WITHOUT_DEFAULT"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn enum_member_without_default_warns() {
        let codes = file_codes("var err: Error\nfunc f():\n\tpass\n");
        assert!(
            codes.iter().any(|c| c == "ENUM_VARIABLE_WITHOUT_DEFAULT"),
            "{codes:?}"
        );
    }

    #[test]
    fn native_virtual_override_with_clashing_param_type_warns() {
        // `_input(event: InputEvent)` is a Node virtual; `event: int` is an incompatible override.
        let codes = file_codes("extends Node\nfunc _input(event: int):\n\tpass\n");
        assert!(
            codes.iter().any(|c| c == "NATIVE_METHOD_OVERRIDE"),
            "{codes:?}"
        );
    }

    #[test]
    fn native_virtual_override_with_correct_param_type_does_not_warn() {
        let codes = file_codes("extends Node\nfunc _input(event: InputEvent):\n\tpass\n");
        assert!(
            !codes.iter().any(|c| c == "NATIVE_METHOD_OVERRIDE"),
            "{codes:?}"
        );
    }

    #[test]
    fn native_virtual_override_with_untyped_param_does_not_warn() {
        let codes = file_codes("extends Node\nfunc _input(event):\n\tpass\n");
        assert!(
            !codes.iter().any(|c| c == "NATIVE_METHOD_OVERRIDE"),
            "{codes:?}"
        );
    }

    #[test]
    fn a_non_virtual_method_is_not_a_native_override() {
        let codes = file_codes("extends Node\nfunc my_helper(x: int):\n\treturn x\n");
        assert!(
            !codes.iter().any(|c| c == "NATIVE_METHOD_OVERRIDE"),
            "{codes:?}"
        );
    }

    #[test]
    fn dotted_enum_override_param_does_not_false_warn() {
        // A valid override whose param is a dotted engine enum must NOT clash (enums are int-backed
        // and resolve to different qualified names on the annotation vs model side). Bug-hunt repro.
        let codes = file_codes(
            "extends MultiplayerPeerExtension\nfunc _set_transfer_mode(p_mode: MultiplayerPeer.TransferMode):\n\tpass\n",
        );
        assert!(
            !codes.iter().any(|c| c == "NATIVE_METHOD_OVERRIDE"),
            "{codes:?}"
        );
    }

    #[test]
    fn unused_signal_warns() {
        let codes = file_codes("signal my_event\nfunc f():\n\tpass\n");
        assert!(codes.iter().any(|c| c == "UNUSED_SIGNAL"), "{codes:?}");
    }

    #[test]
    fn emitted_signal_is_not_unused() {
        let codes = file_codes("signal my_event\nfunc f():\n\tmy_event.emit()\n");
        assert!(!codes.iter().any(|c| c == "UNUSED_SIGNAL"), "{codes:?}");
    }

    #[test]
    fn signal_connected_by_string_is_not_unused() {
        let codes = file_codes("signal my_event\nfunc f():\n\tconnect(\"my_event\", Callable())\n");
        assert!(!codes.iter().any(|c| c == "UNUSED_SIGNAL"), "{codes:?}");
    }

    #[test]
    fn enum_local_with_default_does_not_warn() {
        let h = infer_first_func(
            "func f():\n\tvar m: Tween.TweenProcessMode = Tween.TWEEN_PROCESS_IDLE\n\treturn m\n",
        );
        assert!(
            !codes(&h).contains(&"ENUM_VARIABLE_WITHOUT_DEFAULT"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn static_method_on_instance_warns() {
        // `JSON.stringify` is static; calling it through a JSON *instance* warns.
        let h =
            infer_first_func("func f():\n\tvar j := JSON.new()\n\tj.stringify({})\n\treturn j\n");
        assert!(
            codes(&h).contains(&"STATIC_CALLED_ON_INSTANCE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn static_method_on_the_type_does_not_warn() {
        // `JSON.stringify(...)` (on the type) is the correct form — never flagged.
        let h = infer_first_func("func f():\n\tJSON.stringify({})\n");
        assert!(
            !codes(&h).contains(&"STATIC_CALLED_ON_INSTANCE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn static_method_through_a_type_aliased_local_does_not_warn() {
        // `var t := JSON` aliases the TYPE; `t.stringify()` is valid, not static-on-instance.
        let h = infer_first_func("func f():\n\tvar t := JSON\n\tt.stringify({})\n");
        assert!(
            !codes(&h).contains(&"STATIC_CALLED_ON_INSTANCE"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn property_called_as_function_warns() {
        // `n.name` is a Node property; calling it is PROPERTY_USED_AS_FUNCTION.
        let h = infer_first_func("func f(n: Node):\n\tn.name()\n");
        assert!(
            codes(&h).contains(&"PROPERTY_USED_AS_FUNCTION"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn constant_called_as_function_warns() {
        // `NOTIFICATION_READY` is a Node constant; calling it is CONSTANT_USED_AS_FUNCTION.
        let h = infer_first_func("func f(n: Node):\n\tn.NOTIFICATION_READY()\n");
        assert!(
            codes(&h).contains(&"CONSTANT_USED_AS_FUNCTION"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn calling_a_real_method_is_not_a_kind_misuse() {
        let h = infer_first_func("func f(n: Node):\n\tn.get_parent()\n");
        assert!(
            codes(&h).iter().all(|c| !c.ends_with("_USED_AS_FUNCTION")),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn reading_a_property_as_a_value_is_not_a_kind_misuse() {
        let h = infer_first_func("func f(n: Node):\n\tvar s = n.name\n\treturn s\n");
        assert!(
            codes(&h).iter().all(|c| !c.ends_with("_USED_AS_FUNCTION")),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn enum_member_into_its_own_enum_slot_is_not_int_as_enum() {
        // `var m: Tween.TweenProcessMode = Tween.TWEEN_PROCESS_IDLE` is valid GDScript with no
        // cast — the enum member must type as its enum (not bare `int`), so `check_assign` sees
        // `Enum → Enum` (Ok). A regression here would false-warn on extremely common engine code.
        let h = infer_first_func(
            "func f():\n\tvar m: Tween.TweenProcessMode = Tween.TWEEN_PROCESS_IDLE\n\treturn m\n",
        );
        assert!(
            !codes(&h).contains(&"INT_AS_ENUM_WITHOUT_CAST"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn bare_int_into_enum_slot_still_warns() {
        // The fix must not over-suppress: a genuine uncast `int` into an enum slot still warns.
        let h = infer_first_func("func f():\n\tvar m: Tween.TweenProcessMode = 0\n\treturn m\n");
        assert!(
            codes(&h).contains(&"INT_AS_ENUM_WITHOUT_CAST"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn member_access_resolves_engine_property() {
        // In a Node script, bare `get_node(...)` resolves via the inherited base to Object(Node);
        // `get_parent()` is a real Node method → no UNSAFE.
        let h = infer_first_func(
            "extends Node\nfunc f():\n\tvar n := get_node(\"x\")\n\tn.get_parent()\n",
        );
        assert!(
            codes(&h).iter().all(|c| !c.starts_with("UNSAFE")),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn unsafe_method_on_known_type() {
        let h = infer_first_func(
            "extends Node\nfunc f():\n\tvar n := get_node(\"x\")\n\tn.totally_bogus_method()\n",
        );
        assert!(
            codes(&h).contains(&UNSAFE_METHOD_ACCESS),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn is_narrowing_suppresses_unsafe() {
        // Without narrowing, `x.free()` on an untyped param would be unchecked anyway; with
        // `is Node` it is checked against Node and `free` IS a Node method → no UNSAFE.
        let h = infer_first_func("func f(x):\n\tif x is Node:\n\t\tx.queue_free()\n");
        assert!(
            codes(&h).iter().all(|c| !c.starts_with("UNSAFE")),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn is_narrowing_flags_real_missing_member() {
        // After `is Node`, x is Node; `.bogus()` is genuinely missing → UNSAFE.
        let h = infer_first_func("func f(x):\n\tif x is Node:\n\t\tx.bogus_method()\n");
        assert!(codes(&h).contains(&UNSAFE_METHOD_ACCESS));
    }

    #[test]
    fn early_return_is_guard_narrows_past_the_guard() {
        // `if not (x is Node): return` — the only non-returning path proves x is Node, so after the
        // guard a real Node method is safe and a missing one warns (Workstream 2, beats the engine).
        let safe =
            infer_first_func("func f(x):\n\tif not (x is Node):\n\t\treturn\n\tx.get_parent()\n");
        assert!(
            codes(&safe).iter().all(|c| !c.starts_with("UNSAFE")),
            "real Node method must not warn after the guard: {:?}",
            codes(&safe)
        );
        let bogus =
            infer_first_func("func f(x):\n\tif not (x is Node):\n\t\treturn\n\tx.bogus_method()\n");
        assert!(
            codes(&bogus).contains(&UNSAFE_METHOD_ACCESS),
            "missing method must warn after the guard: {:?}",
            codes(&bogus)
        );
    }

    #[test]
    fn and_short_circuit_narrows_the_rhs() {
        // `x is Node and x.<m>()` types the RHS under x: Node — a real method is safe, a missing
        // one warns. The engine does not narrow here (Workstream 2, beats the engine).
        let safe = infer_first_func("func f(x):\n\tif x is Node and x.get_parent():\n\t\tpass\n");
        assert!(
            codes(&safe).iter().all(|c| !c.starts_with("UNSAFE")),
            "real Node method in the and-rhs must not warn: {:?}",
            codes(&safe)
        );
        let bogus =
            infer_first_func("func f(x):\n\tif x is Node and x.bogus_method():\n\t\tpass\n");
        assert!(
            codes(&bogus).contains(&UNSAFE_METHOD_ACCESS),
            "missing method in the and-rhs must warn: {:?}",
            codes(&bogus)
        );
    }

    // ---- Workstream 1 M1: self-contained checks ----

    #[test]
    fn empty_file_warns() {
        assert!(file_codes("").iter().any(|c| c == "EMPTY_FILE"));
        assert!(
            file_codes("# just a comment\n")
                .iter()
                .any(|c| c == "EMPTY_FILE")
        );
        assert!(
            file_codes("extends Node\n")
                .iter()
                .all(|c| c != "EMPTY_FILE")
        );
    }

    #[test]
    fn unused_variable_and_parameter() {
        let h = infer_first_func("func f(unused_p):\n\tvar unused_v = 1\n");
        assert!(codes(&h).contains(&"UNUSED_PARAMETER"), "{:?}", codes(&h));
        assert!(codes(&h).contains(&"UNUSED_VARIABLE"), "{:?}", codes(&h));
        // A used binding does not warn; a `_`-prefixed one is intentionally ignored.
        let used = infer_first_func("func f(p):\n\tvar v = p\n\treturn v\n");
        assert!(codes(&used).iter().all(|c| !c.starts_with("UNUSED")));
        let underscored = infer_first_func("func f(_ignored):\n\tpass\n");
        assert!(!codes(&underscored).contains(&"UNUSED_PARAMETER"));
    }

    #[test]
    fn standalone_expression_and_ternary() {
        let expr = infer_first_func("func f(a, b):\n\ta + b\n");
        assert!(
            codes(&expr).contains(&"STANDALONE_EXPRESSION"),
            "{:?}",
            codes(&expr)
        );
        let tern = infer_first_func("func f(c):\n\t1 if c else 2\n");
        assert!(
            codes(&tern).contains(&"STANDALONE_TERNARY"),
            "{:?}",
            codes(&tern)
        );
        // A call statement has an effect — never flagged.
        let call = infer_first_func("func f(n):\n\tn.queue_free()\n");
        assert!(codes(&call).iter().all(|c| !c.starts_with("STANDALONE")));
    }

    #[test]
    fn unreachable_code_after_return() {
        let h = infer_first_func("func f():\n\treturn\n\tprint(\"dead\")\n");
        assert!(codes(&h).contains(&"UNREACHABLE_CODE"), "{:?}", codes(&h));
    }

    #[test]
    fn incompatible_ternary_warns() {
        // `"s" if c else 1` — String vs int, no common type.
        let h = infer_first_func("func f(c):\n\tvar x = \"s\" if c else 1\n\treturn x\n");
        assert!(
            codes(&h).contains(&"INCOMPATIBLE_TERNARY"),
            "{:?}",
            codes(&h)
        );
    }

    #[test]
    fn variant_receiver_never_unsafe() {
        // Untyped param → Variant receiver → unchecked, no diagnostic.
        let h = infer_first_func("func f(x):\n\tx.anything_at_all()\n");
        assert!(codes(&h).is_empty(), "{:?}", codes(&h));
    }

    #[test]
    fn unsafe_call_argument_on_variant_into_typed_param() {
        // Passing an untyped (Variant) value to a typed own-method parameter needs an unsafe cast.
        let h = infer_first_func("func f(p):\n\ttake(p)\nfunc take(n: Node2D):\n\tpass\n");
        assert!(
            codes(&h).contains(&UNSAFE_CALL_ARGUMENT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn unsafe_call_argument_silent_on_safe_and_untyped() {
        // A subtype arg (upcast) is safe; an untyped parameter accepts anything — neither warns.
        let upcast =
            infer_first_func("func f(n: Node2D):\n\ttake(n)\nfunc take(n: Node):\n\tpass\n");
        assert!(
            !codes(&upcast).contains(&UNSAFE_CALL_ARGUMENT),
            "upcast is safe: {:?}",
            upcast.result.diagnostics
        );
        let untyped = infer_first_func("func f(p):\n\ttake(p)\nfunc take(n):\n\tpass\n");
        assert!(
            !codes(&untyped).contains(&UNSAFE_CALL_ARGUMENT),
            "untyped param accepts anything: {:?}",
            untyped.result.diagnostics
        );
    }

    #[test]
    fn inference_on_variant() {
        // `:=` from an untyped (Variant) param.
        let h = infer_first_func("func f(x):\n\tvar y := x\n");
        assert!(codes(&h).contains(&INFERENCE_ON_VARIANT));
    }

    #[test]
    fn field_inferred_from_earlier_field_is_typed() {
        // W2-MEMBER-FIXPOINT: `b`'s initializer references the earlier field `a`. A single shallow
        // field pass would see `a` as `Variant` (seam) and fire INFERENCE_ON_VARIANT on `:= a`; the
        // bounded fixpoint seeds `a: int` so `a + 1` is `int` and `:=` is precise — no warning.
        let codes = file_codes("var a := 1\nvar b := a + 1\n");
        assert!(
            !codes.iter().any(|c| c == INFERENCE_ON_VARIANT),
            "field `b` from earlier field `a` should type as int, not Variant: {codes:?}"
        );
    }

    #[test]
    fn field_forward_reference_is_seamed_not_warned() {
        // A field referencing a *later* field still resolves through the fixpoint (both rounds
        // see each other's seeded type), and at worst lands on the conservative seam — never a
        // false INFERENCE_ON_VARIANT. (`b` precedes `a` lexically here.)
        let codes = file_codes("var b := a\nvar a := 1\n");
        assert!(
            !codes.iter().any(|c| c == INFERENCE_ON_VARIANT),
            "forward field reference must not false-warn: {codes:?}"
        );
    }

    #[test]
    fn standalone_inferred_field_unchanged() {
        // No-regression: a self-contained inferred field still types from its literal, no warning.
        let codes = file_codes("var n := 0\n");
        assert!(
            codes.is_empty(),
            "a literal-initialised field should produce no diagnostics: {codes:?}"
        );
    }

    #[test]
    fn lambda_var_is_callable_not_variant() {
        let h = infer_first_func("func f():\n\tvar cb := func():\n\t\tpass\n");
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn multiline_lambda_then_paren_line_no_false_warning() {
        // A multi-line lambda bound to a var, followed by a statement that begins with `(`.
        // The parser now ends the lambda at its dedent (the `(` line is its own statement), so
        // there is no spurious call-on-lambda and no false `INFERENCE_ON_VARIANT`.
        let src = "func f(state, i, loop):\n\tvar cb := func():\n\t\tif i >= state.size():\n\t\t\treturn\n\t(loop as SceneTree).process_frame.connect(cb, CONNECT_ONE_SHOT)\n";
        let h = infer_first_func(src);
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn calling_a_callable_value_is_seam_not_variant() {
        // Invoking an arbitrary expression (here a parenthesized `Callable` value) reaches the
        // seam arm of `infer_call`: the return type isn't tracked, so the result is Unknown,
        // not `Variant`, and the inferred-on-Variant warning never fires.
        let src = "func f(cb: Callable):\n\tvar x := (cb)()\n\treturn x\n";
        let h = infer_first_func(src);
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn ternary_with_seam_branch_does_not_collapse_to_variant() {
        // A ternary whose else-branch is the seam (`await` is untracked → Unknown) must `join`
        // to Unknown, NOT Variant — otherwise `var x := …` fires a false INFERENCE_ON_VARIANT.
        // (Regression: `join` used to absorb any uninformative branch to Variant.)
        let src =
            "func f(c: bool):\n\tvar x := 5 if c else await get_tree().process_frame\n\treturn x\n";
        let h = infer_first_func(src);
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "seam branch should keep the ternary on the seam: {:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn await_a_coroutine_call_recovers_its_return_type() {
        // `await f()` yields the call's value, so await is identity on a non-signal operand:
        // `await make()` for `func make() -> int` types `x` as int (was the seam before).
        let src = "func g() -> int:\n\tvar x := await make()\n\treturn x\nfunc make() -> int:\n\treturn 5\n";
        let h = infer_first_func(src);
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "no false variant warning: {:?}",
            h.result.diagnostics
        );
        let api = gdscript_api::bundled();
        let x = &h.result.bindings[0];
        assert!(
            matches!(&x.ty, Ty::Builtin(b) if api.builtin(*b).name == "int"),
            "await make() should recover int, got {:?}",
            x.ty
        );
    }

    #[test]
    fn await_a_signal_stays_the_seam() {
        // `await sig` yields the signal's payload (needs the Phase-3+ sig table) — must stay the seam,
        // never the Signal type itself, and never a false INFERENCE_ON_VARIANT.
        let src = "func f():\n\tvar x := await get_tree().process_frame\n\treturn x\n";
        let h = infer_first_func(src);
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "awaiting a signal must not warn: {:?}",
            h.result.diagnostics
        );
        assert!(
            matches!(&h.result.bindings[0].ty, Ty::Unknown),
            "awaiting a signal stays the seam, got {:?}",
            h.result.bindings[0].ty
        );
    }

    #[test]
    fn for_var_over_packed_string_array_is_string() {
        // `for s in "a,b".split(",")` iterates a PackedStringArray → String, so `s.to_int()`
        // resolves and `var x := s` does not warn.
        let h = infer_first_func("func f():\n\tfor s in \"a,b\".split(\",\"):\n\t\tvar x := s\n");
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn class_new_is_object_not_variant() {
        let h = infer_first_func("func f():\n\tvar s := GDScript.new()\n");
        assert!(
            !codes(&h).contains(&INFERENCE_ON_VARIANT),
            "{:?}",
            h.result.diagnostics
        );
    }

    #[test]
    fn unknown_seam_never_warns() {
        // `preload(...)` is Unknown; `:=` from it does NOT warn, and member access is unchecked.
        let h = infer_first_func("func f():\n\tvar s := preload(\"res://x.gd\")\n\ts.whatever()\n");
        assert!(codes(&h).is_empty(), "{:?}", codes(&h));
    }

    #[test]
    fn expr_types_are_memoized_for_hover() {
        let h = infer_first_func("func f():\n\tvar n := 42\n");
        // The `42` literal expr should be typed int.
        let has_int = h
            .result
            .expr_ty
            .values()
            .any(|t| matches!(t, Ty::Builtin(_)));
        assert!(has_int);
        // sanity: the body lowered at least one expr
        assert!(!h.body.exprs.is_empty());
    }
}