nova-resolver 0.3.2

The Nova language's name resolver (internal to the nova toolchain)
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
//! Name resolution for the Nova compiler.
//!
//! Phase 1 scope: a single-file module. The resolver walks the top-level
//! items of a parsed [`nova_ast::File`] and produces a [`Definitions`] table
//! mapping every top-level name (functions, sum types, sum-type variants,
//! constants) to a stable [`DefId`]. Duplicate definitions are reported as
//! `E0002` diagnostics.
//!
//! Local (block-scoped) variable resolution happens during type checking,
//! where scoping interacts with inference; this crate owns the *item-level*
//! namespace and the shared [`DefId`] / [`Res`] vocabulary used by the rest
//! of the pipeline.

use indexmap::IndexMap;
use nova_ast::item::{Attribute, ExternItem, Import, ImportKind, TypeDef};
use nova_ast::{File, Function, Item, Type};
use nova_diagnostics::{suggest, Diagnostic, Edit, FileId, Fix, Span};
use rustc_hash::FxHashMap;

pub mod index;
pub use index::{Index, LocalFlags, Occurrence, Role, Target};

/// A stable identifier for a top-level definition within a module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DefId(pub u32);

/// Defines `Builtin`'s variants together with [`Builtin::ALL`] from one
/// variant list, so the two can never disagree โ€” the exact pattern
/// `rt_funcs!` (`nova-mir`) uses for `RtFunc`/`RtFunc::ALL`. Before this,
/// `ALL` was a hand-maintained `[Builtin; N]` literal: it caught a variant
/// added and never mentioned anywhere (the array's length wouldn't match),
/// but not a copy-paste duplicate that swapped in an existing variant for a
/// *different* one while leaving the length (and therefore the build)
/// unchanged โ€” e.g. `Print` listed twice with `Panic` quietly dropped. That
/// is structurally impossible here: `ALL`'s elements come from the exact
/// same identifier list that declares the enum, so duplicating one would
/// duplicate an enum variant name, which does not compile.
macro_rules! builtins {
    ($($(#[$doc:meta])* $variant:ident),+ $(,)?) => {
        /// A compiler-provided builtin function.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum Builtin {
            $($(#[$doc])* $variant,)+
        }

        impl Builtin {
            /// Every `Builtin` variant, in the declaration order above โ€” the
            /// sole authoritative list of "every builtin", generated by the
            /// `builtins!` macro so a variant cannot exist without appearing
            /// here (see the macro's own doc comment for why a duplicate
            /// entry can't silently drop a different variant either).
            /// `builtin_signatures_are_what_the_std_call_sites_use` iterates
            /// this to check every variant's signature.
            pub const ALL: [Builtin; builtins!(@count $($variant)+)] = [
                $(Builtin::$variant),+
            ];
        }
    };
    (@count $($v:ident)+) => {
        [$(builtins!(@one $v)),+].len()
    };
    (@one $v:ident) => { () };
}

builtins! {
    /// `println(s: String)` โ€” write a line to stdout.
    Println,
    /// `print(s: String)` โ€” write to stdout without a trailing newline.
    Print,
    /// `eprint(s: String)` โ€” write to stderr without a trailing newline.
    EPrint,
    /// `eprintln(s: String)` โ€” write a line to stderr.
    EPrintln,
    /// `panic(msg: String)` โ€” abort the program with a message.
    Panic,
    /// `str_cmp(a: String, b: String) -> Int` โ€” byte-lexicographic compare,
    /// returning `-1`, `0`, or `1`. Backs `std/core`'s `impl Ord for String`:
    /// `<` is not defined for `String` (E0013) and `String` is not FFI-safe
    /// (`require_ffi_safe` in `nova-typeck` only accepts scalars), so a
    /// user-visible `extern` is not an option. Reached the same way
    /// `println`/`print`/`panic` are โ€” a `Res::Builtin` checked specially by
    /// `nova-typeck` and lowered straight to a `CallRuntime` in `nova-mir` โ€”
    /// *not* the way `==` on `String` reaches `nova_rt_str_eq`: that is a
    /// pure operator lowering (`binary_result_ty` permits `Eq`/`Ne` for
    /// `Ty::String`, then MIR's `lower_binary` intercepts it) that introduces
    /// no name in any namespace, whereas `str_cmp` is a named function.
    /// Unlike `println`/`print`/`panic`, `str_cmp` is *not* part of the
    /// user-visible language surface: it is seeded only into std modules' own
    /// scopes (see [`Builtin::STD_ONLY`]), so it never becomes a
    /// reserved word in user code.
    StrCmp,
    /// `str_hash(s: String) -> Int` โ€” seeded FNV-1a over the string's bytes,
    /// then splitmix64's finalizer. The seed is per-process, so the same
    /// string hashes differently in two runs; why the finalizer is needed and
    /// what the pair does and does not buy are documented at
    /// `nova_rt_str_hash` and `splitmix64_finalize` in `nova-runtime` rather
    /// than restated here. Backs
    /// `std/core`'s `impl Hash for String`, and exists for the same reason
    /// [`Builtin::StrCmp`] does: no primitive walks a `String`, so a NAMED
    /// operation over its bytes needs a builtin like this one, and an
    /// `extern` cannot stand in because `String` is not FFI-safe. Named is
    /// the operative word -- `==` reaches `nova_rt_str_eq` as a pure operator
    /// lowering introducing no name at all, as [`Builtin::StrCmp`]'s own doc
    /// comment sets out just above. That is a statement
    /// about the primitive layer, not about what Nova code can reach --
    /// `std/bytes` and `std/strings` build byte and char access on builtins
    /// of this kind, and ADR 0005's 2026-08-27 amendment records where an
    /// earlier wording read as the wider claim. Std-only, so `str_hash` is
    /// not a reserved word in user code.
    StrHash,
    /// `char_to_int(c: Char) -> Int` โ€” a `Char`'s Unicode scalar value. The
    /// only way any std module can compare or classify a `Char` numerically:
    /// Nova has no other `Char` โ†’ `Int` conversion (`as` casts are
    /// unsupported, `E0900`; `Char` has no methods beyond its trait impls;
    /// no arithmetic operator accepts a `Char`). Backs `std/core`'s
    /// `impl Hash for Char`, and `std/strings`' non-ASCII whitespace check
    /// (`char_is_whitespace`), and any future std module with the same need.
    /// Unlike every other builtin this is *not* a runtime call โ€” `Char` and
    /// `Int` are both `MirTy::I64`, so `nova-mir` lowers it to a register
    /// move (see `lower_call`) rather than adding a runtime ABI symbol whose
    /// body would be the identity function. Std-only, so `char_to_int` is
    /// not a reserved word in user code.
    CharToInt,
    /// `str_len_chars(s: String) -> Int` โ€” the number of Unicode scalar
    /// values in `s`. Backs `std/strings`' `String::len`. No primitive walks
    /// a `String`, so a length query has to be a builtin, and an `extern`
    /// cannot stand in because `String` is not FFI-safe. Note this builtin is
    /// part of what supplies the capability it names as absent, so read the
    /// absence as one about primitives and not about `String` as user code
    /// sees it. Separate from `str_chars` so a length query allocates
    /// nothing. Std-only, so it is not a reserved word in user code.
    StrLenChars,
    /// `str_chars(s: String) -> [Char]` โ€” the string's Unicode scalar values
    /// in order. Backs `std/strings`' `String::chars`, and every operation in
    /// that module that inspects a string. Also backs `std/core`'s
    /// `impl Debug for String`, which needs to escape the contents. Std-only.
    StrChars,
    /// `str_from_chars(cs: [Char]) -> String` โ€” encode codepoints as UTF-8.
    /// The inverse of [`Builtin::StrChars`], and how every `std/strings`
    /// operation that produces a string produces it: Nova has no `+` for
    /// `String` (`E0013`), so building a result any other way would mean
    /// quadratic interpolation. Std-only.
    StrFromChars,
    /// `str_join(sep: String, parts: [String]) -> String` โ€” `parts` with
    /// `sep` between each pair, copied byte for byte into one result. Backs
    /// `std/strings`' `String.join`, which otherwise has to walk every part
    /// character by character through [`Builtin::StrChars`] and
    /// [`Builtin::StrFromChars`]. Std-only.
    StrJoin,
    /// `str_index_of(haystack: String, needle: String) -> Int` โ€” the
    /// character index of the first occurrence of `needle`, or `-1`, found by
    /// a byte search. Backs `std/strings`' `String.index_of` and
    /// `String.contains`, which used to build a [`Builtin::StrChars`] array
    /// for each string first. Std-only.
    StrIndexOf,
    /// `json_quote(s: String) -> String` โ€” `s` as a JSON string literal,
    /// quotation marks included: the escaped length counted, then the result
    /// written once. Backs `std/json`'s `quote`, which used to scan a
    /// [`Builtin::StrChars`] array and rebuild any string that needed escaping
    /// character by character. Std-only.
    JsonQuote,
    /// `str_to_upper(s: String) -> String` โ€” full Unicode uppercase. Backs
    /// `std/strings`' `String::to_upper`. Whole-string rather than
    /// `Char` โ†’ `Char` because `รŸ` โ†’ `SS` is not 1:1. Std-only.
    StrToUpper,
    /// `str_to_lower(s: String) -> String` โ€” full Unicode lowercase, for the
    /// same reason as [`Builtin::StrToUpper`]. Std-only.
    StrToLower,
    /// `float_fixed(v: Float, places: Int) -> String` โ€” render `v` to a fixed
    /// number of decimal places. **Two callers, not one.** It was introduced
    /// for `std/fmt`'s `Float::fixed` (`std/fmt/lib.nova`), and `std/json`'s
    /// `impl FromJson for Int` (`std/json/lib.nova`) is now the second: it
    /// takes an integral `Float`'s digits from `float_fixed(n, 0)` because
    /// `Float`'s `Display` is a shortest-round-trip rendering rather than an
    /// exact one. So a change to its rounding or its clamping reaches the JSON
    /// decode path as well as `std/fmt`. Nova cannot implement this itself:
    /// decimal rendering of a binary float is a solved problem with sharp
    /// edges, and Nova has no `Float` to `Int` conversion at all to begin one
    /// with. Std-only.
    FloatFixed,
    /// `str_to_float(s: String) -> Float` โ€” parse decimal text as a `Float`.
    /// **Two callers, not one.** It was introduced for `std/json`'s number
    /// scanner, and `impl ToJson for Int` is now the second, which does not go
    /// through the scanner at all. The exact mirror of [`Builtin::FloatFixed`],
    /// and a builtin for the same reason: correctly rounded decimal-to-binary
    /// conversion is a solved problem with sharp edges, and the obvious
    /// `digits ร— 10^exp` accumulation double-rounds โ€” once into the
    /// significand, once into the scaling โ€” so a Nova reimplementation would
    /// not round-trip its own output. That is the whole of the refusal. The
    /// language also has no `Int` โ†’ `Float` conversion (no such builtin, and
    /// `as` casts are unsupported, `E0900`), but that is a cost rather than a
    /// wall: an if/else chain from `Int` to a `Float` literal spans any fixed
    /// digit range, the same construction `std/json`'s `hex_digit` used over
    /// sixteen arms to reach `String` literals, until [`Builtin::JsonQuote`]
    /// replaced it on 2026-10-03. Std-only, so
    /// `str_to_float` is not a reserved word in user code.
    StrToFloat,
    /// `test_selector() -> Int` โ€” which `@test` to run in this process, or a
    /// negative value meaning "print the inventory instead".
    ///
    /// Reads `NOVA_TEST_INDEX`. A negative value is the sentinel rather than
    /// "index >= count", because producing a negative needs no knowledge of the
    /// count โ€” and "greater than or equal" would require the runner to already
    /// know the number it is asking for. An absent or unparseable variable
    /// reads as negative, so running the test binary by hand with no variable
    /// set prints its inventory rather than silently doing nothing.
    ///
    /// `STD_ONLY`, like `str_cmp`: seeded into std modules' scopes only, so it
    /// never becomes a name a user program could call or collide with.
    TestSelector,
    /// `task_spawn(fut: Future<T>) -> Int` โ€” register a future with this
    /// thread's executor and return its task id. Backs `std/task`'s `spawn`.
    ///
    /// A builtin because its parameter is a `Future<T>`, which no `extern` can
    /// mention (`Future` is not FFI-safe, `require_ffi_safe` in `nova-typeck`)
    /// and no Nova expression can construct. Like every `Future`-taking builtin
    /// below it is typed with `Ty::Param(0)`, so it unifies only against a
    /// *generic parameter of index zero* โ€” which is why every `std/task`
    /// function that calls one declares exactly one type parameter, and why a
    /// second one declared before it is a compile error at the call site
    /// (`E0010`) rather than anything quieter. Std-only, so `task_spawn` is not
    /// a reserved word in user code.
    TaskSpawn,
    /// `task_is_done(fut: Future<T>) -> Bool` โ€” whether the task named by
    /// `fut`'s state has completed.
    ///
    /// Backed `JoinHandle::join`'s spin loop before Task 3 replaced it with a
    /// real park on completion ([`Builtin::TaskJoinFuture`]); no call site in
    /// `std/task` remains, but the query is still part of the executor's
    /// Nova-facing surface. Std-only.
    TaskIsDone,
    /// `task_release(fut: Future<T>)` โ€” end the executor's claim on the task
    /// named by `fut`'s state, so a joined task's state is not rooted for the
    /// rest of the process. Idempotent, which is what lets `join` be called
    /// twice on one handle. Std-only.
    TaskRelease,
    /// `task_drive(fut: Future<T>)` โ€” run this thread's executor until every
    /// queued task has finished. Backs `std/task`'s `block_on`, paired with
    /// [`Builtin::TaskOutput`] to read the value: the runtime returns the
    /// output as an `i64`, which is not the machine class of a `Float`.
    /// Std-only.
    TaskDrive,
    /// `task_output(fut: Future<T>) -> T` โ€” the value a finished future wrote
    /// to its state object's output slot.
    ///
    /// Unlike every other builtin here this is *not* a runtime call: it is two
    /// typed field loads (`nova-mir`'s `lower_call`), which is the only way the
    /// value can arrive in `T`'s own machine class โ€” a `Float` output crosses
    /// register banks, so routing it through the executor's `i64` return would
    /// reinterpret its bits. Safe to read at any point after the future has
    /// completed, and any number of times, because the value stays in the state
    /// object and the future keeps that object alive. Std-only.
    TaskOutput,
    /// `task_yield_future() -> Future<unit>` โ€” a fresh future that reports
    /// pending once and then completes.
    ///
    /// The whole of what `std/task`'s `yield_now` awaits, and it has to be a
    /// builtin because a Nova `async fn` body suspends *only* at an `.await`:
    /// there is nothing in the language to await that is not already ready.
    /// Its future is built by `nova_rt_task_yield_future`, the one poll
    /// function `nova-mir`'s async transform did not generate. Std-only.
    TaskYieldFuture,
    /// `task_sleep_future_nanos(nanos: Int) -> Future<unit>` โ€” a fresh future
    /// that parks for `nanos` nanoseconds, then completes.
    ///
    /// The first builtin that actually parks: unlike
    /// [`Builtin::TaskYieldFuture`], which always resumes on the next turn,
    /// this future registers a deadline with the executor's park set (Task
    /// 1's `Wait::Deadline`) and is not polled again until that deadline
    /// passes. Backs `std/time`'s `sleep`. A builtin for the same reason
    /// `task_yield_future` is: an `async fn` body suspends only at an
    /// `.await`, and nothing expressible in Nova produces a future that
    /// starts out pending. Std-only.
    TaskSleepFutureNanos,
    /// `task_join_future(fut: Future<T>) -> Future<unit>` โ€” a fresh future
    /// that parks until the task named by `fut`'s state completes, then
    /// completes itself.
    ///
    /// Resolves `fut` to a task id up front, through the same state-address
    /// lookup [`Builtin::TaskIsDone`]/[`Builtin::TaskRelease`] use, so a
    /// future no task was spawned for aborts immediately rather than
    /// becoming a park nothing can wake. Backs `std/task`'s `join`, which
    /// used to spin on [`Builtin::TaskIsDone`] instead: joining a task that
    /// is parked with nothing left in the program that could ever wake it โ€”
    /// for example, two tasks joining each other in a cycle โ€” now reports a
    /// deadlock rather than costing one poll per turn forever. Joining a
    /// task parked on a deadline (one that is sleeping) is not, by itself,
    /// this. Joining a task that never finishes because it keeps
    /// re-queueing itself (a `yield_now` loop) is a livelock, not a
    /// deadlock, and is not reported: nothing there is parked, so it still
    /// costs one poll per turn forever, undiagnosed
    /// (`docs/adr/0009-async-execution-model.md` ยง1's 2026-08-10 amendment).
    /// A builtin for the same reason `task_sleep_future_nanos`
    /// is: an `async fn` body suspends only at an `.await`, and nothing
    /// expressible in Nova produces a future that starts out pending.
    /// Std-only.
    TaskJoinFuture,
    /// `task_timeout_future(nanos: Int, fut: Future<T>) -> Future<Int>` โ€” a
    /// fresh future that polls `fut` until it completes or `nanos` nanoseconds
    /// pass, producing `0` if the inner future completed and `1` if the
    /// deadline elapsed.
    ///
    /// Carries a status rather than the value, which is what keeps it
    /// expressible: a builtin's signature is a fixed list of types, and the
    /// value is read separately with [`Builtin::TaskOutput`] on the inner
    /// future, from the slot the inner future itself wrote. Backs `std/time`'s
    /// `timeout`. Std-only.
    TaskTimeoutFuture,
    /// `fs_read_to_string(path: String) -> Int` โ€” read `path` as UTF-8.
    ///
    /// Returns a status code (`0` on success, an `IoErrorKind` code otherwise
    /// โ€” see `crates/nova-runtime/src/fs.rs`), not the string itself: an
    /// intrinsic returns exactly one word, and this call must convey both a
    /// `String` and enough information to build an `IoError`. On success the
    /// contents are waiting in [`Builtin::FsTakeString`]. Backs `std/fs`'s
    /// `read_to_string`. Std-only.
    FsReadToString,
    /// `fs_write_string(path: String, content: String) -> Int` โ€” write
    /// `content` to `path`, truncating any existing contents. A status code,
    /// for the same reason as [`Builtin::FsReadToString`]. Backs `std/fs`'s
    /// `write_string`. Std-only.
    FsWriteString,
    /// `fs_take_string() -> String` โ€” take the payload staged by a successful
    /// [`Builtin::FsReadToString`]. Backs `std/fs`'s `read_to_string`.
    /// Std-only.
    FsTakeString,
    /// `fs_last_error_message() -> String` โ€” take the OS-provided message
    /// staged by a failed filesystem operation. Backs `std/fs`'s
    /// `read_to_string` and `write_string`. Std-only.
    FsLastErrorMessage,
    /// `fs_temp_dir() -> String` โ€” the OS temporary-directory path
    /// (`std::env::temp_dir()`, lossily reencoded from UTF-16 on Windows โ€”
    /// see `crates/nova-runtime/src/fs.rs`). Backs `std/fs`'s `temp_dir`.
    /// Not a runtime-call-only concern: this is what lets a fixture build a
    /// writable path without hardcoding one. Std-only.
    FsTempDir,
    /// `fs_exists(path: String) -> Bool` โ€” whether `path` exists on disk.
    /// Not a status code like its siblings: `nova-spec/20-STDLIB.md` ยง5
    /// gives `exists` a plain `Bool`, so a path that exists but cannot be
    /// examined is indistinguishable from one that is absent. Backs
    /// `std/fs`'s `exists`. Std-only.
    FsExists,
    /// `fs_create_dir(path: String) -> Int` โ€” create the directory `path`.
    /// Its parent must exist; an existing `path` is `AlreadyExists`. A
    /// status code, for the same reason as [`Builtin::FsReadToString`].
    /// Backs `std/fs`'s `create_dir`. Std-only.
    FsCreateDir,
    /// `fs_create_dir_all(path: String) -> Int` โ€” create the directory
    /// `path`, and any missing parent directories along the way. Unlike
    /// [`Builtin::FsCreateDir`], an already-existing directory at `path` is
    /// success, not `AlreadyExists`. Backs `std/fs`'s `create_dir_all`.
    /// Std-only.
    FsCreateDirAll,
    /// `fs_remove_file(path: String) -> Int` โ€” remove the file `path`. A
    /// status code, for the same reason as [`Builtin::FsReadToString`].
    /// Backs `std/fs`'s `remove_file`. Std-only.
    FsRemoveFile,
    /// `fs_remove_dir_all(path: String) -> Int` โ€” remove the directory
    /// `path` and everything beneath it. A status code, for the same reason
    /// as [`Builtin::FsReadToString`]. Backs `std/fs`'s `remove_dir_all`.
    /// Std-only.
    FsRemoveDirAll,
    /// `fs_read_dir(path: String) -> Int` โ€” list `path`'s entry names,
    /// sorted. A status code, for the same reason as
    /// [`Builtin::FsReadToString`]; on success the names are waiting in
    /// [`Builtin::FsTakeStringArray`]. Sorted in the runtime because
    /// directory order is unspecified by every OS. Backs `std/fs`'s
    /// `read_dir`. Std-only.
    FsReadDir,
    /// `fs_take_string_array() -> [String]` โ€” take the array staged by a
    /// successful [`Builtin::FsReadDir`]. Backs `std/fs`'s `read_dir`.
    /// Std-only.
    FsTakeStringArray,
    /// `fs_kind(path: String) -> Int` โ€” what `path` is: `0` metadata
    /// unavailable (absent, or unreadable), `1` file, `2` directory. One call
    /// rather than separate `is_file`/`is_dir` intrinsics, so a `DirEntry`
    /// costs one syscall instead of two and the two answers cannot disagree.
    /// Backs `std/fs`'s `read_dir`. Std-only.
    FsKind,
    /// `fs_read(path: String) -> Int` โ€” read the path's raw bytes. `0` on
    /// success, with the contents waiting in [`Builtin::FsTakeBytes`];
    /// otherwise an `IoErrorKind` status code (`crates/nova-runtime/src/fs.rs`).
    /// Unlike [`Builtin::FsReadToString`] this cannot report `InvalidData`:
    /// there is no encoding to violate. Backs `std/fs`'s `read`. Std-only.
    FsRead,
    /// `fs_take_bytes() -> Bytes` โ€” take the payload staged by a successful
    /// [`Builtin::FsRead`]. Backs `std/fs`'s `read`. Std-only.
    FsTakeBytes,
    /// `fs_write(path: String, content: Bytes) -> Int` โ€” write the bytes to
    /// the path, truncating an existing file. Status code, as
    /// [`Builtin::FsReadToString`]. Backs `std/fs`'s `write`. Std-only.
    FsWrite,
    /// `file_open(path: String, read: Bool, write: Bool, append: Bool,
    /// truncate: Bool, create: Bool, create_new: Bool) -> Int` โ€” open `path`
    /// through `std::fs::OpenOptions`, forwarding all six flags one for one.
    /// `0` on success, with the new fd waiting in [`Builtin::FsTakeBytes`] as
    /// an 8-byte little-endian payload โ€” the fd cannot travel in the status
    /// word because the status word already carries the `IoErrorKind`, the
    /// same reason [`Builtin::IoStdoutWrite`]'s byte count does not either;
    /// otherwise an `IoErrorKind` status code, as [`Builtin::FsReadToString`].
    /// The widest builtin in this table, one parameter per `OpenOptions`
    /// method rather than a packed bitmask, so the Nova surface matches
    /// `std::fs::OpenOptions` field for field. Runtime symbol
    /// `nova_rt_file_open` (`crates/nova-runtime/src/file.rs`). Std-only.
    FileOpen,
    /// `file_close(fd: Int) -> Int` โ€” close `fd`, dropping the underlying
    /// file and releasing its OS handle. Idempotent: closing an
    /// already-closed, stale, or forged fd finds nothing in the runtime's
    /// handle table and still reports success, so a caller may close the
    /// same value more than once. No payload, mirroring
    /// [`Builtin::IoStdoutFlush`]. Runtime symbol `nova_rt_file_close`
    /// (`crates/nova-runtime/src/file.rs`). Std-only.
    FileClose,
    /// `file_read(fd: Int, max: Int) -> Int` โ€” read up to `max` bytes from
    /// `fd`, the same status/payload shape as [`Builtin::IoStdinRead`]. `0`
    /// on success, with the bytes read waiting in [`Builtin::FsTakeBytes`];
    /// otherwise an `IoErrorKind` status code, as [`Builtin::FsReadToString`]
    /// โ€” including a closed, stale, or forged fd, which the runtime's handle
    /// table reports as an ordinary `IoError` rather than a panic. An
    /// **empty** payload means end of stream; a short read does not. Runtime
    /// symbol `nova_rt_file_read` (`crates/nova-runtime/src/file.rs`).
    /// Std-only.
    FileRead,
    /// `file_write(fd: Int, buf: Bytes) -> Int` โ€” write `buf` to `fd` with
    /// one `Write::write` call, not a `write_all` loop, the same shape as
    /// [`Builtin::IoStdoutWrite`]. `0` on success, with the number of bytes
    /// actually written waiting in [`Builtin::FsTakeBytes`], encoded as an
    /// 8-byte little-endian count; otherwise an `IoErrorKind` status code, as
    /// [`Builtin::FsReadToString`] โ€” including a closed, stale, or forged
    /// fd, as [`Builtin::FileRead`]. Runtime symbol `nova_rt_file_write`
    /// (`crates/nova-runtime/src/file.rs`). Std-only.
    FileWrite,
    /// `file_flush(fd: Int) -> Int` โ€” flush `fd`. A status code, as
    /// [`Builtin::FsReadToString`], including a closed, stale, or forged fd,
    /// as [`Builtin::FileRead`]; unlike [`Builtin::FileWrite`], a successful
    /// flush stashes no payload of its own for [`Builtin::FsTakeBytes`] to
    /// collect, mirroring [`Builtin::IoStdoutFlush`]. Runtime symbol
    /// `nova_rt_file_flush` (`crates/nova-runtime/src/file.rs`). Std-only.
    FileFlush,
    /// `io_stdin_read(max: Int) -> Int` โ€” read up to `max` bytes from stdin,
    /// the same status/payload shape as [`Builtin::FsRead`]. `0` on success,
    /// with the bytes read waiting in [`Builtin::FsTakeBytes`]; otherwise an
    /// `IoErrorKind` status code, as [`Builtin::FsReadToString`]. An
    /// **empty** payload means end of stream; a short read does not. Runtime
    /// symbol `nova_rt_io_stdin_read` (`crates/nova-runtime/src/io.rs`).
    /// Std-only.
    IoStdinRead,
    /// `io_stdout_write(buf: Bytes) -> Int` โ€” write `buf` to stdout with one
    /// `Write::write` call, not a `write_all` loop, so a short write is
    /// reported rather than retried underneath the caller. `0` on success,
    /// with the number of bytes actually written waiting in
    /// [`Builtin::FsTakeBytes`], encoded as an 8-byte little-endian count;
    /// otherwise an `IoErrorKind` status code, as [`Builtin::FsReadToString`].
    /// Runtime symbol `nova_rt_io_stdout_write`
    /// (`crates/nova-runtime/src/io.rs`). Std-only.
    IoStdoutWrite,
    /// `io_stderr_write(buf: Bytes) -> Int` โ€” write `buf` to stderr. Mirrors
    /// [`Builtin::IoStdoutWrite`] exactly, against the other stream.
    /// Std-only.
    IoStderrWrite,
    /// `io_stdout_flush() -> Int` โ€” flush stdout. A status code, as
    /// [`Builtin::FsReadToString`]; unlike [`Builtin::IoStdoutWrite`], a
    /// successful flush stashes no payload of its own for
    /// [`Builtin::FsTakeBytes`] to collect -- it does not clear whatever a
    /// prior operation left there either. Std-only.
    IoStdoutFlush,
    /// `io_stderr_flush() -> Int` โ€” flush stderr. Mirrors
    /// [`Builtin::IoStdoutFlush`] exactly, against the other stream.
    /// Std-only.
    IoStderrFlush,
    /// `net_connect(addr: String) -> Future<Int>` โ€” connect to `addr`
    /// ("host:port"), non-blockingly.
    ///
    /// **A future constructor, not a status word โ€” the one thing that makes
    /// this builtin and the other future constructors in this group
    /// ([`Builtin::NetRead`], [`Builtin::NetWrite`],
    /// [`Builtin::NetReadTimeout`], [`Builtin::NetAccept`]) unlike every
    /// `fs_*`/`file_*`/`io_*` intrinsic above.** Named rather than counted
    /// positionally, and deliberately with no count at all: the variants below
    /// this one are a mix of future constructors and status words in no
    /// particular order, so "the three below it" would read as "the next
    /// three" and be wrong that way, and any number written here goes stale
    /// the next time `std/net` grows โ€” **this sentence has already been
    /// rewritten twice for exactly that reason**, once when
    /// [`Builtin::NetLocalPort`] landed and again when
    /// [`Builtin::NetAccept`] did.
    ///
    /// The archaeology that used to close this paragraph is retracted rather
    /// than recounted. It said: "Two rewrites over three staleness events:
    /// `main`'s 'the three below it' first went wrong when
    /// [`Builtin::NetListen`] arrived and was left standing for an
    /// increment." The count and the ordinal are both wrong, under either
    /// reading of the wording they describe. Read as its own words invite --
    /// the next three variants -- "the three below it" was **already** wrong
    /// on `main`, because [`Builtin::NetClose`] is the variant directly below
    /// and is not a future constructor at all. Read as the three *other*
    /// future constructors, it stayed true through both
    /// [`Builtin::NetListen`] and [`Builtin::NetLocalPort`], since both are
    /// status words, and only [`Builtin::NetAccept`] falsified it. So
    /// [`Builtin::NetListen`] falsified no wording here at all. The sentence
    /// it did falsify was [`Builtin::NetClose`]'s own "the one member of this
    /// group of five", and that was corrected in the very commit that added
    /// [`Builtin::NetListen`] rather than left standing.
    ///
    /// Those status words return an `i64` directly and synchronously; this
    /// one returns a `*mut u8` future state object
    /// (surfaced to Nova as `Future<Int>`) that must itself be `.await`ed to
    /// produce the `Int` status โ€” `0` on success, with the new fd waiting in
    /// [`Builtin::FsTakeBytes`] as an 8-byte little-endian payload, the same
    /// reason [`Builtin::FileOpen`]'s new fd travels that way; otherwise an
    /// `IoErrorKind` status code, as [`Builtin::FsReadToString`], including
    /// `CONNECTION_REFUSED`'s first producer. A reader arriving here from
    /// `file.rs` should not expect the old shape. Runtime symbol
    /// `nova_rt_net_connect_future` (`crates/nova-runtime/src/net.rs`).
    /// Std-only.
    NetConnect,
    /// `net_close(fd: Int) -> Int` โ€” close `fd`, dropping the underlying
    /// handle and releasing its OS handle.
    ///
    /// **Not a future constructor**, unlike every future constructor
    /// [`Builtin::NetConnect`]'s own doc comment rosters โ€” an ordinary status
    /// word, exactly [`Builtin::FileClose`]'s shape, for the identical reason:
    /// idempotent,
    /// since `std/net`'s `close` cannot consume its receiver (Nova has no
    /// move checking), so a caller can always reach a second call, and
    /// closing an already-closed, stale, or forged fd finds nothing in the
    /// runtime's handle table and still reports success. No payload. Runtime
    /// symbol `nova_rt_net_close` (`crates/nova-runtime/src/net.rs`).
    ///
    /// That contrast read "unlike [`Builtin::NetConnect`] and the read/write
    /// group below it", phrased that way in the commit that added
    /// [`Builtin::NetListen`] so it would survive the group growing. It did
    /// not survive [`Builtin::NetAccept`], which is a future constructor
    /// below this one and is neither a read nor a write, so the one variant
    /// added after the rewrite is exactly the one the growth-proof phrasing
    /// excluded. Deferring to [`Builtin::NetConnect`]'s roster leaves one
    /// list to keep current instead of two that can disagree.
    ///
    /// **Serves a listener as well as a connected stream**, which is why
    /// [`Builtin::NetListen`] adds no close of its own: the runtime keeps both
    /// kinds in one handle table and removes an entry by key regardless of
    /// which kind it holds. `TcpListener::close` in `std/net` calls this same
    /// builtin. Std-only.
    NetClose,
    /// `net_read(fd: Int, max: Int) -> Future<Int>` โ€” read up to `max` bytes
    /// from `fd`, non-blockingly.
    ///
    /// A future constructor, as [`Builtin::NetConnect`]'s doc comment
    /// explains โ€” `.await`ing it produces `0` on success, with the bytes
    /// read waiting in [`Builtin::FsTakeBytes`]; otherwise an `IoErrorKind`
    /// status code, as [`Builtin::FsReadToString`] โ€” including a closed,
    /// stale, or forged fd. An **empty** payload means end of stream; a
    /// short read does not, the same contract [`Builtin::FileRead`] and
    /// [`Builtin::IoStdinRead`] already carry. Runtime symbol
    /// `nova_rt_net_read_future` (`crates/nova-runtime/src/net.rs`).
    /// Std-only.
    NetRead,
    /// `net_write(fd: Int, buf: Bytes) -> Future<Int>` โ€” write `buf` to `fd`
    /// with one non-blocking `Write::write` attempt, not a `write_all` loop.
    ///
    /// A future constructor, as [`Builtin::NetConnect`]'s doc comment
    /// explains โ€” `.await`ing it produces `0` on success, with the number of
    /// bytes actually written waiting in [`Builtin::FsTakeBytes`], encoded
    /// as an 8-byte little-endian count, the same shape
    /// [`Builtin::FileWrite`] uses; otherwise an `IoErrorKind` status code,
    /// as [`Builtin::FsReadToString`] โ€” including a closed, stale, or forged
    /// fd. Runtime symbol `nova_rt_net_write_future`
    /// (`crates/nova-runtime/src/net.rs`). Std-only.
    NetWrite,
    /// `net_read_timeout(fd: Int, max: Int, ms: Int) -> Future<Int>` โ€” read
    /// up to `max` bytes from `fd`, non-blockingly, reporting `TIMED_OUT` if
    /// `ms` milliseconds pass with nothing to read first.
    ///
    /// A future constructor, as [`Builtin::NetConnect`]'s doc comment
    /// explains โ€” otherwise identical to [`Builtin::NetRead`], including
    /// EOF/short-read semantics and where the bytes land on success. Runtime
    /// symbol `nova_rt_net_read_timeout_future`
    /// (`crates/nova-runtime/src/net.rs`). Std-only.
    NetReadTimeout,
    /// `net_listen(addr: String) -> Int` โ€” bind and listen on `addr`
    /// ("host:port"), registering a non-blocking listening socket.
    ///
    /// **Not a future constructor**, one of the three builtins in this group
    /// that are not, with [`Builtin::NetClose`] and
    /// [`Builtin::NetLocalPort`]: the `bind` and `listen` *syscalls*
    /// are immediate kernel bookkeeping and do not block, so there is no
    /// suspension to model and `std/net`'s `bind` is a plain `fn` rather than
    /// an `async fn`. The waiting a server does happens in
    /// [`Builtin::NetAccept`], which is a separate builtin and *is* a future
    /// constructor.
    ///
    /// **That is a claim about the syscalls, not about every argument.** A
    /// numeric address never blocks, but this builtin's parameter is a
    /// `String` a user program chooses, and a hostname resolves through
    /// `std`'s `ToSocketAddrs` โ€” a blocking lookup with no future to park on.
    /// `resolve_addr`'s own doc comment in `crates/nova-runtime/src/net.rs`
    /// records that caveat for `connect`, and it applies here unchanged:
    /// out of scope rather than handled. `nova_rt_net_listen`'s doc comment
    /// also records where its resolution *differs* from `connect`'s, since it
    /// does not go through `resolve_addr` at all.
    ///
    /// Returns a status code as [`Builtin::FsReadToString`] does โ€” `0` on
    /// success, with the new fd waiting in [`Builtin::FsTakeBytes`] as an
    /// 8-byte little-endian payload, the same channel [`Builtin::NetConnect`]
    /// and [`Builtin::FileOpen`] use for their own fds. The fd is closed with
    /// [`Builtin::NetClose`], which serves both kinds of handle.
    ///
    /// **An address already in use arrives as `Other`, not a distinct kind.**
    /// `fs.rs`'s `IoErrorKind` table has no `AddrInUse` variant, so the most
    /// likely failure of this builtin is discriminable only by the message
    /// text the operating system supplied. Adding a variant is a wire-contract
    /// change across the runtime's `fail` and `std/io`'s `io_error_kind_of`
    /// together, and is deliberately not done. Runtime symbol
    /// `nova_rt_net_listen` (`crates/nova-runtime/src/net.rs`). Std-only.
    NetListen,
    /// `net_local_port(fd: Int) -> Int` โ€” the port the listening socket behind
    /// `fd` is bound to, which is how a caller learns the kernel's choice after
    /// [`Builtin::NetListen`] on port 0.
    ///
    /// **Not a future constructor**, joining [`Builtin::NetClose`] and
    /// [`Builtin::NetListen`] rather than the future constructors
    /// [`Builtin::NetConnect`]'s own doc comment rosters. This read "the third
    /// builtin in this group that is not", contrasted "rather than the
    /// read/write group": the ordinal ranks within a group that grows, and
    /// "the read/write group" stopped naming the future constructors the
    /// moment [`Builtin::NetAccept`] joined them, which is the same pair of
    /// habits corrected at [`Builtin::NetConnect`] and [`Builtin::NetClose`]
    /// above. `local_addr` is a `getsockname` call over
    /// bookkeeping the kernel already holds, so there is no suspension to model
    /// and `std/net`'s `local_port` is a plain `fn` rather than an `async fn`.
    ///
    /// **Unlike [`Builtin::NetListen`], that claim needs no caveat about its
    /// argument.** This builtin takes an `Int` fd, not a `String`, so there is
    /// no address for `std`'s `ToSocketAddrs` to resolve and no blocking lookup
    /// to reach. It really cannot block, on any argument.
    ///
    /// Returns a status code as [`Builtin::FsReadToString`] does โ€” `0` on
    /// success, **with the port waiting in [`Builtin::FsTakeBytes`]** as an
    /// 8-byte little-endian payload, the same channel [`Builtin::NetListen`]'s
    /// and [`Builtin::NetConnect`]'s fds ride. The port cannot ride the return
    /// value instead: that word *is* the `IoErrorKind` status, so a port there
    /// would make `0` ambiguous and every non-zero port indistinguishable from
    /// a failure.
    ///
    /// **An `fd` naming a connected stream rather than a listener is an error
    /// here, and an `Other` one.** The runtime keeps both kinds of handle in
    /// one table and its kind-checked lookup collapses wrong-kind into the same
    /// miss an absent, closed, stale or forged fd gives โ€” so a stream's own
    /// local port is unreachable through this builtin, and no distinguishable
    /// wrong-kind status exists to rely on. Runtime symbol
    /// `nova_rt_net_local_port` (`crates/nova-runtime/src/net.rs`). Std-only.
    NetLocalPort,
    /// `net_accept(fd: Int) -> Future<Int>` โ€” wait for the next incoming
    /// connection on the listening socket behind `fd`.
    ///
    /// A future constructor, as [`Builtin::NetConnect`]'s doc comment
    /// explains โ€” unlike [`Builtin::NetClose`] and [`Builtin::NetLocalPort`],
    /// which are status words because their syscalls cannot wait on a peer.
    /// Waiting on a peer is the whole of what this one does, which is why
    /// `std/net`'s `accept` is an `async fn` while `bind` and
    /// `TcpListener::local_port` beside it are plain `fn`s. `.await`ing it
    /// produces `0` on success, with the accepted
    /// connection's new fd waiting in [`Builtin::FsTakeBytes`] as an 8-byte
    /// little-endian payload, the same channel [`Builtin::NetListen`]'s and
    /// [`Builtin::NetConnect`]'s own fds ride; otherwise an `IoErrorKind`
    /// status code, as [`Builtin::FsReadToString`] โ€” including a closed,
    /// stale, or forged fd, and an fd naming a connected stream rather than a
    /// listener, which is the same wrong-kind miss
    /// [`Builtin::NetLocalPort`] describes.
    ///
    /// **The accepted fd is an ordinary `TcpStream` fd**, indistinguishable
    /// from one [`Builtin::NetConnect`] produced, so
    /// [`Builtin::NetRead`]/[`Builtin::NetWrite`]/[`Builtin::NetReadTimeout`]
    /// and [`Builtin::NetClose`] all work on it unchanged.
    ///
    /// **A task parked here cannot also be waiting on a connection.** Staging
    /// two I/O waits in one poll ends the process (`stage_park` in
    /// `crates/nova-runtime/src/task.rs`), so a server that accepts while
    /// serving needs at least two tasks, and this language has no
    /// `select`/`race` to avoid that. Runtime symbol
    /// `nova_rt_net_accept_future` (`crates/nova-runtime/src/net.rs`).
    /// Std-only.
    NetAccept,
    /// `bytes_len(b: Bytes) -> Int` โ€” the byte length. Not a character
    /// count: `Bytes` has no encoding. Backs `std/bytes`'s `Bytes::len`.
    /// No primitive reads a `Bytes` value's own header, exactly as none walks
    /// a `String`, so this reaches the runtime the same way `str_len_chars`
    /// does -- and as there, the absence is one about primitives rather than
    /// about what `std/bytes` then offers on top of them. Std-only.
    BytesLen,
    /// `bytes_from_string_intrinsic(s: String) -> Bytes` โ€” a `Bytes` holding
    /// `s`'s UTF-8 bytes. Backs the free function `bytes_from_string` in
    /// `std/bytes/lib.nova`.
    ///
    /// **Named `..._intrinsic`, not `bytes_from_string`, deliberately.**
    /// `std/bytes` is itself an entry of [`STD_MODULES`], so `Builtin::STD_ONLY`
    /// is seeded into its *own* scope before that module's items are
    /// collected (see `resolve_program`'s pass order). A `pub fn
    /// bytes_from_string` in that same file would then hit `insert_value`'s
    /// `scope.values.contains_key` check against this builtin's own
    /// pre-seeded entry and fail name resolution with `E0002 duplicate
    /// definition` โ€” **not** silently compile into a recursive call, and not
    /// silently shadow the builtin either; `insert_value` has no soft/shadow
    /// path for a module's own item colliding with something already in its
    /// own scope, unlike the separate, later, `entry`-style glob import
    /// `import_std_module` uses to let one *std module's* export lose to
    /// another module's own definition. Verified empirically (see the Task 2
    /// report): naming this builtin `bytes_from_string` reproduces the
    /// `E0002` against `std/bytes/lib.nova` itself, on every compile. Std-only.
    BytesFromString,
    /// `bytes_is_utf8(b: Bytes) -> Bool` โ€” whether `b`'s bytes are valid
    /// UTF-8. Backs `std/bytes`'s `Bytes::to_string`, paired with
    /// [`Builtin::BytesToStringUnchecked`] so that method can be a Nova-level
    /// `if` rather than needing a status-code protocol for one boolean.
    /// Std-only.
    BytesIsUtf8,
    /// `bytes_to_string_unchecked(b: Bytes) -> String` โ€” `b`'s bytes as a
    /// `String`, without checking UTF-8 validity. Backs `std/bytes`'s
    /// `Bytes::to_string`, whose only call site checks
    /// [`Builtin::BytesIsUtf8`] first โ€” an invalid `String` would be unsound,
    /// which is why that check is not optional at the call site even though
    /// this builtin cannot enforce it itself. Std-only.
    BytesToStringUnchecked,
    /// `bytes_at(b: Bytes, i: Int) -> Int` โ€” the byte at `i`, in `0..=255`.
    /// Backs `std/bytes`'s `Bytes::byte_at`, which bounds-checks `i` first and
    /// returns `Option`; this intrinsic aborts on an out-of-range index rather
    /// than returning a sentinel, since that path guards a `std/bytes` bug
    /// rather than a user mistake. Nova cannot index a `Bytes` value's own
    /// buffer (no indexing operator reaches the runtime), so this reaches the
    /// runtime the same way `bytes_len` does. Std-only.
    BytesAt,
    /// `bytes_slice(b: Bytes, start: Int, end: Int) -> Bytes` โ€” the bytes in
    /// `start..end`, clamped to the buffer and to `start <= end`. Backs
    /// `std/bytes`'s `Bytes::slice`. Clamps rather than aborting โ€” a
    /// deliberate divergence from `std/strings`'s `String::slice`, which
    /// panics on an out-of-range bound; a `Bytes` length often comes from
    /// disk rather than from a caller who already knows it, so clamping is
    /// the better failure mode here. Recorded, accepted divergence โ€” see the
    /// design spec's dated note โ€” not agreement with `String::slice`.
    /// Std-only.
    BytesSlice,
    /// `bytes_concat(a: Bytes, b: Bytes) -> Bytes` โ€” `a`'s bytes followed by
    /// `b`'s. Backs `std/bytes`'s `Bytes::concat`. Std-only.
    BytesConcat,
    /// `bytes_to_ints(b: Bytes) -> [Int]` โ€” each byte as an `Int` in
    /// `0..=255`, in order. Backs `std/bytes`'s `Bytes::to_ints`, and in turn
    /// `index_of`/`contains`, which search over the resulting array in Nova
    /// rather than through a per-search intrinsic. Std-only.
    BytesToInts,
    /// `bytes_from_ints_intrinsic(ints: [Int]) -> Bytes` โ€” a `Bytes` holding
    /// each element of `ints` as one byte. Aborts if any element is outside
    /// `0..=255`. Backs the free function `bytes_from_ints` in
    /// `std/bytes/lib.nova`.
    ///
    /// **Named `..._intrinsic`, not `bytes_from_ints`, for the same reason as
    /// [`Builtin::BytesFromString`]** โ€” see that variant's doc comment.
    /// `std/bytes` is itself an entry of [`STD_MODULES`], so a `pub fn
    /// bytes_from_ints` there sharing this builtin's name would collide with
    /// its own pre-seeded builtin entry (`insert_value`'s `E0002`) rather than
    /// calling it. Std-only.
    BytesFromInts,
    /// `bytes_eq(a: Bytes, b: Bytes) -> Bool` โ€” byte-for-byte equality. Backs
    /// `std/bytes`'s `impl Eq for Bytes`. A dedicated intrinsic rather than an
    /// operator lowering: unlike `String`'s `==` (a pure operator lowering
    /// straight to `nova_rt_str_eq`, see [`Builtin::StrCmp`]'s doc comment),
    /// `Bytes` equality is reached only through the `Eq` trait's `eq` method,
    /// so `binary_result_ty` needs no `Ty::Bytes` arm for `==`/`!=`. Std-only.
    BytesEq,
    /// `int_hash_seed() -> Int` โ€” the per-process seed for `std/core`'s `Int`,
    /// `Bool` and `Char` hashing, XORed into the input before `mix64` runs, as
    /// `nova_rt_int_hash_seed` draws it. What it buys is precomputation
    /// resistance: a colliding key set cannot be built offline against a
    /// process that has not started yet.
    ///
    /// A SEPARATE call from the one behind [`Builtin::StrHash`]'s seed. Were
    /// the two one value, `(0).hash()` would equal `("").hash()` exactly, since
    /// both reduce to the same finalizer applied to the seed alone. That the
    /// two differ is what the separate call buys; whether recovering one yields
    /// the other is a question about the draw's internals, answered at
    /// `int_hash_seed` in `nova-runtime` and not settled there either.
    ///
    /// **Nova code can recover this value in one call**, since those `Hash`
    /// impls XOR it in: `(0).hash()` is `mix64(0 ^ seed)`, which is
    /// `mix64(seed)`, and `mix64` is an invertible bijection. That is the same
    /// shape `("").hash()` already has for the string seed, it follows from ADR
    /// 0005's one-shot `Hash` returning a plain `Int`, and the gate claim
    /// already declines the adaptive attacker for whom it matters.
    /// `tests/runtime/hash.nova` performs that recovery, to cancel the seed
    /// when it asserts `mix64`'s canonical vectors. Std-only.
    IntHashSeed,
    /// `http_parse_request(buf: Bytes) -> [Int]` โ€” an HTTP/1.1 request head
    /// parsed into a flat table of byte offsets into `buf` itself. Copies
    /// nothing, allocates nothing on the Rust heap, and holds no state between
    /// calls, so `std/http` has nothing to release and nothing to leak per
    /// request.
    ///
    /// Element 0 is a status: `0` complete, `1` partial (read more and call
    /// again), negative for an error. **On any non-zero status the array has
    /// length 1**, so a caller who skips the status check indexes out of
    /// bounds rather than reading a plausible-looking offset. The full
    /// encoding lives on `nova_rt_http_parse_request` in
    /// `crates/nova-runtime/src/http.rs`, which is the half that writes it.
    /// Std-only.
    HttpParseRequest,
    /// `crypto_hash(op: Int, key: Bytes, data: Bytes, tag: Bytes) -> Int` โ€”
    /// `std/crypto`'s hash/HMAC intrinsic: SHA-256, SHA-512, HMAC-SHA-256, or
    /// HMAC-SHA-256's constant-time tag check, selected by `op` (the `OP_*`
    /// constants in `crates/nova-runtime/src/crypto.rs`). Nova has no way to
    /// reach a vetted hash implementation from source, so every one of these
    /// operations crosses into Rust, which calls into `ring`.
    ///
    /// **The return is a status word, not the digest.** For the digest
    /// operations, `0` means success, with the digest waiting in
    /// [`Builtin::FsTakeBytes`]. For the tag check, `0` means the tag
    /// matched and `1` means it did not โ€” an answer, not an error. **No
    /// negative range at all**: none of `crypto_hash`'s operations can fail
    /// for any input a Nova program can construct. That scope is deliberate
    /// rather than hedging โ€” the digest, HMAC-key and HMAC-sign paths each
    /// end in an `.unwrap()` inside `ring`, on an input-length error needing
    /// roughly 2^61 bytes, so the bound is `ring`'s and not this tree's; the
    /// tag check's `ring::hmac::verify` returns a `Result` and unwraps
    /// nothing. `crates/nova-runtime/src/crypto.rs`'s `ERR_*` block states
    /// this at length.
    /// Runtime symbol `nova_rt_crypto_hash`
    /// (`crates/nova-runtime/src/crypto.rs`). Std-only.
    CryptoHash,
    /// `crypto_random_bytes(n: Int) -> Int` โ€” `std/crypto`'s random-bytes
    /// intrinsic: `n` bytes drawn from the OS entropy source via `ring`.
    /// Nova has no way to reach an OS entropy source from source, so this
    /// crosses into Rust.
    ///
    /// **The return is a status word, not the bytes.** `0` on success, with
    /// the bytes waiting in [`Builtin::FsTakeBytes`]; otherwise
    /// **negative**, naming one of `crypto.rs`'s `ERR_*` kinds โ€” an `n` that
    /// does not fit a `usize`, a request over the size cap, or the entropy
    /// source itself failing. Runtime symbol `nova_rt_crypto_random_bytes`
    /// (`crates/nova-runtime/src/crypto.rs`). Std-only.
    CryptoRandomBytes,
    /// `crypto_random_int(min: Int, max: Int) -> Int` โ€” `std/crypto`'s
    /// bounded random-integer intrinsic: a uniform draw from `min..=max` by
    /// rejection sampling against the OS entropy source. Nova has no way to
    /// reach an OS entropy source from source, so this crosses into Rust.
    ///
    /// **The return is a status word, not the integer.** `0` on success,
    /// with the value waiting in the same [`Builtin::FsTakeBytes`] slot that
    /// [`Builtin::CryptoHash`] and [`Builtin::CryptoRandomBytes`] use,
    /// decoded on the Nova side as `decode_count(fs_take_bytes())`;
    /// otherwise **negative**, naming one of `crypto.rs`'s `ERR_*` kinds.
    /// Three conditions reach that range, not two: an inverted range
    /// (`ERR_INVALID_RANGE`), the entropy source itself failing, and the
    /// bounded rejection loop running out of attempts without landing above
    /// the biased tail โ€” the last two share `ERR_ENTROPY_UNAVAILABLE`, so a
    /// caller cannot tell them apart. Runtime symbol
    /// `nova_rt_crypto_random_int`
    /// (`crates/nova-runtime/src/crypto.rs`). Std-only.
    CryptoRandomInt,
    /// `time_now_nanos() -> Int` โ€” nanoseconds since the runtime's single
    /// process epoch, monotonic and never negative.
    ///
    /// The only part of `std/time` that cannot be Nova code: `Instant` and
    /// `Duration` arithmetic is plain multiplication, division and
    /// subtraction over a private `Int`, so nothing else in ยง9 needs to cross
    /// into Rust. Saturates at `i64::MAX` rather than wrapping; see
    /// `nova_rt_time_now_nanos`. Std-only.
    TimeNowNanos,
    /// `time_now_epoch_nanos() -> Int` โ€” nanoseconds since the **Unix**
    /// epoch, as read by `nova_rt_time_now_epoch_nanos`. Distinct from
    /// `TimeNowNanos`, which is relative to this process's own start, not
    /// to 1970. Std-only.
    TimeNowEpochNanos,
    /// `log_config_level() -> Int` โ€” the logger's configured threshold, as
    /// `nova_rt_log_config_level` reads it. Std-only.
    LogConfigLevel,
    /// `log_config_to_stderr() -> Int` โ€” `1` for stderr, `0` for stdout, as
    /// `nova_rt_log_config_to_stderr` reads it. Std-only.
    LogConfigToStderr,
    /// `log_set_config(level: Int, to_stderr: Int) -> unit` โ€” install a
    /// logger configuration, overwriting any previous one, via
    /// `nova_rt_log_set_config`. Std-only.
    LogSetConfig,
    /// `shutdown_requested() -> Bool` โ€” whether the process has been asked to
    /// stop: the first SIGTERM or SIGINT on Unix, CTRL_BREAK or CTRL_C on
    /// Windows. The first call installs the handler that sets it, so a
    /// program that never calls this keeps every signal's default action.
    /// Read by `std/http`'s `Server::listen` and its connections, once per
    /// tick. Runtime symbol `nova_rt_shutdown_requested`
    /// (`crates/nova-runtime/src/signal.rs`, docs/adr/0022). Std-only.
    ShutdownRequested,
    /// `process_arg_count() -> Int` โ€” how many arguments the program has,
    /// counting the program itself at index 0. Runtime symbol
    /// `nova_rt_process_arg_count` (`crates/nova-runtime/src/process.rs`,
    /// docs/adr/0023). Std-only.
    ProcessArgCount,
    /// `process_arg(i: Int) -> String` โ€” argument `i`, or the empty string
    /// for an index out of range. Runtime symbol `nova_rt_process_arg`.
    /// Std-only.
    ProcessArg,
    /// `process_exit(code: Int) -> unit` โ€” ends the process with `code`
    /// after flushing stdout, and never returns. Runtime symbol
    /// `nova_rt_process_exit`. Std-only.
    ProcessExit,
}

impl Builtin {
    /// The source-level name of the builtin.
    pub fn name(self) -> &'static str {
        match self {
            Builtin::Println => "println",
            Builtin::Print => "print",
            Builtin::EPrint => "eprint",
            Builtin::EPrintln => "eprintln",
            Builtin::Panic => "panic",
            Builtin::StrCmp => "str_cmp",
            Builtin::StrHash => "str_hash",
            Builtin::CharToInt => "char_to_int",
            Builtin::StrLenChars => "str_len_chars",
            Builtin::StrChars => "str_chars",
            Builtin::StrFromChars => "str_from_chars",
            Builtin::StrJoin => "str_join",
            Builtin::StrIndexOf => "str_index_of",
            Builtin::JsonQuote => "json_quote",
            Builtin::StrToUpper => "str_to_upper",
            Builtin::StrToLower => "str_to_lower",
            Builtin::FloatFixed => "float_fixed",
            Builtin::StrToFloat => "str_to_float",
            Builtin::TestSelector => "test_selector",
            Builtin::TaskSpawn => "task_spawn",
            Builtin::TaskIsDone => "task_is_done",
            Builtin::TaskRelease => "task_release",
            Builtin::TaskDrive => "task_drive",
            Builtin::TaskOutput => "task_output",
            Builtin::TaskYieldFuture => "task_yield_future",
            Builtin::TaskSleepFutureNanos => "task_sleep_future_nanos",
            Builtin::TaskJoinFuture => "task_join_future",
            Builtin::TaskTimeoutFuture => "task_timeout_future",
            Builtin::FsReadToString => "fs_read_to_string",
            Builtin::FsWriteString => "fs_write_string",
            Builtin::FsTakeString => "fs_take_string",
            Builtin::FsLastErrorMessage => "fs_last_error_message",
            Builtin::FsTempDir => "fs_temp_dir",
            Builtin::FsExists => "fs_exists",
            Builtin::FsCreateDir => "fs_create_dir",
            Builtin::FsCreateDirAll => "fs_create_dir_all",
            Builtin::FsRemoveFile => "fs_remove_file",
            Builtin::FsRemoveDirAll => "fs_remove_dir_all",
            Builtin::FsReadDir => "fs_read_dir",
            Builtin::FsTakeStringArray => "fs_take_string_array",
            Builtin::FsKind => "fs_kind",
            Builtin::FsRead => "fs_read",
            Builtin::FsTakeBytes => "fs_take_bytes",
            Builtin::FsWrite => "fs_write",
            Builtin::FileOpen => "file_open",
            Builtin::FileClose => "file_close",
            Builtin::FileRead => "file_read",
            Builtin::FileWrite => "file_write",
            Builtin::FileFlush => "file_flush",
            Builtin::IoStdinRead => "io_stdin_read",
            Builtin::IoStdoutWrite => "io_stdout_write",
            Builtin::IoStderrWrite => "io_stderr_write",
            Builtin::IoStdoutFlush => "io_stdout_flush",
            Builtin::IoStderrFlush => "io_stderr_flush",
            Builtin::NetConnect => "net_connect",
            Builtin::NetClose => "net_close",
            Builtin::NetRead => "net_read",
            Builtin::NetWrite => "net_write",
            Builtin::NetReadTimeout => "net_read_timeout",
            Builtin::NetListen => "net_listen",
            Builtin::NetLocalPort => "net_local_port",
            Builtin::NetAccept => "net_accept",
            Builtin::BytesLen => "bytes_len",
            // Deliberately not "bytes_from_string" โ€” see this variant's doc
            // comment for why that would collide with `std/bytes`'s own
            // `pub fn bytes_from_string` wrapper.
            Builtin::BytesFromString => "bytes_from_string_intrinsic",
            Builtin::BytesIsUtf8 => "bytes_is_utf8",
            Builtin::BytesToStringUnchecked => "bytes_to_string_unchecked",
            Builtin::BytesAt => "bytes_at",
            Builtin::BytesSlice => "bytes_slice",
            Builtin::BytesConcat => "bytes_concat",
            Builtin::BytesToInts => "bytes_to_ints",
            // Deliberately not "bytes_from_ints" โ€” see this variant's doc
            // comment for why that would collide with `std/bytes`'s own
            // `pub fn bytes_from_ints` wrapper.
            Builtin::BytesFromInts => "bytes_from_ints_intrinsic",
            Builtin::BytesEq => "bytes_eq",
            Builtin::IntHashSeed => "int_hash_seed",
            Builtin::HttpParseRequest => "http_parse_request",
            Builtin::CryptoHash => "crypto_hash",
            Builtin::CryptoRandomBytes => "crypto_random_bytes",
            Builtin::CryptoRandomInt => "crypto_random_int",
            Builtin::TimeNowNanos => "time_now_nanos",
            Builtin::TimeNowEpochNanos => "time_now_epoch_nanos",
            Builtin::LogConfigLevel => "log_config_level",
            Builtin::LogConfigToStderr => "log_config_to_stderr",
            Builtin::LogSetConfig => "log_set_config",
            Builtin::ShutdownRequested => "shutdown_requested",
            Builtin::ProcessArgCount => "process_arg_count",
            Builtin::ProcessArg => "process_arg",
            Builtin::ProcessExit => "process_exit",
        }
    }

    /// Builtins injected into *every* module's scope โ€” part of the
    /// user-visible language surface, and reserved words everywhere.
    pub const GLOBAL: [Builtin; 5] = [
        Builtin::Println,
        Builtin::Print,
        Builtin::EPrint,
        Builtin::EPrintln,
        Builtin::Panic,
    ];

    /// Builtins injected only into an std module's own scope (any module in
    /// [`STD_MODULES`], not only `std/core`). These are implementation
    /// details of the standard library, not user-visible language surface:
    /// reserving one of these names in *every* module (as [`Builtin::GLOBAL`]
    /// does) would permanently take it away from user code to serve the
    /// standard library's own internals. Each member exists because Nova
    /// source cannot express what it does, and each is documented on its own
    /// variant above, next to the capability it provides and the reason the
    /// language cannot reach it. This list is membership only; call sites
    /// are a `grep` away and are deliberately not enumerated here: doing so
    /// produced stale or wrong counts in three places across three
    /// consecutive review rounds (see the Phase 2.2b whole-branch review),
    /// because the roster is duplicated information that only this array
    /// needs to stay exact.
    pub const STD_ONLY: [Builtin; 81] = [
        Builtin::StrCmp,
        Builtin::StrHash,
        Builtin::CharToInt,
        Builtin::StrLenChars,
        Builtin::StrChars,
        Builtin::StrFromChars,
        Builtin::StrJoin,
        Builtin::StrIndexOf,
        Builtin::JsonQuote,
        Builtin::StrToUpper,
        Builtin::StrToLower,
        Builtin::FloatFixed,
        Builtin::StrToFloat,
        Builtin::TestSelector,
        Builtin::TaskSpawn,
        Builtin::TaskIsDone,
        Builtin::TaskRelease,
        Builtin::TaskDrive,
        Builtin::TaskOutput,
        Builtin::TaskYieldFuture,
        Builtin::TaskSleepFutureNanos,
        Builtin::TaskJoinFuture,
        Builtin::TaskTimeoutFuture,
        Builtin::FsReadToString,
        Builtin::FsWriteString,
        Builtin::FsTakeString,
        Builtin::FsLastErrorMessage,
        Builtin::FsTempDir,
        Builtin::FsExists,
        Builtin::FsCreateDir,
        Builtin::FsCreateDirAll,
        Builtin::FsRemoveFile,
        Builtin::FsRemoveDirAll,
        Builtin::FsReadDir,
        Builtin::FsTakeStringArray,
        Builtin::FsKind,
        Builtin::FsRead,
        Builtin::FsTakeBytes,
        Builtin::FsWrite,
        Builtin::FileOpen,
        Builtin::FileClose,
        Builtin::FileRead,
        Builtin::FileWrite,
        Builtin::FileFlush,
        Builtin::IoStdinRead,
        Builtin::IoStdoutWrite,
        Builtin::IoStderrWrite,
        Builtin::IoStdoutFlush,
        Builtin::IoStderrFlush,
        Builtin::NetConnect,
        Builtin::NetClose,
        Builtin::NetRead,
        Builtin::NetWrite,
        Builtin::NetReadTimeout,
        Builtin::NetListen,
        Builtin::NetLocalPort,
        Builtin::NetAccept,
        Builtin::BytesLen,
        Builtin::BytesFromString,
        Builtin::BytesIsUtf8,
        Builtin::BytesToStringUnchecked,
        Builtin::BytesAt,
        Builtin::BytesSlice,
        Builtin::BytesConcat,
        Builtin::BytesToInts,
        Builtin::BytesFromInts,
        Builtin::BytesEq,
        Builtin::IntHashSeed,
        Builtin::HttpParseRequest,
        Builtin::CryptoHash,
        Builtin::CryptoRandomBytes,
        Builtin::CryptoRandomInt,
        Builtin::TimeNowNanos,
        Builtin::TimeNowEpochNanos,
        Builtin::LogConfigLevel,
        Builtin::LogConfigToStderr,
        Builtin::LogSetConfig,
        Builtin::ShutdownRequested,
        Builtin::ProcessArgCount,
        Builtin::ProcessArg,
        Builtin::ProcessExit,
    ];
}

/// Type names the compiler owns, which a user type declaration may not take.
///
/// `nova-typeck`'s `convert_ty` resolves each of these to its built-in type,
/// or to a shadowing generic parameter, wherever it runs โ€” never to a
/// declaration under this name, which is what `resolve_type` would have to
/// find instead. So a type declared under one of these names could never be
/// referred to in a type annotation.
///
/// That is narrower than "every use". A record literal resolves its head
/// through `resolve_type` directly, never through `convert_ty`
/// (`check_record_literal`), and a sum type's variants live in the *value*
/// namespace, independent of the type name โ€” so construction and pattern
/// matching for a type declared under one of these names worked before this
/// list was enforced. An `impl` header's self type is a `convert_ty` site
/// too, so an `impl` written for one of these names attaches to the
/// built-in, never to the declaration. So what worked before this list was
/// enforced was construction, pattern matching, and inferred local
/// bindings; a signature or an `impl` did not. See `CHANGELOG.md` for
/// exactly what this change breaks.
///
/// `Future` is here and is not a primitive: it is the one built-in type name
/// taking a type argument, handled separately from the nullary table.
/// `Unit` is deliberately absent โ€” it is not a nameable type name; unit is
/// spelled `()`.
///
/// `Bytes` joined later, for the same reason as the five original
/// primitives: an ordinary nullary entry in `convert_ty`'s table, with no
/// carve-out of its own like `Future`'s or `Unit`'s above.
///
/// This is the list, and both `convert_ty`'s and `qualifier_self_ty`'s
/// built-in-name tables (`crates/nova-typeck/src/check.rs`) are expected to
/// agree with it.
pub const RESERVED_TYPE_NAMES: [&str; 7] =
    ["Int", "Float", "Bool", "Char", "String", "Future", "Bytes"];

/// What kind of definition a [`DefId`] refers to.
#[derive(Debug, Clone)]
pub enum DefKind {
    /// A function; the payload is the index of the item in `File::items`.
    Fn { item_index: usize },
    /// A sum type declaration with its variants.
    Sum {
        item_index: usize,
        variants: Vec<VariantDef>,
    },
    /// A record (struct) declaration.
    Record { item_index: usize },
    /// A constant; payload is the item index.
    Const { item_index: usize },
    /// A trait declaration.
    Trait { item_index: usize },
    /// A method: an `ast::Function` living inside an impl block, or a
    /// trait's default-method body. `method_index` selects it within the
    /// owner (impl `functions`, or the trait's provided items).
    Method {
        item_index: usize,
        method_index: usize,
        owner: MethodOwner,
    },
    /// An `extern` function declaration (a C-ABI import, no Nova body).
    /// `fn_index` selects the declaration within the extern block's `items`.
    ExternFn { item_index: usize, fn_index: usize },
    /// An associated type declared in a trait (`type Item`). Carries its
    /// owning trait so a projection can be checked against the right trait
    /// without a separate lookup table.
    AssocType { trait_def: DefId },
}

/// Where a [`DefKind::Method`] lives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MethodOwner {
    /// A method defined in an `impl` block (`item_index` โ†’ the impl item).
    Impl,
    /// A default-method body in a `trait` declaration (`item_index` โ†’ the
    /// trait item, `method_index` โ†’ its `functions`-style provided list).
    TraitDefault,
}

/// One variant of a sum type.
#[derive(Debug, Clone)]
pub struct VariantDef {
    pub name: String,
    pub span: Span,
    /// Number of payload fields (types live in the AST, indexed by the parent).
    pub arity: usize,
}

/// A single top-level definition.
#[derive(Debug, Clone)]
pub struct Def {
    pub name: String,
    pub span: Span,
    pub kind: DefKind,
}

/// What a name in expression position resolves to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Res {
    /// A top-level definition.
    Def(DefId),
    /// Variant `variant_index` of the sum type `DefId`.
    Variant(DefId, usize),
    /// A compiler builtin.
    Builtin(Builtin),
}

