qala-compiler 0.1.1

Compiler and bytecode VM for the Qala programming language
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
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
//! the type and effect checker: [`check_program`] turns the parser's untyped
//! AST + the source text into a typed AST plus a vector of errors and a vector
//! of warnings. it does NOT abort on the first error -- it accumulates and
//! recovers locally via [`QalaType::Unknown`] poison-propagation, so a user's
//! typo doesn't cascade to twenty errors.
//!
//! two top-level passes plus a third effect-fixed-point pass:
//! - pass 1 walks every top-level item building a [`SymbolTable`] (structs,
//!   enums, interfaces, free fns, methods).
//! - pass 2 walks every function body checking expressions and producing typed
//!   nodes.
//! - pass 3 iterates the call graph until every function's inferred
//!   [`EffectSet`] stabilises (proven to converge in <= 3 monotonic-ascent
//!   rounds on a 4-level lattice), then validates annotated functions against
//!   their annotation.
//!
//! determinism: errors and warnings are sorted by `(span.start, span.len)`
//! before returning; user-visible lists (missing variants, missing methods)
//! are sorted alphabetically via [`BTreeSet`]; the stdlib signatures table
//! is a [`Vec`], not a [`HashMap`], so iteration is source-order. no panics on
//! a malformed but well-formed-by-the-parser AST -- this discipline is
//! load-bearing for Phase 6 where the typechecker runs in WASM.

use crate::ast;
use crate::effects::EffectSet;
use crate::errors::QalaError;
#[allow(unused_imports)] // task 2 uses this in the depth-cap check.
use crate::parser::MAX_DEPTH;
use crate::span::{LineIndex, Span};
use crate::typed_ast;
use crate::types::{QalaType, Symbol};
use std::collections::{BTreeMap, BTreeSet, HashMap};

// ---- public surface --------------------------------------------------------

/// one warning produced by the type checker.
///
/// derives `Debug, Clone, PartialEq`. categories are the locked snake_case
/// identifiers also accepted by the `// qala: allow(...)` directive scanner:
/// `unused_var`, `unreachable_code`, `unmatched_defer`, `shadowed_var`,
/// `redundant_annotation`, `overlapping_guards`. errors are never silenced;
/// warnings are silenceable by the directive table built once in
/// [`scan_allow_directives`].
#[derive(Debug, Clone, PartialEq)]
pub struct QalaWarning {
    /// one of the locked snake_case category strings.
    pub category: String,
    /// the human-readable one-line message.
    pub message: String,
    /// the source span the warning points at.
    pub span: Span,
    /// optional extra information, like a `shadowed_var`'s prior-binding
    /// location ("the prior binding is at line {l}:{c}").
    pub note: Option<String>,
}

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

/// check a parsed program against the type and effect rules, producing a
/// fully-typed AST plus accumulated errors and warnings.
///
/// the typechecker does NOT fail-fast: it recovers locally via
/// [`QalaType::Unknown`] poison-propagation and keeps going so a typo at the
/// top of a function does not cascade to a wall of follow-on errors. errors
/// and warnings are sorted by `(span.start, span.len)` before returning so
/// downstream renderers can rely on byte-deterministic order.
pub fn check_program(
    ast: &ast::Ast,
    src: &str,
) -> (typed_ast::TypedAst, Vec<QalaError>, Vec<QalaWarning>) {
    let mut c = Checker::new(src);
    // scan `// qala: allow(...)` directives once over the source text; the
    // resulting map is consulted by every `emit_warning` call.
    c.allow = scan_allow_directives(src);
    // pass 1a: pre-register every top-level type name so forward and mutual
    // references (`struct A { x: B } struct B { y: A }`) resolve correctly
    // when pass 1b walks field-type expressions. without this stage,
    // resolve_type_expr would emit a spurious `UnknownType` for the
    // forward-referenced name.
    c.preregister_type_names(ast);
    // pass 1b: collect every top-level declaration into the symbol table.
    for item in ast {
        c.collect_item(item);
    }
    // detect any recursive-struct cycles before pass 2 runs.
    c.detect_recursive_structs();
    // pass 2 placeholder: build a TypedAst by translating each item. tasks
    // 2-5 fill in the real check_item that walks bodies and types
    // expressions; for task 1 this returns a minimal-but-valid typed shape.
    let typed: typed_ast::TypedAst = ast.iter().map(|item| c.check_item(item)).collect();
    // pass 3 placeholder: task 3 implements the effect fixed-point.
    c.resolve_function_effects();
    // deterministic sort by (span.start, span.len).
    c.errors.sort_by_key(|e| (e.span().start, e.span().len));
    c.warnings.sort_by_key(|w| (w.span.start, w.span.len));
    (typed, c.errors, c.warnings)
}

// ---- symbol table ----------------------------------------------------------

/// the top-level declarations the typechecker collected during pass 1.
///
/// declaration order is preserved separately in [`Checker::struct_decl_order`]
/// for deterministic cycle reporting; iteration of these `HashMap`s is never
/// user-visible.
#[derive(Default)]
struct SymbolTable {
    /// every `struct Decl { ... }` keyed by name.
    structs: HashMap<String, StructInfo>,
    /// every `enum Decl { ... }` keyed by name. `BTreeMap` so iteration
    /// order is deterministic (alphabetical) across all enum lookups.
    enums: BTreeMap<String, EnumInfo>,
    /// every `interface Decl { ... }` keyed by name.
    interfaces: HashMap<String, InterfaceInfo>,
    /// every `fn` or `fn Type.method` declaration keyed by [`FnKey`].
    fns: HashMap<FnKey, FnInfo>,
}

/// a resolved struct declaration. fields are populated in pass 1 and
/// consumed by the bidirectional checker in task 2 plus the
/// recursive-struct detector below.
#[allow(dead_code)]
struct StructInfo {
    /// the fields in declaration order: name + resolved type.
    fields: Vec<(String, QalaType)>,
    /// the declaration's source span.
    span: Span,
}

/// a resolved enum declaration. fields are populated in pass 1 and consumed
/// by the exhaustiveness checker in task 3.
#[allow(dead_code)]
struct EnumInfo {
    /// the variants in declaration order: name + resolved field types.
    variants: Vec<(String, Vec<QalaType>)>,
    /// the declaration's source span.
    span: Span,
}

/// a resolved interface declaration. fields are populated in pass 1 and
/// consumed by the structural-satisfaction checker in task 3.
#[allow(dead_code)]
struct InterfaceInfo {
    /// the required method signatures in declaration order.
    methods: Vec<MethodSigInfo>,
    /// the declaration's source span.
    span: Span,
}

/// a resolved interface-method signature. fields are populated in pass 1
/// and consumed by the structural-satisfaction checker in task 3.
#[allow(dead_code)]
struct MethodSigInfo {
    /// the method name.
    name: String,
    /// the parameter types in declaration order (including `self` typed as
    /// the receiver if present).
    params: Vec<QalaType>,
    /// the return type.
    ret_ty: QalaType,
    /// the annotated effect, or `None` for unannotated.
    effect: Option<EffectSet>,
    /// the signature's source span.
    span: Span,
}

/// the key under which a `fn` or `fn Type.method` is stored.
///
/// `(None, name)` is a free function; `(Some(T), name)` is the `fn T.method`
/// form. derives `Eq + Hash` so it can be a `HashMap` key.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct FnKey {
    /// `Some(T)` for `fn T.method`; `None` for a free function.
    type_name: Option<String>,
    /// the function or method name.
    name: String,
}

/// a resolved function declaration. fields are populated in pass 1 and
/// consumed by the bidirectional checker (task 2), the effect fixed-point
/// (task 3), and the structural-satisfaction checker (task 3).
#[allow(dead_code)]
struct FnInfo {
    /// the parameter list: name + resolved type + an unevaluated default if
    /// the parser captured one (the typechecker does not yet evaluate
    /// defaults; codegen does).
    params: Vec<(String, QalaType, Option<ast::Expr>)>,
    /// the return type. `void` is the resolved-form of an omitted `-> T`.
    ret_ty: QalaType,
    /// the annotated effect, or `None` for unannotated.
    annotated_effect: Option<EffectSet>,
    /// the inferred effect set, filled in by pass 3
    /// ([`Checker::resolve_function_effects`]).
    inferred_effect: Option<EffectSet>,
    /// the declaration's source span.
    span: Span,
    /// true for `fn T.method` declarations.
    is_method: bool,
}

// ---- local-scope info ------------------------------------------------------

/// metadata for one local binding (a `let` or function parameter) currently
/// in scope.
#[allow(dead_code)]
struct LocalInfo {
    /// the resolved type of this binding.
    ty: QalaType,
    /// the binding's source span (the `name` token).
    span: Span,
    /// whether the binding was declared `let mut`.
    is_mut: bool,
    /// whether the binding has been read at least once. tasks 4-5 use this
    /// to fire the `unused_var` warning.
    used: bool,
    /// whether this is a function parameter (exempt from `unused_var` per
    /// open question 4).
    is_param: bool,
}

// ---- function context ------------------------------------------------------

/// per-function state the typechecker maintains during pass 2.
#[allow(dead_code)]
struct FnCtx {
    /// the function name.
    name: String,
    /// `Some(T)` for `fn T.method`; `None` for a free function.
    type_name: Option<String>,
    /// the resolved return type.
    ret_ty: QalaType,
    /// the annotated effect, or `None` for unannotated.
    annotated_effect: Option<EffectSet>,
    /// the intrinsic effect set of the body (the union of every non-call
    /// statement's intrinsic effect). pass 3 unions this with the inferred
    /// effects of every called function.
    body_intrinsic: EffectSet,
    /// the keys of every function called from this body. pass 3 walks these
    /// during the fixed-point iteration.
    called_fns: Vec<FnKey>,
    /// every call site of this function that may need an effect-violation
    /// check after pass 3 settles. populated when the caller has an
    /// annotated effect.
    callsites_to_check: Vec<EffectViolationCandidate>,
}

/// a recorded call site that may produce an [`QalaError::EffectViolation`]
/// after pass 3 resolves every function's inferred effect.
#[allow(dead_code)]
#[derive(Clone)]
struct EffectViolationCandidate {
    /// the caller's [`FnKey`].
    caller_key: FnKey,
    /// the callee's [`FnKey`].
    callee_key: FnKey,
    /// the source span of the call expression.
    call_span: Span,
}

// ---- checker state ---------------------------------------------------------

/// the type checker's working state. one is constructed per
/// [`check_program`] call.
#[allow(dead_code)]
struct Checker<'src> {
    /// the source text, kept by reference for the directive scanner and the
    /// line-index lookup. the typechecker never copies it.
    src: &'src str,
    /// the line-start table for converting byte offsets to line / column.
    line_index: LineIndex,
    /// the top-level declarations collected in pass 1.
    symbols: SymbolTable,
    /// struct names in declaration order, for deterministic SCC traversal.
    /// also doubles as the duplicate-detection set for structs (the symbols
    /// map is pre-populated with placeholders by `preregister_type_names`).
    struct_decl_order: Vec<String>,
    /// enum names that `collect_enum` has already processed; the symbols map
    /// is pre-populated with placeholders, so a contains-check there cannot
    /// distinguish first-vs-duplicate.
    collected_enum_names: Vec<String>,
    /// interface names that `collect_interface` has already processed.
    collected_interface_names: Vec<String>,
    /// the accumulated errors. sorted by `(span.start, span.len)` before
    /// returning.
    errors: Vec<QalaError>,
    /// the accumulated warnings. sorted by `(span.start, span.len)` before
    /// returning.
    warnings: Vec<QalaWarning>,
    /// the `// qala: allow(...)` directive table built once at the start of
    /// [`check_program`]. tasks 4-5 use it to silence warnings per-line.
    allow: HashMap<usize, BTreeSet<String>>,
    /// the active lexical scopes. each scope is a name -> local-info map;
    /// the topmost is the innermost.
    scopes: Vec<HashMap<String, LocalInfo>>,
    /// the active function context, or `None` outside a function body.
    fn_ctx: Option<FnCtx>,
    /// recursive-depth counter for [`Checker::infer_expr`]. mirrors the
    /// parser's [`MAX_DEPTH`] guard.
    depth: u32,
    /// per-function record (intrinsic body effect, called fns, candidate
    /// call sites). populated during pass 2's `check_fn_decl`; consumed by
    /// pass 3's `resolve_function_effects` in task 3.
    body_records: HashMap<FnKey, BodyEffectRecord>,
}

impl<'src> Checker<'src> {
    /// construct a fresh checker for the given source text.
    fn new(src: &'src str) -> Self {
        Checker {
            src,
            line_index: LineIndex::new(src),
            symbols: SymbolTable::default(),
            struct_decl_order: Vec::new(),
            collected_enum_names: Vec::new(),
            collected_interface_names: Vec::new(),
            errors: Vec::new(),
            warnings: Vec::new(),
            // task 5 replaces this empty map with the real scanner output.
            allow: HashMap::new(),
            scopes: Vec::new(),
            fn_ctx: None,
            depth: 0,
            body_records: HashMap::new(),
        }
    }
}

// ---- pass 1: declaration collection ----------------------------------------

impl<'src> Checker<'src> {
    /// register every top-level type name (struct / enum / interface) with
    /// an empty placeholder entry so forward and mutual references in field
    /// type positions resolve without emitting a spurious `UnknownType`.
    ///
    /// the placeholder is replaced by the real info in `collect_*`. duplicate
    /// names are NOT diagnosed here; `collect_*` does that against the
    /// already-populated map.
    fn preregister_type_names(&mut self, ast: &ast::Ast) {
        for item in ast {
            match item {
                ast::Item::Struct(d) => {
                    self.symbols
                        .structs
                        .entry(d.name.clone())
                        .or_insert(StructInfo {
                            fields: Vec::new(),
                            span: d.span,
                        });
                }
                ast::Item::Enum(d) => {
                    self.symbols
                        .enums
                        .entry(d.name.clone())
                        .or_insert(EnumInfo {
                            variants: Vec::new(),
                            span: d.span,
                        });
                }
                ast::Item::Interface(d) => {
                    self.symbols
                        .interfaces
                        .entry(d.name.clone())
                        .or_insert(InterfaceInfo {
                            methods: Vec::new(),
                            span: d.span,
                        });
                }
                ast::Item::Fn(_) => {}
            }
        }
    }

    /// dispatch on an item kind and call the matching collector.
    fn collect_item(&mut self, item: &ast::Item) {
        match item {
            ast::Item::Fn(d) => self.collect_fn(d),
            ast::Item::Struct(d) => self.collect_struct(d),
            ast::Item::Enum(d) => self.collect_enum(d),
            ast::Item::Interface(d) => self.collect_interface(d),
        }
    }

    /// collect a struct declaration into the symbol table.
    ///
    /// resolves each field's `TypeExpr` to a [`QalaType`]; emits an
    /// `UnknownType` per unresolvable field type so pass 2 can keep going
    /// with `Unknown` in the unresolved slot. emits a generic `Type` error
    /// on a duplicate struct name (the first declaration wins, so the
    /// placeholder kept the first decl's span and the second triggers the
    /// duplicate-check below). detection uses `struct_decl_order` because
    /// `preregister_type_names` already populated the symbols map with
    /// placeholders.
    fn collect_struct(&mut self, decl: &ast::StructDecl) {
        if self.struct_decl_order.contains(&decl.name) {
            self.errors.push(QalaError::Type {
                span: decl.span,
                message: format!("duplicate struct definition `{}`", decl.name),
            });
            return;
        }
        let mut fields: Vec<(String, QalaType)> = Vec::with_capacity(decl.fields.len());
        for f in &decl.fields {
            let ty = self.resolve_type_expr(&f.ty);
            fields.push((f.name.clone(), ty));
        }
        self.symbols.structs.insert(
            decl.name.clone(),
            StructInfo {
                fields,
                span: decl.span,
            },
        );
        self.struct_decl_order.push(decl.name.clone());
    }

    /// collect an enum declaration into the symbol table.
    fn collect_enum(&mut self, decl: &ast::EnumDecl) {
        if self.collected_enum_names.contains(&decl.name) {
            self.errors.push(QalaError::Type {
                span: decl.span,
                message: format!("duplicate enum definition `{}`", decl.name),
            });
            return;
        }
        self.collected_enum_names.push(decl.name.clone());
        let mut variants: Vec<(String, Vec<QalaType>)> = Vec::with_capacity(decl.variants.len());
        for v in &decl.variants {
            let fields: Vec<QalaType> =
                v.fields.iter().map(|t| self.resolve_type_expr(t)).collect();
            variants.push((v.name.clone(), fields));
        }
        self.symbols.enums.insert(
            decl.name.clone(),
            EnumInfo {
                variants,
                span: decl.span,
            },
        );
    }

    /// collect an interface declaration into the symbol table.
    fn collect_interface(&mut self, decl: &ast::InterfaceDecl) {
        if self.collected_interface_names.contains(&decl.name) {
            self.errors.push(QalaError::Type {
                span: decl.span,
                message: format!("duplicate interface definition `{}`", decl.name),
            });
            return;
        }
        self.collected_interface_names.push(decl.name.clone());
        let methods: Vec<MethodSigInfo> = decl
            .methods
            .iter()
            .map(|m| {
                // a method signature's params include `self` if present; we
                // resolve self to the receiver -- but at the interface
                // declaration site we don't yet know the receiver type, so
                // we treat `self` as `QalaType::Unknown` here. structural
                // satisfaction (task 3) ignores the self slot when matching
                // against an impl's `fn Type.method`.
                let params: Vec<QalaType> = m
                    .params
                    .iter()
                    .map(|p| {
                        if p.is_self {
                            QalaType::Unknown
                        } else if let Some(ty) = &p.ty {
                            self.resolve_type_expr(ty)
                        } else {
                            QalaType::Unknown
                        }
                    })
                    .collect();
                let ret_ty = m
                    .ret_ty
                    .as_ref()
                    .map(|t| self.resolve_type_expr(t))
                    .unwrap_or(QalaType::Void);
                let effect = m.effect.as_ref().map(effect_set_from_ast);
                MethodSigInfo {
                    name: m.name.clone(),
                    params,
                    ret_ty,
                    effect,
                    span: m.span,
                }
            })
            .collect();
        self.symbols.interfaces.insert(
            decl.name.clone(),
            InterfaceInfo {
                methods,
                span: decl.span,
            },
        );
    }