/// Index of a module within a compiled program.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ModuleId(pub u32);

/// One module's visible namespaces: its own items (public and private), the
/// implicit std modules (see [`STD_MODULES`]), and names it imports.
/// Resolution is performed relative to a module.
#[derive(Debug, Default)]
struct ModuleScope {
    name: String,
    values: FxHashMap<String, Res>,
    types: FxHashMap<String, DefId>,
    traits: FxHashMap<String, DefId>,
}

/// The item-level namespaces of a whole program (one or more modules).
///
/// `defs` and `DefId`s are global; name lookups are **module-relative** โ€” a
/// name is resolved in the scope of the module that owns the item currently
/// being checked (see [`Definitions::module_of`]).
#[derive(Debug, Default)]
pub struct Definitions {
    defs: Vec<Def>,
    modules: Vec<ModuleScope>,
    /// Merged-item-index โ†’ owning module.
    item_module: Vec<u32>,
    /// Each module's exports, std's included (spec 3.4b ยง4.6).
    exports: Vec<Exports>,
    /// What each module could import, by the name an import writes.
    importable: Vec<Vec<(String, ModuleId)>>,
    /// Each module's package key ([`ModuleSource::package`]).
    packages: Vec<Option<u32>>,
    /// The first std module's index: the user modules come before it.
    std_start: usize,
}

impl Definitions {
    /// All collected definitions, indexable by `DefId.0`.
    pub fn defs(&self) -> &[Def] {
        &self.defs
    }

    /// Look up a definition by id.
    pub fn def(&self, id: DefId) -> &Def {
        &self.defs[id.0 as usize]
    }

    /// The module that owns the item at `item_index` in the merged file.
    pub fn module_of(&self, item_index: usize) -> ModuleId {
        ModuleId(self.item_module.get(item_index).copied().unwrap_or(0))
    }

    /// Number of modules in the program.
    pub fn module_count(&self) -> usize {
        self.modules.len()
    }

    /// The name of a module.
    pub fn module_name(&self, module: ModuleId) -> &str {
        self.modules
            .get(module.0 as usize)
            .map(|m| m.name.as_str())
            .unwrap_or("")
    }

    /// Resolve a name in *value* position, relative to `module`.
    pub fn resolve_value(&self, module: ModuleId, name: &str) -> Option<Res> {
        self.modules
            .get(module.0 as usize)
            .and_then(|m| m.values.get(name).copied())
    }

    /// Resolve a name in *type* position, relative to `module`.
    pub fn resolve_type(&self, module: ModuleId, name: &str) -> Option<DefId> {
        self.modules
            .get(module.0 as usize)
            .and_then(|m| m.types.get(name).copied())
    }