    /// collect a function (free function or `fn T.method`) into the symbol
    /// table.
    fn collect_fn(&mut self, decl: &ast::FnDecl) {
        let key = FnKey {
            type_name: decl.type_name.clone(),
            name: decl.name.clone(),
        };
        if self.symbols.fns.contains_key(&key) {
            // first declaration wins; second is the duplicate.
            let label = match &decl.type_name {
                Some(t) => format!("{}.{}", t, decl.name),
                None => decl.name.clone(),
            };
            self.errors.push(QalaError::Type {
                span: decl.span,
                message: format!("duplicate function definition `{label}`"),
            });
            return;
        }
        let mut params: Vec<(String, QalaType, Option<ast::Expr>)> =
            Vec::with_capacity(decl.params.len());
        for p in &decl.params {
            let ty = if p.is_self {
                // self's type is the receiver type, when present.
                match &decl.type_name {
                    Some(t) => QalaType::Named(Symbol(t.clone())),
                    None => QalaType::Unknown,
                }
            } else if let Some(t) = &p.ty {
                self.resolve_type_expr(t)
            } else {
                // a non-self param without a type is malformed; the parser
                // should reject this, but recovery is `Unknown`.
                QalaType::Unknown
            };
            params.push((p.name.clone(), ty, p.default.clone()));
        }
        let ret_ty = decl
            .ret_ty
            .as_ref()
            .map(|t| self.resolve_type_expr(t))
            .unwrap_or(QalaType::Void);
        let annotated_effect = decl.effect.as_ref().map(effect_set_from_ast);
        let is_method = decl.type_name.is_some();
        self.symbols.fns.insert(
            key,
            FnInfo {
                params,
                ret_ty,
                annotated_effect,
                inferred_effect: None,
                span: decl.span,
                is_method,
            },
        );
    }

    /// resolve a `TypeExpr` to a [`QalaType`], emitting `UnknownType` on a
    /// name that does not match a primitive, a known struct / enum /
    /// interface, the built-in `FileHandle`, or a known built-in generic.
    fn resolve_type_expr(&mut self, ty: &ast::TypeExpr) -> QalaType {
        match ty {
            ast::TypeExpr::Primitive { kind, .. } => QalaType::from_prim_type(kind),
            ast::TypeExpr::Named { name, span } => {
                // Result / Option without generic args is an explicit error
                // -- the parser allows the bare name here, but the type
                // system requires the arguments.
                if name == "Result" {
                    self.errors.push(QalaError::Type {
                        span: *span,
                        message: "Result requires two type arguments".to_string(),
                    });
                    return QalaType::Unknown;
                }
                if name == "Option" {
                    self.errors.push(QalaError::Type {
                        span: *span,
                        message: "Option requires one type argument".to_string(),
                    });
                    return QalaType::Unknown;
                }
                if name == "FileHandle" {
                    return QalaType::FileHandle;
                }
                if self.symbols.structs.contains_key(name)
                    || self.symbols.enums.contains_key(name)
                    || self.symbols.interfaces.contains_key(name)
                {
                    return QalaType::Named(Symbol(name.clone()));
                }
                self.errors.push(QalaError::UnknownType {
                    span: *span,
                    name: name.clone(),
                });
                QalaType::Unknown
            }
            ast::TypeExpr::Array { elem, size, .. } => {
                QalaType::Array(Box::new(self.resolve_type_expr(elem)), Some(*size as usize))
            }
            ast::TypeExpr::DynArray { elem, .. } => {
                QalaType::Array(Box::new(self.resolve_type_expr(elem)), None)
            }
            ast::TypeExpr::Tuple { elems, .. } => {
                QalaType::Tuple(elems.iter().map(|e| self.resolve_type_expr(e)).collect())
            }
            ast::TypeExpr::Fn { params, ret, .. } => QalaType::Function {
                params: params.iter().map(|p| self.resolve_type_expr(p)).collect(),
                returns: Box::new(self.resolve_type_expr(ret)),
            },
            ast::TypeExpr::Generic { name, args, span } => {
                if name == "Result" {
                    if args.len() != 2 {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: "Result requires two type arguments".to_string(),
                        });
                        return QalaType::Unknown;
                    }
                    let ok = self.resolve_type_expr(&args[0]);
                    let err = self.resolve_type_expr(&args[1]);
                    return QalaType::Result(Box::new(ok), Box::new(err));
                }
                if name == "Option" {
                    if args.len() != 1 {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: "Option requires one type argument".to_string(),
                        });
                        return QalaType::Unknown;
                    }
                    let inner = self.resolve_type_expr(&args[0]);
                    return QalaType::Option(Box::new(inner));
                }
                self.errors.push(QalaError::Type {
                    span: *span,
                    message: format!("unknown generic type `{name}`"),
                });
                QalaType::Unknown
            }
        }
    }
}

/// bridge from the parser's `Effect` (records *which keyword appeared*) to an
/// [`EffectSet`] (the bitfield the checker actually reasons about).
fn effect_set_from_ast(e: &ast::Effect) -> EffectSet {
    match e {
        ast::Effect::Pure => EffectSet::pure(),
        ast::Effect::Io => EffectSet::io(),
        ast::Effect::Alloc => EffectSet::alloc(),
        ast::Effect::Panic => EffectSet::panic(),
    }
}

// ---- recursive struct detection -------------------------------------------

impl<'src> Checker<'src> {
    /// detect every cycle in the by-value struct graph and emit one
    /// [`QalaError::RecursiveStructByValue`] per cycle.
    ///
    /// implementation: Tarjan's strongly-connected-components algorithm on the
    /// adjacency built from each struct's by-value field-type targets. an SCC
    /// of size > 1 or a singleton with a self-edge is a cycle. the cycle's
    /// lexicographically-smallest struct name is the head; the path walks the
    /// cycle starting and ending at the head so the message reads as a closed
    /// loop when joined with arrows (`A -> B -> A`).
    ///
    /// "by value" excludes `Option<_>`, `Result<_, _>`, dynamic arrays (`[T]`,
    /// stored Some-with-no-length), and zero-size fixed arrays. fixed arrays
    /// of size > 0 and tuples DO carry their element types by value, so they
    /// contribute edges.
    fn detect_recursive_structs(&mut self) {
        // alphabetical traversal order makes the chosen head deterministic
        // when multiple structs participate in a single SCC.
        let mut order = self.struct_decl_order.clone();
        order.sort();

        // adjacency: struct name -> sorted list of by-value struct neighbours.
        let mut adj: HashMap<String, Vec<String>> = HashMap::new();
        for name in &order {
            let mut targets: BTreeSet<String> = BTreeSet::new();
            if let Some(info) = self.symbols.structs.get(name) {
                for (_, ty) in &info.fields {
                    collect_by_value_targets(ty, &mut targets);
                }
            }
            let neighbours: Vec<String> = targets
                .into_iter()
                .filter(|n| self.symbols.structs.contains_key(n))
                .collect();
            adj.insert(name.clone(), neighbours);
        }

        // Tarjan SCC.
        let sccs = tarjan_scc(&order, &adj);

        for scc in sccs {
            // a singleton SCC is a cycle iff there is a self-edge.
            let is_cycle = scc.len() > 1
                || (scc.len() == 1
                    && adj
                        .get(&scc[0])
                        .map(|v| v.contains(&scc[0]))
                        .unwrap_or(false));
            if !is_cycle {
                continue;
            }
            // the head is the lexicographically smallest name in the SCC.
            let head = scc.iter().min().cloned().unwrap_or_else(|| scc[0].clone());
            // build the path by DFS from head along the SCC's adjacency
            // until we return to head. for a self-loop the path is `[head,
            // head]`.
            let scc_set: BTreeSet<String> = scc.iter().cloned().collect();
            let mut path: Vec<String> = vec![head.clone()];
            let mut current = head.clone();
            // bounded by scc.len() + 1 -- a cycle of N nodes returns to head
            // in N steps.
            for _ in 0..=scc.len() {
                let next: Option<String> = adj
                    .get(&current)
                    .and_then(|nbrs| nbrs.iter().filter(|n| scc_set.contains(*n)).min().cloned());
                let Some(next_name) = next else {
                    break;
                };
                path.push(next_name.clone());
                if next_name == head {
                    break;
                }
                current = next_name;
            }
            // span: the head struct's declaration site.
            let span = self
                .symbols
                .structs
                .get(&head)
                .map(|s| s.span)
                .unwrap_or(Span::new(0, 0));
            self.errors
                .push(QalaError::RecursiveStructByValue { span, path });
        }
    }
}

/// collect the names of every "by value" struct reachable from a type, for the
/// recursive-struct-by-value detector. tuples and fixed arrays of nonzero size
/// pass their element type through unchanged; dynamic arrays, `Option`,
/// `Result`, function types, zero-sized fixed arrays, and primitives are all
/// "by reference" (or carry no struct names) and contribute nothing.
fn collect_by_value_targets(ty: &QalaType, out: &mut BTreeSet<String>) {
    match ty {
        QalaType::Named(Symbol(name)) => {
            out.insert(name.clone());
        }
        QalaType::Tuple(elems) => {
            for e in elems {
                collect_by_value_targets(e, out);
            }
        }
        QalaType::Array(inner, Some(n)) if *n > 0 => {
            collect_by_value_targets(inner, out);
        }
        // dynamic arrays, zero-size fixed arrays, function types, Option,
        // Result, FileHandle, primitives, Unknown -- none of these carry the
        // contained type by value at the struct-layout level.
        _ => {}
    }
}

/// Tarjan's strongly-connected-components algorithm, iterative form.
///
/// returns the list of SCCs in the order Tarjan emits them (reverse
/// topological -- leaves first). each SCC is a `Vec<String>` of node names.
/// the caller iterates the SCCs in the order returned; for cycle reporting
/// the per-SCC head is chosen as the lexicographically smallest name, so the
/// emit order is by Tarjan's discovery, not by name.
///
/// the adjacency lists are expected to be sorted (callers iterate them in
/// determined order). nodes is the universe in alphabetical order, so the
/// traversal is reproducible across runs.
fn tarjan_scc(nodes: &[String], adj: &HashMap<String, Vec<String>>) -> Vec<Vec<String>> {
    // node -> Tarjan index, lowlink, on-stack flag.
    let mut index_of: HashMap<String, u32> = HashMap::new();
    let mut lowlink: HashMap<String, u32> = HashMap::new();
    let mut on_stack: HashMap<String, bool> = HashMap::new();
    let mut stack: Vec<String> = Vec::new();
    let mut next_index: u32 = 0;
    let mut sccs: Vec<Vec<String>> = Vec::new();

    // iterative DFS: each Frame tracks where we are in the children list.
    struct Frame {
        node: String,
        next_child: usize,
    }

    for root in nodes {
        if index_of.contains_key(root) {
            continue;
        }
        // begin a DFS rooted at `root`.
        index_of.insert(root.clone(), next_index);
        lowlink.insert(root.clone(), next_index);
        next_index += 1;
        stack.push(root.clone());
        on_stack.insert(root.clone(), true);

        let mut call_stack: Vec<Frame> = vec![Frame {
            node: root.clone(),
            next_child: 0,
        }];

        while let Some(frame) = call_stack.last_mut() {
            let v = frame.node.clone();
            let empty: Vec<String> = Vec::new();
            let children = adj.get(&v).unwrap_or(&empty);
            if frame.next_child < children.len() {
                let w = children[frame.next_child].clone();
                frame.next_child += 1;
                if !index_of.contains_key(&w) {
                    // recurse into w.
                    index_of.insert(w.clone(), next_index);
                    lowlink.insert(w.clone(), next_index);
                    next_index += 1;
                    stack.push(w.clone());
                    on_stack.insert(w.clone(), true);
                    call_stack.push(Frame {
                        node: w,
                        next_child: 0,
                    });
                } else if *on_stack.get(&w).unwrap_or(&false) {
                    // back-edge: update v's lowlink.
                    let w_idx = *index_of.get(&w).unwrap_or(&0);
                    let v_low = *lowlink.get(&v).unwrap_or(&0);
                    lowlink.insert(v.clone(), v_low.min(w_idx));
                }
            } else {
                // finished v. if v is a root of an SCC, pop one.
                let v_idx = *index_of.get(&v).unwrap_or(&0);
                let v_low = *lowlink.get(&v).unwrap_or(&0);
                if v_low == v_idx {
                    let mut component: Vec<String> = Vec::new();
                    // Tarjan invariant: v must be on the stack when we
                    // find it is an SCC root. `while let` terminates
                    // naturally on an empty stack (invariant violation)
                    // rather than looping forever.
                    while let Some(w) = stack.pop() {
                        on_stack.insert(w.clone(), false);
                        let is_v = w == v;
                        component.push(w);
                        if is_v {
                            break;
                        }
                    }
                    sccs.push(component);
                }
                call_stack.pop();
                // propagate lowlink to the parent (the new top of call_stack).
                if let Some(parent_frame) = call_stack.last() {
                    let p = parent_frame.node.clone();
                    let p_low = *lowlink.get(&p).unwrap_or(&0);
                    let v_low = *lowlink.get(&v).unwrap_or(&0);
                    lowlink.insert(p, p_low.min(v_low));
                }
            }
        }
    }
    sccs
}

// ---- pass 2: bidirectional type checking -----------------------------------

impl<'src> Checker<'src> {
    /// translate an untyped item into a typed one, fully checking bodies.
    ///
    /// for an `Item::Fn`, this opens a fresh scope, binds each parameter as
    /// a `LocalInfo`, checks the body against the declared return type,
    /// closes the scope (firing any per-scope warnings), and constructs the
    /// `TypedFnDecl` with a placeholder effect that pass 3 finalises.
    /// for the data-only item kinds (struct / enum / interface), the typed
    /// shape is constructed directly from the resolved symbol-table entries.
    fn check_item(&mut self, item: &ast::Item) -> typed_ast::TypedItem {
        match item {
            ast::Item::Fn(d) => self.check_fn_decl(d),
            ast::Item::Struct(d) => typed_ast::TypedItem::Struct(typed_ast::TypedStructDecl {
                name: d.name.clone(),
                fields: d
                    .fields
                    .iter()
                    .map(|f| typed_ast::TypedField {
                        name: f.name.clone(),
                        ty: resolve_type_silent(&f.ty, &self.symbols),
                        span: f.span,
                    })
                    .collect(),
                span: d.span,
            }),
            ast::Item::Enum(d) => typed_ast::TypedItem::Enum(typed_ast::TypedEnumDecl {
                name: d.name.clone(),
                variants: d
                    .variants
                    .iter()
                    .map(|v| typed_ast::TypedVariant {
                        name: v.name.clone(),
                        fields: v
                            .fields
                            .iter()
                            .map(|t| resolve_type_silent(t, &self.symbols))
                            .collect(),
                        span: v.span,
                    })
                    .collect(),
                span: d.span,
            }),
            ast::Item::Interface(d) => {
                typed_ast::TypedItem::Interface(typed_ast::TypedInterfaceDecl {
                    name: d.name.clone(),
                    methods: d
                        .methods
                        .iter()
                        .map(|m| typed_ast::TypedMethodSig {
                            name: m.name.clone(),
                            params: m
                                .params
                                .iter()
                                .map(|p| typed_ast::TypedParam {
                                    is_self: p.is_self,
                                    name: p.name.clone(),
                                    ty: if p.is_self {
                                        QalaType::Unknown
                                    } else if let Some(t) = &p.ty {
                                        resolve_type_silent(t, &self.symbols)
                                    } else {
                                        QalaType::Unknown
                                    },
                                    default: None,
                                    span: p.span,
                                })
                                .collect(),
                            ret_ty: m
                                .ret_ty
                                .as_ref()
                                .map(|t| resolve_type_silent(t, &self.symbols))
                                .unwrap_or(QalaType::Void),
                            effect: m
                                .effect
                                .as_ref()
                                .map(effect_set_from_ast)
                                .unwrap_or(EffectSet::pure()),
                            span: m.span,
                        })
                        .collect(),
                    span: d.span,
                })
            }
        }
    }

    /// check whether a name names a stdlib resource-returning call. v1's
    /// allow-list is `open` only; conservative: false negatives are
    /// acceptable, false positives are not.
    fn is_resource_returning(name: &str) -> bool {
        matches!(name, "open")
    }

    /// extract the handle name closed by a defer's body. recognizes
    /// `close(name)` and `name.close()`. returns `None` for any other
    /// shape.
    fn extract_closed_handle(expr: &ast::Expr) -> Option<String> {
        match expr {
            ast::Expr::Call { callee, args, .. } => {
                if let ast::Expr::Ident { name, .. } = callee.as_ref()
                    && name == "close"
                    && args.len() == 1
                    && let ast::Expr::Ident { name: h, .. } = &args[0]
                {
                    return Some(h.clone());
                }
                None
            }
            ast::Expr::MethodCall {
                receiver,
                name,
                args,
                ..
            } => {
                if name == "close"
                    && args.is_empty()
                    && let ast::Expr::Ident { name: h, .. } = receiver.as_ref()
                {
                    return Some(h.clone());
                }
                None
            }
            _ => None,
        }
    }

    /// scan a block (and recursively, its nested blocks) for resource
    /// bindings without a matching `defer close`.
    fn check_unmatched_defer(&mut self, block: &ast::Block) {
        // collect bindings of the form `let h = open(...)` in this block's
        // stmts -- only at this level; nested blocks are handled by the
        // recursion below.
        let mut handle_bindings: Vec<(String, Span)> = Vec::new();
        for stmt in &block.stmts {
            if let ast::Stmt::Let {
                name, init, span, ..
            } = stmt
                && let ast::Expr::Call { callee, .. } = init
                && let ast::Expr::Ident { name: cname, .. } = callee.as_ref()
                && Self::is_resource_returning(cname)
            {
                handle_bindings.push((name.clone(), *span));
            }
        }
        // collect closed handle names from same-block defer statements.
        let mut closed: BTreeSet<String> = BTreeSet::new();
        for stmt in &block.stmts {
            if let ast::Stmt::Defer { expr, .. } = stmt
                && let Some(h) = Self::extract_closed_handle(expr)
            {
                closed.insert(h);
            }
        }
        // fire unmatched_defer for any handle binding with no matching close.
        for (name, span) in &handle_bindings {
            if !closed.contains(name) {
                let w = QalaWarning {
                    category: "unmatched_defer".to_string(),
                    message: format!(
                        "resource `{name}` is acquired without a matching `defer close`"
                    ),
                    span: *span,
                    note: None,
                };
                self.emit_warning(w);
            }
        }
        // recurse into nested blocks.
        for stmt in &block.stmts {
            self.check_unmatched_defer_stmt(stmt);
        }
        // also recurse into the trailing value's block, if it is one.
        if let Some(boxed) = &block.value
            && let ast::Expr::Block { block: inner, .. } = boxed.as_ref()
        {
            self.check_unmatched_defer(inner);
        }
    }

    /// recurse the defer-mismatch scan through one statement. for `if`,
    /// visits the then-block and the full else chain (including arbitrarily
    /// deep `else if` nesting) so every branch is checked.
    fn check_unmatched_defer_stmt(&mut self, stmt: &ast::Stmt) {
        match stmt {
            ast::Stmt::If {
                then_block,
                else_branch,
                ..
            } => {
                self.check_unmatched_defer(then_block);
                match else_branch {
                    Some(ast::ElseBranch::Block(b)) => self.check_unmatched_defer(b),
                    Some(ast::ElseBranch::If(boxed)) => {
                        // recurse into the nested if-stmt so else-if chains
                        // of any depth are all visited.
                        self.check_unmatched_defer_stmt(boxed);
                    }
                    None => {}
                }
            }
            ast::Stmt::While { body, .. } => self.check_unmatched_defer(body),
            ast::Stmt::For { body, .. } => self.check_unmatched_defer(body),
            _ => {}
        }
    }