    /// Resolve a name in *trait* position, relative to `module`.
    pub fn resolve_trait(&self, module: ModuleId, name: &str) -> Option<DefId> {
        self.modules
            .get(module.0 as usize)
            .and_then(|m| m.traits.get(name).copied())
    }

    /// Iterate all method definitions as `(DefId, item_index, method_index,
    /// owner)`.
    pub fn methods(&self) -> impl Iterator<Item = (DefId, usize, usize, MethodOwner)> + '_ {
        self.defs
            .iter()
            .enumerate()
            .filter_map(|(i, d)| match d.kind {
                DefKind::Method {
                    item_index,
                    method_index,
                    owner,
                } => Some((DefId(i as u32), item_index, method_index, owner)),
                _ => None,
            })
    }

    /// Iterate all function definitions as `(DefId, item_index)`.
    pub fn functions(&self) -> impl Iterator<Item = (DefId, usize)> + '_ {
        self.defs
            .iter()
            .enumerate()
            .filter_map(|(i, d)| match d.kind {
                DefKind::Fn { item_index } => Some((DefId(i as u32), item_index)),
                _ => None,
            })
    }

    /// Iterate all `extern` function declarations as
    /// `(DefId, item_index, fn_index)` (fn_index into the extern block's items).
    pub fn extern_functions(&self) -> impl Iterator<Item = (DefId, usize, usize)> + '_ {
        self.defs
            .iter()
            .enumerate()
            .filter_map(|(i, d)| match d.kind {
                DefKind::ExternFn {
                    item_index,
                    fn_index,
                } => Some((DefId(i as u32), item_index, fn_index)),
                _ => None,
            })
    }
}

/// What a name in a module's scope is bound to: what completion offers
/// (spec `docs/superpowers/specs/2026-10-08-phase-3-2-lsp-core-design.md`
/// ยง4.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeEntry {
    /// A value: a definition, a variant or a builtin.
    Value(Res),
    /// A record or a sum type.
    Type(DefId),
    /// A trait.
    Trait(DefId),
}

impl Definitions {
    /// Every name `module` can see, in all three namespaces:
    /// - its own items;
    /// - its imports;
    /// - the builtins;
    /// - std's glob-imported names.
    ///
    /// A module binds each name once per namespace, so a std name the
    /// module shadows appears once, as the module's own. The result is
    /// sorted by name, then values, types and traits, for a stable order.
    pub fn names_in_scope(&self, module: ModuleId) -> Vec<(String, ScopeEntry)> {
        let Some(scope) = self.modules.get(module.0 as usize) else {
            return Vec::new();
        };
        let mut out: Vec<(String, ScopeEntry)> = Vec::new();
        out.extend(
            scope
                .values
                .iter()
                .map(|(n, r)| (n.clone(), ScopeEntry::Value(*r))),
        );
        out.extend(
            scope
                .types
                .iter()
                .map(|(n, d)| (n.clone(), ScopeEntry::Type(*d))),
        );
        out.extend(
            scope
                .traits
                .iter()
                .map(|(n, d)| (n.clone(), ScopeEntry::Trait(*d))),
        );
        let rank = |e: &ScopeEntry| match e {
            ScopeEntry::Value(_) => 0,
            ScopeEntry::Type(_) => 1,
            ScopeEntry::Trait(_) => 2,
        };
        out.sort_by(|a, b| a.0.cmp(&b.0).then(rank(&a.1).cmp(&rank(&b.1))));
        out
    }
}

/// What a module exports under one name, in each namespace (spec 3.4b
/// ยง4.2).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Exported {
    pub value: Option<Res>,
    pub ty: Option<DefId>,
    pub trait_def: Option<DefId>,
}

impl Definitions {
    /// The modules `module` could import, by the name an import writes
    /// (spec 3.4b ยง4.6).
    pub fn importable(&self, module: ModuleId) -> &[(String, ModuleId)] {
        self.importable
            .get(module.0 as usize)
            .map_or(&[], Vec::as_slice)
    }

    /// What `module` exports under `name`.
    pub fn exported(&self, module: ModuleId, name: &str) -> Exported {
        let Some(e) = self.exports.get(module.0 as usize) else {
            return Exported::default();
        };
        Exported {
            value: e.values.get(name).copied(),
            ty: e.types.get(name).copied(),
            trait_def: e.traits.get(name).copied(),
        }
    }

    /// Whether `a` and `b` are modules of one package. A loose program's
    /// modules are.
    pub fn same_package(&self, a: ModuleId, b: ModuleId) -> bool {
        self.packages.get(a.0 as usize) == self.packages.get(b.0 as usize)
    }

    /// What `module` binds `name` to, in each namespace, other than through
    /// std's glob (plan decision 8): a binding equal to some std module's
    /// export of that name came through it. Builtins are bound outside std.
    pub fn bound_outside_std(&self, module: ModuleId, name: &str) -> Exported {
        let Some(scope) = self.modules.get(module.0 as usize) else {
            return Exported::default();
        };
        let std = &self.exports[self.std_start.min(self.exports.len())..];
        Exported {
            value: scope
                .values
                .get(name)
                .copied()
                .filter(|r| !std.iter().any(|e| e.values.get(name) == Some(r))),
            ty: scope
                .types
                .get(name)
                .copied()
                .filter(|d| !std.iter().any(|e| e.types.get(name) == Some(d))),
            trait_def: scope
                .traits
                .get(name)
                .copied()
                .filter(|d| !std.iter().any(|e| e.traits.get(name) == Some(d))),
        }
    }

    /// Whether `module` is one of the implicit std modules.
    pub fn is_std_module(&self, module: ModuleId) -> bool {
        let m = module.0 as usize;
        m >= self.std_start && m < self.modules.len()
    }

    /// Whether a fix may edit `module` (spec 3.4b ยง3.1; plan decision 19):
    /// it is the root package's, whose key is 0, or a loose program's, and
    /// not std's.
    pub fn owned(&self, module: ModuleId) -> bool {
        !self.is_std_module(module)
            && matches!(self.packages.get(module.0 as usize), Some(None | Some(0)))
    }
}

/// What an `import` names, by its first segment (spec 3.3a ยง4.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportTarget {
    /// The module at this index of [`resolve_program`]'s `modules`.
    Module(usize),
    /// The driver has already reported this import (E0004, or a
    /// dev-dependency imported from `src/`): bind nothing, and say nothing
    /// more.
    Reported,
}

/// A source module: a parsed file, its label, and what its imports name.
pub struct ModuleSource<'a> {
    /// A label for the module. Messages print an import as written, so the
    /// label is never a lookup key.
    pub name: String,
    pub file: &'a File,
    /// What each import names, by its first segment. An import missing here
    /// is "cannot find module".
    pub imports: std::collections::HashMap<String, ImportTarget>,
    /// The module's source text, for fixes placed by lines (spec
    /// `docs/superpowers/specs/2026-10-10-phase-3-4b-fixes-and-colour-design.md`
    /// ยง4.7). `None` in the resolver's own tests.
    pub text: Option<&'a str>,
    /// A key equal for two modules of one package; `None` for a loose
    /// program, whose files count as one package (spec 3.4b ยง4.6).
    pub package: Option<u32>,
    /// Every loaded module this one could import: the name an import of it
    /// writes, and its index in `modules` (spec 3.4b ยง4.6).
    pub importable: Vec<(String, usize)>,
}

impl<'a> ModuleSource<'a> {
    /// A module with an empty import table; [`name_imports`] fills it by
    /// name.
    pub fn new(name: impl Into<String>, file: &'a File) -> Self {
        ModuleSource {
            name: name.into(),
            file,
            imports: std::collections::HashMap::new(),
            text: None,
            package: None,
            importable: Vec::new(),
        }
    }
}

/// Fill each module's import table by module name, as a program without
/// packages has always resolved (ADR 0003): `import m` names the first
/// module called `m`. Every other module becomes importable by its name
/// (spec 3.4b ยง4.6).
pub fn name_imports(modules: &mut [ModuleSource]) {
    let names: Vec<String> = modules.iter().map(|m| m.name.clone()).collect();
    for (i, module) in modules.iter_mut().enumerate() {
        for item in &module.file.items {
            let Item::Import(import) = &item.value else {
                continue;
            };
            let Some(first) = import.path.value.segments.first() else {
                continue;
            };
            if let Some(index) = names.iter().position(|n| *n == first.value) {
                module
                    .imports
                    .insert(first.value.clone(), ImportTarget::Module(index));
            }
        }
        module.importable = names
            .iter()
            .enumerate()
            .filter(|(j, _)| *j != i)
            .map(|(j, n)| (n.clone(), j))
            .collect();
    }
}

/// The public exports of one module (its `pub` items), used to resolve imports.
#[derive(Debug, Default)]
struct Exports {
    values: FxHashMap<String, Res>,
    types: FxHashMap<String, DefId>,
    traits: FxHashMap<String, DefId>,
}

fn push_def(defs: &mut Vec<Def>, def: Def) -> DefId {
    let id = DefId(defs.len() as u32);
    defs.push(def);
    id
}

/// A well-formed `@test` function, collected by [`collect_item`] in the same
/// order [`resolve_program`]'s item walk visits it โ€” source order (modules in
/// registration order, items within a module in file order; see
/// `collected_tests_are_in_source_order_with_should_panic_attached` in
/// `nova-typeck` for why that order must be exact and stable). Task 3 reads
/// this to build a dispatching `main` that runs one test per process,
/// selected by index; Task 5 reads test names back out of the compiled
/// binary, not from this struct directly โ€” so an index and a name can never
/// silently disagree between the two only if this order never does either.
#[derive(Debug, Clone)]
pub struct TestFn {
    pub def_id: DefId,
    pub name: String,
    pub should_panic: bool,
}

/// Output of [`resolve`]: the namespace table, the merged file whose
/// `item_index`es the definitions refer to (the input plus the implicit std
/// modules, see [`STD_MODULES`]), and any diagnostics. Downstream stages must
/// type-check against this `file`, not the original input, since
/// `item_index`es index into it.
#[derive(Debug)]
pub struct ResolveResult {
    pub definitions: Definitions,
    pub file: File,
    pub diagnostics: Vec<Diagnostic>,
    pub tests: Vec<TestFn>,
}

/// Output of [`resolve_program`]: the merged file, its namespaces, any
/// diagnostics, and the `@test` functions collected along the way. The merged
/// file's `item_index`es are what `Definitions` refers to, so downstream
/// stages consume both together.
pub struct ProgramResolution {
    pub file: File,
    pub definitions: Definitions,
    pub diagnostics: Vec<Diagnostic>,
    pub tests: Vec<TestFn>,
    /// The occurrences of import items, for the language server's index
    /// (spec 3.4a ยง3.3). Always filled; the driver merges them only when
    /// asked.
    pub imports: Vec<Occurrence>,
}

/// Collect the item-level namespace of a single file.
///
/// Reports `E0002` for duplicate definitions in the same namespace. Imports
/// and `module` declarations are accepted but ignored in Phase 1 (single-file
/// compilation); traits/impls/records are collected in later Phase 1 steps.
pub fn resolve(file: &File) -> ResolveResult {
    let mut sources = [ModuleSource::new("main", file)];
    name_imports(&mut sources);
    // No `FileDb` to register the embedded std modules into here, so every
    // one of them gets the same `FileId::DUMMY` sentinel used throughout the
    // test suite โ€” one per `STD_MODULES` entry, in order.
    let std_files: Vec<FileId> = STD_MODULES.iter().map(|_| FileId::DUMMY).collect();
    let prog = resolve_program(&sources, &std_files, None);
    ResolveResult {
        definitions: prog.definitions,
        file: prog.file,
        diagnostics: prog.diagnostics,
        tests: prog.tests,
    }
}

/// Resolve a multi-module program: collect each module's item namespace,
/// enforce `pub` visibility across modules, wire up `import`s, and merge all
/// items into one file for whole-program compilation downstream.
///
/// `std_files` are the [`FileId`]s the caller registered each of
/// [`STD_MODULES`]'s sources under, one per entry, in the same order. Only the
/// driver owns a `FileDb`, so the ids cannot be invented here; threading them
/// through means a syntax error inside an embedded std module is reported
/// against a real file instead of [`FileId::DUMMY`]. The single-module
/// [`resolve`] wrapper passes `FileId::DUMMY` for each, since it has no
/// `FileDb` to register into. Entries beyond `std_files`'s length are simply
/// not compiled in (the driver always supplies one id per `STD_MODULES`
/// entry, so this is not expected to happen).
///
/// `extra_std` is `Some((`[`STD_TEST_MODULE`]`, file_id))` under `nova test`
/// and `None` otherwise (the driver decides). When present it is treated as
/// one more std module โ€” glob-imported into every other module exactly like
/// each [`STD_MODULES`] entry, and on the receiving end of their glob-imports too
/// (so `assert_eq`'s bounds can name `Eq`/`Debug` with no `import`) โ€” but it
/// is threaded through this one parameter rather than folded into
/// `STD_MODULES` itself, so that array's length stays fixed regardless of
/// compilation mode; every other consumer of `STD_MODULES` (and the driver's
/// one-`FileId`-per-entry allocation) is therefore unaffected by its
/// existence.
///
/// `item_index`es in the returned [`ProgramResolution::file`] are global
/// (module items concatenated in `modules` order, plus the implicit std
/// modules last, in [`STD_MODULES`] order, plus `extra_std` if present).
pub fn resolve_program(
    modules: &[ModuleSource],
    std_files: &[FileId],
    extra_std: Option<((&str, &str), FileId)>,
) -> ProgramResolution {
    let mut definitions = Definitions::default();
    let mut diagnostics = Vec::new();
    let mut merged = Vec::new();
    let mut tests = Vec::new();
    let mut imports: Vec<Occurrence> = Vec::new();

    // Every `STD_MODULES` entry plus, only when the caller passed one, the
    // extra std module โ€” combined here so the rest of this function has one
    // uniform list to iterate instead of a special case for the extra entry.
    let std_entries: Vec<(&str, &str)> = STD_MODULES
        .iter()
        .copied()
        .chain(extra_std.map(|(entry, _)| entry))
        .collect();
    let std_file_ids: Vec<FileId> = std_files
        .iter()
        .copied()
        .chain(extra_std.map(|(_, file_id)| file_id))
        .collect();

    // Compile each implicit std module (in `std_entries` order) so their
    // public types/traits/values get real DefIds and layouts (and are then
    // glob-imported into every other module below). Each ships with the
    // compiler, so a parse failure here is a compiler bug โ€” but it is
    // reported against a real file so it is debuggable, and a module that
    // fails to parse outright is skipped entirely (`None`) rather than
    // silently merged in as empty.
    let std_modules: Vec<Option<File>> = std_entries
        .iter()
        .zip(std_file_ids.iter())
        .map(|(&(_, src), &file_id)| {
            let (ast, diags) = std_module(src, file_id);
            diagnostics.extend(diags);
            ast
        })
        .collect();

    // They go *after* all user modules, so user module indices are
    // unaffected โ€” module 0 stays the first user module.
    let user_count = modules.len();
    let all: Vec<ModuleSource> = modules
        .iter()
        .map(|m| ModuleSource {
            name: m.name.clone(),
            file: m.file,
            imports: m.imports.clone(),
            text: m.text,
            package: m.package,
            importable: m.importable.clone(),
        })
        .chain(
            std_entries
                .iter()
                .zip(std_modules.iter())
                .filter_map(|(&(name, _), file)| {
                    file.as_ref()
                        .map(|file| ModuleSource::new(name.to_string(), file))
                }),
        )
        .collect();

    // The std modules that parsed successfully are exactly the contiguous
    // range after the user modules โ€” nothing else is appended after them โ€”
    // so "is `mid` *a* std module" (rather than checking against one stored
    // "the std module" index) is this one range check.
    let std_start = user_count;
    let is_std_module = |mid: usize| mid >= std_start;

    let mut exports: Vec<Exports> = Vec::new();

    // A scope per module, seeded with the compiler builtins. `Builtin::GLOBAL`
    // goes into every module; `Builtin::STD_ONLY` goes only into an std
    // module's own scope, so none of them ever becomes a reserved word in
    // user code (see the `Builtin` doc comments).
    for (mid, m) in all.iter().enumerate() {
        let mut scope = ModuleScope {
            name: m.name.clone(),
            ..Default::default()
        };
        for b in Builtin::GLOBAL {
            scope.values.insert(b.name().to_string(), Res::Builtin(b));
        }
        if is_std_module(mid) {
            for b in Builtin::STD_ONLY {
                scope.values.insert(b.name().to_string(), Res::Builtin(b));
            }
        }
        definitions.modules.push(scope);
        exports.push(Exports::default());
    }

    // Spec 3.4b ยง3.1 (plan decision 19): a fix may edit only the root
    // package's modules or a loose program's.
    let owned = |mid: usize| mid < std_start && matches!(all[mid].package, None | Some(0));

    // Pass 1: collect each module's own definitions into its scope + exports.
    for (mid, m) in all.iter().enumerate() {
        let mut first_value: IndexMap<String, Span> = IndexMap::new();
        let mut first_type: IndexMap<String, Span> = IndexMap::new();
        let before = diagnostics.len();
        for item in &m.file.items {
            let item_index = merged.len();
            definitions.item_module.push(mid as u32);
            collect_item(
                &mut definitions.defs,
                &mut definitions.modules[mid],
                &mut exports[mid],
                &mut first_value,
                &mut first_type,
                &mut diagnostics,
                &mut tests,
                item_index,
                &item.value,
            );
            merged.push(item.clone());
        }
        if !owned(mid) {
            diagnostics[before..]
                .iter_mut()
                .for_each(|d| d.fixes.clear());
        }
    }

    // Pass 2: resolve `import`s, binding other modules' public names. What
    // each import names is its module's table (spec 3.3a ยง4.5).
    let mut public_fixes: Vec<(usize, usize, String)> = Vec::new();
    for (mid, m) in all.iter().enumerate() {
        let before = diagnostics.len();
        for item in &m.file.items {
            if let Item::Import(imp) = &item.value {
                resolve_import(
                    &mut definitions,
                    &exports,
                    &all,
                    mid,
                    imp,
                    &mut diagnostics,
                    &mut imports,
                    &mut public_fixes,
                );
            }
        }
        if !owned(mid) {
            diagnostics[before..]
                .iter_mut()
                .for_each(|d| d.fixes.clear());
        }
    }

    // Spec 3.4b ยง3.2: making an item public must not bind its name into a
    // module that already has it, which would be E0002 there. Every module's
    // own items and imports are bound by now, and std's glob, which never
    // conflicts, has not run.
    for (at, target, name) in public_fixes {
        let clash = all.iter().enumerate().any(|(g, m)| {
            g != target && would_receive(m, target, &name) && binds(&definitions.modules[g], &name)
        });
        if clash {
            diagnostics[at].fixes.clear();
        }
    }

    // Glob each std module's public names into every *other* module โ€” LAST,
    // so it is the lowest-priority binding: a name the module already defines
    // or imports wins (no conflict), and only otherwise-unbound names fall
    // through to a std module. A program may thus define or import its own
    // `Option`/`Result`/`Vec`. This also runs std-into-std โ€” std/core's
    // exports glob into std/collections's scope exactly as they would into a
    // user module's, which is what lets std/collections use
    // `Option`/`Some`/`None` with no `import` of its own.
    for (mid, std_exports) in exports.iter().enumerate().skip(std_start) {
        import_std_module(&mut definitions, std_exports, mid);
    }

    // Spec 3.4b ยง4.6: what a fix needs to know.
    definitions.importable = all
        .iter()
        .map(|m| {
            m.importable
                .iter()
                .map(|(n, i)| (n.clone(), ModuleId(*i as u32)))
                .collect()
        })
        .collect();
    definitions.packages = all.iter().map(|m| m.package).collect();
    definitions.std_start = std_start;
    definitions.exports = exports;

    ProgramResolution {
        file: File { items: merged },
        definitions,
        diagnostics,
        tests,
        imports,
    }
}

/// The embedded standard-library modules, compiled as implicit modules and
/// glob-imported into every user module. Order is significant only in that it
/// fixes module indices; user modules always come first, then these in the
/// order listed here โ€” `std/core` stays first so its module index is
/// unchanged from when it was the only embedded module. The sources come
/// from the `nova-std` crate, which embeds `std/` at build time through
/// paths inside its own package, so the compiler stays a single
/// self-contained executable and `cargo package` keeps the files. Each name
/// is `$std.*`, not a valid identifier, so it can never collide with a user
/// module name or be named in an `import`.
pub const STD_MODULES: [(&str, &str); 16] = [
    ("$std.core", nova_std::CORE),
    ("$std.bytes", nova_std::BYTES),
    ("$std.io", nova_std::IO),
    ("$std.fs", nova_std::FS),
    ("$std.collections", nova_std::COLLECTIONS),
    ("$std.strings", nova_std::STRINGS),
    ("$std.fmt", nova_std::FMT),
    ("$std.task", nova_std::TASK),
    ("$std.sync", nova_std::SYNC),
    ("$std.net", nova_std::NET),
    ("$std.time", nova_std::TIME),
    ("$std.json", nova_std::JSON),
    ("$std.log", nova_std::LOG),
    ("$std.http", nova_std::HTTP),
    ("$std.crypto", nova_std::CRYPTO),
    ("$std.process", nova_std::PROCESS),
];

/// `std/test`, seeded only under `nova test`. Kept out of [`STD_MODULES`] so
/// that array's length does not depend on compilation mode: every consumer
/// iterates it and the driver allocates one `FileId` per entry, so a
/// conditional member would make `FileId` allocation depend on which
/// subcommand is running.
pub const STD_TEST_MODULE: (&str, &str) = ("$std.test", nova_std::TEST);

/// Lex and parse one embedded std module. Its source ships with the compiler,
/// so any failure is a compiler bug โ€” but it is reported against `file_id` so
/// it is debuggable rather than silently dropped. Returns `None` when parsing
/// fails outright (nothing to merge in as a module); the caller still gets
/// the diagnostics either way.
fn std_module(src: &str, file_id: FileId) -> (Option<File>, Vec<Diagnostic>) {
    let (tokens, lex_errors) = nova_lexer::lex(src, file_id);
    let mut diags: Vec<Diagnostic> = lex_errors
        .iter()
        .map(|e| Diagnostic::error("L0001", e.to_string()).with_primary_label(e.span(), "here"))
        .collect();
    let (ast, parse_errors) = nova_parser::parse(&tokens, file_id);
    diags.extend(
        parse_errors.iter().map(|e| {
            Diagnostic::error("P0001", e.to_string()).with_primary_label(e.span(), "here")
        }),
    );
    (ast, diags)
}

/// Bind one std module's public names into every *other* module's scope,
/// leaving any name a module already defines or imports untouched (a user โ€”
/// or another std module's own โ€” item shadows a std one). Called once per
/// entry in [`STD_MODULES`], so this also runs std-into-std (e.g. std/core's
/// `Option` into std/collections's scope), which is what lets std/collections
/// use `Option`/`Some`/`None` with no `import` of its own.
fn import_std_module(definitions: &mut Definitions, std_exports: &Exports, std_mid: usize) {
    let values: Vec<(String, Res)> = std_exports
        .values
        .iter()
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    let types: Vec<(String, DefId)> = std_exports
        .types
        .iter()
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    let traits: Vec<(String, DefId)> = std_exports
        .traits
        .iter()
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    for mid in 0..definitions.modules.len() {
        if mid == std_mid {
            continue;
        }
        let scope = &mut definitions.modules[mid];
        for (n, r) in &values {
            scope.values.entry(n.clone()).or_insert(*r);
        }
        for (n, id) in &types {
            scope.types.entry(n.clone()).or_insert(*id);
        }
        for (n, id) in &traits {
            scope.traits.entry(n.clone()).or_insert(*id);
        }
    }
}