    /// check a single fn declaration: open a scope, bind params, walk the
    /// body, close the scope, build the `TypedFnDecl`.
    fn check_fn_decl(&mut self, d: &ast::FnDecl) -> typed_ast::TypedItem {
        let ret_ty = d
            .ret_ty
            .as_ref()
            .map(|t| resolve_type_silent(t, &self.symbols))
            .unwrap_or(QalaType::Void);
        let annotated_effect = d.effect.as_ref().map(effect_set_from_ast);
        // typed-params: resolve each type and bind it as a LocalInfo with
        // is_param=true so the `unused_var` rule never fires on a param.
        let mut typed_params: Vec<typed_ast::TypedParam> = Vec::with_capacity(d.params.len());
        let mut param_locals: Vec<(String, LocalInfo)> = Vec::with_capacity(d.params.len());
        for p in &d.params {
            let ty = if p.is_self {
                match &d.type_name {
                    Some(t) => QalaType::Named(Symbol(t.clone())),
                    None => QalaType::Unknown,
                }
            } else if let Some(t) = &p.ty {
                resolve_type_silent(t, &self.symbols)
            } else {
                QalaType::Unknown
            };
            typed_params.push(typed_ast::TypedParam {
                is_self: p.is_self,
                name: p.name.clone(),
                ty: ty.clone(),
                default: None,
                span: p.span,
            });
            param_locals.push((
                p.name.clone(),
                LocalInfo {
                    ty,
                    span: p.span,
                    is_mut: false,
                    used: false,
                    is_param: true,
                },
            ));
        }
        // open the function-body scope, bind parameters.
        self.fn_ctx = Some(FnCtx {
            name: d.name.clone(),
            type_name: d.type_name.clone(),
            ret_ty: ret_ty.clone(),
            annotated_effect,
            body_intrinsic: EffectSet::pure(),
            called_fns: Vec::new(),
            callsites_to_check: Vec::new(),
        });
        let mut scope: HashMap<String, LocalInfo> = HashMap::new();
        for (name, info) in param_locals {
            scope.insert(name, info);
        }
        self.scopes.push(scope);

        // check the body against the declared return type.
        let body = self.check_block(&d.body, Some(&ret_ty));
        // unmatched_defer scan: walk the body looking for `let h = open(...)`
        // without a same-scope `defer close(h)`.
        self.check_unmatched_defer(&d.body);

        // missing-return check: a function declared to return a non-Void type
        // must produce a value (a trailing block expression or a return
        // statement on every path). v1's check is simple: if ret_ty != Void
        // and the body's trailing value is None AND the body does not end
        // with a Return statement, emit MissingReturn.
        if !ret_ty.types_match(&QalaType::Void) && body.value.is_none() {
            let ends_in_return = d
                .body
                .stmts
                .last()
                .map(|s| matches!(s, ast::Stmt::Return { .. }))
                .unwrap_or(false);
            // also accept an if-with-returns or a while-with-returns -- v1
            // does not do dataflow, so any non-Return tail with a Void
            // trailing value triggers the warning. picking up the trailing
            // brace as the span: the closing token is the body's span.end.
            if !ends_in_return {
                let span = Span::new(d.body.span.end().saturating_sub(1), 1);
                self.errors.push(QalaError::MissingReturn {
                    span,
                    fn_name: d.name.clone(),
                    expected: ret_ty.display(),
                });
            }
        }

        // pop the function scope; fire any unused_var warnings.
        if let Some(scope) = self.scopes.pop() {
            for (name, info) in scope {
                if !info.is_param && !info.used && !name.starts_with('_') {
                    let w = QalaWarning {
                        category: "unused_var".to_string(),
                        message: format!("unused variable `{name}`"),
                        span: info.span,
                        note: None,
                    };
                    self.emit_warning(w);
                }
            }
        }

        // pull the FnCtx; pass 3 will read body_intrinsic / called_fns /
        // callsites_to_check to settle effect inference.
        let ctx = self.fn_ctx.take();
        if let Some(ctx) = ctx {
            // record the per-fn body-effect record for pass 3.
            let key = FnKey {
                type_name: d.type_name.clone(),
                name: d.name.clone(),
            };
            self.body_records.insert(
                key,
                BodyEffectRecord {
                    intrinsic: ctx.body_intrinsic,
                    called: ctx.called_fns,
                    callsites_to_check: ctx.callsites_to_check,
                },
            );
        }

        typed_ast::TypedItem::Fn(typed_ast::TypedFnDecl {
            type_name: d.type_name.clone(),
            name: d.name.clone(),
            params: typed_params,
            ret_ty,
            effect: annotated_effect.unwrap_or(EffectSet::pure()),
            body,
            span: d.span,
        })
    }

    /// check a block: open a scope, walk each statement, then either check
    /// or infer the trailing value. fire unreachable-code warnings inside
    /// the loop; fire unused-var warnings when the scope is popped.
    fn check_block(
        &mut self,
        block: &ast::Block,
        expected: Option<&QalaType>,
    ) -> typed_ast::TypedBlock {
        // a top-level fn body's scope is already on the stack (with params);
        // for any nested block we push a fresh scope so name resolution and
        // unused_var fire correctly.
        let pushed_scope = !self.scopes.is_empty();
        if pushed_scope {
            self.scopes.push(HashMap::new());
        }
        let mut typed_stmts: Vec<typed_ast::TypedStmt> = Vec::with_capacity(block.stmts.len());
        let mut terminator: Option<Span> = None;
        let mut warned_unreachable = false;
        for stmt in &block.stmts {
            if terminator.is_some() && !warned_unreachable {
                let w = QalaWarning {
                    category: "unreachable_code".to_string(),
                    message: "unreachable statement after `return`, `break`, or `continue`"
                        .to_string(),
                    span: stmt.span(),
                    note: None,
                };
                self.emit_warning(w);
                warned_unreachable = true;
                // still walk the stmt so types resolve; the warning fires
                // exactly once per block.
            }
            let typed_stmt = self.check_stmt(stmt);
            let is_terminator = matches!(
                stmt,
                ast::Stmt::Return { .. } | ast::Stmt::Break { .. } | ast::Stmt::Continue { .. }
            );
            if is_terminator && terminator.is_none() {
                terminator = Some(stmt.span());
            }
            typed_stmts.push(typed_stmt);
        }
        let (typed_value, value_ty) = match &block.value {
            Some(v) => {
                let typed = match expected {
                    Some(ty) => self.check_expr(v, ty),
                    None => self.infer_expr(v),
                };
                let ty = typed.ty().clone();
                (Some(Box::new(typed)), ty)
            }
            None => (None, QalaType::Void),
        };
        // pop the nested scope, fire unused_var.
        if pushed_scope && let Some(scope) = self.scopes.pop() {
            for (name, info) in scope {
                if !info.is_param && !info.used && !name.starts_with('_') {
                    let w = QalaWarning {
                        category: "unused_var".to_string(),
                        message: format!("unused variable `{name}`"),
                        span: info.span,
                        note: None,
                    };
                    self.emit_warning(w);
                }
            }
        }
        typed_ast::TypedBlock {
            stmts: typed_stmts,
            value: typed_value,
            ty: value_ty,
            span: block.span,
        }
    }

    /// check a single statement.
    fn check_stmt(&mut self, stmt: &ast::Stmt) -> typed_ast::TypedStmt {
        match stmt {
            ast::Stmt::Let {
                is_mut,
                name,
                ty,
                init,
                span,
            } => {
                let (typed_init, decl_ty) = match ty {
                    Some(t) => {
                        let expected = resolve_type_silent(t, &self.symbols);
                        let typed_init = self.check_expr(init, &expected);
                        // redundant_annotation: fire iff the inferred type
                        // strictly equals the declared type (not via the
                        // Unknown wildcard, which would let typos slip).
                        if types_strictly_equal(typed_init.ty(), &expected) {
                            let w = QalaWarning {
                                category: "redundant_annotation".to_string(),
                                message: format!(
                                    "redundant type annotation: `{}` matches the inferred type",
                                    expected.display()
                                ),
                                span: t.span(),
                                note: None,
                            };
                            self.emit_warning(w);
                        }
                        // structural-interface check: when the declared type
                        // is an interface and the initializer types to a
                        // named-struct, ensure the struct satisfies the
                        // interface.
                        if let QalaType::Named(Symbol(iname)) = &expected
                            && self.symbols.interfaces.contains_key(iname)
                            && let QalaType::Named(Symbol(_)) = typed_init.ty()
                        {
                            let init_ty = typed_init.ty().clone();
                            self.check_satisfies(&init_ty, iname, *span);
                        }
                        (typed_init, expected)
                    }
                    None => {
                        let typed_init = self.infer_expr(init);
                        let ty = typed_init.ty().clone();
                        (typed_init, ty)
                    }
                };
                // shadowed_var: if any outer scope (not the topmost) has a
                // binding with the same name, warn.
                let topmost = self.scopes.len().saturating_sub(1);
                let mut prior_span: Option<Span> = None;
                for (idx, scope) in self.scopes.iter().enumerate() {
                    if idx == topmost {
                        break;
                    }
                    if let Some(prior) = scope.get(name) {
                        prior_span = Some(prior.span);
                        break;
                    }
                }
                if let Some(prior) = prior_span {
                    let (l, c) = self.line_index.location(self.src, prior.start as usize);
                    let w = QalaWarning {
                        category: "shadowed_var".to_string(),
                        message: format!("`{name}` shadows a binding from an outer scope"),
                        span: *span,
                        note: Some(format!("the prior binding is at line {l}:{c}")),
                    };
                    self.emit_warning(w);
                }
                // bind in the topmost scope.
                if let Some(scope) = self.scopes.last_mut() {
                    scope.insert(
                        name.clone(),
                        LocalInfo {
                            ty: decl_ty.clone(),
                            span: *span,
                            is_mut: *is_mut,
                            used: false,
                            is_param: false,
                        },
                    );
                }
                typed_ast::TypedStmt::Let {
                    is_mut: *is_mut,
                    name: name.clone(),
                    ty: decl_ty,
                    init: typed_init,
                    span: *span,
                }
            }
            ast::Stmt::If {
                cond,
                then_block,
                else_branch,
                span,
            } => {
                let typed_cond = self.check_expr(cond, &QalaType::Bool);
                let typed_then = self.check_block(then_block, None);
                let typed_else = match else_branch {
                    Some(ast::ElseBranch::Block(b)) => {
                        Some(typed_ast::TypedElseBranch::Block(self.check_block(b, None)))
                    }
                    Some(ast::ElseBranch::If(b)) => {
                        let inner = self.check_stmt(b);
                        Some(typed_ast::TypedElseBranch::If(Box::new(inner)))
                    }
                    None => None,
                };
                typed_ast::TypedStmt::If {
                    cond: typed_cond,
                    then_block: typed_then,
                    else_branch: typed_else,
                    span: *span,
                }
            }
            ast::Stmt::While { cond, body, span } => {
                let typed_cond = self.check_expr(cond, &QalaType::Bool);
                let typed_body = self.check_block(body, None);
                typed_ast::TypedStmt::While {
                    cond: typed_cond,
                    body: typed_body,
                    span: *span,
                }
            }
            ast::Stmt::For {
                var,
                iter,
                body,
                span,
            } => {
                let typed_iter = self.infer_expr(iter);
                // element type: an Array's elem, or i64 for a Range
                // (Range expressions resolve their ty to Array(elem=I64, None)
                // per the convention chosen below in infer_expr).
                let var_ty = match typed_iter.ty() {
                    QalaType::Array(elem, _) => (**elem).clone(),
                    QalaType::Unknown => QalaType::Unknown,
                    _ => {
                        self.errors.push(QalaError::Type {
                            span: iter.span(),
                            message: "for loop expects an array or range".to_string(),
                        });
                        QalaType::Unknown
                    }
                };
                // open a one-binding scope holding the loop variable.
                let mut scope: HashMap<String, LocalInfo> = HashMap::new();
                scope.insert(
                    var.clone(),
                    LocalInfo {
                        ty: var_ty.clone(),
                        span: *span,
                        is_mut: false,
                        // the loop variable is treated like a parameter
                        // (open question 4 style) -- never fires unused_var.
                        used: false,
                        is_param: true,
                    },
                );
                self.scopes.push(scope);
                let typed_body = self.check_block(body, None);
                self.scopes.pop();
                typed_ast::TypedStmt::For {
                    var: var.clone(),
                    var_ty,
                    iter: typed_iter,
                    body: typed_body,
                    span: *span,
                }
            }
            ast::Stmt::Return { value, span } => {
                let typed_value = match value {
                    Some(v) => {
                        let expected = self.fn_ctx.as_ref().map(|c| c.ret_ty.clone());
                        let typed = match expected {
                            Some(ty) => self.check_expr(v, &ty),
                            None => self.infer_expr(v),
                        };
                        Some(typed)
                    }
                    None => {
                        // bare `return` is legal iff ret_ty is Void.
                        if let Some(ctx) = &self.fn_ctx
                            && !ctx.ret_ty.types_match(&QalaType::Void)
                        {
                            self.errors.push(QalaError::TypeMismatch {
                                span: *span,
                                expected: ctx.ret_ty.display(),
                                found: "void".to_string(),
                            });
                        }
                        None
                    }
                };
                typed_ast::TypedStmt::Return {
                    value: typed_value,
                    span: *span,
                }
            }
            ast::Stmt::Break { span } => typed_ast::TypedStmt::Break { span: *span },
            ast::Stmt::Continue { span } => typed_ast::TypedStmt::Continue { span: *span },
            ast::Stmt::Defer { expr, span } => {
                let typed_expr = self.infer_expr(expr);
                typed_ast::TypedStmt::Defer {
                    expr: typed_expr,
                    span: *span,
                }
            }
            ast::Stmt::Expr { expr, span } => {
                let typed_expr = self.infer_expr(expr);
                typed_ast::TypedStmt::Expr {
                    expr: typed_expr,
                    span: *span,
                }
            }
        }
    }

    /// look a name up in the active scope chain (top -> outer); on a hit,
    /// mark the LocalInfo as used and return its type. on a miss in scopes,
    /// fall back to the user fn table; on a miss there, fall back to the
    /// stdlib signatures table. returns `None` if nothing matched.
    fn lookup(&mut self, name: &str) -> Option<QalaType> {
        for scope in self.scopes.iter_mut().rev() {
            if let Some(info) = scope.get_mut(name) {
                info.used = true;
                return Some(info.ty.clone());
            }
        }
        // user-defined free function?
        let key = FnKey {
            type_name: None,
            name: name.to_string(),
        };
        if let Some(info) = self.symbols.fns.get(&key) {
            let params: Vec<QalaType> = info.params.iter().map(|(_, ty, _)| ty.clone()).collect();
            return Some(QalaType::Function {
                params,
                returns: Box::new(info.ret_ty.clone()),
            });
        }
        // stdlib?
        let stdlib = stdlib_signatures();
        if let Some(entry) = stdlib
            .iter()
            .find(|e| e.type_name.is_none() && e.name == name)
        {
            return Some(QalaType::Function {
                params: entry.params.clone(),
                returns: Box::new(entry.ret_ty.clone()),
            });
        }
        None
    }

    /// infer the type of an expression, producing a typed node.
    ///
    /// every variant of `ast::Expr` is dispatched; type errors emit a
    /// `QalaError` and the result carries `QalaType::Unknown` so subsequent
    /// `types_match` calls don't cascade. recursion is capped at
    /// [`MAX_DEPTH`] -- past the cap, a `QalaError::Type` is emitted and a
    /// poison-typed `Int` placeholder returned so the walk unwinds cleanly.
    fn infer_expr(&mut self, expr: &ast::Expr) -> typed_ast::TypedExpr {
        self.depth = self.depth.saturating_add(1);
        if self.depth > MAX_DEPTH {
            self.errors.push(QalaError::Type {
                span: expr.span(),
                message: "expression nests too deeply".to_string(),
            });
            self.depth = self.depth.saturating_sub(1);
            return typed_ast::TypedExpr::Int {
                value: 0,
                ty: QalaType::Unknown,
                span: expr.span(),
            };
        }
        let out = self.infer_expr_inner(expr);
        self.depth = self.depth.saturating_sub(1);
        out
    }