/// Collect one item's definitions into `scope` (and `exp` if `pub`), pushing
/// global `Def`s into `defs`.
///
/// Also validates the item's `attrs` (Task 2): an unknown attribute name is
/// always `E0082`, `@test` on anything other than a function is `E0083`, a
/// `@test` function that is `async` or has parameters, generics, or a
/// non-`Unit` return is `E0084`, and an unknown `@test(...)` argument is
/// `E0085` โ€” never silently ignored, so a mistyped `@tset` cannot compile into
/// a function that looks like a test and never runs as one. A well-formed
/// `@test` function is pushed onto `tests`.
///
/// Every `Item` variant carries `attrs` and is validated here, `import`,
/// `module` and `extern` included (fix round 1: `@tset` before an `extern`
/// block used to compile with zero diagnostics, since neither the AST nor
/// the parser gave those three item kinds anywhere to put a parsed
/// attribute โ€” see `nova-ast`'s `Import`/`Module`/`ExternBlock` and
/// `nova-parser`'s `try_parse_item`). The rule is now uniform: every item may
/// carry attributes, and validation โ€” not the AST shape โ€” decides what is
/// legal, so there is no item kind left where a silent drop is possible.
#[allow(clippy::too_many_arguments)]
fn collect_item(
    defs: &mut Vec<Def>,
    scope: &mut ModuleScope,
    exp: &mut Exports,
    first_value: &mut IndexMap<String, Span>,
    first_type: &mut IndexMap<String, Span>,
    diagnostics: &mut Vec<Diagnostic>,
    tests: &mut Vec<TestFn>,
    item_index: usize,
    item: &Item,
) {
    match item {
        Item::Function(f) => {
            let name = f.name.value.clone();
            let span = f.name.span;
            let id = push_def(
                defs,
                Def {
                    name: name.clone(),
                    span,
                    kind: DefKind::Fn { item_index },
                },
            );
            insert_value(
                scope,
                exp,
                first_value,
                diagnostics,
                name,
                span,
                Res::Def(id),
                is_pub(f.vis),
            );
            validate_test_function(f, id, diagnostics, tests);
        }
        Item::Type(t) => {
            validate_attrs_reject_test(&t.attrs, "a type declaration", diagnostics);
            match &t.def {
                TypeDef::Sum(variants) => {
                    let name = t.name.value.clone();
                    let span = t.name.span;
                    if reject_reserved_type_name(diagnostics, &name, span) {
                        return;
                    }
                    let pubv = is_pub(t.vis);
                    let variant_defs: Vec<VariantDef> = variants
                        .iter()
                        .map(|v| VariantDef {
                            name: v.name.value.clone(),
                            span: v.name.span,
                            arity: v.fields.len(),
                        })
                        .collect();
                    let id = push_def(
                        defs,
                        Def {
                            name: name.clone(),
                            span,
                            kind: DefKind::Sum {
                                item_index,
                                variants: variant_defs,
                            },
                        },
                    );
                    insert_type(scope, exp, first_type, diagnostics, name, span, id, pubv);
                    // Variants live in the value namespace and inherit the type's
                    // visibility, so `Some(x)` / `Circle(1.0)` resolve unprefixed.
                    for (vi, v) in variants.iter().enumerate() {
                        insert_value(
                            scope,
                            exp,
                            first_value,
                            diagnostics,
                            v.name.value.clone(),
                            v.name.span,
                            Res::Variant(id, vi),
                            pubv,
                        );
                    }
                }
                TypeDef::Alias(_) => {
                    diagnostics.push(unsupported(
                        t.name.span,
                        "type aliases are not supported yet in the Phase 1 compiler",
                    ));
                }
            }
        }
        Item::Const(c) => {
            validate_attrs_reject_test(&c.attrs, "a const", diagnostics);
            let name = c.name.value.clone();
            let span = c.name.span;
            let id = push_def(
                defs,
                Def {
                    name: name.clone(),
                    span,
                    kind: DefKind::Const { item_index },
                },
            );
            insert_value(
                scope,
                exp,
                first_value,
                diagnostics,
                name,
                span,
                Res::Def(id),
                is_pub(c.vis),
            );
        }
        Item::Record(r) => {
            validate_attrs_reject_test(&r.attrs, "a record", diagnostics);
            let name = r.name.value.clone();
            let span = r.name.span;
            if reject_reserved_type_name(diagnostics, &name, span) {
                return;
            }
            let id = push_def(
                defs,
                Def {
                    name: name.clone(),
                    span,
                    kind: DefKind::Record { item_index },
                },
            );
            insert_type(
                scope,
                exp,
                first_type,
                diagnostics,
                name,
                span,
                id,
                is_pub(r.vis),
            );
        }
        Item::Trait(t) => {
            validate_attrs_reject_test(&t.attrs, "a trait", diagnostics);
            let name = t.name.value.clone();
            let span = t.name.span;
            let pubv = is_pub(t.vis);
            let id = push_def(
                defs,
                Def {
                    name: name.clone(),
                    span,
                    kind: DefKind::Trait { item_index },
                },
            );
            if scope.traits.contains_key(&name) {
                diagnostics.push(
                    Diagnostic::error("E0002", format!("duplicate trait `{name}`"))
                        .with_primary_label(span, "redefined here"),
                );
            } else {
                scope.traits.insert(name.clone(), id);
                if pubv {
                    exp.traits.insert(name, id);
                }
            }
            // Default-method bodies become their own method defs (global);
            // each associated type gets its own `DefId` too, named after
            // itself. A `match` (not `if let`) on purpose: unlike a
            // non-exhaustive `if let`, this is not something `cargo check`
            // can force open when a new `TraitItem` variant is added, so it
            // must already cover every arm.
            for (method_index, ti) in t.items.iter().enumerate() {
                match ti {
                    nova_ast::item::TraitItem::Provided(f) => {
                        push_def(
                            defs,
                            Def {
                                name: format!("{}::{}$default", t.name.value, f.name.value),
                                span: f.name.span,
                                kind: DefKind::Method {
                                    item_index,
                                    method_index,
                                    owner: MethodOwner::TraitDefault,
                                },
                            },
                        );
                    }
                    nova_ast::item::TraitItem::AssocType { name: at_name, .. } => {
                        // Not inserted into `scope.types`: an associated type
                        // is not a type name you can write bare, only
                        // reachable through a projection (`Self::Item`).
                        push_def(
                            defs,
                            Def {
                                name: at_name.value.clone(),
                                span: at_name.span,
                                kind: DefKind::AssocType { trait_def: id },
                            },
                        );
                    }
                    nova_ast::item::TraitItem::Required(_) => {}
                }
            }
        }
        Item::Impl(i) => {
            validate_attrs_reject_test(&i.attrs, "an impl block", diagnostics);
            // Impls are globally coherent โ€” collected program-wide, resolved by
            // type rather than by name, so they are not bound into any scope.
            let self_name = type_full_name(&i.ty.value);
            for (method_index, f) in i.functions.iter().enumerate() {
                let mangled = match &i.trait_ {
                    Some(tr) => format!("{}.{}.{}", self_name, path_tail(&tr.value), f.name.value),
                    None => format!("{}.{}", self_name, f.name.value),
                };
                push_def(
                    defs,
                    Def {
                        name: mangled,
                        span: f.name.span,
                        kind: DefKind::Method {
                            item_index,
                            method_index,
                            owner: MethodOwner::Impl,
                        },
                    },
                );
            }
        }
        Item::Extern(block) => {
            validate_attrs_reject_test(&block.attrs, "an extern block", diagnostics);
            // Each declaration binds as a callable value under its (unmangled)
            // C symbol name. ABI / signature validity is checked in typeck.
            // Extern fns are module-private (the grammar has no `pub` on them).
            for (fn_index, ext_item) in block.items.iter().enumerate() {
                let ExternItem::Fn(sig) = ext_item;
                let name = sig.name.value.clone();
                let span = sig.name.span;
                let id = push_def(
                    defs,
                    Def {
                        name: name.clone(),
                        span,
                        kind: DefKind::ExternFn {
                            item_index,
                            fn_index,
                        },
                    },
                );
                insert_value(
                    scope,
                    exp,
                    first_value,
                    diagnostics,
                    name,
                    span,
                    Res::Def(id),
                    false,
                );
            }
        }
        Item::Import(imp) => {
            validate_attrs_reject_test(&imp.attrs, "an import", diagnostics);
            // Otherwise handled in pass 2.
        }
        Item::Module(m) => {
            validate_attrs_reject_test(&m.attrs, "a module declaration", diagnostics);
            // Carries no items of its own to collect.
        }
    }
}

/// `E0089`: `name` is one of [`RESERVED_TYPE_NAMES`]. Called from the sum-type
/// and record arms of [`collect_item`] โ€” the two forms that introduce a type
/// name โ€” before either pushes a `Def` or inserts into the type namespace, so
/// a rejected declaration registers nothing: it does not occupy a `DefId`, is
/// not collected by any later pass, and cannot collide with a genuine
/// duplicate of the same name. Two declarations under the same reserved name
/// each raise their own `E0089` rather than the second colliding as `E0002`
/// โ€” for the same reason: neither one is ever registered, so there is
/// nothing on record for a second occurrence to collide with.
///
/// "Not collected by any later pass" holds only because every such pass in
/// `nova-typeck` walks `Definitions::defs()` rather than the AST directly, so
/// skipping `push_def` here is sufficient โ€” today. That is a cross-crate
/// invariant this function's ordering relies on but cannot enforce; nothing
/// stops a future pass from walking items directly instead. The same drift
/// class this module already flags for `convert_ty`'s and `qualifier_self_ty`'s
/// tables (see [`RESERVED_TYPE_NAMES`]'s own doc): a comment, not a compiler
/// backstop.
fn reject_reserved_type_name(diagnostics: &mut Vec<Diagnostic>, name: &str, span: Span) -> bool {
    if !RESERVED_TYPE_NAMES.contains(&name) {
        return false;
    }
    diagnostics.push(
        Diagnostic::error(
            "E0089",
            format!(
                "`{name}` is already a built-in type; a type declared under \
                 this name could never be referred to in a type annotation, \
                 since `{name}` in a type position never resolves to a \
                 declaration under this name"
            ),
        )
        .with_primary_label(span, "redeclares a built-in type name"),
    );
    true
}

/// Attribute names the compiler recognizes. An attribute whose name is not in
/// this list is always `E0082` โ€” parsing an attribute and then enforcing
/// nothing about its name is exactly the failure mode `@test` must not be
/// allowed: a misspelled `@tset` that compiled would define a function that
/// looks like a test and never runs as one.
const KNOWN_ATTRIBUTES: &[&str] = &["test"];

/// Arguments `@test(...)` accepts. Anything else is `E0085`.
const KNOWN_TEST_ARGS: &[&str] = &["should_panic"];

/// The `E0084` note attached when a `@test` function is `async`
/// (see [`test_shape_violations`]).
///
/// A note rather than a longer message because it has to be *actionable on its
/// own*: the whole point of rejecting the shape is that the user's next edit
/// should be the working one, so the replacement pattern is spelled out as
/// source rather than described, and `block_on`'s role in it is named.
const TEST_ASYNC_NOTE: &str = "an `async fn` returns a future, and a `@test` function's result is \
     discarded rather than awaited, so an `async` test's body would never run; \
     write the test as a synchronous one that drives the future itself, e.g. \
     `@test fn t() { assert_eq(block_on(f()), 42) }` โ€” `block_on` runs `f()`'s \
     future to completion and produces its value";

/// `E0082`: `attr`'s name is not in [`KNOWN_ATTRIBUTES`]. Shared by every
/// item kind that can carry attributes, so a typo is caught the same way no
/// matter what it is attached to.
///
/// Labels `attr.name.span`, never `attr.span`: `attr.span` (see
/// `nova-parser`'s `parse_attributes`) is set to the span of the leading `@`
/// token alone โ€” one byte wide, never covering the name that follows it โ€” so
/// underlining it would point at the `@` and leave the actual misspelled
/// word unmarked. `attr.name` is a separate `Spanned<String>` built by
/// `parse_ident`, with its own accurate span over just the identifier text,
/// and is what every diagnostic in this file uses instead. `attr.span` is
/// read nowhere in this module.
fn unknown_attribute(attr: &Attribute) -> Diagnostic {
    Diagnostic::error(
        "E0082",
        format!(
            "unknown attribute `@{}`; known attributes are: {}",
            attr.name.value,
            KNOWN_ATTRIBUTES.join(", "),
        ),
    )
    .with_primary_label(attr.name.span, "unknown attribute")
}

/// Validate the attributes of an item that can never itself be a test: every
/// item kind except a function (record, type declaration, trait, impl block,
/// const, import, module, extern block โ€” see [`validate_test_function`] for
/// the function case). An unknown name is still `E0082`; `@test` on one of
/// these is `E0083`, since only a function can ever run as a test. `kind`
/// names the item for the message and already carries its article (e.g.
/// `"a record"`, `"an impl block"`).
fn validate_attrs_reject_test(attrs: &[Attribute], kind: &str, diagnostics: &mut Vec<Diagnostic>) {
    for attr in attrs {
        if attr.name.value == "test" {
            diagnostics.push(
                Diagnostic::error(
                    "E0083",
                    format!("`@test` can only be applied to a function, not {kind}"),
                )
                .with_primary_label(attr.name.span, "not a function"),
            );
        } else if !KNOWN_ATTRIBUTES.contains(&attr.name.value.as_str()) {
            diagnostics.push(unknown_attribute(attr));
        }
    }
}

/// Validate a function's attributes and, if it carries a well-formed `@test`,
/// push a [`TestFn`] onto `tests`. `def_id` is the caller's already-collected
/// `DefId` for `f` (from its own `push_def`), so a rejected `@test` still
/// leaves the function itself resolved and callable like any other โ€”
/// rejection refuses only its *test-ness*, never its existence in the
/// namespace.
///
/// Pushes onto `tests` in the order [`resolve_program`]'s item walk visits
/// this function, which is source order โ€” see [`TestFn`]'s doc comment for
/// why that must hold exactly and
/// `collected_tests_are_in_source_order_with_should_panic_attached` in
/// `nova-typeck` for the test that pins it.
///
/// Pushes **at most one** `TestFn`, even if `f` carries more than one
/// well-formed `@test` (syntactically legal โ€” `f.attrs` is a plain `Vec`
/// with no uniqueness constraint on `name`, the same reason `@derive(...)`
/// and `@test` can coexist on one function). Without the `collected` guard
/// below, `@test\n@test\nfn t() {}` would push the same `def_id`/name onto
/// `tests` twice, and `nova test` would list and run one function as if it
/// were two different tests. The first well-formed `@test`, in attribute
/// order, is the one whose `should_panic` wins; later ones are still
/// validated (an invalid argument or bad shape on a second `@test` still
/// reports its own diagnostic) but never collected again.
fn validate_test_function(
    f: &Function,
    def_id: DefId,
    diagnostics: &mut Vec<Diagnostic>,
    tests: &mut Vec<TestFn>,
) {
    let mut collected = false;
    for attr in &f.attrs {
        if attr.name.value != "test" {
            // Spec 3.4b ยง4.3: on a function only, since `@test` on anything
            // else is E0083 (decision 38).
            let mut d = unknown_attribute(attr);
            if let Some(fix) = suggest::change_to(&attr.name, KNOWN_ATTRIBUTES.iter().copied()) {
                d = d.with_fix(fix);
            }
            diagnostics.push(d);
            continue;
        }
        let mut well_formed = true;
        let mut should_panic = false;
        for arg in &attr.args {
            if arg.value == "should_panic" {
                should_panic = true;
            } else {
                let mut d = Diagnostic::error(
                    "E0085",
                    format!(
                        "unknown `@test` argument `{}`; the accepted arguments are: {}",
                        arg.value,
                        KNOWN_TEST_ARGS.join(", "),
                    ),
                )
                .with_primary_label(arg.span, "unknown argument");
                if let Some(fix) = suggest::change_to(arg, KNOWN_TEST_ARGS.iter().copied()) {
                    d = d.with_fix(fix);
                }
                diagnostics.push(d);
                well_formed = false;
            }
        }
        let violations = test_shape_violations(f);
        if !violations.is_empty() {
            let names: Vec<&str> = violations.iter().map(|(name, _)| *name).collect();
            let mut diag = Diagnostic::error(
                "E0084",
                format!("a `@test` function may not have {}", names.join(", ")),
            )
            .with_primary_label(f.name.span, "invalid test signature");
            for (name, span) in &violations {
                if let Some(span) = span {
                    diag = diag.with_secondary_label(*span, format!("{name} here"));
                }
            }
            if f.is_async {
                diag = diag.with_note(TEST_ASYNC_NOTE);
            }
            diagnostics.push(diag);
            well_formed = false;
        }
        if well_formed && !collected {
            tests.push(TestFn {
                def_id,
                name: f.name.value.clone(),
                should_panic,
            });
            collected = true;
        }
    }
}

/// Ways a function's signature disqualifies it from `@test` (`E0084`): an
/// `async` body, parameters, generics, or an explicit non-`Unit` return type. A
/// test is called with no arguments and its result is discarded, so there is no
/// caller that could ever supply the one or consume the other. A missing
/// return type and an explicit `-> ()` are both `Unit` and neither is a
/// violation โ€” only an explicit *non*-`Unit` return type is.
///
/// `async` is rejected for the same reason and one more: an `async fn` returns
/// a future, and a discarded future is never awaited, so the body of an
/// `async` `@test` could not run at all. Rejecting it is what the `nova test`
/// design specified from the start (`@test fn t() { block_on(f()) }` is the
/// supported way to test async code); accepting it silently is what
/// `TEST_ASYNC_NOTE` exists to steer a user out of.
///
/// The `async` violation carries no span because the AST records `is_async` as
/// a bare `bool` with no span of its own, and the `async` keyword precedes the
/// name, so `f.name.span` would point a label at the wrong token. `None` is
/// therefore "no better span than the primary label's", not "no location".
fn test_shape_violations(f: &Function) -> Vec<(&'static str, Option<Span>)> {
    let mut violations = Vec::new();
    if f.is_async {
        violations.push(("an `async` body", None));
    }
    if let (Some(first), Some(last)) = (f.params.first(), f.params.last()) {
        violations.push(("parameters", Some(first.name.span.merge(last.ty.span))));
    }
    if let (Some(first), Some(last)) = (f.generics.first(), f.generics.last()) {
        violations.push((
            "generic parameters",
            Some(first.name.span.merge(last.name.span)),
        ));
    }
    if let Some(rt) = &f.return_ty {
        if !matches!(&rt.value, Type::Tuple(items) if items.is_empty()) {
            violations.push(("a non-Unit return type", Some(rt.span)));
        }
    }
    violations
}

/// Bind another module's public names into the importing module's scope.
/// Each "make public" fix it offers is recorded in `public_fixes`: the
/// diagnostic's index, the target module and the name (spec 3.4b ยง4.4).
#[allow(clippy::too_many_arguments)]
fn resolve_import(
    definitions: &mut Definitions,
    exports: &[Exports],
    modules: &[ModuleSource],
    mid: usize,
    imp: &Import,
    diagnostics: &mut Vec<Diagnostic>,
    occurrences: &mut Vec<Occurrence>,
    public_fixes: &mut Vec<(usize, usize, String)>,
) {
    let span = imp.path.span;
    // Only single-segment module imports are supported. A qualified or nested
    // path (`a::b`) would otherwise silently drop its leading segments and bind
    // an unrelated module; reject it explicitly like `import ... as`.
    if imp.path.value.segments.len() > 1 {
        diagnostics.push(unsupported(
            span,
            "qualified or nested import paths (`a::b`) are not supported yet; \
             import a top-level module by its name",
        ));
        return;
    }
    let target_name = imp
        .path
        .value
        .segments
        .last()
        .map(|s| s.value.as_str())
        .unwrap_or("");
    let target = match modules[mid].imports.get(target_name) {
        Some(ImportTarget::Module(target)) => *target,
        Some(ImportTarget::Reported) => return,
        None => {
            diagnostics.push(
                Diagnostic::error("E0001", format!("cannot find module `{target_name}`"))
                    .with_primary_label(span, "no such module"),
            );
            return;
        }
    };
    if target == mid {
        diagnostics.push(
            Diagnostic::error("E0001", format!("module `{target_name}` imports itself"))
                .with_primary_label(span, "self-import"),
        );
        return;
    }
    // Spec 3.4a ยง3.3: the module, at its own segment. Only one-segment
    // paths reach here, and `path.span` would also cover a list's `::`.
    if let Some(first) = imp.path.value.segments.first() {
        occurrences.push(Occurrence {
            span: first.span,
            role: Role::Use,
            target: Target::Module(ModuleId(target as u32)),
            shorthand: false,
        });
    }
    match &imp.kind {
        ImportKind::Simple => {
            // Glob: bring all of the target module's public names into scope.
            let names: Vec<(String, Res)> = exports[target]
                .values
                .iter()
                .map(|(k, v)| (k.clone(), *v))
                .collect();
            for (n, r) in names {
                bind_value(&mut definitions.modules[mid], diagnostics, n, span, r);
            }
            let tys: Vec<(String, DefId)> = exports[target]
                .types
                .iter()
                .map(|(k, v)| (k.clone(), *v))
                .collect();
            for (n, id) in tys {
                bind_type(&mut definitions.modules[mid], diagnostics, n, span, id);
            }
            let trs: Vec<(String, DefId)> = exports[target]
                .traits
                .iter()
                .map(|(k, v)| (k.clone(), *v))
                .collect();
            for (n, id) in trs {
                bind_trait(&mut definitions.modules[mid], diagnostics, n, span, id);
            }
        }
        ImportKind::List(names) => {
            for n in names {
                let name = &n.value;
                let mut found = false;
                if let Some(r) = exports[target].values.get(name).copied() {
                    bind_value(
                        &mut definitions.modules[mid],
                        diagnostics,
                        name.clone(),
                        n.span,
                        r,
                    );
                    let named = match r {
                        Res::Def(id) => Target::Def(id),
                        Res::Variant(sum, i) => Target::Variant(sum, i as u32),
                        Res::Builtin(b) => Target::Builtin(b),
                    };
                    occurrences.push(Occurrence {
                        span: n.span,
                        role: Role::Use,
                        target: named,
                        shorthand: false,
                    });
                    found = true;
                }
                if let Some(id) = exports[target].types.get(name).copied() {
                    bind_type(
                        &mut definitions.modules[mid],
                        diagnostics,
                        name.clone(),
                        n.span,
                        id,
                    );
                    occurrences.push(Occurrence {
                        span: n.span,
                        role: Role::Use,
                        target: Target::Def(id),
                        shorthand: false,
                    });
                    found = true;
                }
                if let Some(id) = exports[target].traits.get(name).copied() {
                    bind_trait(
                        &mut definitions.modules[mid],
                        diagnostics,
                        name.clone(),
                        n.span,
                        id,
                    );
                    occurrences.push(Occurrence {
                        span: n.span,
                        role: Role::Use,
                        target: Target::Def(id),
                        shorthand: false,
                    });
                    found = true;
                }
                if !found {
                    let mut diag = Diagnostic::error(
                        "E0001",
                        format!("`{name}` is not a public item of module `{target_name}`"),
                    )
                    .with_primary_label(n.span, "not found or not `pub`");
                    let same_package = modules[mid].package == modules[target].package;
                    if let Some(fix) =
                        make_public(&modules[target], name, target_name, same_package)
                    {
                        diag = diag.with_fix(fix);
                        public_fixes.push((diagnostics.len(), target, name.clone()));
                    }
                    diagnostics.push(diag);
                }
            }
        }
        ImportKind::Alias(_) => {
            diagnostics.push(unsupported(
                span,
                "`import ... as` aliases are not supported yet",
            ));
        }
    }
}

fn is_pub(vis: nova_ast::item::Visibility) -> bool {
    matches!(vis, nova_ast::item::Visibility::Pub)
}

/// "make `x` public in `m`" (spec 3.4b ยง4.4): `pub ` before the keyword of
/// each private item `module` declares named `name`, when `module` is the
/// importer's own package's. The keyword is found in the module's text.
fn make_public(module: &ModuleSource, name: &str, import: &str, same_package: bool) -> Option<Fix> {
    if !same_package {
        return None;
    }
    let text = module.text?;
    let mut edits = Vec::new();
    for item in &module.file.items {
        let (vis, item_name) = match &item.value {
            Item::Function(f) => (f.vis, &f.name),
            Item::Record(r) => (r.vis, &r.name),
            Item::Type(t) => (t.vis, &t.name),
            Item::Trait(t) => (t.vis, &t.name),
            Item::Const(c) => (c.vis, &c.name),
            _ => continue,
        };
        if item_name.value != name || is_pub(vis) {
            continue;
        }
        let at = nova_diagnostics::lines::keyword_start(text, item_name.span.start as usize)?;
        edits.push(Edit::insert(at as u32, item_name.span.file, "pub "));
    }
    (!edits.is_empty()).then(|| Fix::new(format!("make `{name}` public in `{import}`"), edits))
}

/// Whether `module` would receive `name` once module `target` exports it:
/// it imports `target` whole, or by a list naming `name`.
fn would_receive(module: &ModuleSource, target: usize, name: &str) -> bool {
    module.file.items.iter().any(|item| {
        let Item::Import(imp) = &item.value else {
            return false;
        };
        let [first] = imp.path.value.segments.as_slice() else {
            return false;
        };
        if module.imports.get(&first.value) != Some(&ImportTarget::Module(target)) {
            return false;
        }
        match &imp.kind {
            ImportKind::Simple => true,
            ImportKind::List(names) => names.iter().any(|n| n.value == name),
            _ => false,
        }
    })
}

/// Whether `scope` binds `name` in any namespace.
fn binds(scope: &ModuleScope, name: &str) -> bool {
    scope.values.contains_key(name)
        || scope.types.contains_key(name)
        || scope.traits.contains_key(name)
}

#[allow(clippy::too_many_arguments)]
fn insert_value(
    scope: &mut ModuleScope,
    exp: &mut Exports,
    first: &mut IndexMap<String, Span>,
    diagnostics: &mut Vec<Diagnostic>,
    name: String,
    span: Span,
    res: Res,
    is_pub: bool,
) {
    if scope.values.contains_key(&name) {
        let mut diag = Diagnostic::error("E0002", format!("duplicate definition of `{name}`"))
            .with_primary_label(span, "redefined here");
        if let Some(prev) = first.get(&name) {
            diag = diag.with_secondary_label(*prev, "first defined here");
        } else {
            diag = diag.with_note(format!("`{name}` is a compiler builtin"));
        }
        diagnostics.push(diag);
        return;
    }
    first.insert(name.clone(), span);
    if is_pub {
        exp.values.insert(name.clone(), res);
    }
    scope.values.insert(name, res);
}

#[allow(clippy::too_many_arguments)]
fn insert_type(
    scope: &mut ModuleScope,
    exp: &mut Exports,
    first: &mut IndexMap<String, Span>,
    diagnostics: &mut Vec<Diagnostic>,
    name: String,
    span: Span,
    id: DefId,
    is_pub: bool,
) {
    if scope.types.contains_key(&name) {
        let mut diag = Diagnostic::error("E0002", format!("duplicate definition of type `{name}`"))
            .with_primary_label(span, "redefined here");
        if let Some(prev) = first.get(&name) {
            diag = diag.with_secondary_label(*prev, "first defined here");
        }
        diagnostics.push(diag);
        return;
    }
    first.insert(name.clone(), span);
    if is_pub {
        exp.types.insert(name.clone(), id);
    }
    scope.types.insert(name, id);
}

/// Bind an imported name into a module's value namespace, or report a conflict.
fn bind_value(
    scope: &mut ModuleScope,
    diagnostics: &mut Vec<Diagnostic>,
    name: String,
    span: Span,
    res: Res,
) {
    if scope.values.contains_key(&name) {
        diagnostics.push(
            Diagnostic::error(
                "E0002",
                format!("`{name}` is already defined or imported in this module"),
            )
            .with_primary_label(span, "conflicting import"),
        );
        return;
    }
    scope.values.insert(name, res);
}

fn bind_type(
    scope: &mut ModuleScope,
    diagnostics: &mut Vec<Diagnostic>,
    name: String,
    span: Span,
    id: DefId,
) {
    if scope.types.contains_key(&name) {
        diagnostics.push(
            Diagnostic::error(
                "E0002",
                format!("type `{name}` is already defined or imported in this module"),
            )
            .with_primary_label(span, "conflicting import"),
        );
        return;
    }
    scope.types.insert(name, id);
}

fn bind_trait(
    scope: &mut ModuleScope,
    diagnostics: &mut Vec<Diagnostic>,
    name: String,
    span: Span,
    id: DefId,
) {
    if scope.traits.contains_key(&name) {
        diagnostics.push(
            Diagnostic::error(
                "E0002",
                format!("trait `{name}` is already defined or imported in this module"),
            )
            .with_primary_label(span, "conflicting import"),
        );
        return;
    }
    scope.traits.insert(name, id);
}

fn unsupported(span: Span, msg: &str) -> Diagnostic {
    Diagnostic::error("E0900", msg).with_primary_label(span, "not supported yet")
}

/// A short textual head for a type, used only to build unique method
/// symbol names (semantic resolution happens later in the type checker).
/// A textual name for an impl self type that includes its type arguments, so
/// that two impls sharing a head but differing in arguments (`Pair<Int, Bool>`
/// vs `Pair<Int, Int>`) yield distinct method names and never collide when
/// monomorphized. Uses only `_`/`.`-style separators to stay linker-safe.
/// A generic parameter contributes its source name (`Box<T>` โ†’ `Box_T`); a
/// concrete instantiation still gets a distinct mangled instance via type
/// arguments at monomorphization.
fn type_full_name(ty: &nova_ast::Type) -> String {
    match ty {
        nova_ast::Type::Path { path, args } => {
            let head = path_tail(path);
            if args.is_empty() {
                head
            } else {
                let parts: Vec<String> = args.iter().map(|a| type_full_name(&a.value)).collect();
                format!("{head}_{}", parts.join("_"))
            }
        }
        nova_ast::Type::Array(elem) => format!("Arr_{}", type_full_name(&elem.value)),
        _ => "anon".to_string(),
    }
}