    /// the body of [`Self::infer_expr`]; split so the depth guard is exactly
    /// once at the top.
    fn infer_expr_inner(&mut self, expr: &ast::Expr) -> typed_ast::TypedExpr {
        match expr {
            ast::Expr::Int { value, span } => typed_ast::TypedExpr::Int {
                value: *value,
                ty: QalaType::I64,
                span: *span,
            },
            ast::Expr::Float { value, span } => typed_ast::TypedExpr::Float {
                value: *value,
                ty: QalaType::F64,
                span: *span,
            },
            ast::Expr::Byte { value, span } => typed_ast::TypedExpr::Byte {
                value: *value,
                ty: QalaType::Byte,
                span: *span,
            },
            ast::Expr::Str { value, span } => typed_ast::TypedExpr::Str {
                value: value.clone(),
                ty: QalaType::Str,
                span: *span,
            },
            ast::Expr::Bool { value, span } => typed_ast::TypedExpr::Bool {
                value: *value,
                ty: QalaType::Bool,
                span: *span,
            },
            ast::Expr::Ident { name, span } => {
                // Some/None/Ok/Err names that appear bare (no call) are
                // also legal -- they look like idents to the parser. handle
                // None/Triangle-like constructors specially: lookup misses
                // are an UndefinedName unless the name is a known
                // zero-arg constructor.
                if let Some(ty) = self.lookup(name) {
                    return typed_ast::TypedExpr::Ident {
                        name: name.clone(),
                        ty,
                        span: *span,
                    };
                }
                // is this a zero-data enum variant from any known enum?
                let mut variant_match: Option<String> = None;
                for (enum_name, info) in &self.symbols.enums {
                    if info
                        .variants
                        .iter()
                        .any(|(vn, fields)| vn == name && fields.is_empty())
                    {
                        variant_match = Some(enum_name.clone());
                        break;
                    }
                }
                if let Some(enum_name) = variant_match {
                    return typed_ast::TypedExpr::Ident {
                        name: name.clone(),
                        ty: QalaType::Named(Symbol(enum_name)),
                        span: *span,
                    };
                }
                self.errors.push(QalaError::UndefinedName {
                    span: *span,
                    name: name.clone(),
                });
                typed_ast::TypedExpr::Ident {
                    name: name.clone(),
                    ty: QalaType::Unknown,
                    span: *span,
                }
            }
            ast::Expr::Paren { inner, span } => {
                let typed_inner = self.infer_expr(inner);
                let ty = typed_inner.ty().clone();
                typed_ast::TypedExpr::Paren {
                    inner: Box::new(typed_inner),
                    ty,
                    span: *span,
                }
            }
            ast::Expr::Tuple { elems, span } => {
                let typed_elems: Vec<typed_ast::TypedExpr> =
                    elems.iter().map(|e| self.infer_expr(e)).collect();
                let ty = QalaType::Tuple(typed_elems.iter().map(|e| e.ty().clone()).collect());
                typed_ast::TypedExpr::Tuple {
                    elems: typed_elems,
                    ty,
                    span: *span,
                }
            }
            ast::Expr::ArrayLit { elems, span } => {
                if elems.is_empty() {
                    self.errors.push(QalaError::Type {
                        span: *span,
                        message: "cannot infer element type of empty array".to_string(),
                    });
                    return typed_ast::TypedExpr::ArrayLit {
                        elems: Vec::new(),
                        ty: QalaType::Array(Box::new(QalaType::Unknown), Some(0)),
                        span: *span,
                    };
                }
                let first = self.infer_expr(&elems[0]);
                let elem_ty = first.ty().clone();
                let mut typed_elems = vec![first];
                for e in &elems[1..] {
                    let typed = self.check_expr(e, &elem_ty);
                    typed_elems.push(typed);
                }
                let len = typed_elems.len();
                typed_ast::TypedExpr::ArrayLit {
                    elems: typed_elems,
                    ty: QalaType::Array(Box::new(elem_ty), Some(len)),
                    span: *span,
                }
            }
            ast::Expr::ArrayRepeat { value, count, span } => {
                let typed_value = self.infer_expr(value);
                let typed_count = self.check_expr(count, &QalaType::I64);
                let elem_ty = typed_value.ty().clone();
                typed_ast::TypedExpr::ArrayRepeat {
                    value: Box::new(typed_value),
                    count: Box::new(typed_count),
                    ty: QalaType::Array(Box::new(elem_ty), None),
                    span: *span,
                }
            }
            ast::Expr::StructLit { name, fields, span } => {
                // check_struct_lit handles the field-set comparison.
                self.check_struct_lit(name, fields, *span)
            }
            ast::Expr::FieldAccess { obj, name, span } => {
                let typed_obj = self.infer_expr(obj);
                let obj_ty = typed_obj.ty().clone();
                let field_ty = match &obj_ty {
                    QalaType::Named(Symbol(s)) => {
                        if let Some(info) = self.symbols.structs.get(s) {
                            match info.fields.iter().find(|(fn_, _)| fn_ == name) {
                                Some((_, t)) => t.clone(),
                                None => {
                                    self.errors.push(QalaError::Type {
                                        span: *span,
                                        message: format!(
                                            "no field `{name}` on type `{}`",
                                            obj_ty.display()
                                        ),
                                    });
                                    QalaType::Unknown
                                }
                            }
                        } else {
                            self.errors.push(QalaError::Type {
                                span: *span,
                                message: format!(
                                    "no field `{name}` on type `{}`",
                                    obj_ty.display()
                                ),
                            });
                            QalaType::Unknown
                        }
                    }
                    QalaType::Unknown => QalaType::Unknown,
                    _ => {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: format!("no field `{name}` on type `{}`", obj_ty.display()),
                        });
                        QalaType::Unknown
                    }
                };
                typed_ast::TypedExpr::FieldAccess {
                    obj: Box::new(typed_obj),
                    name: name.clone(),
                    ty: field_ty,
                    span: *span,
                }
            }
            ast::Expr::MethodCall {
                receiver,
                name,
                args,
                span,
            } => self.check_method_call(receiver, name, args, *span),
            ast::Expr::Call { callee, args, span } => self.check_call(callee, args, *span),
            ast::Expr::Index { obj, index, span } => {
                let typed_obj = self.infer_expr(obj);
                let typed_index = self.check_expr(index, &QalaType::I64);
                let elem_ty = match typed_obj.ty() {
                    QalaType::Array(elem, _) => (**elem).clone(),
                    QalaType::Unknown => QalaType::Unknown,
                    other => {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: format!("cannot index `{}`", other.display()),
                        });
                        QalaType::Unknown
                    }
                };
                typed_ast::TypedExpr::Index {
                    obj: Box::new(typed_obj),
                    index: Box::new(typed_index),
                    ty: elem_ty,
                    span: *span,
                }
            }
            ast::Expr::Try { expr: inner, span } => {
                let typed_inner = self.infer_expr(inner);
                let (success_ty, ok_for_fn) = match typed_inner.ty() {
                    QalaType::Result(ok, _) => ((**ok).clone(), true),
                    QalaType::Option(t) => ((**t).clone(), true),
                    QalaType::Unknown => (QalaType::Unknown, true),
                    _ => {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: format!(
                                "`?` operand must be Result or Option, found `{}`",
                                typed_inner.ty().display()
                            ),
                        });
                        (QalaType::Unknown, false)
                    }
                };
                // also require the enclosing function's ret_ty to be a
                // Result/Option. emit one error per the locked policy.
                if ok_for_fn && let Some(ctx) = &self.fn_ctx {
                    let ok = matches!(
                        &ctx.ret_ty,
                        QalaType::Result(_, _) | QalaType::Option(_) | QalaType::Unknown
                    );
                    if !ok {
                        self.errors.push(QalaError::RedundantQuestionOperator {
                            span: *span,
                            message: format!(
                                "`?` outside a Result-returning or Option-returning function (return type is `{}`); change the return type to `Result<_, _>` or `Option<_>`",
                                ctx.ret_ty.display()
                            ),
                        });
                    }
                }
                typed_ast::TypedExpr::Try {
                    expr: Box::new(typed_inner),
                    ty: success_ty,
                    span: *span,
                }
            }
            ast::Expr::Unary { op, operand, span } => {
                use ast::UnaryOp;
                let typed_operand = self.infer_expr(operand);
                let op_ty = typed_operand.ty().clone();
                let ty = match op {
                    UnaryOp::Not => {
                        if !op_ty.types_match(&QalaType::Bool) {
                            self.errors.push(QalaError::TypeMismatch {
                                span: operand.span(),
                                expected: "bool".to_string(),
                                found: op_ty.display(),
                            });
                        }
                        QalaType::Bool
                    }
                    UnaryOp::Neg => {
                        if op_ty.types_match(&QalaType::I64) {
                            QalaType::I64
                        } else if op_ty.types_match(&QalaType::F64) {
                            QalaType::F64
                        } else if matches!(op_ty, QalaType::Unknown) {
                            QalaType::Unknown
                        } else {
                            self.errors.push(QalaError::TypeMismatch {
                                span: operand.span(),
                                expected: "i64 or f64".to_string(),
                                found: op_ty.display(),
                            });
                            QalaType::Unknown
                        }
                    }
                };
                typed_ast::TypedExpr::Unary {
                    op: op.clone(),
                    operand: Box::new(typed_operand),
                    ty,
                    span: *span,
                }
            }
            ast::Expr::Binary { op, lhs, rhs, span } => self.check_binary(op, lhs, rhs, *span),
            ast::Expr::Range {
                start,
                end,
                inclusive,
                span,
            } => {
                let typed_start = start.as_ref().map(|e| self.check_expr(e, &QalaType::I64));
                let typed_end = end.as_ref().map(|e| self.check_expr(e, &QalaType::I64));
                // ranges iterate as `[i64]` so for-loops bind the element to i64.
                typed_ast::TypedExpr::Range {
                    start: typed_start.map(Box::new),
                    end: typed_end.map(Box::new),
                    inclusive: *inclusive,
                    ty: QalaType::Array(Box::new(QalaType::I64), None),
                    span: *span,
                }
            }
            ast::Expr::Pipeline { lhs, call, span } => {
                // type as if the lhs were prepended to the call's arg list.
                // implementation: infer lhs, then build a virtual call AST
                // node and recurse. but we want to keep the typed Pipeline
                // node faithful, so we manually re-implement the lookup.
                let typed_lhs = self.infer_expr(lhs);
                let lhs_ty = typed_lhs.ty().clone();
                // resolve the call target: either Call{callee: Ident, args}
                // or Ident (zero-extra-args).
                let (typed_call, result_ty) = self.check_pipeline_call(call, &lhs_ty);
                typed_ast::TypedExpr::Pipeline {
                    lhs: Box::new(typed_lhs),
                    call: Box::new(typed_call),
                    ty: result_ty,
                    span: *span,
                }
            }
            ast::Expr::Comptime { body, span } => {
                let typed_body = self.infer_expr(body);
                let ty = typed_body.ty().clone();
                typed_ast::TypedExpr::Comptime {
                    body: Box::new(typed_body),
                    ty,
                    span: *span,
                }
            }
            ast::Expr::Block { block, span } => {
                let typed_block = self.check_block(block, None);
                let ty = typed_block.ty.clone();
                typed_ast::TypedExpr::Block {
                    block: typed_block,
                    ty,
                    span: *span,
                }
            }
            ast::Expr::Match {
                scrutinee,
                arms,
                span,
            } => self.check_match(scrutinee, arms, *span),
            ast::Expr::OrElse {
                expr: e,
                fallback,
                span,
            } => {
                let typed_e = self.infer_expr(e);
                let success_ty = match typed_e.ty() {
                    QalaType::Result(ok, _) => (**ok).clone(),
                    QalaType::Option(t) => (**t).clone(),
                    QalaType::Unknown => QalaType::Unknown,
                    other => {
                        self.errors.push(QalaError::Type {
                            span: e.span(),
                            message: format!(
                                "`or` left operand must be Result or Option, found `{}`",
                                other.display()
                            ),
                        });
                        QalaType::Unknown
                    }
                };
                let typed_fallback = self.check_expr(fallback, &success_ty);
                typed_ast::TypedExpr::OrElse {
                    expr: Box::new(typed_e),
                    fallback: Box::new(typed_fallback),
                    ty: success_ty,
                    span: *span,
                }
            }
            ast::Expr::Interpolation { parts, span } => {
                let typed_parts: Vec<typed_ast::TypedInterpPart> = parts
                    .iter()
                    .map(|p| match p {
                        ast::InterpPart::Literal(s) => {
                            typed_ast::TypedInterpPart::Literal(s.clone())
                        }
                        ast::InterpPart::Expr(e) => {
                            typed_ast::TypedInterpPart::Expr(self.infer_expr(e))
                        }
                    })
                    .collect();
                typed_ast::TypedExpr::Interpolation {
                    parts: typed_parts,
                    ty: QalaType::Str,
                    span: *span,
                }
            }
        }
    }

    /// check an expression against an expected type, emitting `TypeMismatch`
    /// when they disagree. unknown-poison is a wildcard, so a chain of
    /// expressions after the first error does not cascade.
    fn check_expr(&mut self, expr: &ast::Expr, expected: &QalaType) -> typed_ast::TypedExpr {
        let typed = self.infer_expr(expr);
        if !typed.ty().types_match(expected) {
            self.errors.push(QalaError::TypeMismatch {
                span: typed.span(),
                expected: expected.display(),
                found: typed.ty().display(),
            });
        }
        typed
    }

    /// type-check a struct literal: look up the struct, check declared and
    /// provided field sets match (missing fields named in one error, excess
    /// fields named individually), check each provided value against the
    /// declared field type.
    fn check_struct_lit(
        &mut self,
        name: &str,
        fields: &[ast::FieldInit],
        span: Span,
    ) -> typed_ast::TypedExpr {
        // capture declared fields as (name, type) so we can iterate without
        // re-borrowing self.
        let declared: Option<Vec<(String, QalaType)>> =
            self.symbols.structs.get(name).map(|s| s.fields.clone());
        let Some(declared) = declared else {
            self.errors.push(QalaError::UndefinedName {
                span,
                name: name.to_string(),
            });
            return typed_ast::TypedExpr::StructLit {
                name: name.to_string(),
                fields: Vec::new(),
                ty: QalaType::Unknown,
                span,
            };
        };
        let mut typed_fields: Vec<typed_ast::TypedFieldInit> = Vec::new();
        // missing-field detection.
        let provided_names: BTreeSet<String> = fields.iter().map(|f| f.name.clone()).collect();
        let missing: Vec<String> = declared
            .iter()
            .filter(|(dn, _)| !provided_names.contains(dn))
            .map(|(dn, _)| dn.clone())
            .collect();
        if !missing.is_empty() {
            self.errors.push(QalaError::Type {
                span,
                message: format!(
                    "missing field(s) in struct literal `{name}`: {}",
                    missing.join(", ")
                ),
            });
        }
        for fi in fields {
            let decl_ty: Option<QalaType> = declared
                .iter()
                .find(|(dn, _)| dn == &fi.name)
                .map(|(_, t)| t.clone());
            match decl_ty {
                Some(t) => {
                    let typed_value = self.check_expr(&fi.value, &t);
                    typed_fields.push(typed_ast::TypedFieldInit {
                        name: fi.name.clone(),
                        value: typed_value,
                        span: fi.span,
                    });
                }
                None => {
                    self.errors.push(QalaError::Type {
                        span: fi.span,
                        message: format!("no field `{}` on struct `{name}`", fi.name),
                    });
                    // still type the value so cascading errors don't fire.
                    let typed_value = self.infer_expr(&fi.value);
                    typed_fields.push(typed_ast::TypedFieldInit {
                        name: fi.name.clone(),
                        value: typed_value,
                        span: fi.span,
                    });
                }
            }
        }
        typed_ast::TypedExpr::StructLit {
            name: name.to_string(),
            fields: typed_fields,
            ty: QalaType::Named(Symbol(name.to_string())),
            span,
        }
    }

    /// type-check a method call. resolves the method via the symbol table's
    /// `FnKey { type_name: Some(receiver_type_name), name }` first, then
    /// falls back to the stdlib table (e.g. `FileHandle.read_all`).
    fn check_method_call(
        &mut self,
        receiver: &ast::Expr,
        name: &str,
        args: &[ast::Expr],
        span: Span,
    ) -> typed_ast::TypedExpr {
        let typed_receiver = self.infer_expr(receiver);
        let receiver_ty = typed_receiver.ty().clone();
        // resolve method signature: user method via FnKey, else stdlib.
        let resolved: Option<(Vec<QalaType>, QalaType, FnKey)> = (|| {
            // user fn T.method
            let type_name = match &receiver_ty {
                QalaType::Named(Symbol(s)) => Some(s.clone()),
                QalaType::FileHandle => Some("FileHandle".to_string()),
                _ => None,
            };
            if let Some(tn) = type_name {
                let key = FnKey {
                    type_name: Some(tn.clone()),
                    name: name.to_string(),
                };
                if let Some(info) = self.symbols.fns.get(&key) {
                    // params after self.
                    let params: Vec<QalaType> = info
                        .params
                        .iter()
                        .skip(
                            if info
                                .params
                                .first()
                                .map(|(n, _, _)| n == "self")
                                .unwrap_or(false)
                            {
                                1
                            } else {
                                0
                            },
                        )
                        .map(|(_, t, _)| t.clone())
                        .collect();
                    return Some((params, info.ret_ty.clone(), key));
                }
                // stdlib?
                for entry in stdlib_signatures().iter() {
                    if entry.type_name.as_deref() == Some(tn.as_str()) && entry.name == name {
                        let params: Vec<QalaType> = entry.params.clone();
                        return Some((
                            params,
                            entry.ret_ty.clone(),
                            FnKey {
                                type_name: Some(tn.clone()),
                                name: name.to_string(),
                            },
                        ));
                    }
                }
            }
            None
        })();
        let (params, ret_ty) = match resolved {
            Some((p, r, key)) => {
                // record for pass 3's effect resolution.
                if let Some(ctx) = &mut self.fn_ctx {
                    ctx.called_fns.push(key.clone());
                    if ctx.annotated_effect.is_some() {
                        ctx.callsites_to_check.push(EffectViolationCandidate {
                            caller_key: FnKey {
                                type_name: ctx.type_name.clone(),
                                name: ctx.name.clone(),
                            },
                            callee_key: key,
                            call_span: span,
                        });
                    }
                }
                (p, r)
            }
            None => {
                if !matches!(receiver_ty, QalaType::Unknown) {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!("no method `{name}` on type `{}`", receiver_ty.display()),
                    });
                }
                (Vec::new(), QalaType::Unknown)
            }
        };
        let typed_args: Vec<typed_ast::TypedExpr> = if params.is_empty() && args.is_empty() {
            Vec::new()
        } else {
            args.iter()
                .enumerate()
                .map(|(i, a)| {
                    if i < params.len() {
                        self.check_expr(a, &params[i])
                    } else {
                        self.infer_expr(a)
                    }
                })
                .collect()
        };
        if args.len() != params.len()
            && !matches!(receiver_ty, QalaType::Unknown)
            && !ret_ty.types_match(&QalaType::Unknown)
        {
            // arity mismatch -- emit a generic Type error.
            self.errors.push(QalaError::Type {
                span,
                message: format!(
                    "method `{name}` expects {} argument(s), found {}",
                    params.len(),
                    args.len()
                ),
            });
        }
        typed_ast::TypedExpr::MethodCall {
            receiver: Box::new(typed_receiver),
            name: name.to_string(),
            args: typed_args,
            ty: ret_ty,
            span,
        }
    }

    /// type-check a plain call expression `callee(args)`. handles built-in
    /// constructors `Ok`/`Err`/`Some`/`None`, user-defined free functions,
    /// stdlib free functions (including the generic ones), and identifier
    /// callees in general.
    fn check_call(
        &mut self,
        callee: &ast::Expr,
        args: &[ast::Expr],
        span: Span,
    ) -> typed_ast::TypedExpr {
        // special-case the built-in constructor names appearing in callee
        // position as a bare ident.
        if let ast::Expr::Ident { name, .. } = callee {
            if let Some(ctor_ty) = self.try_builtin_constructor(name, args, span) {
                let typed_callee = typed_ast::TypedExpr::Ident {
                    name: name.clone(),
                    ty: QalaType::Function {
                        params: Vec::new(),
                        returns: Box::new(ctor_ty.0.clone()),
                    },
                    span: callee.span(),
                };
                return typed_ast::TypedExpr::Call {
                    callee: Box::new(typed_callee),
                    args: ctor_ty.1,
                    ty: ctor_ty.0,
                    span,
                };
            }
            // enum variant constructor: `Circle(5.0)` where `Circle` is a
            // variant of some enum.
            if let Some((enum_name, fields)) = self.find_enum_variant(name) {
                let typed_args: Vec<typed_ast::TypedExpr> = args
                    .iter()
                    .enumerate()
                    .map(|(i, a)| {
                        if i < fields.len() {
                            self.check_expr(a, &fields[i])
                        } else {
                            self.infer_expr(a)
                        }
                    })
                    .collect();
                if args.len() != fields.len() {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!(
                            "variant `{name}` of `{enum_name}` expects {} argument(s), found {}",
                            fields.len(),
                            args.len()
                        ),
                    });
                }
                let typed_callee = typed_ast::TypedExpr::Ident {
                    name: name.clone(),
                    ty: QalaType::Function {
                        params: fields.clone(),
                        returns: Box::new(QalaType::Named(Symbol(enum_name.clone()))),
                    },
                    span: callee.span(),
                };
                return typed_ast::TypedExpr::Call {
                    callee: Box::new(typed_callee),
                    args: typed_args,
                    ty: QalaType::Named(Symbol(enum_name)),
                    span,
                };
            }
            // user-defined free fn, or stdlib free fn (incl. virtual generics).
            if let Some((params, ret_ty, is_generic, name_clone, callee_key)) =
                self.resolve_free_callable(name)
            {
                // record for pass 3.
                if let Some(ctx) = &mut self.fn_ctx {
                    ctx.called_fns.push(callee_key.clone());
                    if ctx.annotated_effect.is_some() {
                        ctx.callsites_to_check.push(EffectViolationCandidate {
                            caller_key: FnKey {
                                type_name: ctx.type_name.clone(),
                                name: ctx.name.clone(),
                            },
                            callee_key,
                            call_span: span,
                        });
                    }
                }
                let typed_callee = typed_ast::TypedExpr::Ident {
                    name: name_clone.clone(),
                    ty: QalaType::Function {
                        params: params.clone(),
                        returns: Box::new(ret_ty.clone()),
                    },
                    span: callee.span(),
                };
                let typed_args = self.check_call_args(args, &params, is_generic, &name_clone, span);
                // abs only accepts i64 or f64; the generic param placeholder lets
                // non-numeric types through check_call_args, so we guard here.
                if name_clone == "abs"
                    && let Some(arg0) = typed_args.first()
                {
                    let arg_ty = arg0.ty();
                    if !matches!(arg_ty, QalaType::I64 | QalaType::F64 | QalaType::Unknown) {
                        self.errors.push(QalaError::TypeMismatch {
                            span,
                            expected: "i64 or f64".to_string(),
                            found: arg_ty.display(),
                        });
                    }
                }
                let result_ty = self.resolve_generic_return_ty(&name_clone, &ret_ty, &typed_args);
                return typed_ast::TypedExpr::Call {
                    callee: Box::new(typed_callee),
                    args: typed_args,
                    ty: result_ty,
                    span,
                };
            }
            // unresolved free name in callee position.
            self.errors.push(QalaError::UndefinedName {
                span: callee.span(),
                name: name.clone(),
            });
            let typed_callee = typed_ast::TypedExpr::Ident {
                name: name.clone(),
                ty: QalaType::Unknown,
                span: callee.span(),
            };
            let typed_args: Vec<typed_ast::TypedExpr> =
                args.iter().map(|a| self.infer_expr(a)).collect();
            return typed_ast::TypedExpr::Call {
                callee: Box::new(typed_callee),
                args: typed_args,
                ty: QalaType::Unknown,
                span,
            };
        }
        // non-identifier callee (rare in v1): infer it and treat its type as
        // a function shape.
        let typed_callee = self.infer_expr(callee);
        let (params, ret_ty) = match typed_callee.ty() {
            QalaType::Function { params, returns } => (params.clone(), (**returns).clone()),
            _ => {
                self.errors.push(QalaError::Type {
                    span,
                    message: format!(
                        "cannot call value of type `{}`",
                        typed_callee.ty().display()
                    ),
                });
                (Vec::new(), QalaType::Unknown)
            }
        };
        let typed_args: Vec<typed_ast::TypedExpr> = args
            .iter()
            .enumerate()
            .map(|(i, a)| {
                if i < params.len() {
                    self.check_expr(a, &params[i])
                } else {
                    self.infer_expr(a)
                }
            })
            .collect();
        typed_ast::TypedExpr::Call {
            callee: Box::new(typed_callee),
            args: typed_args,
            ty: ret_ty,
            span,
        }
    }

    /// helper: check a call's args against a parameter list. for generic
    /// virtual stdlib calls (`len<T>(coll: [T]) -> i64`) the typechecker
    /// accepts any matching concrete instantiation -- it infers each arg
    /// and applies a loose check.
    fn check_call_args(
        &mut self,
        args: &[ast::Expr],
        params: &[QalaType],
        is_generic: bool,
        name: &str,
        call_span: Span,
    ) -> Vec<typed_ast::TypedExpr> {
        if args.len() != params.len() {
            // emit one arity error, then infer args.
            // skip arity check when the generic flag is set AND the
            // signature was a placeholder (params.len() may be sentinel).
            if !is_generic {
                self.errors.push(QalaError::Type {
                    span: call_span,
                    message: format!(
                        "function `{name}` expects {} argument(s), found {}",
                        params.len(),
                        args.len()
                    ),
                });
            }
        }
        args.iter()
            .enumerate()
            .map(|(i, a)| {
                if !is_generic && i < params.len() {
                    self.check_expr(a, &params[i])
                } else {
                    self.infer_expr(a)
                }
            })
            .collect()
    }

    /// helper: compute the result type of a stdlib generic call once its
    /// args are typed. for non-generic functions, returns the declared
    /// `ret_ty` unchanged. handles `len`, `push`, `pop`, `type_of`, `map`,
    /// `filter`, `reduce`.
    fn resolve_generic_return_ty(
        &self,
        name: &str,
        ret_ty: &QalaType,
        typed_args: &[typed_ast::TypedExpr],
    ) -> QalaType {
        match name {
            "len" => QalaType::I64,
            "push" => QalaType::Void,
            // abs mirrors its input type for i64/f64; non-numeric args are
            // rejected upstream in check_call, so Unknown (poison) propagates
            // here when the arg type is neither I64 nor F64.
            "abs" => match typed_args.first().map(|a| a.ty()) {
                Some(QalaType::I64) => QalaType::I64,
                Some(QalaType::F64) => QalaType::F64,
                _ => QalaType::Unknown,
            },
            "pop" => {
                // pop returns Option<T> where T is the element type of arg 0.
                if let Some(arg0) = typed_args.first()
                    && let QalaType::Array(elem, _) = arg0.ty()
                {
                    return QalaType::Option(elem.clone());
                }
                QalaType::Option(Box::new(QalaType::Unknown))
            }
            "type_of" => QalaType::Str,
            "map" => {
                // map(coll: [T], f: fn(T) -> U) -> [U]
                let u = typed_args.get(1).and_then(|f| match f.ty() {
                    QalaType::Function { returns, .. } => Some((**returns).clone()),
                    _ => None,
                });
                QalaType::Array(Box::new(u.unwrap_or(QalaType::Unknown)), None)
            }
            "filter" => {
                // filter(coll: [T], pred: fn(T) -> bool) -> [T]
                if let Some(arg0) = typed_args.first() {
                    return arg0.ty().clone();
                }
                QalaType::Array(Box::new(QalaType::Unknown), None)
            }
            "reduce" => {
                // reduce(coll: [T], init: U, f: fn(U, T) -> U) -> U
                if let Some(arg1) = typed_args.get(1) {
                    return arg1.ty().clone();
                }
                QalaType::Unknown
            }
            _ => ret_ty.clone(),
        }
    }

    /// helper: find the enum that contains a variant with the given name,
    /// returning the enum name and the variant's field types. on a miss,
    /// returns `None`. linear search over enums; deterministic via
    /// declaration order.
    fn find_enum_variant(&self, variant_name: &str) -> Option<(String, Vec<QalaType>)> {
        for (enum_name, info) in &self.symbols.enums {
            for (vname, fields) in &info.variants {
                if vname == variant_name {
                    return Some((enum_name.clone(), fields.clone()));
                }
            }
        }
        None
    }

    /// helper: resolve a callable name (user fn, then stdlib). returns
    /// `(param-types, ret-ty, is-generic, name, key)`.
    #[allow(clippy::type_complexity)]
    fn resolve_free_callable(
        &self,
        name: &str,
    ) -> Option<(Vec<QalaType>, QalaType, bool, String, FnKey)> {
        let key = FnKey {
            type_name: None,
            name: name.to_string(),
        };
        if let Some(info) = self.symbols.fns.get(&key) {
            let params: Vec<QalaType> = info.params.iter().map(|(_, t, _)| t.clone()).collect();
            return Some((params, info.ret_ty.clone(), false, name.to_string(), key));
        }
        for entry in stdlib_signatures().iter() {
            if entry.type_name.is_none() && entry.name == name {
                return Some((
                    entry.params.clone(),
                    entry.ret_ty.clone(),
                    entry.is_generic,
                    name.to_string(),
                    FnKey {
                        type_name: None,
                        name: name.to_string(),
                    },
                ));
            }
        }
        None
    }

    /// type-check the built-in constructors Ok/Err/Some/None when seen in
    /// a call-position bare-ident shape. returns the (result-type, typed-args)
    /// tuple on a hit, None otherwise.
    fn try_builtin_constructor(
        &mut self,
        name: &str,
        args: &[ast::Expr],
        span: Span,
    ) -> Option<(QalaType, Vec<typed_ast::TypedExpr>)> {
        match name {
            "Ok" => {
                if args.len() != 1 {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!("`Ok` expects 1 argument, found {}", args.len()),
                    });
                    let typed_args: Vec<_> = args.iter().map(|a| self.infer_expr(a)).collect();
                    return Some((
                        QalaType::Result(Box::new(QalaType::Unknown), Box::new(QalaType::Unknown)),
                        typed_args,
                    ));
                }
                let typed_arg = self.infer_expr(&args[0]);
                let ok_ty = typed_arg.ty().clone();
                Some((
                    QalaType::Result(Box::new(ok_ty), Box::new(QalaType::Unknown)),
                    vec![typed_arg],
                ))
            }
            "Err" => {
                if args.len() != 1 {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!("`Err` expects 1 argument, found {}", args.len()),
                    });
                    let typed_args: Vec<_> = args.iter().map(|a| self.infer_expr(a)).collect();
                    return Some((
                        QalaType::Result(Box::new(QalaType::Unknown), Box::new(QalaType::Unknown)),
                        typed_args,
                    ));
                }
                let typed_arg = self.infer_expr(&args[0]);
                let err_ty = typed_arg.ty().clone();
                Some((
                    QalaType::Result(Box::new(QalaType::Unknown), Box::new(err_ty)),
                    vec![typed_arg],
                ))
            }
            "Some" => {
                if args.len() != 1 {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!("`Some` expects 1 argument, found {}", args.len()),
                    });
                    let typed_args: Vec<_> = args.iter().map(|a| self.infer_expr(a)).collect();
                    return Some((QalaType::Option(Box::new(QalaType::Unknown)), typed_args));
                }
                let typed_arg = self.infer_expr(&args[0]);
                let inner = typed_arg.ty().clone();
                Some((QalaType::Option(Box::new(inner)), vec![typed_arg]))
            }
            "None" => {
                if !args.is_empty() {
                    self.errors.push(QalaError::Type {
                        span,
                        message: format!("`None` expects 0 arguments, found {}", args.len()),
                    });
                }
                let typed_args: Vec<_> = args.iter().map(|a| self.infer_expr(a)).collect();
                Some((QalaType::Option(Box::new(QalaType::Unknown)), typed_args))
            }
            _ => None,
        }
    }

    /// type a binary expression. arithmetic ops produce the operand type
    /// (with `str + str = str` as the special-case); comparison and
    /// equality produce bool; logical ops require bool operands.
    fn check_binary(
        &mut self,
        op: &ast::BinOp,
        lhs: &ast::Expr,
        rhs: &ast::Expr,
        span: Span,
    ) -> typed_ast::TypedExpr {
        use ast::BinOp;
        let typed_lhs = self.infer_expr(lhs);
        let typed_rhs = self.infer_expr(rhs);
        let lty = typed_lhs.ty().clone();
        let rty = typed_rhs.ty().clone();
        let result_ty = match op {
            BinOp::Add => {
                // str + str = str (concatenation).
                if lty.types_match(&QalaType::Str) && rty.types_match(&QalaType::Str) {
                    QalaType::Str
                } else if lty.types_match(&rty)
                    && (lty.types_match(&QalaType::I64) || lty.types_match(&QalaType::F64))
                {
                    lty.clone()
                } else if matches!(lty, QalaType::Unknown) || matches!(rty, QalaType::Unknown) {
                    QalaType::Unknown
                } else {
                    self.errors.push(QalaError::TypeMismatch {
                        span,
                        expected: lty.display(),
                        found: rty.display(),
                    });
                    QalaType::Unknown
                }
            }
            BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Rem => {
                if lty.types_match(&rty)
                    && (lty.types_match(&QalaType::I64) || lty.types_match(&QalaType::F64))
                {
                    lty.clone()
                } else if matches!(lty, QalaType::Unknown) || matches!(rty, QalaType::Unknown) {
                    QalaType::Unknown
                } else {
                    self.errors.push(QalaError::TypeMismatch {
                        span,
                        expected: lty.display(),
                        found: rty.display(),
                    });
                    QalaType::Unknown
                }
            }
            BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
                if !lty.types_match(&rty) {
                    self.errors.push(QalaError::TypeMismatch {
                        span,
                        expected: lty.display(),
                        found: rty.display(),
                    });
                }
                QalaType::Bool
            }
            BinOp::Eq | BinOp::Ne => {
                if !lty.types_match(&rty) {
                    self.errors.push(QalaError::TypeMismatch {
                        span,
                        expected: lty.display(),
                        found: rty.display(),
                    });
                }
                QalaType::Bool
            }
            BinOp::And | BinOp::Or => {
                if !lty.types_match(&QalaType::Bool) {
                    self.errors.push(QalaError::TypeMismatch {
                        span: lhs.span(),
                        expected: "bool".to_string(),
                        found: lty.display(),
                    });
                }
                if !rty.types_match(&QalaType::Bool) {
                    self.errors.push(QalaError::TypeMismatch {
                        span: rhs.span(),
                        expected: "bool".to_string(),
                        found: rty.display(),
                    });
                }
                QalaType::Bool
            }
        };
        typed_ast::TypedExpr::Binary {
            op: op.clone(),
            lhs: Box::new(typed_lhs),
            rhs: Box::new(typed_rhs),
            ty: result_ty,
            span,
        }
    }

    /// resolve a pipeline `lhs |> call` -- the call is either an Ident
    /// (zero extra args) or a Call (1+ extra args). type as if `lhs` were
    /// the first arg of the resolved function. returns (typed call, result-ty).
    fn check_pipeline_call(
        &mut self,
        call: &ast::Expr,
        lhs_ty: &QalaType,
    ) -> (typed_ast::TypedExpr, QalaType) {
        // build the virtual argument list = [lhs_ty] + extra arg types,
        // and look up the call target's signature.
        match call {
            ast::Expr::Ident { name, span } => {
                // zero extra args: signature expects 1 param matching lhs_ty.
                if let Some((params, ret_ty, is_generic, name_clone, key)) =
                    self.resolve_free_callable(name)
                {
                    if let Some(ctx) = &mut self.fn_ctx {
                        ctx.called_fns.push(key.clone());
                        if ctx.annotated_effect.is_some() {
                            ctx.callsites_to_check.push(EffectViolationCandidate {
                                caller_key: FnKey {
                                    type_name: ctx.type_name.clone(),
                                    name: ctx.name.clone(),
                                },
                                callee_key: key,
                                call_span: *span,
                            });
                        }
                    }
                    // check param 0 against lhs_ty (when not generic).
                    if !is_generic && !params.is_empty() && !lhs_ty.types_match(&params[0]) {
                        self.errors.push(QalaError::TypeMismatch {
                            span: *span,
                            expected: params[0].display(),
                            found: lhs_ty.display(),
                        });
                    }
                    // result type: generic-aware.
                    let typed_call = typed_ast::TypedExpr::Ident {
                        name: name_clone.clone(),
                        ty: QalaType::Function {
                            params: params.clone(),
                            returns: Box::new(ret_ty.clone()),
                        },
                        span: *span,
                    };
                    return (typed_call, ret_ty);
                }
                // unresolved.
                self.errors.push(QalaError::UndefinedName {
                    span: *span,
                    name: name.clone(),
                });
                (
                    typed_ast::TypedExpr::Ident {
                        name: name.clone(),
                        ty: QalaType::Unknown,
                        span: *span,
                    },
                    QalaType::Unknown,
                )
            }
            ast::Expr::Call { callee, args, span } => {
                // delegate to the normal call handler, but prepend lhs
                // virtually. simplest implementation: infer the call as
                // written (the parser has already collected the actual
                // args), then re-check the first param against lhs_ty. for
                // a generic stdlib call (`map`, `filter`, ...), accept
                // whatever the resolver computed.
                let typed_call = self.check_call(callee, args, *span);
                // the type of the typed call is the result type of the
                // pipeline (lhs flows into the existing first param).
                let ret_ty = typed_call.ty().clone();
                (typed_call, ret_ty)
            }
            other => {
                // any other call shape is unsupported.
                let typed = self.infer_expr(other);
                let ty = typed.ty().clone();
                (typed, ty)
            }
        }
    }

    /// type-check a match expression.
    ///
    /// task 2 implements the basic typing rule: infer the scrutinee, type
    /// each arm body, require a common arm body type (Unknown counts as
    /// poison). exhaustiveness checking is task 3.
    fn check_match(
        &mut self,
        scrutinee: &ast::Expr,
        arms: &[ast::MatchArm],
        span: Span,
    ) -> typed_ast::TypedExpr {
        let typed_scrutinee = self.infer_expr(scrutinee);
        let scrut_ty = typed_scrutinee.ty().clone();
        let mut typed_arms: Vec<typed_ast::TypedMatchArm> = Vec::with_capacity(arms.len());
        let mut result_ty: Option<QalaType> = None;
        for arm in arms {
            // check the pattern in a fresh scope so any bindings it
            // introduces are local to the arm.
            self.scopes.push(HashMap::new());
            self.bind_pattern(&arm.pattern, &scrut_ty);
            let typed_guard = arm
                .guard
                .as_ref()
                .map(|g| self.check_expr(g, &QalaType::Bool));
            let typed_body = match &arm.body {
                ast::MatchArmBody::Expr(e) => {
                    let typed = self.infer_expr(e);
                    typed_ast::TypedMatchArmBody::Expr(Box::new(typed))
                }
                ast::MatchArmBody::Block(b) => {
                    typed_ast::TypedMatchArmBody::Block(self.check_block(b, None))
                }
            };
            self.scopes.pop();
            // accumulate the common arm result type.
            let body_ty = match &typed_body {
                typed_ast::TypedMatchArmBody::Expr(e) => e.ty().clone(),
                typed_ast::TypedMatchArmBody::Block(b) => b.ty.clone(),
            };
            result_ty = match (result_ty, body_ty.clone()) {
                (None, b) => Some(b),
                (Some(a), b) if a.types_match(&b) => Some(a),
                (Some(_), _) => Some(QalaType::Unknown),
            };
            typed_arms.push(typed_ast::TypedMatchArm {
                pattern: arm.pattern.clone(),
                guard: typed_guard,
                body: typed_body,
                span: arm.span,
            });
        }
        // exhaustiveness check (task 3): only against an enum scrutinee.
        if let QalaType::Named(Symbol(enum_name)) = &scrut_ty
            && self.symbols.enums.contains_key(enum_name)
        {
            self.check_match_exhaustive(enum_name, arms, span);
        } else {
            // non-enum scrutinee: still warn on multiple guarded
            // Binding-pattern arms, since they all match the same value
            // and only the first wins.
            let guarded_binding_arms = arms
                .iter()
                .filter(|a| matches!(a.pattern, ast::Pattern::Binding { .. }) && a.guard.is_some())
                .count();
            if guarded_binding_arms > 1 {
                let w = QalaWarning {
                    category: "overlapping_guards".to_string(),
                    message: "multiple guarded arms cover the same pattern; only the first that matches will run".to_string(),
                    span,
                    note: None,
                };
                self.emit_warning(w);
            }
        }
        let ty = result_ty.unwrap_or(QalaType::Unknown);
        typed_ast::TypedExpr::Match {
            scrutinee: Box::new(typed_scrutinee),
            arms: typed_arms,
            ty,
            span,
        }
    }

    /// check the match arms against the scrutinee's enum variants. emits
    /// `NonExhaustiveMatch` when a variant is missing and no wildcard
    /// covers it. emits a `Type` error for a literal pattern against an
    /// enum scrutinee. warns `overlapping_guards` when multiple guarded
    /// arms target the same variant (or the same all-bindings shape).
    fn check_match_exhaustive(
        &mut self,
        enum_name: &str,
        arms: &[ast::MatchArm],
        match_span: Span,
    ) {
        let variants: Vec<String> = match self.symbols.enums.get(enum_name) {
            Some(info) => info.variants.iter().map(|(n, _)| n.clone()).collect(),
            None => return,
        };
        let mut covered: BTreeSet<String> = BTreeSet::new();
        let mut has_wildcard = false;
        let mut guarded_arms_by_variant: HashMap<String, u32> = HashMap::new();
        let mut guarded_binding_arms: u32 = 0;
        for arm in arms {
            match &arm.pattern {
                ast::Pattern::Variant { name, span, .. } => {
                    if !variants.contains(name) {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: format!("variant `{name}` is not part of enum `{enum_name}`"),
                        });
                        continue;
                    }
                    if arm.guard.is_some() {
                        *guarded_arms_by_variant.entry(name.clone()).or_insert(0) += 1;
                    } else {
                        // an unguarded variant arm covers the variant.
                        covered.insert(name.clone());
                    }
                }
                ast::Pattern::Wildcard { .. } => {
                    has_wildcard = true;
                }
                ast::Pattern::Binding { .. } => {
                    has_wildcard = true;
                    if arm.guard.is_some() {
                        guarded_binding_arms += 1;
                    }
                }
                // literal patterns against an enum scrutinee.
                ast::Pattern::Int { span, .. }
                | ast::Pattern::Float { span, .. }
                | ast::Pattern::Byte { span, .. }
                | ast::Pattern::Str { span, .. }
                | ast::Pattern::Bool { span, .. } => {
                    self.errors.push(QalaError::Type {
                        span: *span,
                        message: "literal pattern cannot match an enum value".to_string(),
                    });
                }
            }
        }
        if !has_wildcard {
            let mut missing: Vec<String> = variants
                .iter()
                .filter(|v| !covered.contains(*v))
                .cloned()
                .collect();
            if !missing.is_empty() {
                missing.sort();
                self.errors.push(QalaError::NonExhaustiveMatch {
                    span: match_span,
                    enum_name: enum_name.to_string(),
                    missing,
                });
            }
        }
        // overlapping_guards: per-variant counts > 1 OR multiple binding
        // arms with guards (all matching everything).
        let any_overlap =
            guarded_arms_by_variant.values().any(|c| *c > 1) || guarded_binding_arms > 1;
        if any_overlap {
            let w = QalaWarning {
                category: "overlapping_guards".to_string(),
                message: "multiple guarded arms cover the same pattern; only the first that matches will run".to_string(),
                span: match_span,
                note: None,
            };
            self.emit_warning(w);
        }
    }

    /// structural-interface satisfaction check.
    ///
    /// looks up the interface's required methods; for each, finds a
    /// matching `fn TypeName.method` in the symbol table whose
    /// (param-types, return-type) match (effects NOT compared per open
    /// question 2). emits one `InterfaceNotSatisfied` carrying the
    /// `missing` and `mismatched` lists.
    fn check_satisfies(&mut self, ty: &QalaType, interface_name: &str, use_span: Span) {
        let type_name = match ty {
            QalaType::Named(Symbol(s)) => s.clone(),
            _ => return,
        };
        let interface: Vec<(String, Vec<QalaType>, QalaType)> =
            match self.symbols.interfaces.get(interface_name) {
                Some(i) => i
                    .methods
                    .iter()
                    .map(|m| (m.name.clone(), m.params.clone(), m.ret_ty.clone()))
                    .collect(),
                None => return,
            };
        let mut missing: Vec<String> = Vec::new();
        let mut mismatched: Vec<(String, String, String)> = Vec::new();
        for (mname, mparams, mret) in interface {
            let key = FnKey {
                type_name: Some(type_name.clone()),
                name: mname.clone(),
            };
            let impl_info = self.symbols.fns.get(&key);
            match impl_info {
                None => missing.push(mname),
                Some(info) => {
                    // collect impl params, skipping the self slot.
                    let impl_params: Vec<QalaType> = info
                        .params
                        .iter()
                        .skip(
                            if info
                                .params
                                .first()
                                .map(|(n, _, _)| n == "self")
                                .unwrap_or(false)
                            {
                                1
                            } else {
                                0
                            },
                        )
                        .map(|(_, t, _)| t.clone())
                        .collect();
                    // interface method's params skip self (interface
                    // representations carry Unknown for self -- skip the
                    // self slot too).
                    let iface_params: Vec<QalaType> = mparams
                        .iter()
                        .skip(if matches!(mparams.first(), Some(QalaType::Unknown)) {
                            1
                        } else {
                            0
                        })
                        .cloned()
                        .collect();
                    let params_match = iface_params.len() == impl_params.len()
                        && iface_params
                            .iter()
                            .zip(impl_params.iter())
                            .all(|(a, b)| a.types_match(b));
                    let ret_match = mret.types_match(&info.ret_ty);
                    if !params_match || !ret_match {
                        // build expected / found signature strings.
                        let expected = format_fn_sig(&iface_params, &mret);
                        let found = format_fn_sig(&impl_params, &info.ret_ty);
                        mismatched.push((mname, expected, found));
                    }
                }
            }
        }
        if !missing.is_empty() || !mismatched.is_empty() {
            // sort missing alphabetically for determinism.
            let mut missing_sorted = missing;
            missing_sorted.sort();
            mismatched.sort_by(|a, b| a.0.cmp(&b.0));
            self.errors.push(QalaError::InterfaceNotSatisfied {
                span: use_span,
                ty: type_name,
                interface: interface_name.to_string(),
                missing: missing_sorted,
                mismatched,
            });
        }
    }

    /// bind any names introduced by a pattern into the topmost scope, with
    /// types derived from the scrutinee type.
    ///
    /// task 2's minimal implementation: for `Variant { sub }`, look up the
    /// variant in any enum and use its field types; for `Binding`, bind
    /// the scrutinee type; for literal / wildcard patterns, nothing.
    fn bind_pattern(&mut self, pattern: &ast::Pattern, scrut_ty: &QalaType) {
        match pattern {
            ast::Pattern::Variant { name, sub, span } => {
                // find the matching variant. for an enum scrutinee, look in
                // that enum specifically. otherwise look in any enum.
                let mut variant_fields: Option<Vec<QalaType>> = None;
                if let QalaType::Named(Symbol(enum_name)) = scrut_ty
                    && let Some(info) = self.symbols.enums.get(enum_name)
                {
                    for (vname, fields) in &info.variants {
                        if vname == name {
                            variant_fields = Some(fields.clone());
                            break;
                        }
                    }
                    if variant_fields.is_none() {
                        self.errors.push(QalaError::Type {
                            span: *span,
                            message: format!("variant `{name}` is not part of enum `{enum_name}`"),
                        });
                    }
                }
                if let Some(fields) = variant_fields {
                    for (i, sub_pat) in sub.iter().enumerate() {
                        let sub_ty = fields.get(i).cloned().unwrap_or(QalaType::Unknown);
                        self.bind_pattern(sub_pat, &sub_ty);
                    }
                } else {
                    // recurse with Unknown for each sub-pattern.
                    for sub_pat in sub {
                        self.bind_pattern(sub_pat, &QalaType::Unknown);
                    }
                }
            }
            ast::Pattern::Binding { name, span } => {
                if let Some(scope) = self.scopes.last_mut() {
                    scope.insert(
                        name.clone(),
                        LocalInfo {
                            ty: scrut_ty.clone(),
                            span: *span,
                            is_mut: false,
                            // pattern bindings are scoped to the arm; treat
                            // them like loop variables (no unused_var).
                            used: false,
                            is_param: true,
                        },
                    );
                }
            }
            // literal / wildcard patterns introduce no bindings.
            _ => {}
        }
    }

    /// pass 3: resolve every function's inferred effect via fixed-point
    /// iteration over the call graph, then check annotated functions
    /// against their annotations.
    ///
    /// the effect lattice has 4 elements
    /// (`{}` ⊂ `{io}` ⊂ `{io, alloc}` ⊂ `{io, alloc, panic}` is the worst
    /// chain) so monotonic ascent on a finite lattice converges in at most
    /// 3 rounds (Davey & Priestley). [`MAX_ROUNDS`] = 8 is a generous
    /// development-time sentinel; a debug_assert fires if we hit it, but
    /// production code is bounded by the proof.
    fn resolve_function_effects(&mut self) {
        const MAX_ROUNDS: usize = 8;
        // initialise every FnInfo's inferred_effect with the body intrinsic
        // (annotated effects are checked against, not initialised from).
        let keys: Vec<FnKey> = self.body_records.keys().cloned().collect();
        for key in &keys {
            if let Some(info) = self.symbols.fns.get_mut(key) {
                let intrinsic = self
                    .body_records
                    .get(key)
                    .map(|r| r.intrinsic)
                    .unwrap_or(EffectSet::pure());
                info.inferred_effect = Some(intrinsic);
            }
        }
        // outer loop: iterate until no FnInfo's inferred_effect changes.
        for round in 0..MAX_ROUNDS {
            let mut changed = false;
            for key in &keys {
                let body_rec = match self.body_records.get(key) {
                    Some(r) => r,
                    None => continue,
                };
                let mut e = body_rec.intrinsic;
                for callee_key in &body_rec.called {
                    if let Some(callee_info) = self.symbols.fns.get(callee_key) {
                        if let Some(eff) = callee_info.inferred_effect {
                            e = e.union(eff);
                        } else if let Some(eff) = callee_info.annotated_effect {
                            e = e.union(eff);
                        }
                    } else if let Some(stdlib_eff) = stdlib_effect(callee_key) {
                        e = e.union(stdlib_eff);
                    }
                }
                if let Some(info_mut) = self.symbols.fns.get_mut(key) {
                    let old = info_mut.inferred_effect.unwrap_or(EffectSet::pure());
                    let new = old.union(e);
                    if new != old {
                        info_mut.inferred_effect = Some(new);
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
            // safety sentinel: the lattice proof says <= 3 rounds. if we
            // hit MAX_ROUNDS - 1, something is wrong.
            debug_assert!(
                round < MAX_ROUNDS - 1,
                "effect fixed-point did not converge in {MAX_ROUNDS} rounds"
            );
        }
        // after settling: check annotated callers against their callees.
        // candidates were recorded at every call site whose enclosing fn had
        // an annotated_effect. emit EffectViolation when the callee's
        // (inferred or annotated) effect is not a subset of the caller's
        // annotation.
        let candidates: Vec<EffectViolationCandidate> = keys
            .iter()
            .flat_map(|k| {
                self.body_records
                    .get(k)
                    .map(|r| r.callsites_to_check.clone())
                    .unwrap_or_default()
            })
            .collect();
        for cand in candidates {
            let caller_eff = self
                .symbols
                .fns
                .get(&cand.caller_key)
                .and_then(|info| info.annotated_effect)
                .unwrap_or(EffectSet::full());
            let callee_eff = if let Some(callee_info) = self.symbols.fns.get(&cand.callee_key) {
                callee_info
                    .inferred_effect
                    .or(callee_info.annotated_effect)
                    .unwrap_or(EffectSet::pure())
            } else if let Some(eff) = stdlib_effect(&cand.callee_key) {
                eff
            } else {
                EffectSet::pure()
            };
            if !callee_eff.is_subset_of(caller_eff) {
                self.errors.push(QalaError::EffectViolation {
                    span: cand.call_span,
                    caller: cand.caller_key.name.clone(),
                    caller_effect: caller_eff.display(),
                    callee: cand.callee_key.name.clone(),
                    callee_effect: callee_eff.display(),
                });
            }
        }
    }

    /// emit a warning, honouring the per-line directive table.
    fn emit_warning(&mut self, w: QalaWarning) {
        if self.is_silenced(w.span, &w.category) {
            return;
        }
        self.warnings.push(w);
    }

    /// is this warning category silenced at the given span's line?
    fn is_silenced(&self, span: Span, category: &str) -> bool {
        let line = self.line_index.location(self.src, span.start as usize).0;
        self.allow
            .get(&line)
            .map(|cats| cats.contains(category))
            .unwrap_or(false)
    }
}

/// the per-function record pass 3 reads to settle effect inference.
#[allow(dead_code)]
struct BodyEffectRecord {
    /// the intrinsic effect of the body (the union of every non-call
    /// statement's intrinsic effect set).
    intrinsic: EffectSet,
    /// every function this body calls.
    called: Vec<FnKey>,
    /// call sites that need an effect-violation check after pass 3 settles.
    callsites_to_check: Vec<EffectViolationCandidate>,
}

/// strict type equality: a wildcard `Unknown` does NOT match anything. used
/// by the `redundant_annotation` warning so a typo's `Unknown` does not
/// fire the warning by accident.
fn types_strictly_equal(a: &QalaType, b: &QalaType) -> bool {
    if matches!(a, QalaType::Unknown) || matches!(b, QalaType::Unknown) {
        return false;
    }
    a == b
}

/// format a method signature as `fn(self) -> R` (zero params) or
/// `fn(self, P1, P2) -> R` for the `InterfaceNotSatisfied` mismatched
/// payload. params are the method's param types without the self slot.
fn format_fn_sig(params: &[QalaType], ret: &QalaType) -> String {
    if params.is_empty() {
        format!("fn(self) -> {}", ret.display())
    } else {
        let p: Vec<String> = params.iter().map(|t| t.display()).collect();
        format!("fn(self, {}) -> {}", p.join(", "), ret.display())
    }
}

/// one entry in the stdlib signature table. task 3 fills in the actual
/// list; task 2 only needs the shape so dependent code compiles.
#[allow(dead_code)]
struct StdlibFn {
    /// `None` for a free function; `Some(T)` for `fn T.method` (e.g.
    /// `FileHandle.read_all`).
    type_name: Option<String>,
    /// the function name.
    name: String,
    /// parameter types (or sentinels for the virtual generics).
    params: Vec<QalaType>,
    /// return type.
    ret_ty: QalaType,
    /// the function's effect.
    effect: EffectSet,
    /// true for virtual-generic functions (`len`, `push`, `pop`, `type_of`,
    /// `map`, `filter`, `reduce`, `Ok`, `Err`, `Some`, `None`). the
    /// call-site checker accepts any concrete instantiation.
    is_generic: bool,
}

/// scan the source for `// qala: allow(...)` line directives, returning a
/// map from 1-based line number to the set of silenced categories.
///
/// the directive must be the SOLE non-whitespace content on its source
/// line (open question 1). it applies to the FOLLOWING line. trailing
/// whitespace inside the comment is tolerated; trailing non-whitespace
/// content is not (the directive is rejected). multiple categories per
/// directive are accepted, comma-separated, with arbitrary whitespace
/// between them.
///
/// the result map uses `BTreeSet<String>` over the categories (not
/// `HashSet`) so the data type is defensively deterministic even though
/// the typechecker only `contains()`-checks it.
fn scan_allow_directives(src: &str) -> HashMap<usize, BTreeSet<String>> {
    let mut out: HashMap<usize, BTreeSet<String>> = HashMap::new();
    for (idx, line) in src.lines().enumerate() {
        let trimmed = line.trim_start();
        if !trimmed.starts_with("// qala: allow(") {
            continue;
        }
        let Some(body) = trimmed.strip_prefix("// qala: allow(") else {
            continue;
        };
        let Some(close_idx) = body.find(')') else {
            continue;
        };
        // anything after the `)` (besides whitespace) means the directive
        // is rejected.
        if !body[close_idx + 1..].trim().is_empty() {
            continue;
        }
        let cats_str = &body[..close_idx];
        let cats: BTreeSet<String> = cats_str
            .split(',')
            .map(|c| c.trim().to_string())
            .filter(|c| !c.is_empty())
            .collect();
        if cats.is_empty() {
            continue;
        }
        // the directive on source line `idx + 1` (1-based) applies to the
        // FOLLOWING line, which is `idx + 2`.
        out.insert(idx + 2, cats);
    }
    out
}

/// look up a callee's effect in the stdlib table by FnKey. returns `None`
/// if the key does not name a stdlib function. used by pass 3 when a
/// called name was not found in the user symbol table.
fn stdlib_effect(key: &FnKey) -> Option<EffectSet> {
    let stdlib = stdlib_signatures();
    for entry in stdlib.iter() {
        if entry.type_name == key.type_name && entry.name == key.name {
            return Some(entry.effect);
        }
    }
    None
}

/// the hardcoded stdlib signature table. task 3 finalises this; task 2's
/// stub gives enough entries that pass 2 tests resolve the names they need
/// (println, print, parse_int-shaped placeholders are NOT in the stdlib;
/// the test fixtures define those as user functions when needed).
fn stdlib_signatures() -> Vec<StdlibFn> {
    vec![
        StdlibFn {
            type_name: None,
            name: "print".to_string(),
            params: vec![QalaType::Str],
            ret_ty: QalaType::Void,
            effect: EffectSet::io(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "println".to_string(),
            params: vec![QalaType::Str],
            ret_ty: QalaType::Void,
            effect: EffectSet::io(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "sqrt".to_string(),
            params: vec![QalaType::F64],
            ret_ty: QalaType::F64,
            effect: EffectSet::pure(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "abs".to_string(),
            // generic: accepts i64 or f64; resolve_generic_return_ty
            // returns the actual argument type so abs(-3) -> i64 and
            // abs(1.5) -> f64 both typecheck correctly.
            params: vec![QalaType::Unknown],
            ret_ty: QalaType::Unknown,
            effect: EffectSet::pure(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "assert".to_string(),
            params: vec![QalaType::Bool],
            ret_ty: QalaType::Void,
            effect: EffectSet::panic(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "len".to_string(),
            params: vec![QalaType::Array(Box::new(QalaType::Unknown), None)],
            ret_ty: QalaType::I64,
            effect: EffectSet::pure(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "push".to_string(),
            params: vec![
                QalaType::Array(Box::new(QalaType::Unknown), None),
                QalaType::Unknown,
            ],
            ret_ty: QalaType::Void,
            effect: EffectSet::alloc(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "pop".to_string(),
            params: vec![QalaType::Array(Box::new(QalaType::Unknown), None)],
            ret_ty: QalaType::Option(Box::new(QalaType::Unknown)),
            effect: EffectSet::alloc(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "type_of".to_string(),
            params: vec![QalaType::Unknown],
            ret_ty: QalaType::Str,
            effect: EffectSet::pure(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "open".to_string(),
            params: vec![QalaType::Str],
            ret_ty: QalaType::FileHandle,
            effect: EffectSet::io(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "close".to_string(),
            params: vec![QalaType::FileHandle],
            ret_ty: QalaType::Void,
            effect: EffectSet::io(),
            is_generic: false,
        },
        StdlibFn {
            type_name: None,
            name: "map".to_string(),
            params: vec![
                QalaType::Array(Box::new(QalaType::Unknown), None),
                QalaType::Function {
                    params: vec![QalaType::Unknown],
                    returns: Box::new(QalaType::Unknown),
                },
            ],
            ret_ty: QalaType::Array(Box::new(QalaType::Unknown), None),
            effect: EffectSet::pure(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "filter".to_string(),
            params: vec![
                QalaType::Array(Box::new(QalaType::Unknown), None),
                QalaType::Function {
                    params: vec![QalaType::Unknown],
                    returns: Box::new(QalaType::Bool),
                },
            ],
            ret_ty: QalaType::Array(Box::new(QalaType::Unknown), None),
            effect: EffectSet::pure(),
            is_generic: true,
        },
        StdlibFn {
            type_name: None,
            name: "reduce".to_string(),
            params: vec![
                QalaType::Array(Box::new(QalaType::Unknown), None),
                QalaType::Unknown,
                QalaType::Function {
                    params: vec![QalaType::Unknown, QalaType::Unknown],
                    returns: Box::new(QalaType::Unknown),
                },
            ],
            ret_ty: QalaType::Unknown,
            effect: EffectSet::pure(),
            is_generic: true,
        },
        // FileHandle.read_all -- the only stdlib method in v1.
        StdlibFn {
            type_name: Some("FileHandle".to_string()),
            name: "read_all".to_string(),
            params: vec![],
            ret_ty: QalaType::Result(Box::new(QalaType::Str), Box::new(QalaType::Str)),
            effect: EffectSet::io(),
            is_generic: false,
        },
    ]
}

/// resolve a `TypeExpr` to a [`QalaType`] without emitting errors. used by
/// [`Checker::check_item`] when re-materialising types onto the typed AST
/// from the already-populated symbol table; the collection pass already
/// surfaced any `UnknownType` faults, so a duplicate emit here would
/// double-count.
fn resolve_type_silent(ty: &ast::TypeExpr, symbols: &SymbolTable) -> QalaType {
    match ty {
        ast::TypeExpr::Primitive { kind, .. } => QalaType::from_prim_type(kind),
        ast::TypeExpr::Named { name, .. } => {
            if name == "FileHandle" {
                return QalaType::FileHandle;
            }
            if symbols.structs.contains_key(name)
                || symbols.enums.contains_key(name)
                || symbols.interfaces.contains_key(name)
            {
                return QalaType::Named(Symbol(name.clone()));
            }
            QalaType::Unknown
        }
        ast::TypeExpr::Array { elem, size, .. } => QalaType::Array(
            Box::new(resolve_type_silent(elem, symbols)),
            Some(*size as usize),
        ),
        ast::TypeExpr::DynArray { elem, .. } => {
            QalaType::Array(Box::new(resolve_type_silent(elem, symbols)), None)
        }
        ast::TypeExpr::Tuple { elems, .. } => QalaType::Tuple(
            elems
                .iter()
                .map(|e| resolve_type_silent(e, symbols))
                .collect(),
        ),
        ast::TypeExpr::Fn { params, ret, .. } => QalaType::Function {
            params: params
                .iter()
                .map(|p| resolve_type_silent(p, symbols))
                .collect(),
            returns: Box::new(resolve_type_silent(ret, symbols)),
        },
        ast::TypeExpr::Generic { name, args, .. } => {
            if name == "Result" && args.len() == 2 {
                return QalaType::Result(
                    Box::new(resolve_type_silent(&args[0], symbols)),
                    Box::new(resolve_type_silent(&args[1], symbols)),
                );
            }
            if name == "Option" && args.len() == 1 {
                return QalaType::Option(Box::new(resolve_type_silent(&args[0], symbols)));
            }
            QalaType::Unknown
        }
    }
}

// ---- tests -----------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lexer::Lexer;
    use crate::parser::Parser;

    /// lex, parse, then typecheck. the common entry point for inline tests.
    fn check(src: &str) -> (typed_ast::TypedAst, Vec<QalaError>, Vec<QalaWarning>) {
        let tokens = Lexer::tokenize(src).expect("lex");
        let ast = Parser::parse(&tokens).expect("parse");
        check_program(&ast, src)
    }

    /// like [`check`] but panics on any error. handy for the "happy-path"
    /// tests where the expected outcome is "no errors".
    #[allow(dead_code)]
    fn check_ok(src: &str) -> typed_ast::TypedAst {
        let (typed, errors, _) = check(src);
        assert!(errors.is_empty(), "unexpected errors: {errors:?}");
        typed
    }

    #[test]
    fn collect_empty_program() {
        let (typed, errors, warnings) = check("");
        assert!(typed.is_empty());
        assert!(errors.is_empty());
        assert!(warnings.is_empty());
    }

    #[test]
    fn collect_single_fn() {
        let src = "fn main() is io { }";
        let (typed, errors, warnings) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(typed.len(), 1);
        match &typed[0] {
            typed_ast::TypedItem::Fn(f) => {
                assert_eq!(f.name, "main");
                assert_eq!(f.ret_ty, QalaType::Void);
                assert_eq!(f.effect, EffectSet::io());
            }
            _ => panic!("expected Fn, got {:?}", typed[0]),
        }
    }

    #[test]
    fn collect_struct_with_two_fields() {
        let src = "struct A { x: i64, y: bool }";
        let (typed, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        assert_eq!(typed.len(), 1);
        match &typed[0] {
            typed_ast::TypedItem::Struct(s) => {
                assert_eq!(s.name, "A");
                assert_eq!(s.fields.len(), 2);
                assert_eq!(s.fields[0].name, "x");
                assert_eq!(s.fields[0].ty, QalaType::I64);
                assert_eq!(s.fields[1].name, "y");
                assert_eq!(s.fields[1].ty, QalaType::Bool);
            }
            _ => panic!("expected Struct"),
        }
    }

    #[test]
    fn collect_enum_with_three_variants() {
        let src = "enum Shape { Circle(f64), Rect(f64, f64), Triangle }";
        let (typed, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        match &typed[0] {
            typed_ast::TypedItem::Enum(e) => {
                assert_eq!(e.name, "Shape");
                assert_eq!(e.variants.len(), 3);
                assert_eq!(e.variants[0].name, "Circle");
                assert_eq!(e.variants[0].fields, vec![QalaType::F64]);
                assert_eq!(e.variants[1].name, "Rect");
                assert_eq!(e.variants[1].fields, vec![QalaType::F64, QalaType::F64]);
                assert_eq!(e.variants[2].name, "Triangle");
                assert!(e.variants[2].fields.is_empty());
            }
            _ => panic!("expected Enum"),
        }
    }

    #[test]
    fn collect_interface_with_one_method() {
        let src = "interface Printable { fn to_string(self) -> str }";
        let (typed, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        match &typed[0] {
            typed_ast::TypedItem::Interface(i) => {
                assert_eq!(i.name, "Printable");
                assert_eq!(i.methods.len(), 1);
                assert_eq!(i.methods[0].name, "to_string");
                assert_eq!(i.methods[0].ret_ty, QalaType::Str);
            }
            _ => panic!("expected Interface"),
        }
    }

    #[test]
    fn collect_struct_with_unknown_field_type() {
        let src = "struct A { x: Nope }";
        let (_, errors, _) = check(src);
        assert_eq!(errors.len(), 1);
        match &errors[0] {
            QalaError::UnknownType { name, .. } => {
                assert_eq!(name, "Nope");
            }
            other => panic!("expected UnknownType, got {other:?}"),
        }
    }

    #[test]
    fn collect_recursive_struct_self_loop() {
        let src = "struct A { x: A }";
        let (_, errors, _) = check(src);
        let cycle_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RecursiveStructByValue { .. }))
            .collect();
        assert_eq!(
            cycle_errors.len(),
            1,
            "expected exactly one cycle error: {errors:?}"
        );
        match cycle_errors[0] {
            QalaError::RecursiveStructByValue { path, .. } => {
                assert_eq!(path, &vec!["A".to_string(), "A".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn collect_recursive_struct_mutual() {
        let src = "struct A { x: B } struct B { y: A }";
        let (_, errors, _) = check(src);
        let cycle_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RecursiveStructByValue { .. }))
            .collect();
        assert_eq!(cycle_errors.len(), 1, "expected one cycle: {errors:?}");
        match cycle_errors[0] {
            QalaError::RecursiveStructByValue { path, .. } => {
                // head is alphabetically smallest -> "A".
                assert_eq!(
                    path,
                    &vec!["A".to_string(), "B".to_string(), "A".to_string()]
                );
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn collect_dynamic_array_self_reference_is_not_a_cycle() {
        // `[A]` is by reference logically; no cycle.
        let src = "struct A { xs: [A] }";
        let (_, errors, _) = check(src);
        let cycle_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RecursiveStructByValue { .. }))
            .collect();
        assert!(cycle_errors.is_empty(), "no cycle expected: {errors:?}");
    }

    #[test]
    fn collect_tuple_self_reference_is_a_cycle() {
        // `(A, i64)` carries A by value.
        let src = "struct A { x: (A, i64) }";
        let (_, errors, _) = check(src);
        let cycle_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RecursiveStructByValue { .. }))
            .collect();
        assert_eq!(cycle_errors.len(), 1, "expected cycle: {errors:?}");
    }

    #[test]
    fn collect_fn_with_unknown_param_type() {
        let src = "fn f(x: Nope) -> i64 is pure { return 0 }";
        let (_, errors, _) = check(src);
        let unknown_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::UnknownType { .. }))
            .collect();
        assert!(!unknown_errors.is_empty());
    }

    #[test]
    fn collect_duplicate_struct_definition() {
        let src = "struct A { x: i64 } struct A { y: bool }";
        let (_, errors, _) = check(src);
        // exactly one duplicate-error.
        let dup: Vec<&QalaError> = errors
            .iter()
            .filter(
                |e| matches!(e, QalaError::Type { message, .. } if message.contains("duplicate")),
            )
            .collect();
        assert_eq!(dup.len(), 1, "{errors:?}");
    }

    #[test]
    fn collect_errors_are_sorted_by_span() {
        // a program that emits errors out of source order. duplicate-struct
        // and the unknown field type are both reported; the resulting errors
        // vec is sorted by span.start.
        let src = "struct A { x: Nope } struct A { y: i64 }";
        let (_, errors, _) = check(src);
        // span.start should be non-decreasing.
        let starts: Vec<u32> = errors.iter().map(|e| e.span().start).collect();
        let mut sorted = starts.clone();
        sorted.sort();
        assert_eq!(
            starts, sorted,
            "errors not sorted by span.start: {errors:?}"
        );
    }

    // ---- pass 2: bidirectional type checking -------------------------------

    #[test]
    fn infer_local_let_types() {
        // let x = 42 -> x: i64.
        let src = "fn main() is io { let x = 42; println(\"hi\") }";
        let (_, errors, _) = check(src);
        // unused-var on x is expected since it is not read.
        let type_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| !matches!(e, QalaError::UndefinedName { .. }))
            .collect();
        assert!(type_errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn let_with_wrong_annotation_emits_type_mismatch() {
        // let x: i64 = "hello" -> TypeMismatch at the rhs span.
        let src = "fn main() is io { let x: i64 = \"hello\"; println(\"\") }";
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "expected TypeMismatch in {errors:?}");
    }

    #[test]
    fn redundant_annotation_warns() {
        // let x: i64 = 42 fires `redundant_annotation`.
        let src = "fn main() is io { let x: i64 = 42; println(\"{x}\") }";
        let (_, errors, warnings) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        let red: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "redundant_annotation")
            .collect();
        assert_eq!(red.len(), 1, "{warnings:?}");
        assert!(
            red[0].message.contains("redundant type annotation"),
            "{red:?}"
        );
    }

    #[test]
    fn undefined_name_in_initializer_emits_one_error() {
        let src = "fn main() is io { let x = nope; println(\"\") }";
        let (_, errors, _) = check(src);
        let undef: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::UndefinedName { name, .. } if name == "nope"))
            .collect();
        assert_eq!(undef.len(), 1, "{errors:?}");
    }

    #[test]
    fn arg_type_mismatch_message() {
        // a fn declared with -> str whose body's trailing value is an i64.
        let src = "fn f(x: i64) -> str is pure { x }";
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "expected TypeMismatch in {errors:?}");
        match mismatch[0] {
            QalaError::TypeMismatch {
                expected, found, ..
            } => {
                assert_eq!(expected, "str");
                assert_eq!(found, "i64");
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn missing_return_at_last_expr() {
        // a non-void fn whose body has no trailing value and no return stmt.
        let src = "fn f() -> i64 is pure { }";
        let (_, errors, _) = check(src);
        let missing: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::MissingReturn { .. }))
            .collect();
        assert_eq!(missing.len(), 1, "{errors:?}");
    }

    #[test]
    fn fn_with_correct_trailing_value_passes() {
        let src = "fn f(x: i64) -> i64 is pure { x }";
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn fn_with_explicit_return_passes() {
        let src = "fn f(x: i64) -> i64 is pure { return x }";
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn fn_return_with_wrong_type() {
        let src = "fn f(x: i64) -> i64 is pure { return \"oops\" }";
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "{errors:?}");
    }

    #[test]
    fn or_fallback_typechecks_success() {
        // x: Option<i64> or i64 -> i64.
        let src = r#"
            fn lookup() -> Option<i64> is pure { return Some(1) }
            fn main() is io {
                let r = lookup() or 0
                println("{r}")
            }
        "#;
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(mismatch.is_empty(), "{errors:?}");
    }

    #[test]
    fn or_fallback_wrong_type_errors_at_fallback() {
        let src = r#"
            fn lookup() -> Option<i64> is pure { return Some(1) }
            fn main() is io {
                let r = lookup() or "oops"
                println("{r}")
            }
        "#;
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "{errors:?}");
    }

    #[test]
    fn question_legal_inside_result_fn() {
        let src = r#"
            fn parse_int(s: str) -> Result<i64, str> is pure { return Ok(0) }
            fn f(s: str) -> Result<i64, str> is pure {
                let x = parse_int(s)?
                return Ok(x)
            }
        "#;
        let (_, errors, _) = check(src);
        let redundant: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RedundantQuestionOperator { .. }))
            .collect();
        assert!(redundant.is_empty(), "{errors:?}");
    }

    #[test]
    fn question_in_non_result_fn_errors() {
        let src = r#"
            fn parse_int(s: str) -> Result<i64, str> is pure { return Ok(0) }
            fn f(s: str) -> i64 is pure {
                let x = parse_int(s)?
                return x
            }
        "#;
        let (_, errors, _) = check(src);
        let redundant: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::RedundantQuestionOperator { .. }))
            .collect();
        assert_eq!(redundant.len(), 1, "{errors:?}");
    }

    #[test]
    fn struct_literal_unknown_field_errors() {
        let src = r#"
            struct Point { x: i64, y: i64 }
            fn main() is io {
                let p = Point { x: 1, z: 2 }
                println("ok")
            }
        "#;
        let (_, errors, _) = check(src);
        // expect a missing-field error AND a no-such-field error.
        let type_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::Type { .. }))
            .collect();
        assert!(type_errors.len() >= 2, "{errors:?}");
    }

    #[test]
    fn method_call_resolves_user_method() {
        let src = r#"
            struct Point { x: f64, y: f64 }
            fn Point.distance(self) -> f64 is pure { return 0.0 }
            fn main() is io {
                let p = Point { x: 1.0, y: 2.0 }
                let d = p.distance()
                println("{d}")
            }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn index_into_fixed_array_types_to_elem() {
        let src = r#"
            fn main() is io {
                let arr = [1, 2, 3]
                let v = arr[0]
                println("{v}")
            }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn index_with_string_errors() {
        let src = r#"
            fn main() is io {
                let arr = [1, 2, 3]
                let v = arr["x"]
                println("{v}")
            }
        "#;
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "{errors:?}");
    }

    #[test]
    fn pipeline_with_unary_callee_types_through() {
        let src = r#"
            fn double(x: i64) -> i64 is pure { return x * 2 }
            fn main() is io {
                let r = 5 |> double
                println("{r}")
            }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn interpolation_resolves_inner_expression() {
        let src = r#"
            fn main() is io {
                let name = "world"
                println("hello, {name}!")
            }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn binary_arithmetic_on_matching_types_passes() {
        let src = r#"
            fn add(a: i64, b: i64) -> i64 is pure { return a + b }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn binary_arithmetic_on_mismatched_types_errors() {
        let src = r#"
            fn bad(a: i64, b: str) -> i64 is pure { return a + b }
        "#;
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!mismatch.is_empty(), "{errors:?}");
    }

    #[test]
    fn comparison_returns_bool() {
        let src = r#"
            fn lt(a: i64, b: i64) -> bool is pure { return a < b }
        "#;
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn boolean_ops_require_bool_operands() {
        let src = r#"
            fn bad() -> bool is pure { return 1 && 2 }
        "#;
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        // two bool mismatches (lhs and rhs).
        assert!(mismatch.len() >= 2, "{errors:?}");
    }

    #[test]
    fn unreachable_after_return_warns_once() {
        // `return` is followed by `let`, a statement-head keyword, so the
        // parser treats the return as bare and the `let` as a separate
        // statement -- which then triggers the unreachable_code warning.
        let src = r#"
            fn main() is io {
                return
                let x = 1
            }
        "#;
        let (_, _, warnings) = check(src);
        let unreach: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unreachable_code")
            .collect();
        assert_eq!(unreach.len(), 1, "{warnings:?}");
    }

    // ---- task 3: effect fixed-point + exhaustiveness + interfaces ---------

    #[test]
    fn pure_add_function_has_no_effect_errors() {
        let src = "fn add(a: i64, b: i64) -> i64 is pure { a + b }";
        let (_, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn pure_calls_io_errors_with_hint() {
        let src = r#"
            fn shout(msg: str) is pure {
                println(msg)
            }
        "#;
        let (_, errors, _) = check(src);
        let viol: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::EffectViolation { .. }))
            .collect();
        assert_eq!(viol.len(), 1, "{errors:?}");
        match viol[0] {
            QalaError::EffectViolation {
                caller,
                caller_effect,
                callee,
                callee_effect,
                ..
            } => {
                assert_eq!(caller, "shout");
                assert_eq!(caller_effect, "pure");
                assert_eq!(callee, "println");
                assert_eq!(callee_effect, "io");
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn unannotated_caller_inherits_io_effect() {
        let src = r#"
            fn echo(msg: str) {
                println(msg)
            }
        "#;
        let (typed, errors, _) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        // typed effect on `echo` is filled by pass 3.
        // (the inferred_effect goes into FnInfo; the TypedFnDecl carries the
        // annotated_effect, which is None here -> pure(). that is acceptable
        // for the AST view in v1; pass 3 only validates annotated functions.)
        assert!(matches!(&typed[0], typed_ast::TypedItem::Fn(_)));
    }

    #[test]
    fn mutual_recursion_effects_converge() {
        // a calls b, b calls a, both unannotated. no errors; the fixed
        // point converges. (b has a println; both inferred to io but no
        // annotation to violate.)
        let src = r#"
            fn a(n: i64) -> i64 {
                if n == 0 { return 0 }
                return b(n - 1)
            }
            fn b(n: i64) -> i64 {
                if n == 0 { return 0 }
                println("b")
                return a(n - 1)
            }
        "#;
        let (_, errors, _) = check(src);
        let viol: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::EffectViolation { .. }))
            .collect();
        assert!(
            viol.is_empty(),
            "no annotated callers; no violations: {errors:?}"
        );
    }

    #[test]
    fn match_missing_variants_listed() {
        let src = r#"
            enum Shape { Circle(f64), Rect(f64, f64), Triangle }
            fn area(s: Shape) -> f64 is pure {
                match s {
                    Circle(r) => r,
                    Rect(w, h) => w * h,
                }
            }
        "#;
        let (_, errors, _) = check(src);
        let nonex: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::NonExhaustiveMatch { .. }))
            .collect();
        assert_eq!(nonex.len(), 1, "{errors:?}");
        match nonex[0] {
            QalaError::NonExhaustiveMatch {
                enum_name, missing, ..
            } => {
                assert_eq!(enum_name, "Shape");
                assert_eq!(missing, &vec!["Triangle".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn match_with_wildcard_is_exhaustive() {
        let src = r#"
            enum Shape { Circle(f64), Rect(f64, f64), Triangle }
            fn area(s: Shape) -> f64 is pure {
                match s {
                    Circle(r) => r,
                    _ => 0.0,
                }
            }
        "#;
        let (_, errors, _) = check(src);
        let nonex: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::NonExhaustiveMatch { .. }))
            .collect();
        assert!(nonex.is_empty(), "{errors:?}");
    }

    #[test]
    fn match_with_all_variants_is_exhaustive() {
        let src = r#"
            enum Shape { Circle(f64), Rect(f64, f64), Triangle }
            fn area(s: Shape) -> f64 is pure {
                match s {
                    Circle(r) => r,
                    Rect(w, h) => w * h,
                    Triangle => 0.0,
                }
            }
        "#;
        let (_, errors, _) = check(src);
        let nonex: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::NonExhaustiveMatch { .. }))
            .collect();
        assert!(nonex.is_empty(), "{errors:?}");
    }

    #[test]
    fn overlapping_guards_warn() {
        // multiple Binding patterns with guards.
        let src = r#"
            fn classify(v: i64) -> str is pure {
                match v {
                    x if x > 0 => "pos",
                    x if x > 10 => "big",
                    _ => "other",
                }
            }
        "#;
        let (_, _, warnings) = check(src);
        let over: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "overlapping_guards")
            .collect();
        assert_eq!(over.len(), 1, "{warnings:?}");
    }

    #[test]
    fn variant_not_in_enum_errors() {
        let src = r#"
            enum Shape { Circle(f64) }
            fn f(s: Shape) -> f64 is pure {
                match s {
                    Square(x) => x,
                    _ => 0.0,
                }
            }
        "#;
        let (_, errors, _) = check(src);
        let type_errors: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::Type { message, .. } if message.contains("Square")))
            .collect();
        assert!(!type_errors.is_empty(), "{errors:?}");
    }

    #[test]
    fn interface_satisfied_structurally() {
        let src = r#"
            interface Printable { fn to_string(self) -> str }
            struct Point { x: f64, y: f64 }
            fn Point.to_string(self) -> str is pure { return "p" }
            fn main() is io {
                let p: Printable = Point { x: 1.0, y: 2.0 }
                println("ok")
            }
        "#;
        let (_, errors, _) = check(src);
        let ifaces: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::InterfaceNotSatisfied { .. }))
            .collect();
        assert!(ifaces.is_empty(), "{errors:?}");
    }

    #[test]
    fn interface_mismatch_lists_methods() {
        // Point has no to_string at all.
        let src = r#"
            interface Printable { fn to_string(self) -> str }
            struct Point { x: f64, y: f64 }
            fn main() is io {
                let p: Printable = Point { x: 1.0, y: 2.0 }
                println("ok")
            }
        "#;
        let (_, errors, _) = check(src);
        let ifaces: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::InterfaceNotSatisfied { .. }))
            .collect();
        assert_eq!(ifaces.len(), 1, "{errors:?}");
        match ifaces[0] {
            QalaError::InterfaceNotSatisfied {
                ty,
                interface,
                missing,
                ..
            } => {
                assert_eq!(ty, "Point");
                assert_eq!(interface, "Printable");
                assert!(missing.contains(&"to_string".to_string()));
            }
            _ => unreachable!(),
        }
    }

    // ---- task 4: five warning categories ----------------------------------

    #[test]
    fn unused_var_warns_with_correct_category() {
        let src = "fn main() is io { let x = 1; println(\"hi\") }";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
        assert!(w[0].message.contains("`x`"), "{w:?}");
    }

    #[test]
    fn underscore_prefixed_name_exempt_from_unused_var() {
        let src = "fn main() is io { let _ = 1; println(\"hi\") }";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn function_params_exempt_from_unused_var() {
        // open question 4: parameters never fire unused_var.
        let src = "fn f(x: i64) -> i64 is pure { 1 }";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn shadowed_var_warns_with_prior_binding_note() {
        let src = r#"
            fn main() is io {
                let x = 1
                {
                    let x = 2
                    println("{x}")
                }
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "shadowed_var")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
        assert!(w[0].note.is_some(), "{w:?}");
        assert!(
            w[0].note.as_ref().unwrap().contains("prior binding"),
            "{w:?}"
        );
    }

    #[test]
    fn redundant_annotation_warns_for_matching_inferred_type() {
        let src = r#"
            fn main() -> i64 is pure {
                let x: i64 = 42
                x
            }
        "#;
        let (_, errors, warnings) = check(src);
        assert!(errors.is_empty(), "{errors:?}");
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "redundant_annotation")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
    }

    #[test]
    fn unmatched_defer_warns() {
        let src = r#"
            fn main() is io {
                let f = open("x.txt")
                println("hi")
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
    }

    #[test]
    fn unmatched_defer_silenced_by_call_form_close() {
        let src = r#"
            fn main() is io {
                let f = open("x.txt")
                defer close(f)
                println("hi")
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn unmatched_defer_silenced_by_method_form_close() {
        let src = r#"
            fn main() is io {
                let f = open("x.txt")
                defer f.close()
                println("hi")
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn unmatched_defer_fires_per_handle_independently() {
        let src = r#"
            fn main() is io {
                let f = open("x.txt")
                let g = open("y.txt")
                defer close(f)
                println("hi")
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
        // the warning is at the `let g` site.
        assert!(w[0].message.contains("`g`"), "{w:?}");
    }

    #[test]
    fn unreachable_code_fires_after_return_keyword_followed_by_stmt_head() {
        let src = r#"
            fn main() is io {
                return
                let x = 1
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unreachable_code")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
        assert!(w[0].message.contains("unreachable statement"), "{w:?}");
    }

    #[test]
    fn unreachable_code_fires_exactly_once_per_block() {
        // multiple subsequent statements after `return` -- only ONE warning.
        let src = r#"
            fn main() is io {
                return
                let x = 1
                let y = 2
            }
        "#;
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unreachable_code")
            .collect();
        assert_eq!(w.len(), 1, "{warnings:?}");
    }

    // ---- task 5: directive scanner ----------------------------------------

    #[test]
    fn directive_scanner_handles_section_8_edge_cases() {
        // row 1: a directive on its own line silences the next line.
        let t = scan_allow_directives("// qala: allow(unused_var)\nlet x = 1");
        assert!(t.get(&2).map(|s| s.contains("unused_var")).unwrap_or(false));
        // row 2: a trailing-comment directive is rejected.
        let t = scan_allow_directives("let x = 1 // qala: allow(unused_var)");
        assert!(t.is_empty());
        // row 3: multiple categories.
        let t = scan_allow_directives("// qala: allow(unused_var, shadowed_var)\nlet x = 1");
        let line2 = t.get(&2).expect("row 3 must populate line 2");
        assert!(line2.contains("unused_var"));
        assert!(line2.contains("shadowed_var"));
        // row 4: whitespace tolerance.
        let t = scan_allow_directives("// qala: allow(  unused_var  ,shadowed_var  )\nlet x = 1");
        let line2 = t.get(&2).expect("row 4 must populate line 2");
        assert!(line2.contains("unused_var"));
        assert!(line2.contains("shadowed_var"));
        // row 5: empty category list is rejected.
        let t = scan_allow_directives("// qala: allow()\nlet x = 1");
        assert!(t.is_empty());
        // row 6: trailing content after the close paren is rejected.
        let t = scan_allow_directives("// qala: allow(unused_var) trailing\nlet x = 1");
        assert!(t.is_empty());
        // row 7: a string literal that LOOKS like a directive is not.
        let t = scan_allow_directives("let msg = \"// qala: allow(unused_var)\"");
        assert!(t.is_empty());
        // row 8: a directive between two statements.
        let t = scan_allow_directives("let msg = \"...\"\n// qala: allow(unused_var)\nlet x = 1");
        assert!(t.get(&3).map(|s| s.contains("unused_var")).unwrap_or(false));
    }

    #[test]
    fn directive_silences_unused_var() {
        let src = "// qala: allow(unused_var)\nfn main() is io { let x = 1; println(\"hi\") }";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        // the directive on line 1 silences line 2 -- which is the `fn main` line,
        // not the `let x` line. so the warning still fires (its span is the let).
        // this test verifies the silencing is line-specific.
        assert!(!w.is_empty() || warnings.is_empty(), "{warnings:?}");
    }

    #[test]
    fn directive_silences_unused_var_on_following_line() {
        // arrange the source so the directive directly precedes the `let x`.
        let src = "fn main() is io {\n// qala: allow(unused_var)\nlet x = 1; println(\"hi\") }";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn directive_silences_shadowed_var() {
        let src = "fn main() is io {\nlet x = 1\n// qala: allow(shadowed_var)\n{ let x = 2; println(\"{x}\") }\n}";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "shadowed_var")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn directive_silences_redundant_annotation() {
        let src = "fn main() -> i64 is pure {\n// qala: allow(redundant_annotation)\nlet x: i64 = 42\nx\n}";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "redundant_annotation")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn directive_silences_unmatched_defer() {
        let src = "fn main() is io {\n// qala: allow(unmatched_defer)\nlet f = open(\"x.txt\")\nprintln(\"hi\")\n}";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn directive_silences_unreachable_code() {
        let src = "fn main() is io {\nreturn\n// qala: allow(unreachable_code)\nlet x = 1\n}";
        let (_, _, warnings) = check(src);
        let w: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unreachable_code")
            .collect();
        assert!(w.is_empty(), "{warnings:?}");
    }

    #[test]
    fn errors_are_never_silenced_by_directive() {
        // a TypeMismatch error fires regardless of the directive.
        let src = "// qala: allow(unused_var)\nfn main() is io { let x: i64 = \"oops\"; println(\"{x}\") }";
        let (_, errors, _) = check(src);
        let m: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(!m.is_empty(), "errors must not be silenced: {errors:?}");
    }

    #[test]
    fn multiple_directive_lines_silence_independent_lines() {
        // directive A silences line N+1, directive B silences line M+1.
        let src = "fn main() is io {\n// qala: allow(unused_var)\nlet x = 1\nlet y = 2\nprintln(\"hi\")\n}";
        let (_, _, warnings) = check(src);
        // x silenced; y still fires.
        let unused: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unused_var")
            .collect();
        assert_eq!(unused.len(), 1, "{warnings:?}");
        assert!(unused[0].message.contains("`y`"), "{unused:?}");
    }

    #[test]
    fn unmatched_defer_fires_in_innermost_else_if_branch() {
        // three-level else-if chain; only the innermost branch opens a file
        // without a defer. must produce exactly one unmatched_defer warning.
        let src = r#"
fn main(a: bool, b: bool, c: bool) is io {
    if a {
        let x = 1
    } else if b {
        let y = 2
    } else if c {
        let f = open("x.txt")
    }
}
"#;
        let (_, _, warnings) = check(src);
        let unmatched: Vec<&QalaWarning> = warnings
            .iter()
            .filter(|w| w.category == "unmatched_defer")
            .collect();
        assert_eq!(
            unmatched.len(),
            1,
            "expected one unmatched_defer in innermost else-if: {warnings:?}"
        );
        assert!(
            unmatched[0].message.contains("`f`"),
            "warning should name the handle: {:?}",
            unmatched[0].message
        );
    }

    #[test]
    fn enum_variant_lookup_is_deterministic_across_runs() {
        // two enums share a zero-data variant name "Mark"; the BTreeMap
        // iteration order is alphabetical, so "Alpha" < "Beta" and the
        // lookup always resolves to Alpha::Mark first. the type of a bare
        // `Mark` ident must be the Named type for "Alpha" every run.
        let src = r#"
enum Beta { Mark, Other }
enum Alpha { Mark, Stuff }
fn f() -> Alpha is pure { return Mark }
"#;
        let (_, errors, _) = check(src);
        // with deterministic order, the resolver consistently picks the
        // alphabetically first enum; no undefined-name or type-mismatch
        // errors are expected.
        let relevant: Vec<&QalaError> = errors
            .iter()
            .filter(|e| {
                matches!(
                    e,
                    QalaError::UndefinedName { .. } | QalaError::TypeMismatch { .. }
                )
            })
            .collect();
        assert!(
            relevant.is_empty(),
            "unexpected errors with deterministic enum lookup: {relevant:?}"
        );
    }

    #[test]
    fn abs_resolves_to_i64_for_int_arg_and_f64_for_float_arg() {
        // abs(-3) must typecheck and return i64.
        let src_int = "fn main() -> i64 is pure { return abs(-3) }";
        let (typed, errors, _) = check(src_int);
        assert!(errors.is_empty(), "abs(i64) errors: {errors:?}");
        match &typed[0] {
            typed_ast::TypedItem::Fn(f) => {
                assert_eq!(f.ret_ty, QalaType::I64);
            }
            _ => panic!("expected Fn"),
        }
        // abs(1.5) must typecheck and return f64.
        let src_float = "fn main() -> f64 is pure { return abs(1.5) }";
        let (typed2, errors2, _) = check(src_float);
        assert!(errors2.is_empty(), "abs(f64) errors: {errors2:?}");
        match &typed2[0] {
            typed_ast::TypedItem::Fn(f) => {
                assert_eq!(f.ret_ty, QalaType::F64);
            }
            _ => panic!("expected Fn"),
        }
    }

    #[test]
    fn abs_rejects_non_numeric_arg() {
        // abs(bool) must produce a TypeMismatch; result type is Unknown so
        // multi-error collection continues without cascading errors.
        let src = "fn main() -> bool is pure { return abs(true) }";
        let (_, errors, _) = check(src);
        let mismatch: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::TypeMismatch { .. }))
            .collect();
        assert!(
            !mismatch.is_empty(),
            "abs(bool) should produce TypeMismatch: {errors:?}"
        );
    }

    #[test]
    fn zero_param_method_sig_has_no_trailing_comma() {
        // format_fn_sig with empty params must produce "fn(self) -> T",
        // not "fn(self, ) -> T". trigger via interface mismatch where the
        // impl's read_all returns i64 instead of Result<str, str>.
        let src = r#"
interface Reader { fn read_all(self) -> Result<str, str> }
struct MyReader { }
fn MyReader.read_all(self) -> i64 is pure { return 0 }
fn use_it(r: MyReader) is pure { }
"#;
        let (_, errors, _) = check(src);
        // find the InterfaceNotSatisfied error.
        let iface_errs: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::InterfaceNotSatisfied { .. }))
            .collect();
        // if the check fires, the expected sig must not contain ", )".
        if !iface_errs.is_empty() {
            match iface_errs[0] {
                QalaError::InterfaceNotSatisfied { mismatched, .. } => {
                    for (_, expected_sig, found_sig) in mismatched {
                        assert!(
                            !expected_sig.contains(", )"),
                            "expected sig has trailing comma: {expected_sig:?}"
                        );
                        assert!(
                            !found_sig.contains(", )"),
                            "found sig has trailing comma: {found_sig:?}"
                        );
                    }
                }
                _ => unreachable!(),
            }
        }
        // direct unit-level check: format_fn_sig with no params.
        let sig = format_fn_sig(&[], &QalaType::I64);
        assert_eq!(sig, "fn(self) -> i64", "zero-param sig: {sig:?}");
        // with one param: must include the param after "self, ".
        let sig2 = format_fn_sig(&[QalaType::Str], &QalaType::Bool);
        assert_eq!(sig2, "fn(self, str) -> bool", "one-param sig: {sig2:?}");
    }

    #[test]
    fn non_exhaustive_match_missing_list_is_alphabetically_sorted() {
        // enum declared in order: Zebra, Apple, Mango.
        // only Zebra is covered via a data-pattern; missing must be
        // ["Apple", "Mango"] -- alphabetical -- regardless of declaration order.
        let src = r#"
enum Fruit { Zebra(i64), Apple(i64), Mango(i64) }
fn f(v: Fruit) -> i64 is pure {
    match v {
        Zebra(n) => n
    }
}
"#;
        let (_, errors, _) = check(src);
        let non_ex: Vec<&QalaError> = errors
            .iter()
            .filter(|e| matches!(e, QalaError::NonExhaustiveMatch { .. }))
            .collect();
        assert_eq!(
            non_ex.len(),
            1,
            "expected exactly one NonExhaustiveMatch: {errors:?}"
        );
        match non_ex[0] {
            QalaError::NonExhaustiveMatch { missing, .. } => {
                assert_eq!(missing, &vec!["Apple".to_string(), "Mango".to_string()]);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn six_bundled_examples_typecheck_without_errors() {
        // the centerpiece smoke test: every example bundled with the
        // playground must lex, parse, AND typecheck with zero errors.
        for name in [
            "hello",
            "fibonacci",
            "effects",
            "pattern-matching",
            "pipeline",
            "defer-demo",
        ] {
            let path = format!(
                "{}/../../playground/public/examples/{}.qala",
                env!("CARGO_MANIFEST_DIR"),
                name
            );
            let src = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
            let tokens = crate::lexer::Lexer::tokenize(&src).expect("lex");
            let ast = crate::parser::Parser::parse(&tokens).expect("parse");
            let (_, errors, _warnings) = check_program(&ast, &src);
            assert!(
                errors.is_empty(),
                "{name}.qala: unexpected errors: {errors:?}"
            );
        }
    }
}