/// The last segment of a path (`a::b::c` โ†’ `c`).
fn path_tail(path: &nova_ast::Path) -> String {
    path.segments
        .last()
        .map(|s| s.value.clone())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use nova_diagnostics::FileId;
    use nova_lexer::lex;
    use nova_parser::parse;

    fn resolve_src(src: &str) -> ResolveResult {
        let file_id = FileId::DUMMY;
        let (tokens, lex_errors) = lex(src, file_id);
        assert!(lex_errors.is_empty(), "lex errors: {lex_errors:?}");
        let (ast, parse_errors) = parse(&tokens, file_id);
        assert!(parse_errors.is_empty(), "parse errors: {parse_errors:?}");
        resolve(&ast.expect("no AST produced"))
    }

    fn parse_file(src: &str) -> nova_ast::File {
        let (tokens, _) = lex(src, FileId::DUMMY);
        let (ast, errs) = parse(&tokens, FileId::DUMMY);
        assert!(errs.is_empty(), "parse errors: {errs:?}");
        ast.expect("no AST")
    }

    /// Resolve a two-module program: `main` plus `lib`.
    fn resolve_two(main_src: &str, lib_src: &str) -> ProgramResolution {
        let main = parse_file(main_src);
        let lib = parse_file(lib_src);
        let mut sources = [
            ModuleSource::new("main", &main),
            ModuleSource::new("lib", &lib),
        ];
        name_imports(&mut sources);
        let std_files: Vec<FileId> = STD_MODULES.iter().map(|_| FileId::DUMMY).collect();
        resolve_program(&sources, &std_files, None)
    }

    fn error_codes(diags: &[Diagnostic]) -> Vec<&str> {
        diags.iter().map(|d| d.code.as_str()).collect()
    }

    // === Phase 3.3a: import tables (spec
    // docs/superpowers/specs/2026-10-08-phase-3-3a-local-packages-design.md ยง4.5) ===

    #[test]
    fn an_import_table_can_name_a_module_by_any_label() {
        let main = parse_file("import geom::{area}\nfn main() { let a = area() }\n");
        let lib = parse_file("pub fn area() -> Int { 1 }\n");
        let mut sources = [
            ModuleSource::new("main", &main),
            ModuleSource::new("geom", &lib),
        ];
        sources[1].name = "a label no import names".to_string();
        sources[0]
            .imports
            .insert("geom".to_string(), ImportTarget::Module(1));
        let std_files: Vec<FileId> = STD_MODULES.iter().map(|_| FileId::DUMMY).collect();
        let p = resolve_program(&sources, &std_files, None);
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
        assert!(matches!(
            p.definitions.resolve_value(ModuleId(0), "area"),
            Some(Res::Def(_))
        ));
    }

    #[test]
    fn a_reported_import_binds_nothing_and_says_nothing() {
        let main = parse_file("import geom\nfn main() {}\n");
        let mut sources = [ModuleSource::new("main", &main)];
        sources[0]
            .imports
            .insert("geom".to_string(), ImportTarget::Reported);
        let std_files: Vec<FileId> = STD_MODULES.iter().map(|_| FileId::DUMMY).collect();
        let p = resolve_program(&sources, &std_files, None);
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
    }

    #[test]
    fn an_import_missing_from_the_table_cannot_find_its_module() {
        let main = parse_file("import geom\nfn main() {}\n");
        let lib = parse_file("pub fn area() -> Int { 1 }\n");
        // No `name_imports`: the table is empty, whatever the modules' names.
        let sources = [
            ModuleSource::new("main", &main),
            ModuleSource::new("geom", &lib),
        ];
        let std_files: Vec<FileId> = STD_MODULES.iter().map(|_| FileId::DUMMY).collect();
        let p = resolve_program(&sources, &std_files, None);
        assert_eq!(error_codes(&p.diagnostics), ["E0001"]);
        assert!(p.diagnostics[0]
            .message
            .contains("cannot find module `geom`"));
    }

    #[test]
    fn import_binds_public_names_across_modules() {
        let p = resolve_two(
            "import lib::{add}\nfn main() { let x = add(1, 2) }\n",
            "pub fn add(a: Int, b: Int) -> Int { a + b }\nfn secret() -> Int { 0 }\n",
        );
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
        // `add` is visible in module 0 (main) after the import.
        assert!(matches!(
            p.definitions.resolve_value(ModuleId(0), "add"),
            Some(Res::Def(_))
        ));
    }

    #[test]
    fn importing_a_private_item_is_rejected() {
        let p = resolve_two(
            "import lib::{secret}\nfn main() { }\n",
            "pub fn add() -> Int { 0 }\nfn secret() -> Int { 0 }\n",
        );
        assert!(
            error_codes(&p.diagnostics).contains(&"E0001"),
            "{:?}",
            p.diagnostics
        );
    }

    #[test]
    fn dangling_import_reports_missing_module() {
        let p = resolve_two(
            "import nope::{x}\nfn main() { }\n",
            "pub fn add() -> Int { 0 }\n",
        );
        assert!(
            error_codes(&p.diagnostics).contains(&"E0001"),
            "{:?}",
            p.diagnostics
        );
    }

    #[test]
    fn private_item_is_not_visible_to_other_modules() {
        let p = resolve_two(
            "import lib\nfn main() { }\n",
            "pub fn add() -> Int { 0 }\nfn secret() -> Int { 0 }\n",
        );
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
        // Glob import brings `add` but not `secret`.
        assert!(p.definitions.resolve_value(ModuleId(0), "add").is_some());
        assert!(p.definitions.resolve_value(ModuleId(0), "secret").is_none());
    }

    #[test]
    fn same_name_in_two_modules_does_not_collide() {
        // Each module has its own `helper`; no duplicate-definition error.
        // (Codegen keeps them distinct via DefId-mangled symbols; see the
        // `modules_same_name_functions_dispatch_correctly` CLI test.)
        let p = resolve_two(
            "fn helper() -> Int { 1 }\nfn main() { }\n",
            "pub fn helper() -> Int { 2 }\n",
        );
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
    }

    #[test]
    fn qualified_import_path_is_rejected() {
        // `import lib::extra` is a qualified/nested path; it must be reported,
        // not silently resolved to the last segment's module.
        let p = resolve_two(
            "import lib::extra\nfn main() { }\n",
            "pub fn add() -> Int { 0 }\n",
        );
        assert!(
            error_codes(&p.diagnostics).contains(&"E0900"),
            "{:?}",
            p.diagnostics
        );
    }

    #[test]
    fn std_core_option_result_are_in_scope() {
        // Option/Result and their variants resolve with no import or definition.
        let r = resolve_src("fn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert!(r.definitions.resolve_type(ModuleId(0), "Option").is_some());
        assert!(r.definitions.resolve_type(ModuleId(0), "Result").is_some());
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "Some"),
            Some(Res::Variant(_, 0))
        ));
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "None"),
            Some(Res::Variant(_, 1))
        ));
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "Ok"),
            Some(Res::Variant(_, 0))
        ));
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "Err"),
            Some(Res::Variant(_, 1))
        ));
    }

    #[test]
    fn extern_fn_resolves_as_callable_extern_def() {
        let r = resolve_src("extern \"C\" { fn sqrt(x: Float) -> Float }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let Some(Res::Def(id)) = r.definitions.resolve_value(ModuleId(0), "sqrt") else {
            panic!("sqrt should resolve to a Def");
        };
        assert!(matches!(
            r.definitions.def(id).kind,
            DefKind::ExternFn { .. }
        ));
    }

    #[test]
    fn user_type_shadows_std_core() {
        // A user-defined `Option` shadows std/core's without an E0002 clash:
        // the module's own definition wins over the soft std/core import.
        let r = resolve_src("type Option<T> = | Present(T) | Absent\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let opt = r
            .definitions
            .resolve_type(ModuleId(0), "Option")
            .expect("Option resolves");
        // It is the user's two-variant `Option`, not std/core's.
        assert!(matches!(
            r.definitions.def(opt).kind,
            DefKind::Sum { ref variants, .. } if variants.len() == 2 && variants[0].name == "Present"
        ));
    }

    #[test]
    fn user_trait_shadows_std_core() {
        // The trait-namespace analogue of `user_type_shadows_std_core`: a
        // user-defined `Display` shadows std/core's without an E0002 clash,
        // the module's own trait winning over the soft std/core import. Pins
        // the `or_insert`-vs-`insert` precedence `import_std_module`'s `traits`
        // loop relies on (mirrored from the pre-existing `values`/`types`
        // loops) โ€” the easiest part of that fix to accidentally break later,
        // since nothing else in this file failed the way it would if this
        // regressed (std/core's `Display` would silently win instead, and
        // every method call would still type-check, just against the wrong
        // trait).
        let r = resolve_src("trait Display { fn only_here(self) -> Int }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let tr = r
            .definitions
            .resolve_trait(ModuleId(0), "Display")
            .expect("Display resolves");
        // It is module 0's own trait (declaring `only_here`), not std/core's
        // `Display` (declaring `fmt`), which lives in a different module.
        assert!(matches!(
            r.definitions.def(tr).kind,
            DefKind::Trait { item_index } if r.definitions.module_of(item_index) == ModuleId(0)
        ));
    }

    #[test]
    fn associated_type_is_not_in_the_type_namespace() {
        // `Item` is not a type name you can write bare โ€” it is reachable only
        // through a projection (`Self::Item`, resolved in a later task). If a
        // future change ever seeded it into `scope.types` too, this would
        // start returning `Some`, silently making it a global type name.
        let r = resolve_src("trait It { type Item }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert_eq!(r.definitions.resolve_type(ModuleId(0), "Item"), None);
    }

    #[test]
    fn associated_type_is_not_in_the_value_namespace() {
        // Mirrors the test above for the other namespace: an associated
        // type's `Def` is created by `push_def` alone and never registered in
        // `scope.values` either, so it must not resolve as an expression name
        // (there is no value `Item` could denote). Untested until now, not
        // known broken.
        let r = resolve_src("trait It { type Item }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert_eq!(r.definitions.resolve_value(ModuleId(0), "Item"), None);
    }

    #[test]
    fn user_fn_named_str_cmp_is_not_a_reserved_word() {
        // Regression for the `str_cmp` builtin becoming an accidental
        // reserved word in every module: `Builtin::STD_ONLY` (unlike
        // `Builtin::GLOBAL`) is seeded only into an std module's own scope,
        // so a user module defining its own `str_cmp` must compile cleanly โ€”
        // no E0002 "duplicate definition" / "compiler builtin" diagnostic.
        let r = resolve_src("fn str_cmp(a: Int, b: Int) -> Int { a + b }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "str_cmp"),
            Some(Res::Def(_))
        ));
    }

    /// Same property as `user_fn_named_str_cmp_is_not_a_reserved_word`, for
    /// every other member of `Builtin::STD_ONLY`. Written as a loop over
    /// the constant so that adding a builtin to it without deciding this
    /// question cannot happen: a new std-only builtin is covered here the
    /// moment it joins the list.
    #[test]
    fn no_std_only_builtin_is_a_reserved_word() {
        for b in Builtin::STD_ONLY {
            let name = b.name();
            let src = format!("fn {name}(a: Int, b: Int) -> Int {{ a + b }}\nfn main() {{ }}\n");
            let r = resolve_src(&src);
            assert!(r.diagnostics.is_empty(), "`{name}`: {:?}", r.diagnostics);
            assert!(
                matches!(
                    r.definitions.resolve_value(ModuleId(0), name),
                    Some(Res::Def(_))
                ),
                "`{name}` should resolve to the user's own definition"
            );
        }
    }

    /// The other half of the std-only contract: each of these names *is*
    /// visible inside an std module, so `std/core` can call it. Without this,
    /// dropping a builtin from `STD_ONLY` altogether would still leave
    /// `no_std_only_builtin_is_a_reserved_word` passing.
    #[test]
    fn std_only_builtins_are_visible_inside_std_modules() {
        let r = resolve_src("fn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        // Module 0 is the single user module; the std modules follow it, one
        // per `STD_MODULES` entry, in order (ADR 0004). *Every* one of them
        // gets these builtins, not only `$std.core`.
        for mid in 1..=STD_MODULES.len() {
            for b in Builtin::STD_ONLY {
                assert!(
                    matches!(
                        r.definitions.resolve_value(ModuleId(mid as u32), b.name()),
                        Some(Res::Builtin(seen)) if seen == b
                    ),
                    "`{}` must resolve to its builtin inside std module {mid}",
                    b.name()
                );
            }
        }
    }

    /// Every `std/net` builtin is `STD_ONLY`, per the brief this task
    /// was written against. `STD_ONLY.contains` rather than the loop
    /// `no_std_only_builtin_is_a_reserved_word`/
    /// `std_only_builtins_are_visible_inside_std_modules` already run over
    /// the whole array: this test pins each one *by name*, so deleting one
    /// from `STD_ONLY` (rather than merely narrowing its behaviour) fails
    /// here specifically instead of only shrinking a loop bound elsewhere.
    ///
    /// The list grows with the module, and has grown three times while
    /// `std/net` gained its listener: `NetListen` joined the original five,
    /// then `NetLocalPort`, then `NetAccept`. This test is the reason a new net
    /// builtin cannot be
    /// added to the enum and left out of `STD_ONLY` without a named failure --
    /// provided whoever adds it also adds it *here*, which no compiler
    /// enforces. That is the one gap: `STD_ONLY`'s own declared length is a
    /// build error when it drifts, but this list is a hand-maintained roster,
    /// so an omission here is silent rather than caught.
    ///
    /// `STD_ONLY` membership is the whole of what this asserts. It was
    /// originally named `..._and_build_futures`, which promised a second
    /// property its body never checked -- that coverage genuinely exists, in
    /// `nova-typeck`'s `builtin_signatures_are_what_the_std_call_sites_use`
    /// (`crates/nova-typeck/src/check.rs`), which is where each builtin's
    /// `Future<_>` return type is actually pinned against its `std/net` call
    /// site.
    #[test]
    fn the_net_builtins_are_std_only() {
        for b in [
            Builtin::NetConnect,
            Builtin::NetClose,
            Builtin::NetRead,
            Builtin::NetWrite,
            Builtin::NetReadTimeout,
            Builtin::NetListen,
            Builtin::NetLocalPort,
            Builtin::NetAccept,
        ] {
            assert!(
                Builtin::STD_ONLY.contains(&b),
                "{b:?} must be invisible to user code"
            );
        }
    }

    #[test]
    fn user_fn_named_panic_is_a_reserved_word() {
        // The deliberate counterpart of
        // `user_fn_named_str_cmp_is_not_a_reserved_word`, and the reason that
        // test needs a sibling: `panic` is in `Builtin::GLOBAL`, so it *is*
        // seeded into every module's scope and a user `fn panic` is an E0002
        // clash against a builtin. That is intended โ€” `panic` is user-visible
        // language surface like `println`/`print` โ€” but it permanently takes
        // the name away from user code, so which side of the
        // `GLOBAL`/`STD_ONLY` split each builtin sits on has to be pinned
        // in both directions. Moving `Panic` to `STD_ONLY` would silently
        // make `panic(...)` unresolvable in user programs while every existing
        // test still passed.
        let r = resolve_src("fn panic(msg: String) { }\nfn main() { }\n");
        let codes: Vec<&str> = r.diagnostics.iter().map(|d| d.code.as_str()).collect();
        assert!(codes.contains(&"E0002"), "{:?}", r.diagnostics);
        // Specifically the builtin-clash form of E0002 (no earlier user
        // definition to point at), not a duplicate-user-definition one.
        assert!(
            r.diagnostics
                .iter()
                .any(|d| d.notes.iter().any(|n| n.contains("compiler builtin"))),
            "expected the `panic` is a compiler builtin note: {:?}",
            r.diagnostics
        );
    }

    #[test]
    fn std_core_traits_are_visible_from_a_user_module() {
        // Regression test for a gap `import_std_module` had: it merged `values`
        // and `types` from std/core's exports into every other module's scope,
        // but not `traits`, so a trait declared in std/core (e.g. `Display`,
        // `Eq`, `Ord`) could never be named from user code even though its
        // impls live right there in std/core alongside it. A user module that
        // declares no trait of its own must still resolve std/core's by name.
        let r = resolve_src("fn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        for name in ["Display", "Debug", "Eq", "Ord", "Clone", "Default"] {
            assert!(
                r.definitions.resolve_trait(ModuleId(0), name).is_some(),
                "expected std/core's `{name}` trait to resolve from module 0"
            );
        }
    }

    #[test]
    fn std_collections_module_is_compiled_and_visible() {
        // A name defined in std/collections must resolve from a user module,
        // exactly as std/core's names do.
        let r = resolve_src("fn main() { }");
        assert!(
            r.definitions.resolve_type(ModuleId(0), "Vec").is_some(),
            "Vec should be visible from a user module"
        );
    }

    #[test]
    fn importing_a_std_core_name_from_a_module_is_allowed() {
        // A user module may export a name coinciding with a std/core name; a
        // glob import of it binds (shadowing the soft std/core import), not a
        // spurious E0002.
        let p = resolve_two(
            "import lib\nfn main() { }\n",
            "pub type Status = | Ok | Fail\n",
        );
        assert!(p.diagnostics.is_empty(), "{:?}", p.diagnostics);
        // `Ok` resolves (to the imported Status variant), not rejected.
        assert!(p.definitions.resolve_value(ModuleId(0), "Ok").is_some());
    }

    #[test]
    fn collects_functions_and_sum_types() {
        let r = resolve_src(
            "type Shape = | Circle(Int) | Empty\n\
             fn area(s: Shape) -> Int { 0 }\n\
             fn main() { }\n",
        );
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "area"),
            Some(Res::Def(_))
        ));
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "Circle"),
            Some(Res::Variant(_, 0))
        ));
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "Empty"),
            Some(Res::Variant(_, 1))
        ));
        assert!(r.definitions.resolve_type(ModuleId(0), "Shape").is_some());
        assert!(matches!(
            r.definitions.resolve_value(ModuleId(0), "println"),
            Some(Res::Builtin(Builtin::Println))
        ));
    }

    #[test]
    fn collects_records() {
        let r = resolve_src("record Point { x: Float, y: Float }\nfn main() { }\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let id = r
            .definitions
            .resolve_type(ModuleId(0), "Point")
            .expect("Point resolves");
        assert!(matches!(r.definitions.def(id).kind, DefKind::Record { .. }));
    }

    #[test]
    fn collects_traits_and_impl_methods() {
        let r = resolve_src(
            "record P { v: Int }\n\
             trait Show { fn name(self) -> String\n fn shout(self) -> String { self.name() } }\n\
             impl Show for P { fn name(self) -> String { \"p\" } }\n\
             impl P { fn get(self) -> Int { self.v } }\n\
             fn main() { }\n",
        );
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        assert!(r.definitions.resolve_trait(ModuleId(0), "Show").is_some());
        // `methods()` is whole-program โ€” it also sees every method std/core
        // defines on Option/Result โ€” so scope the count to this source's own
        // module (module 0) rather than asserting a total that shifts every
        // time std/core grows. This source defines exactly 3: the trait's
        // default `shout`, the trait-impl `name`, and the inherent `get`.
        let methods = r
            .definitions
            .methods()
            .filter(|&(_, item_index, _, _)| r.definitions.module_of(item_index) == ModuleId(0))
            .count();
        assert_eq!(methods, 3, "expected this module's own 3 method defs");
    }

    #[test]
    fn duplicate_function_reports_e0002() {
        let r = resolve_src("fn f() { }\nfn f() { }\n");
        assert_eq!(r.diagnostics.len(), 1);
        assert_eq!(r.diagnostics[0].code, "E0002");
    }

    #[test]
    fn shadowing_builtin_reports_e0002() {
        let r = resolve_src("fn println() { }\n");
        assert_eq!(r.diagnostics.len(), 1);
        assert_eq!(r.diagnostics[0].code, "E0002");
    }

    // === Phase 3.2: names in scope (spec
    // docs/superpowers/specs/2026-10-08-phase-3-2-lsp-core-design.md ยง4.3) ===

    #[test]
    fn names_in_scope_lists_items_imports_builtins_variants_and_std() {
        let r = resolve_two(
            "import lib::{area}\nrecord Point { x: Int }\nfn main() {}\n",
            "pub fn area() -> Int { 1 }\n",
        );
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let names = r.definitions.names_in_scope(ModuleId(0));
        let has = |name: &str, kind: fn(&ScopeEntry) -> bool| {
            names.iter().any(|(n, e)| n == name && kind(e))
        };
        assert!(has("main", |e| matches!(e, ScopeEntry::Value(Res::Def(_)))));
        assert!(has("Point", |e| matches!(e, ScopeEntry::Type(_))));
        assert!(has("area", |e| matches!(e, ScopeEntry::Value(Res::Def(_)))));
        assert!(has("println", |e| matches!(
            e,
            ScopeEntry::Value(Res::Builtin(_))
        )));
        assert!(has("Some", |e| matches!(
            e,
            ScopeEntry::Value(Res::Variant(_, _))
        )));
        assert!(has("Vec", |e| matches!(e, ScopeEntry::Type(_))));
        assert!(has("Display", |e| matches!(e, ScopeEntry::Trait(_))));
        let mut sorted = names.clone();
        sorted.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(
            names.iter().map(|n| &n.0).collect::<Vec<_>>(),
            sorted.iter().map(|n| &n.0).collect::<Vec<_>>(),
            "sorted by name"
        );
    }

    #[test]
    fn a_std_name_the_module_shadows_is_listed_once_as_its_own() {
        let r = resolve_two("record Vec { n: Int }\nfn main() {}\n", "pub fn f() {}\n");
        assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
        let vecs: Vec<DefId> = r
            .definitions
            .names_in_scope(ModuleId(0))
            .into_iter()
            .filter_map(|(n, e)| match e {
                ScopeEntry::Type(id) if n == "Vec" => Some(id),
                _ => None,
            })
            .collect();
        assert_eq!(vecs.len(), 1, "{vecs:?}");
        let DefKind::Record { item_index } = r.definitions.def(vecs[0]).kind else {
            panic!("not a record");
        };
        assert_eq!(r.definitions.module_of(item_index), ModuleId(0));
    }

    // === Phase 3.4a: import occurrences (spec
    // docs/superpowers/specs/2026-10-10-phase-3-4a-navigation-design.md ยง3.3) ===

    fn occurrence_at(prog: &ProgramResolution, src: &str, needle: &str) -> Vec<(Role, Target)> {
        let start = src.find(needle).unwrap() as u32;
        prog.imports
            .iter()
            .filter(|o| o.span.start == start && o.span.end == start + needle.len() as u32)
            .map(|o| (o.role, o.target))
            .collect()
    }

    #[test]
    fn an_imports_module_is_a_use_of_it() {
        let main = "import lib\nfn main() { let a = area() }\n";
        let prog = resolve_two(main, "pub fn area() -> Int { 1 }\n");
        assert_eq!(
            occurrence_at(&prog, main, "lib"),
            vec![(Role::Use, Target::Module(ModuleId(1)))]
        );
    }

    #[test]
    fn a_list_imports_module_is_its_first_segment() {
        let main = "import lib::{area}\nfn main() { let a = area() }\n";
        let prog = resolve_two(main, "pub fn area() -> Int { 1 }\n");
        // `lib` alone, not `lib::`.
        assert_eq!(
            occurrence_at(&prog, main, "lib"),
            vec![(Role::Use, Target::Module(ModuleId(1)))]
        );
    }

    #[test]
    fn a_listed_name_is_a_use_of_each_namespace_it_binds() {
        // User modules' defs come before std's, so `position` finds these.
        let main = "import lib::{area, Figure, Paint, Round}\nfn main() {}\n";
        let lib = "pub fn area() -> Int { 1 }\n\
                   pub type Figure = | Round(Int) | Square(Int)\n\
                   pub trait Paint { fn paint(self) -> String }\n";
        let prog = resolve_two(main, lib);
        let id = |name: &str| {
            DefId(
                prog.definitions
                    .defs()
                    .iter()
                    .position(|d| d.name == name)
                    .unwrap() as u32,
            )
        };
        assert_eq!(
            occurrence_at(&prog, main, "area"),
            vec![(Role::Use, Target::Def(id("area")))]
        );
        assert_eq!(
            occurrence_at(&prog, main, "Figure"),
            vec![(Role::Use, Target::Def(id("Figure")))]
        );
        assert_eq!(
            occurrence_at(&prog, main, "Paint"),
            vec![(Role::Use, Target::Def(id("Paint")))]
        );
        assert_eq!(
            occurrence_at(&prog, main, "Round"),
            vec![(Role::Use, Target::Variant(id("Figure"), 0))]
        );
    }

    #[test]
    fn an_unresolved_import_records_nothing() {
        let main = "import nowhere\nimport lib::{missing}\nfn main() {}\n";
        let prog = resolve_two(main, "pub fn area() -> Int { 1 }\n");
        assert!(occurrence_at(&prog, main, "nowhere").is_empty());
        assert!(occurrence_at(&prog, main, "missing").is_empty());
        // The module of a list import still resolves.
        assert_eq!(occurrence_at(&prog, main, "lib").len(), 1);
    }

    // === Phase 3.4b: what a fix needs to know (spec
    // docs/superpowers/specs/2026-10-10-phase-3-4b-fixes-and-colour-design.md ยง4.6) ===

    #[test]
    fn name_imports_makes_every_other_module_importable() {
        let p = resolve_two("fn main() {}\n", "pub fn area() -> Int { 1 }\n");
        let d = &p.definitions;
        assert_eq!(
            d.importable(ModuleId(0)),
            [("lib".to_string(), ModuleId(1))]
        );
        assert_eq!(
            d.importable(ModuleId(1)),
            [("main".to_string(), ModuleId(0))]
        );
        assert!(d.same_package(ModuleId(0), ModuleId(1)));
        // A loose program's modules are owned; std's are not.
        assert!(d.owned(ModuleId(0)) && d.owned(ModuleId(1)) && !d.owned(ModuleId(2)));
    }

    #[test]
    fn exported_names_each_namespace_a_public_name_has() {
        let p = resolve_two(
            "fn main() {}\n",
            "pub record Area { x: Int }\npub fn area() -> Int { 1 }\nfn hidden() -> Int { 0 }\n",
        );
        let d = &p.definitions;
        let area = d.exported(ModuleId(1), "area");
        assert!(matches!(area.value, Some(Res::Def(_))), "{area:?}");
        assert!(area.ty.is_none() && area.trait_def.is_none(), "{area:?}");
        assert!(d.exported(ModuleId(1), "Area").ty.is_some());
        assert_eq!(d.exported(ModuleId(1), "hidden"), Exported::default());
    }

    #[test]
    fn a_name_bound_through_std_is_not_bound_outside_it() {
        let p = resolve_two(
            "record Option { x: Int }\nfn main() {}\n",
            "pub fn area() -> Int { 1 }\n",
        );
        let d = &p.definitions;
        assert_eq!(
            d.bound_outside_std(ModuleId(0), "Some"),
            Exported::default()
        );
        assert!(d.bound_outside_std(ModuleId(0), "Option").ty.is_some());
        assert!(matches!(
            d.bound_outside_std(ModuleId(0), "println").value,
            Some(Res::Builtin(_))
        ));
        assert!(d.is_std_module(ModuleId(2)) && !d.is_std_module(ModuleId(1)));
    }
}