xlsynth 0.46.0

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

use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::aot_entrypoint_metadata::{
    get_entrypoint_function_signature, AotEntrypointMetadata, AotFunctionSignature, AotType,
    AotTypeLayout,
};
use crate::aot_lib::{AotCompiled, AotResult};
use crate::dslx_bridge::{convert_imported_module, BridgeBuilder};
use crate::rust_bridge_builder::{
    render_rust_module_fragments, rust_type_path_between_dslx_modules, RustBridgeBuilder,
};
use crate::xlsynth_error::XlsynthError;
use crate::{
    convert_dslx_to_ir_text, dslx, dslx_path_to_module_name,
    mangle_dslx_name_with_calling_convention, DslxCallingConvention, DslxConvertOptions,
};

#[derive(Debug, Clone)]
/// Inputs required to compile one XLS IR function into generated AOT wrapper
/// artifacts.
pub struct AotBuildSpec<'a> {
    /// Base name used for emitted artifact filenames and generated symbol
    /// wrappers.
    pub name: &'a str,
    /// XLS IR package text that contains `top`.
    pub ir_text: &'a str,
    /// Name of the IR function to compile as the AOT entrypoint.
    pub top: &'a str,
}

/// Inputs required to compile one DSLX function into a typed DSLX AOT wrapper.
///
/// The generated module contains Rust bridge definitions for
/// `type_module_paths`, Rust bridge definitions for `dslx_path`, and a `Runner`
/// whose public signature uses canonical paths to those generated Rust bridge
/// types.
pub struct TypedDslxAotBuildSpec<'a> {
    /// Base name used for emitted artifact filenames and generated symbol
    /// wrappers.
    pub name: &'a str,
    /// DSLX source file that contains the top function.
    pub dslx_path: &'a Path,
    /// Name of the DSLX function to compile as the AOT entrypoint.
    pub top: &'a str,
    /// DSLX conversion options used for typechecking, dependency discovery, and
    /// IR lowering.
    pub dslx_options: DslxConvertOptions<'a>,
    /// DSLX modules whose public types should be emitted beside the top module
    /// wrapper.
    pub type_module_paths: Vec<&'a Path>,
}

/// Collects several typed DSLX AOT entrypoints into one generated Rust package.
///
/// Package builds emit the participating DSLX modules once and place one
/// runner module per entrypoint beneath the DSLX module that owns the selected
/// top function. That keeps the public Rust types nominally shared across
/// runners instead of minting one copy per generated wrapper file.
pub struct TypedDslxAotPackageBuilder<'a> {
    /// Base name used for the generated shared Rust source file.
    name: &'a str,
    /// Entrypoints to compile into the package.
    specs: Vec<TypedDslxAotBuildSpec<'a>>,
}

/// Paths and metadata for one AOT entrypoint inside a shared typed DSLX
/// package.
#[derive(Debug, Clone)]
pub struct GeneratedTypedDslxAotEntrypoint {
    /// Build spec name after validation and filename sanitization.
    pub name: String,
    /// Object file containing the compiled AOT entrypoint.
    pub object_file: PathBuf,
    /// Serialized entrypoint metadata consumed by the generated descriptor.
    pub entrypoints_proto_file: PathBuf,
    /// Parsed AOT metadata for the selected entrypoint.
    pub metadata: AotEntrypointMetadata,
}

/// Paths and metadata for a generated shared typed DSLX AOT package.
#[derive(Debug, Clone)]
pub struct GeneratedTypedDslxAotPackage {
    /// Package name after validation and filename sanitization.
    pub name: String,
    /// Generated Rust source file that callers include once from build output.
    pub rust_file: PathBuf,
    /// Compiled AOT artifacts for each requested package entrypoint.
    pub entrypoints: Vec<GeneratedTypedDslxAotEntrypoint>,
}

struct TypedDslxCompiledEntrypoint<'a> {
    spec: &'a TypedDslxAotBuildSpec<'a>,
    base_name: String,
    dslx_text: String,
    proto_file_name: String,
    object_file: PathBuf,
    proto_file: PathBuf,
    metadata: AotEntrypointMetadata,
    signature: AotFunctionSignature,
}

/// Paths and metadata for emitted AOT wrapper artifacts in a build output
/// directory.
///
/// The generated Rust wrapper includes typed encode/decode helpers and a thin
/// `Runner` wrapper over `xlsynth::AotRunner`.
#[derive(Debug, Clone)]
pub struct GeneratedAotModule {
    /// Build spec name after validation and filename sanitization.
    pub name: String,
    /// Generated Rust source file that callers include from their build output.
    pub rust_file: PathBuf,
    /// Object file containing the compiled AOT entrypoint.
    pub object_file: PathBuf,
    /// Serialized entrypoint metadata consumed by the generated descriptor.
    pub entrypoints_proto_file: PathBuf,
    /// Parsed AOT metadata for the selected entrypoint.
    pub metadata: AotEntrypointMetadata,
}

/// Compiles IR text into raw AOT object code and parsed entrypoint metadata.
pub fn compile_ir_to_aot(ir_text: &str, top: &str) -> AotResult<AotCompiled> {
    AotCompiled::compile_ir(ir_text, top)
}

/// Emits AOT artifacts into Cargo's `OUT_DIR`.
///
/// This is the build-script friendly entry point and requires `OUT_DIR` to be
/// set in the environment.
pub fn emit_aot_module_from_ir_text(spec: &AotBuildSpec<'_>) -> AotResult<GeneratedAotModule> {
    let out_dir = std::env::var("OUT_DIR").map_err(|e| {
        XlsynthError(format!(
            "AOT build environment error: OUT_DIR was not set while emitting AOT module: {e}"
        ))
    })?;
    emit_aot_module_from_ir_text_with_out_dir(spec, Path::new(&out_dir))
}

/// Emits typed DSLX AOT artifacts into Cargo's `OUT_DIR`.
///
/// This DSLX-aware entry point is additive to the IR-only API and preserves
/// the old structural wrapper behavior for existing callers.
pub fn emit_typed_dslx_aot_module_from_file(
    spec: &TypedDslxAotBuildSpec<'_>,
) -> AotResult<GeneratedAotModule> {
    let out_dir = std::env::var("OUT_DIR").map_err(|e| {
        XlsynthError(format!(
            "AOT build environment error: OUT_DIR was not set while emitting typed DSLX AOT module: {e}"
        ))
    })?;
    emit_typed_dslx_aot_module_from_file_with_out_dir(spec, Path::new(&out_dir))
}

impl<'a> TypedDslxAotPackageBuilder<'a> {
    /// Creates an empty package builder.
    pub fn new(name: &'a str) -> Self {
        Self {
            name,
            specs: Vec::new(),
        }
    }

    /// Appends one typed DSLX AOT entrypoint to the package.
    pub fn add_entrypoint(mut self, spec: TypedDslxAotBuildSpec<'a>) -> Self {
        self.specs.push(spec);
        self
    }

    /// Emits the package into Cargo's `OUT_DIR`.
    pub fn build(&self) -> AotResult<GeneratedTypedDslxAotPackage> {
        let out_dir = std::env::var("OUT_DIR").map_err(|e| {
            XlsynthError(format!(
                "AOT build environment error: OUT_DIR was not set while emitting typed DSLX AOT package: {e}"
            ))
        })?;
        self.build_with_out_dir(Path::new(&out_dir))
    }

    /// Emits the package into an explicit output directory.
    pub fn build_with_out_dir(&self, out_dir: &Path) -> AotResult<GeneratedTypedDslxAotPackage> {
        emit_typed_dslx_aot_package_with_out_dir(self, out_dir)
    }
}

fn compile_typed_dslx_entrypoint_artifacts<'a>(
    spec: &'a TypedDslxAotBuildSpec<'a>,
    out_dir: &Path,
) -> AotResult<TypedDslxCompiledEntrypoint<'a>> {
    if spec.name.is_empty() {
        return Err(XlsynthError(
            "AOT invalid argument: typed DSLX build spec name must not be empty".to_string(),
        ));
    }
    if spec.top.is_empty() {
        return Err(XlsynthError(
            "AOT invalid argument: typed DSLX build spec top function must not be empty"
                .to_string(),
        ));
    }

    for dslx_source_path in collect_typed_dslx_aot_dependencies(spec)? {
        println!("cargo:rerun-if-changed={}", dslx_source_path.display());
    }

    let dslx_text = std::fs::read_to_string(spec.dslx_path).map_err(|e| {
        XlsynthError(format!(
            "AOT I/O failed for {}: {e}",
            spec.dslx_path.display()
        ))
    })?;
    let ir_text = convert_dslx_to_ir_text(&dslx_text, spec.dslx_path, &spec.dslx_options)?.ir;
    let dslx_module_name = dslx_path_to_module_name(spec.dslx_path)?;
    let calling_convention = if spec.dslx_options.force_implicit_token_calling_convention {
        DslxCallingConvention::ImplicitToken
    } else {
        DslxCallingConvention::Typical
    };
    let aot_top =
        mangle_dslx_name_with_calling_convention(dslx_module_name, spec.top, calling_convention)?;
    let compile = compile_ir_to_aot(&ir_text, &aot_top)?;
    let base_name = sanitize_identifier(spec.name);
    let AotCompiled {
        object_code,
        entrypoints_proto,
        metadata,
    } = compile;
    let signature = get_entrypoint_function_signature(&entrypoints_proto)
        .map_err(|e| XlsynthError(format!("AOT metadata parse failed: {}", e.0)))?;

    let object_file = out_dir.join(format!("{base_name}.aot.o"));
    let proto_file = out_dir.join(format!("{base_name}.entrypoints.pb"));
    write_file(&object_file, &object_code)?;
    write_file(&proto_file, &entrypoints_proto)?;
    let proto_file_name = proto_file
        .file_name()
        .and_then(|f| f.to_str())
        .ok_or_else(|| {
            XlsynthError(format!(
                "AOT build environment error: failed to derive UTF-8 file name from proto path {}",
                proto_file.display()
            ))
        })?
        .to_string();
    emit_link_archive(&base_name, &object_file)?;

    Ok(TypedDslxCompiledEntrypoint {
        spec,
        base_name,
        dslx_text,
        proto_file_name,
        object_file,
        proto_file,
        metadata,
        signature,
    })
}

/// Emits typed DSLX AOT artifacts into an explicit output directory.
///
/// This compiles the DSLX top function, emits bridge definitions for selected
/// DSLX modules, validates those semantic types against AOT metadata, and
/// writes a generated Rust module that encodes/decodes typed DSLX values
/// directly.
pub fn emit_typed_dslx_aot_module_from_file_with_out_dir(
    spec: &TypedDslxAotBuildSpec<'_>,
    out_dir: &Path,
) -> AotResult<GeneratedAotModule> {
    let compiled = compile_typed_dslx_entrypoint_artifacts(spec, out_dir)?;
    let rust_file = out_dir.join(format!("{}_typed_dslx_aot_wrapper.rs", compiled.base_name));
    let generated = render_typed_dslx_generated_module(
        spec,
        &compiled.dslx_text,
        &compiled.base_name,
        &compiled.proto_file_name,
        &compiled.metadata,
        &compiled.signature,
    )?;
    write_file(&rust_file, generated.as_bytes())?;
    run_rustfmt_best_effort(&rust_file);

    Ok(GeneratedAotModule {
        name: compiled.base_name,
        rust_file,
        object_file: compiled.object_file,
        entrypoints_proto_file: compiled.proto_file,
        metadata: compiled.metadata,
    })
}

/// Emits AOT object/proto/wrapper artifacts into an explicit output directory.
///
/// This compiles the target function, writes the object and entrypoint proto,
/// generates a typed Rust wrapper module, and emits a static archive suitable
/// for linking into the final crate.
pub fn emit_aot_module_from_ir_text_with_out_dir(
    spec: &AotBuildSpec<'_>,
    out_dir: &Path,
) -> AotResult<GeneratedAotModule> {
    if spec.name.is_empty() {
        return Err(XlsynthError(
            "AOT invalid argument: build spec name must not be empty".to_string(),
        ));
    }
    if spec.top.is_empty() {
        return Err(XlsynthError(
            "AOT invalid argument: build spec top function must not be empty".to_string(),
        ));
    }

    let compile = compile_ir_to_aot(spec.ir_text, spec.top)?;
    let base_name = sanitize_identifier(spec.name);
    let AotCompiled {
        object_code,
        entrypoints_proto,
        metadata: selected_metadata,
    } = compile;
    let signature = get_entrypoint_function_signature(&entrypoints_proto)
        .map_err(|e| XlsynthError(format!("AOT metadata parse failed: {}", e.0)))?;

    let object_file = out_dir.join(format!("{base_name}.aot.o"));
    let proto_file = out_dir.join(format!("{base_name}.entrypoints.pb"));
    let rust_file = out_dir.join(format!("{base_name}_aot_wrapper.rs"));

    write_file(&object_file, &object_code)?;
    write_file(&proto_file, &entrypoints_proto)?;

    let proto_file_name = proto_file
        .file_name()
        .and_then(|f| f.to_str())
        .ok_or_else(|| {
            XlsynthError(format!(
                "AOT build environment error: failed to derive UTF-8 file name from proto path {}",
                proto_file.display()
            ))
        })?;

    let generated = render_generated_module(
        &base_name,
        proto_file_name,
        &selected_metadata,
        &signature,
        spec.name,
        spec.top,
    )?;
    write_file(&rust_file, generated.as_bytes())?;
    run_rustfmt_best_effort(&rust_file);

    emit_link_archive(&base_name, &object_file)?;

    Ok(GeneratedAotModule {
        name: base_name,
        rust_file,
        object_file,
        entrypoints_proto_file: proto_file,
        metadata: selected_metadata,
    })
}

/// Reads IR text from disk and emits AOT artifacts into `OUT_DIR`.
///
/// This helper also emits `cargo:rerun-if-changed` for the IR file so Cargo
/// rebuilds generated artifacts when the input IR changes.
pub fn emit_aot_module_from_ir_file(
    name: &str,
    ir_path: &Path,
    top: &str,
) -> AotResult<GeneratedAotModule> {
    println!("cargo:rerun-if-changed={}", ir_path.display());
    let ir_text = std::fs::read_to_string(ir_path)
        .map_err(|e| XlsynthError(format!("AOT I/O failed for {}: {e}", ir_path.display())))?;
    let spec = AotBuildSpec {
        name,
        ir_text: &ir_text,
        top,
    };
    emit_aot_module_from_ir_text(&spec)
}

fn write_file(path: &Path, contents: &[u8]) -> AotResult<()> {
    std::fs::write(path, contents)
        .map_err(|e| XlsynthError(format!("AOT I/O failed for {}: {e}", path.display())))
}

fn run_rustfmt_best_effort(path: &Path) {
    let _ = Command::new("rustfmt").arg(path).status();
}

fn sanitize_identifier(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for (index, ch) in name.chars().enumerate() {
        let valid = ch == '_' || ch.is_ascii_alphanumeric();
        let ch = if valid { ch } else { '_' };
        if index == 0 && ch.is_ascii_digit() {
            out.push('_');
        }
        out.push(ch);
    }
    if out.is_empty() {
        "aot_entrypoint".to_string()
    } else {
        out
    }
}

fn sanitize_value_identifier(name: &str, fallback: &str) -> String {
    let mut out = String::with_capacity(name.len().max(fallback.len()));
    for (index, ch) in name.chars().enumerate() {
        let ch = if ch == '_' || ch.is_ascii_alphanumeric() {
            ch
        } else {
            '_'
        };
        if index == 0 && ch.is_ascii_digit() {
            out.push('_');
        }
        out.push(ch.to_ascii_lowercase());
    }
    if out.is_empty() {
        out = fallback.to_string();
    }
    if is_rust_keyword(&out) {
        out.push('_');
    }
    out
}

fn sanitize_type_identifier(name: &str, fallback: &str) -> String {
    let mut out = String::new();
    let mut start_word = true;
    for ch in name.chars() {
        if ch == '_' || ch.is_ascii_alphanumeric() {
            if out.is_empty() && ch.is_ascii_digit() {
                out.push('_');
            }
            if start_word {
                out.push(ch.to_ascii_uppercase());
                start_word = false;
            } else {
                out.push(ch);
            }
        } else {
            start_word = true;
        }
    }
    if out.is_empty() {
        fallback.to_string()
    } else {
        out
    }
}

fn is_rust_keyword(name: &str) -> bool {
    matches!(
        name,
        "as" | "break"
            | "const"
            | "continue"
            | "crate"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "Self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "type"
            | "unsafe"
            | "use"
            | "where"
            | "while"
            | "async"
            | "await"
            | "dyn"
            | "abstract"
            | "become"
            | "box"
            | "do"
            | "final"
            | "macro"
            | "override"
            | "priv"
            | "try"
            | "typeof"
            | "unsized"
            | "virtual"
            | "yield"
    )
}

fn scalar_bits_rust_type(bit_count: usize) -> &'static str {
    match bit_count {
        1 => "bool",
        0..=8 => "u8",
        9..=16 => "u16",
        17..=32 => "u32",
        33..=64 => "u64",
        _ => panic!(
            "scalar_bits_rust_type only supports widths <= 64, got {}",
            bit_count
        ),
    }
}

fn scalar_bits_native_width(bit_count: usize) -> usize {
    match bit_count {
        1 => 1,
        0..=8 => 8,
        9..=16 => 16,
        17..=32 => 32,
        33..=64 => 64,
        _ => panic!(
            "scalar_bits_native_width only supports widths <= 64, got {}",
            bit_count
        ),
    }
}

fn scalar_bits_storage_bytes(bit_count: usize) -> usize {
    match bit_count {
        1 => 1,
        0..=8 => 1,
        9..=16 => 2,
        17..=32 => 4,
        33..=64 => 8,
        _ => panic!(
            "scalar_bits_storage_bytes only supports widths <= 64, got {}",
            bit_count
        ),
    }
}

fn format_usize_array(values: &[usize]) -> String {
    if values.is_empty() {
        "&[]".to_string()
    } else {
        format!(
            "&[{}]",
            values
                .iter()
                .map(|v| v.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        )
    }
}

#[derive(Debug, Clone)]
enum ResolvedType {
    Bits {
        bit_count: usize,
    },
    Tuple {
        name: String,
        fields: Vec<ResolvedType>,
    },
    Array {
        size: usize,
        element: Box<ResolvedType>,
    },
    Token,
}

#[derive(Debug, Clone)]
struct TupleDef {
    name: String,
    field_types: Vec<ResolvedType>,
}

#[derive(Debug, Default)]
struct TypeResolver {
    bit_widths: BTreeSet<usize>,
    tuple_defs: Vec<TupleDef>,
    used_type_names: HashSet<String>,
}

impl TypeResolver {
    fn lower_type(&mut self, ty: &AotType, hint: &str) -> ResolvedType {
        match ty {
            AotType::Bits { bit_count } => {
                self.bit_widths.insert(*bit_count);
                ResolvedType::Bits {
                    bit_count: *bit_count,
                }
            }
            AotType::Token => ResolvedType::Token,
            AotType::Array { size, element } => ResolvedType::Array {
                size: *size,
                element: Box::new(self.lower_type(element, &format!("{hint}Element"))),
            },
            AotType::Tuple { elements } => {
                let tuple_name = self.allocate_type_name(hint);
                let mut field_types = Vec::with_capacity(elements.len());
                for (index, element) in elements.iter().enumerate() {
                    field_types
                        .push(self.lower_type(element, &format!("{tuple_name}Field{index}")));
                }
                self.tuple_defs.push(TupleDef {
                    name: tuple_name.clone(),
                    field_types: field_types.clone(),
                });
                ResolvedType::Tuple {
                    name: tuple_name,
                    fields: field_types,
                }
            }
        }
    }

    fn allocate_type_name(&mut self, hint: &str) -> String {
        let base = sanitize_type_identifier(hint, "GeneratedType");
        let mut candidate = base.clone();
        let mut suffix = 1usize;
        while !self.used_type_names.insert(candidate.clone()) {
            suffix += 1;
            candidate = format!("{base}{suffix}");
        }
        candidate
    }
}

fn rust_type_name(ty: &ResolvedType) -> String {
    match ty {
        ResolvedType::Bits { bit_count } => format!("Bits{bit_count}"),
        ResolvedType::Tuple { name, .. } => name.clone(),
        ResolvedType::Array { size, element } => format!("[{}; {size}]", rust_type_name(element)),
        ResolvedType::Token => "Token".to_string(),
    }
}

fn is_named_tuple(ty: &ResolvedType, name: &str) -> bool {
    matches!(ty, ResolvedType::Tuple { name: ty_name, .. } if ty_name == name)
}

fn render_type_declarations(
    resolver: &TypeResolver,
    input_types: &[ResolvedType],
    output_type: &ResolvedType,
) -> String {
    let mut out = String::new();
    out.push_str("#[derive(Debug, Clone, PartialEq, Eq)]\n");
    out.push_str("pub struct Token {}\n\n");

    for bit_count in &resolver.bit_widths {
        if *bit_count <= 64 {
            out.push_str(&format!(
                "pub type Bits{bit_count} = {};\n",
                scalar_bits_rust_type(*bit_count)
            ));
        } else {
            let byte_count = bit_count.div_ceil(8);
            out.push_str(&format!("pub type Bits{bit_count} = [u8; {byte_count}];\n"));
        }
    }
    if !resolver.bit_widths.is_empty() {
        out.push('\n');
    }

    for tuple in &resolver.tuple_defs {
        out.push_str("#[derive(Debug, Clone, PartialEq, Eq)]\n");
        if tuple.field_types.is_empty() {
            out.push_str(&format!("pub struct {} {{}}\n\n", tuple.name));
            continue;
        }
        out.push_str(&format!("pub struct {} {{\n", tuple.name));
        for (index, field_ty) in tuple.field_types.iter().enumerate() {
            out.push_str(&format!(
                "    pub field{index}: {},\n",
                rust_type_name(field_ty)
            ));
        }
        out.push_str("}\n\n");
    }

    for (index, input_ty) in input_types.iter().enumerate() {
        let input_name = format!("Input{index}");
        if !is_named_tuple(input_ty, &input_name) {
            out.push_str(&format!(
                "pub type {input_name} = {};\n",
                rust_type_name(input_ty)
            ));
        }
    }
    if !input_types.is_empty() {
        out.push('\n');
    }

    if !is_named_tuple(output_type, "Output") {
        out.push_str(&format!(
            "pub type Output = {};\n\n",
            rust_type_name(output_type)
        ));
    }

    out
}

fn render_layout_constants(prefix: &str, layouts: &[AotTypeLayout]) -> String {
    let mut out = String::new();
    for (index, layout) in layouts.iter().enumerate() {
        out.push_str(&format!(
            "const {prefix}{index}_LAYOUT: &[xlsynth::aot_entrypoint_metadata::AotElementLayout] = &[\n"
        ));
        for element in &layout.elements {
            out.push_str(&format!(
                "    xlsynth::aot_entrypoint_metadata::AotElementLayout {{ offset: {}, data_size: {}, padded_size: {} }},\n",
                element.offset, element.data_size, element.padded_size
            ));
        }
        out.push_str("];\n");
    }
    out
}

fn push_line(lines: &mut Vec<String>, text: impl AsRef<str>) {
    lines.push(text.as_ref().to_string());
}

fn emit_pack_statements(
    ty: &ResolvedType,
    value_expr: &str,
    layout_name: &str,
    dst_name: &str,
    leaf_index_expr: &str,
    lines: &mut Vec<String>,
    next_loop_index: &mut usize,
) {
    match ty {
        ResolvedType::Bits { bit_count } => {
            if *bit_count <= 64 {
                if *bit_count == 1 {
                    push_line(
                        lines,
                        format!("let encoded_bit: u8 = u8::from(*&({value_expr}));"),
                    );
                    push_line(
                        lines,
                        format!(
                            "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &[encoded_bit]);"
                        ),
                    );
                } else {
                    let native_width = scalar_bits_native_width(*bit_count);
                    if *bit_count == 0 {
                        push_line(
                            lines,
                            format!(
                                "assert!(({value_expr}) == 0, \"AOT encode overflow: value does not fit in 0 bits\");"
                            ),
                        );
                    } else if *bit_count < native_width {
                        push_line(
                            lines,
                            format!(
                                "assert!((({value_expr}) >> {bit_count}) == 0, \"AOT encode overflow: value does not fit in {bit_count} bits\");"
                            ),
                        );
                    }
                    push_line(
                        lines,
                        format!(
                            "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &({value_expr}).to_ne_bytes());"
                        ),
                    );
                }
            } else {
                let bit_remainder = bit_count % 8;
                if bit_remainder != 0 {
                    let last_byte_index = bit_count.div_ceil(8) - 1;
                    push_line(
                        lines,
                        format!(
                            "assert!((({value_expr})[{last_byte_index}] >> {bit_remainder}) == 0, \"AOT encode overflow: value does not fit in {bit_count} bits\");"
                        ),
                    );
                }
                push_line(
                    lines,
                    format!(
                        "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &({value_expr}));"
                    ),
                );
            }
        }
        ResolvedType::Token => {
            push_line(
                lines,
                format!(
                    "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &[]);"
                ),
            );
        }
        ResolvedType::Tuple { fields, .. } => {
            let mut offset = 0usize;
            for (index, field) in fields.iter().enumerate() {
                let field_leaf_base = if offset == 0 {
                    leaf_index_expr.to_string()
                } else {
                    format!("{leaf_index_expr} + {offset}")
                };
                emit_pack_statements(
                    field,
                    &format!("({value_expr}).field{index}"),
                    layout_name,
                    dst_name,
                    &field_leaf_base,
                    lines,
                    next_loop_index,
                );
                offset = offset.saturating_add(leaf_count(field));
            }
        }
        ResolvedType::Array { size, element } => {
            let element_leaves = leaf_count(element);
            if *size == 0 || element_leaves == 0 {
                return;
            }
            let loop_name = format!("index_{}", *next_loop_index);
            *next_loop_index += 1;
            push_line(lines, format!("for {loop_name} in 0..{size} {{"));
            let element_leaf_base = if element_leaves == 1 {
                format!("{leaf_index_expr} + {loop_name}")
            } else {
                format!("{leaf_index_expr} + {loop_name} * {element_leaves}")
            };
            emit_pack_statements(
                element,
                &format!("({value_expr})[{loop_name}]"),
                layout_name,
                dst_name,
                &element_leaf_base,
                lines,
                next_loop_index,
            );
            push_line(lines, "}");
        }
    }
}

fn render_decode_expr(
    ty: &ResolvedType,
    layout_name: &str,
    src_name: &str,
    leaf_index_expr: &str,
    next_loop_index: &mut usize,
) -> String {
    match ty {
        ResolvedType::Bits { bit_count } => {
            if *bit_count <= 64 {
                if *bit_count == 1 {
                    format!(
                        "{{ let mut dst_bytes = [0u8; 1]; \
                        xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut dst_bytes); \
                        assert!(dst_bytes[0] <= 1, \"AOT decode overflow: value does not fit in 1 bit\"); \
                        dst_bytes[0] != 0 }}"
                    )
                } else {
                    let native_type = scalar_bits_rust_type(*bit_count);
                    let storage_bytes = scalar_bits_storage_bytes(*bit_count);
                    let native_width = scalar_bits_native_width(*bit_count);
                    let mut expr = format!(
                        "{{ let mut dst_bytes = [0u8; {storage_bytes}]; \
                        xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut dst_bytes); \
                        let decoded = {native_type}::from_ne_bytes(dst_bytes); "
                    );
                    if *bit_count == 0 {
                        expr.push_str(
                            "assert!(decoded == 0, \"AOT decode overflow: value does not fit in 0 bits\"); ",
                        );
                    } else if *bit_count < native_width {
                        expr.push_str(&format!(
                            "assert!((decoded >> {bit_count}) == 0, \"AOT decode overflow: value does not fit in {bit_count} bits\"); "
                        ));
                    }
                    expr.push_str("decoded }");
                    expr
                }
            } else {
                let byte_count = bit_count.div_ceil(8);
                let mut expr = format!(
                    "{{ let mut dst_bytes = [0u8; {byte_count}]; \
                    xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut dst_bytes); "
                );
                let bit_remainder = bit_count % 8;
                if bit_remainder != 0 {
                    let last_byte_index = bit_count.div_ceil(8) - 1;
                    expr.push_str(&format!(
                        "assert!((dst_bytes[{last_byte_index}] >> {bit_remainder}) == 0, \"AOT decode overflow: value does not fit in {bit_count} bits\"); "
                    ));
                }
                expr.push_str("dst_bytes }");
                expr
            }
        }
        ResolvedType::Token => {
            format!(
                "{{ let mut dst_bytes = [0u8; 0]; \
                xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut dst_bytes); \
                Token {{}} }}"
            )
        }
        ResolvedType::Tuple { name, fields } => {
            if fields.is_empty() {
                return format!("{name} {{}}");
            }
            let mut field_entries = Vec::with_capacity(fields.len());
            let mut offset = 0usize;
            for (index, field) in fields.iter().enumerate() {
                let field_leaf_base = if offset == 0 {
                    leaf_index_expr.to_string()
                } else {
                    format!("{leaf_index_expr} + {offset}")
                };
                field_entries.push(format!(
                    "field{index}: {}",
                    render_decode_expr(
                        field,
                        layout_name,
                        src_name,
                        &field_leaf_base,
                        next_loop_index
                    )
                ));
                offset = offset.saturating_add(leaf_count(field));
            }
            format!("{name} {{ {} }}", field_entries.join(", "))
        }
        ResolvedType::Array { size: _, element } => {
            let element_leaves = leaf_count(element);
            let loop_name = format!("index_{}", *next_loop_index);
            *next_loop_index += 1;
            let element_leaf_base = if element_leaves == 0 {
                leaf_index_expr.to_string()
            } else if element_leaves == 1 {
                format!("{leaf_index_expr} + {loop_name}")
            } else {
                format!("{leaf_index_expr} + {loop_name} * {element_leaves}")
            };
            let element_expr = render_decode_expr(
                element,
                layout_name,
                src_name,
                &element_leaf_base,
                next_loop_index,
            );
            format!("std::array::from_fn(|{loop_name}| {{ {element_expr} }})")
        }
    }
}

fn leaf_count(ty: &ResolvedType) -> usize {
    match ty {
        ResolvedType::Bits { .. } => 1,
        ResolvedType::Token => 1,
        ResolvedType::Tuple { fields, .. } => fields.iter().map(leaf_count).sum(),
        ResolvedType::Array { size, element } => {
            if *size == 0 {
                0
            } else {
                size.saturating_mul(leaf_count(element))
            }
        }
    }
}

fn render_encode_function(index: usize, ty: &ResolvedType, expected_size: usize) -> String {
    let layout_name = format!("INPUT{index}_LAYOUT");
    let mut lines = Vec::new();
    push_line(
        &mut lines,
        "#[allow(clippy::deref_addrof, clippy::explicit_auto_deref, clippy::identity_op)]",
    );
    push_line(
        &mut lines,
        format!("fn encode_input_{index}(_value: &Input{index}, dst: &mut [u8]) {{"),
    );
    push_line(
        &mut lines,
        format!("debug_assert_eq!(dst.len(), {expected_size});"),
    );
    push_line(&mut lines, "dst.fill(0);");
    let mut loop_index = 0usize;
    emit_pack_statements(
        ty,
        "_value",
        &layout_name,
        "dst",
        "0usize",
        &mut lines,
        &mut loop_index,
    );
    let expected_leaves = leaf_count(ty);
    push_line(
        &mut lines,
        format!("debug_assert_eq!({layout_name}.len(), {expected_leaves});"),
    );
    push_line(&mut lines, "}");
    lines.join("\n")
}

fn render_decode_function(ty: &ResolvedType, expected_size: usize) -> String {
    let layout_name = "OUTPUT0_LAYOUT";
    let mut lines = Vec::new();
    push_line(
        &mut lines,
        "#[allow(clippy::identity_op, clippy::let_and_return)]",
    );
    push_line(&mut lines, "fn decode_output_0(src: &[u8]) -> Output {");
    push_line(
        &mut lines,
        format!("debug_assert_eq!(src.len(), {expected_size});"),
    );
    let mut loop_index = 0usize;
    let decode_expr = render_decode_expr(ty, layout_name, "src", "0usize", &mut loop_index);
    push_line(&mut lines, format!("let output: Output = {decode_expr};"));
    let expected_leaves = leaf_count(ty);
    push_line(
        &mut lines,
        format!("debug_assert_eq!({layout_name}.len(), {expected_leaves});"),
    );
    push_line(&mut lines, "output");
    push_line(&mut lines, "}");
    lines.join("\n")
}

fn validate_signature_and_layouts(
    metadata: &AotEntrypointMetadata,
    signature: &AotFunctionSignature,
) -> AotResult<()> {
    if signature.params.len() != metadata.input_buffer_sizes.len() {
        return Err(XlsynthError(format!(
            "AOT metadata mismatch: parameter count={} but input buffer count={}",
            signature.params.len(),
            metadata.input_buffer_sizes.len()
        )));
    }
    if signature.input_layouts.len() != metadata.input_buffer_sizes.len() {
        return Err(XlsynthError(format!(
            "AOT metadata mismatch: input layout count={} but input buffer count={}",
            signature.input_layouts.len(),
            metadata.input_buffer_sizes.len()
        )));
    }
    if signature.output_layouts.len() != metadata.output_buffer_sizes.len() {
        return Err(XlsynthError(format!(
            "AOT metadata mismatch: output layout count={} but output buffer count={}",
            signature.output_layouts.len(),
            metadata.output_buffer_sizes.len()
        )));
    }
    if signature.output_layouts.len() != 1 {
        return Err(XlsynthError(format!(
            "AOT generated typed wrapper currently expects exactly 1 output; got {}",
            signature.output_layouts.len()
        )));
    }
    for (index, (layout, size)) in signature
        .input_layouts
        .iter()
        .zip(metadata.input_buffer_sizes.iter())
        .enumerate()
    {
        if layout.size != *size {
            return Err(XlsynthError(format!(
                "AOT metadata mismatch for input {index}: layout size={} buffer size={size}",
                layout.size
            )));
        }
    }
    for (index, (layout, size)) in signature
        .output_layouts
        .iter()
        .zip(metadata.output_buffer_sizes.iter())
        .enumerate()
    {
        if layout.size != *size {
            return Err(XlsynthError(format!(
                "AOT metadata mismatch for output {index}: layout size={} buffer size={size}",
                layout.size
            )));
        }
    }
    Ok(())
}

fn make_unique_argument_names(signature: &AotFunctionSignature) -> Vec<String> {
    let mut used = HashSet::new();
    let mut out = Vec::with_capacity(signature.params.len());
    for (index, param) in signature.params.iter().enumerate() {
        let base = sanitize_value_identifier(&param.name, &format!("arg{index}"));
        let mut candidate = base.clone();
        let mut suffix = 1usize;
        while !used.insert(candidate.clone()) {
            suffix += 1;
            candidate = format!("{base}_{suffix}");
        }
        out.push(candidate);
    }
    out
}

/// A DSLX enum member as generated Rust code needs to name and encode it.
///
/// `value` is already rendered as a signed or unsigned scalar literal according
/// to the enum underlying type. The encode and decode generators use this
/// value when translating between the Rust bridge enum and the AOT ABI bits.
#[derive(Debug, Clone)]
struct TypedDslxEnumVariant {
    /// Rust enum variant identifier emitted by the DSLX bridge.
    name: String,
    /// Scalar discriminant literal used in generated match arms.
    value: String,
}

/// A DSLX struct field paired with the lowered semantic type of that field.
///
/// Field order is the original DSLX declaration order. The AOT ABI for structs
/// is structural, so the order here is the order used when flattening fields to
/// leaf buffers and when reconstructing the generated Rust struct.
#[derive(Debug, Clone)]
struct TypedDslxField {
    /// Rust field identifier emitted by the DSLX bridge.
    name: String,
    /// Lowered semantic type for this field.
    ty: TypedDslxType,
}

/// A DSLX semantic type that can be mapped to the current AOT ABI model.
///
/// Each variant carries the Rust bridge type spelling used in generated public
/// signatures plus the structural facts needed to validate and traverse the
/// AOT layout. Types that cannot flatten to bits, enum-underlying bits,
/// structs, or fixed arrays are rejected during lowering.
#[derive(Debug, Clone)]
enum TypedDslxType {
    /// A DSLX bits-like type represented by `IrUBits<N>` or `IrSBits<N>`.
    Bits {
        /// Rust bridge type path used in generated signatures and helpers.
        rust_type: String,
        /// Whether generated conversion should use signed scalar semantics.
        is_signed: bool,
        /// Number of payload bits in the AOT ABI leaf.
        bit_count: usize,
    },
    /// A DSLX enum represented by a Rust bridge enum and underlying bits.
    Enum {
        /// Rust bridge enum path used in generated signatures and match arms.
        rust_type: String,
        /// Whether the enum's underlying bits are signed.
        is_signed: bool,
        /// Width of the enum's underlying bits.
        bit_count: usize,
        /// Enum variants and their scalar discriminants.
        variants: Vec<TypedDslxEnumVariant>,
    },
    /// A DSLX struct represented by a Rust bridge struct.
    Struct {
        /// Rust bridge struct path used in generated signatures and literals.
        rust_type: String,
        /// Struct fields in DSLX declaration order.
        fields: Vec<TypedDslxField>,
    },
    /// A fixed-size DSLX array represented by a Rust array.
    Array {
        /// Rust bridge array type spelling used in generated signatures.
        rust_type: String,
        /// Number of array elements.
        size: usize,
        /// Lowered semantic type for each element.
        element: Box<TypedDslxType>,
    },
}

/// A typed DSLX function parameter ready for generated runner emission.
///
/// `rust_type` is kept beside `ty` because the public runner signature needs
/// the caller-facing alias or imported path, while `ty` is the recursive shape
/// used for ABI validation and buffer traversal.
#[derive(Debug, Clone)]
struct TypedDslxParam {
    /// DSLX parameter name, sanitized later for generated Rust arguments.
    name: String,
    /// Rust bridge type spelling used in the generated public signature.
    rust_type: String,
    /// Lowered semantic type for this parameter.
    ty: TypedDslxType,
}

/// One concrete parametric struct definition that typed AOT must materialize.
///
/// Rust bridge generation normally emits concrete parametric structs when the
/// defining module itself references them. Typed AOT needs a package-level view
/// so direct imported instantiations can still be emitted in the defining
/// module even when only another module mentions them.
struct TypedConcreteParametricStruct {
    /// Exact DSLX struct declaration being specialized.
    ///
    /// Definition identity matters because sibling imports may both declare a
    /// parametric struct with the same DSLX identifier.
    struct_def: dslx::StructDef,
    /// Canonical DSLX module name that owns the original struct declaration.
    defining_module_name: String,
    /// Concrete Rust struct identifier to emit inside the defining module.
    ///
    /// The suffix is derived from the fully bound parametric values, so it is
    /// also the concrete-value portion of this specialization's key.
    rust_name: String,
    /// Concrete fields rendered relative to the defining module.
    fields: Vec<TypedDslxField>,
}

/// The typed DSLX view of one AOT entrypoint signature.
///
/// This is the semantic counterpart to `AotFunctionSignature`: it preserves
/// Rust bridge names while still carrying enough structure to prove that the
/// DSLX type boundary matches the compiled AOT metadata.
#[derive(Debug, Clone)]
struct TypedAotFunctionSignature {
    /// Parameters in DSLX function order.
    params: Vec<TypedDslxParam>,
    /// Rust bridge return type spelling used in the generated public signature.
    return_rust_type: String,
    /// Lowered semantic type for the return value.
    return_type: TypedDslxType,
}

/// A DSLX struct definition handle kept for exact owner-module resolution.
///
/// Duplicate struct names can appear in sibling imported modules. Keeping the
/// definition object allows lookup by definition identity before falling back
/// to bare names.
struct TypedDslxStructDefContext {
    def: dslx::StructDef,
}

/// A DSLX type alias definition handle kept for recursive alias expansion.
struct TypedDslxAliasDefContext {
    name: String,
    def: dslx::TypeAlias,
}

/// Type and name information collected for one typechecked DSLX module.
///
/// The type context is the authoritative place to resolve struct members and
/// enum underlying types for definitions owned by this module. The name sets
/// are only fallback indexes for definitions where the DSLX bindings do not
/// expose enough direct owner information.
struct TypedDslxModuleContext {
    /// Canonical DSLX module name used to derive nested Rust module paths.
    dslx_name: String,
    /// Type information produced by DSLX typechecking for this module.
    type_info: dslx::TypeInfo,
    /// Struct names declared by this module.
    struct_names: BTreeSet<String>,
    /// Struct definitions declared by this module.
    struct_defs: Vec<TypedDslxStructDefContext>,
    /// Type aliases declared by this module.
    type_alias_defs: Vec<TypedDslxAliasDefContext>,
    /// Enum names declared by this module.
    enum_names: BTreeSet<String>,
}

/// Cross-module lookup state used while lowering typed DSLX AOT signatures.
///
/// The context contains the requested bridge modules and the top module in one
/// search space so nested fields and imported annotations can resolve to the
/// correct `TypeInfo` and generated Rust module path.
struct TypedDslxTypeContext {
    modules: Vec<TypedDslxModuleContext>,
}

/// Typechecking result for all DSLX modules participating in one AOT wrapper.
///
/// Bridge modules are emitted before the top module so their public type
/// definitions are available to the generated runner. The top module owns the
/// function selected as the AOT entrypoint.
struct TypedDslxTypecheckedModules {
    bridge_modules: Vec<dslx::TypecheckedModule>,
    top_module: dslx::TypecheckedModule,
}

struct TypedDslxPackageModule {
    canonical_path: PathBuf,
    typechecked: dslx::TypecheckedModule,
}

struct TypedDslxPackageTypecheckedModules {
    modules: Vec<TypedDslxPackageModule>,
}

/// A type annotation paired with the module context that owns it.
struct ResolvedDslxTypeAnnotation<'a> {
    type_info: &'a dslx::TypeInfo,
    annotation: dslx::TypeAnnotation,
}

impl TypedDslxType {
    /// Returns the Rust type spelling already selected for generated source.
    ///
    /// Field rendering needs the public Rust spelling, while the enum variant
    /// still carries the recursive semantic shape used for ABI validation.
    fn rust_type(&self) -> &str {
        match self {
            TypedDslxType::Bits { rust_type, .. }
            | TypedDslxType::Enum { rust_type, .. }
            | TypedDslxType::Struct { rust_type, .. }
            | TypedDslxType::Array { rust_type, .. } => rust_type,
        }
    }
}

/// A non-empty DSLX import subject such as `foo` or `foo.bar`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct DslxImportSubject {
    segments: Vec<String>,
}

impl DslxImportSubject {
    /// Parses the subject token from a DSLX `import` statement.
    ///
    /// The token may be dotted, as in `foo.bar`, and empty path segments are
    /// ignored so malformed or blank subjects do not enter dependency
    /// traversal.
    fn from_token(token: &str) -> Option<Self> {
        let segments = token
            .split('.')
            .map(str::trim)
            .filter(|segment| !segment.is_empty())
            .map(str::to_string)
            .collect::<Vec<_>>();
        if segments.is_empty() {
            None
        } else {
            Some(Self { segments })
        }
    }

    /// Converts the import subject to the relative `.x` file path DSLX
    /// searches.
    ///
    /// For example, `foo.bar` becomes `foo/bar.x`. The caller is responsible
    /// for trying that relative path against the applicable import roots.
    fn relative_path(&self) -> PathBuf {
        let mut path = self
            .segments
            .iter()
            .fold(PathBuf::new(), |mut path, segment| {
                path.push(segment);
                path
            });
        path.set_extension("x");
        path
    }
}

/// Returns the DSLX files whose contents can affect a typed DSLX AOT build.
///
/// Cargo build scripts must report every source file that can change the
/// generated object/proto/wrapper artifacts. The roots are the top DSLX module
/// and every generated bridge module, then imports are followed through the
/// same search roots that DSLX conversion uses.
fn collect_typed_dslx_aot_dependencies(
    spec: &TypedDslxAotBuildSpec<'_>,
) -> AotResult<BTreeSet<PathBuf>> {
    let mut dependencies = BTreeSet::new();
    let mut pending_paths = std::iter::once(spec.dslx_path.to_path_buf())
        .chain(spec.type_module_paths.iter().map(|path| path.to_path_buf()))
        .collect::<Vec<_>>();

    while let Some(path) = pending_paths.pop() {
        let canonical_path = std::fs::canonicalize(&path).map_err(|e| {
            XlsynthError(format!(
                "AOT I/O failed while resolving DSLX dependency {}: {e}",
                path.display()
            ))
        })?;
        if dependencies.insert(canonical_path.clone()) {
            let dslx_text = std::fs::read_to_string(&canonical_path).map_err(|e| {
                XlsynthError(format!(
                    "AOT I/O failed for DSLX dependency {}: {e}",
                    canonical_path.display()
                ))
            })?;
            pending_paths.extend(
                dslx_import_subjects(&dslx_text)
                    .into_iter()
                    .filter_map(|subject| {
                        resolve_dslx_import_path(&canonical_path, &subject, spec)
                    }),
            );
        }
    }

    Ok(dependencies)
}

/// Extracts DSLX import subjects from source text for Cargo invalidation.
///
/// This is intentionally a lightweight source scan, not a full parser. It only
/// feeds `cargo:rerun-if-changed` discovery; actual typechecking still uses the
/// DSLX front end and reports authoritative syntax or import errors.
fn dslx_import_subjects(dslx_text: &str) -> Vec<DslxImportSubject> {
    dslx_text
        .lines()
        .flat_map(dslx_import_subjects_from_line)
        .collect()
}

/// Extracts import subjects from one source line after dropping trailing
/// comments.
///
/// The scan accepts multiple semicolon-delimited statements on a line because
/// build-script invalidation should be conservative for compact fixture files.
fn dslx_import_subjects_from_line(line: &str) -> Vec<DslxImportSubject> {
    let code = line.split("//").next().unwrap_or("").trim();
    code.split(';')
        .filter_map(|statement| {
            let mut tokens = statement.split_whitespace();
            if tokens.next() == Some("import") {
                tokens.next().and_then(DslxImportSubject::from_token)
            } else {
                None
            }
        })
        .collect()
}

/// Resolves one DSLX import subject against the same roots used by conversion.
///
/// Resolution tries the importing file's directory, explicit additional search
/// paths, and the configured or default DSLX standard library. Missing imports
/// are left unresolved here so typechecking can produce the canonical error.
fn resolve_dslx_import_path(
    importer_path: &Path,
    subject: &DslxImportSubject,
    spec: &TypedDslxAotBuildSpec<'_>,
) -> Option<PathBuf> {
    let importer_dir = importer_path.parent();
    let default_stdlib_path = Path::new(xlsynth_sys::DSLX_STDLIB_PATH);
    let stdlib_path = spec
        .dslx_options
        .dslx_stdlib_path
        .unwrap_or(default_stdlib_path);
    let relative_path = subject.relative_path();
    importer_dir
        .into_iter()
        .chain(spec.dslx_options.additional_search_paths.iter().copied())
        .chain(std::iter::once(stdlib_path))
        .map(|root| root.join(&relative_path))
        .find(|path| path.is_file())
}

/// Parses DSLX source text as a module with an explicit module name.
///
/// The explicit name is needed for bridge modules discovered through import
/// roots: their file name alone is not enough to preserve the dotted DSLX
/// module path that later maps to nested Rust modules.
fn parse_dslx_text_as_module(
    dslx_text: &str,
    path: &Path,
    module_name: &str,
    import_data: &mut dslx::ImportData,
) -> AotResult<dslx::TypecheckedModule> {
    let path_str = path.to_str().ok_or_else(|| {
        XlsynthError(format!(
            "AOT build environment error: DSLX path is not UTF-8: {}",
            path.display()
        ))
    })?;
    dslx::parse_and_typecheck(dslx_text, path_str, module_name, import_data)
}

/// Parses a DSLX source file using the module name implied by its path.
///
/// This is used for the top module because its file path is the public build
/// spec input, so `dslx_path_to_module_name` is the same convention used by
/// the DSLX-to-IR lowering path.
fn parse_dslx_file(
    dslx_text: &str,
    path: &Path,
    import_data: &mut dslx::ImportData,
) -> AotResult<dslx::TypecheckedModule> {
    let module_name = dslx_path_to_module_name(path)?;
    parse_dslx_text_as_module(dslx_text, path, module_name, import_data)
}

/// Computes the canonical DSLX module name for an imported source path.
///
/// If the file is below an additional search root, the relative path becomes a
/// dotted module name such as `foo.widget`. Otherwise the file stem fallback
/// matches normal top-module handling.
fn dslx_module_name_from_import_path(path: &Path, search_paths: &[&Path]) -> AotResult<String> {
    for search_path in search_paths {
        if let Ok(relative_path) = path.strip_prefix(search_path) {
            let without_extension = relative_path.with_extension("");
            let segments = without_extension
                .components()
                .filter_map(|component| match component {
                    std::path::Component::Normal(segment) => {
                        Some(segment.to_string_lossy().to_string())
                    }
                    _ => None,
                })
                .collect::<Vec<_>>();
            if !segments.is_empty() {
                return Ok(segments.join("."));
            }
        }
    }
    Ok(dslx_path_to_module_name(path)?.to_string())
}

/// Typechecks the bridge modules and top module in one import-data context.
///
/// Sharing `ImportData` keeps definitions and `TypeInfo` objects comparable
/// across modules. Typechecking bridge modules first also gives the generated
/// Rust module renderer a stable ordering for public type definitions.
fn typecheck_typed_dslx_modules(
    spec: &TypedDslxAotBuildSpec<'_>,
    top_dslx_text: &str,
) -> AotResult<TypedDslxTypecheckedModules> {
    let mut import_data = dslx::ImportData::new(
        spec.dslx_options.dslx_stdlib_path,
        &spec.dslx_options.additional_search_paths,
    );
    let mut bridge_modules = Vec::with_capacity(spec.type_module_paths.len());
    for bridge_path in &spec.type_module_paths {
        let bridge_text = std::fs::read_to_string(bridge_path).map_err(|e| {
            XlsynthError(format!("AOT I/O failed for {}: {e}", bridge_path.display()))
        })?;
        let module_name = dslx_module_name_from_import_path(
            bridge_path,
            &spec.dslx_options.additional_search_paths,
        )?;
        bridge_modules.push(parse_dslx_text_as_module(
            &bridge_text,
            bridge_path,
            &module_name,
            &mut import_data,
        )?);
    }
    let top_module = parse_dslx_file(top_dslx_text, spec.dslx_path, &mut import_data)?;
    Ok(TypedDslxTypecheckedModules {
        bridge_modules,
        top_module,
    })
}

/// Validates package-wide options that must be shared by every entrypoint.
fn ensure_package_specs_compatible(specs: &[TypedDslxAotBuildSpec<'_>]) -> AotResult<()> {
    let Some(first) = specs.first() else {
        return Err(XlsynthError(
            "AOT invalid argument: typed DSLX package must contain at least one entrypoint"
                .to_string(),
        ));
    };
    for spec in specs.iter().skip(1) {
        if spec.dslx_options != first.dslx_options {
            return Err(XlsynthError(
                "AOT invalid argument: typed DSLX package entrypoints must use identical DSLX conversion options"
                    .to_string(),
            ));
        }
    }
    Ok(())
}

/// Typechecks all unique modules participating in one shared typed DSLX
/// package.
fn typecheck_typed_dslx_package_modules(
    specs: &[TypedDslxAotBuildSpec<'_>],
) -> AotResult<TypedDslxPackageTypecheckedModules> {
    ensure_package_specs_compatible(specs)?;
    let first = &specs[0];
    let mut import_data = dslx::ImportData::new(
        first.dslx_options.dslx_stdlib_path,
        &first.dslx_options.additional_search_paths,
    );
    let mut seen_paths = BTreeSet::new();
    let mut modules = Vec::new();

    for path in specs.iter().flat_map(|spec| spec.type_module_paths.iter()) {
        let canonical_path = std::fs::canonicalize(path).map_err(|e| {
            XlsynthError(format!(
                "AOT I/O failed while resolving DSLX package module {}: {e}",
                path.display()
            ))
        })?;
        if seen_paths.insert(canonical_path.clone()) {
            let dslx_text = std::fs::read_to_string(&canonical_path).map_err(|e| {
                XlsynthError(format!(
                    "AOT I/O failed for DSLX package module {}: {e}",
                    canonical_path.display()
                ))
            })?;
            let module_name = dslx_module_name_from_import_path(
                path,
                &first.dslx_options.additional_search_paths,
            )?;
            modules.push(TypedDslxPackageModule {
                canonical_path,
                typechecked: parse_dslx_text_as_module(
                    &dslx_text,
                    path,
                    &module_name,
                    &mut import_data,
                )?,
            });
        }
    }

    for spec in specs {
        let canonical_path = std::fs::canonicalize(spec.dslx_path).map_err(|e| {
            XlsynthError(format!(
                "AOT I/O failed while resolving DSLX package top {}: {e}",
                spec.dslx_path.display()
            ))
        })?;
        if seen_paths.insert(canonical_path.clone()) {
            let dslx_text = std::fs::read_to_string(&canonical_path).map_err(|e| {
                XlsynthError(format!(
                    "AOT I/O failed for DSLX package top {}: {e}",
                    canonical_path.display()
                ))
            })?;
            let module_name = dslx_module_name_from_import_path(
                spec.dslx_path,
                &first.dslx_options.additional_search_paths,
            )?;
            modules.push(TypedDslxPackageModule {
                canonical_path,
                typechecked: parse_dslx_text_as_module(
                    &dslx_text,
                    spec.dslx_path,
                    &module_name,
                    &mut import_data,
                )?,
            });
        }
    }

    Ok(TypedDslxPackageTypecheckedModules { modules })
}

/// Collects the module-local type definitions needed for typed AOT lowering.
///
/// The result deliberately records struct definitions, not only names, because
/// imported modules may declare same-named structs and the lowerer must prefer
/// exact definition identity when the DSLX bindings expose it.
fn collect_module_context(typechecked_module: &dslx::TypecheckedModule) -> TypedDslxModuleContext {
    let module = typechecked_module.get_module();
    let mut struct_names = BTreeSet::new();
    let mut struct_defs = Vec::new();
    let mut type_alias_defs = Vec::new();
    let mut enum_names = BTreeSet::new();
    for index in 0..module.get_member_count() {
        if let Some(member) = module.get_member(index).to_matchable() {
            match member {
                dslx::MatchableModuleMember::StructDef(struct_def) => {
                    let name = struct_def.get_identifier();
                    struct_names.insert(name.clone());
                    struct_defs.push(TypedDslxStructDefContext { def: struct_def });
                }
                dslx::MatchableModuleMember::TypeAlias(type_alias) => {
                    type_alias_defs.push(TypedDslxAliasDefContext {
                        name: type_alias.get_identifier(),
                        def: type_alias,
                    });
                }
                dslx::MatchableModuleMember::EnumDef(enum_def) => {
                    enum_names.insert(enum_def.get_identifier());
                }
                _ => {
                    // Only named types matter when later qualifying generated
                    // Rust paths.
                }
            }
        }
    }
    TypedDslxModuleContext {
        dslx_name: module.get_name(),
        type_info: typechecked_module.get_type_info(),
        struct_names,
        struct_defs,
        type_alias_defs,
        enum_names,
    }
}

impl TypedDslxTypeContext {
    /// Builds lookup state from all typechecked modules in wrapper emission
    /// order.
    ///
    /// The top module is included after bridge modules so callers can omit it
    /// from `type_module_paths` while still allowing return and parameter types
    /// declared in the top file.
    fn new(typechecked: &TypedDslxTypecheckedModules) -> Self {
        Self::from_modules(
            typechecked
                .bridge_modules
                .iter()
                .chain(std::iter::once(&typechecked.top_module)),
        )
    }

    /// Builds lookup state from an arbitrary ordered set of typechecked
    /// modules.
    fn from_modules<'a>(modules: impl IntoIterator<Item = &'a dslx::TypecheckedModule>) -> Self {
        Self {
            modules: modules.into_iter().map(collect_module_context).collect(),
        }
    }

    /// Finds a type alias by module and DSLX alias identifier.
    fn type_alias_in_module<'a>(
        &'a self,
        module_name: &str,
        alias_name: &str,
    ) -> Option<(&'a TypedDslxModuleContext, &'a dslx::TypeAlias)> {
        self.modules
            .iter()
            .find(|module| module.dslx_name == module_name)
            .and_then(|module| {
                module
                    .type_alias_defs
                    .iter()
                    .find(|alias| alias.name == alias_name)
                    .map(|alias| (module, &alias.def))
            })
    }

    /// Finds the module context that produced a `TypeInfo` object.
    fn module_for_type_info<'a>(
        &'a self,
        type_info: &dslx::TypeInfo,
    ) -> Option<&'a TypedDslxModuleContext> {
        self.modules
            .iter()
            .find(|module| module.type_info.is_same_type_context(type_info))
    }

    /// Resolves one type-reference annotation to the RHS annotation of a DSLX
    /// type alias, when the reference names an alias rather than a concrete
    /// type.
    fn type_alias_rhs_for_annotation<'a>(
        &'a self,
        current_type_info: &'a dslx::TypeInfo,
        type_annotation: &dslx::TypeAnnotation,
    ) -> AotResult<Option<ResolvedDslxTypeAnnotation<'a>>> {
        let Some(type_ref_annotation) = type_annotation.to_type_ref_type_annotation() else {
            return Ok(None);
        };
        let type_definition = type_ref_annotation.get_type_ref().get_type_definition();
        if let Some(colon_ref) = type_definition.to_colon_ref() {
            let alias_name = colon_ref.get_attr();
            let Some(import) = colon_ref.resolve_import_subject() else {
                return Ok(None);
            };
            let module_name = import.get_subject().join(".");
            let Some((module, type_alias)) = self.type_alias_in_module(&module_name, &alias_name)
            else {
                return Ok(None);
            };
            return Ok(Some(ResolvedDslxTypeAnnotation {
                type_info: &module.type_info,
                annotation: type_alias.get_type_annotation(),
            }));
        }
        let Some(type_alias) = type_definition.to_type_alias() else {
            return Ok(None);
        };
        let alias_name = type_alias.get_identifier();
        if let Some(module) = self.module_for_type_info(current_type_info) {
            if let Some(alias) = module
                .type_alias_defs
                .iter()
                .find(|alias| alias.name == alias_name)
            {
                return Ok(Some(ResolvedDslxTypeAnnotation {
                    type_info: &module.type_info,
                    annotation: alias.def.get_type_annotation(),
                }));
            }
        }
        Ok(Some(ResolvedDslxTypeAnnotation {
            type_info: current_type_info,
            annotation: type_alias.get_type_annotation(),
        }))
    }

    /// Expands type aliases until the annotation names a non-alias type.
    fn expand_type_alias_rhs_annotation<'a>(
        &'a self,
        current_type_info: &'a dslx::TypeInfo,
        type_annotation: &dslx::TypeAnnotation,
        depth: usize,
    ) -> AotResult<Option<ResolvedDslxTypeAnnotation<'a>>> {
        const MAX_ALIAS_EXPANSION_DEPTH: usize = 32;
        if depth >= MAX_ALIAS_EXPANSION_DEPTH {
            return Err(XlsynthError(format!(
                "AOT typed DSLX type lowering exceeded alias expansion depth of {MAX_ALIAS_EXPANSION_DEPTH}"
            )));
        }
        let Some(resolved) =
            self.type_alias_rhs_for_annotation(current_type_info, type_annotation)?
        else {
            return Ok(None);
        };
        let next = self.expand_type_alias_rhs_annotation(
            resolved.type_info,
            &resolved.annotation,
            depth + 1,
        )?;
        Ok(next.or(Some(resolved)))
    }

    /// Finds the module that owns a DSLX struct definition.
    ///
    /// Exact definition identity is preferred because same-named structs are
    /// legal in different imported modules. If exact identity is unavailable,
    /// the current type context disambiguates a bare-name match before the
    /// lowerer reports ambiguity.
    fn defining_module_for_struct(
        &self,
        current_type_info: Option<&dslx::TypeInfo>,
        struct_def: &dslx::StructDef,
    ) -> AotResult<Option<&TypedDslxModuleContext>> {
        let struct_name = struct_def.get_identifier();
        let exact_matches = self
            .modules
            .iter()
            .filter(|module| {
                module
                    .struct_defs
                    .iter()
                    .any(|known| known.def.is_same_definition(struct_def))
            })
            .collect::<Vec<_>>();
        match exact_matches.as_slice() {
            [module] => return Ok(Some(module)),
            modules if modules.len() > 1 => {
                return Err(XlsynthError(format!(
                    "AOT typed DSLX type lowering found multiple defining modules for struct `{struct_name}`"
                )));
            }
            _ => {}
        }
        let name_matches = self
            .modules
            .iter()
            .filter(|module| module.struct_names.contains(&struct_name))
            .collect::<Vec<_>>();
        match name_matches.as_slice() {
            [] => Ok(None),
            [module] => Ok(Some(module)),
            _ => {
                if let Some(current_type_info) = current_type_info {
                    let current_match = name_matches
                        .iter()
                        .copied()
                        .find(|module| module.type_info.is_same_type_context(current_type_info));
                    if current_match.is_some() {
                        return Ok(current_match);
                    }
                }
                Err(XlsynthError(format!(
                    "AOT typed DSLX type lowering found multiple DSLX structs named `{struct_name}`"
                )))
            }
        }
    }

    /// Finds the module that owns a DSLX enum definition.
    ///
    /// Non-empty enums expose owner information through their first member's
    /// value expression. Empty enums have no member to inspect, so the lookup
    /// falls back to the unique declared enum name across participating
    /// modules.
    fn defining_module_for_enum(
        &self,
        enum_def: &dslx::EnumDef,
    ) -> AotResult<Option<&TypedDslxModuleContext>> {
        if enum_def.get_member_count() == 0 {
            let enum_name = enum_def.get_identifier();
            return self
                .modules
                .iter()
                .find(|module| module.enum_names.contains(&enum_name))
                .map(Some)
                .ok_or_else(|| {
                    XlsynthError(format!(
                        "AOT typed DSLX type lowering could not find defining module for enum `{enum_name}`"
                    ))
                });
        }
        let defining_module_name = enum_def
            .get_member(0)
            .get_value()
            .get_owner_module()
            .get_name();
        self.modules
            .iter()
            .find(|module| module.dslx_name == defining_module_name)
            .map(Some)
            .ok_or_else(|| {
                XlsynthError(format!(
                    "AOT typed DSLX type lowering could not find defining module `{defining_module_name}` for enum `{}`",
                    enum_def.get_identifier()
                ))
            })
    }

    /// Resolves a module qualifier from an explicit DSLX type annotation.
    ///
    /// A colon reference such as `foo::Widget` is stronger evidence than the
    /// concrete type alone because aliases can hide the original source module.
    /// Preserving that qualifier keeps generated Rust paths canonical.
    fn defining_module_for_type_annotation(
        &self,
        type_annotation: &dslx::TypeAnnotation,
    ) -> AotResult<Option<&TypedDslxModuleContext>> {
        let defining_module_name = type_annotation
            .to_type_ref_type_annotation()
            .and_then(|annotation| {
                annotation
                    .get_type_ref()
                    .get_type_definition()
                    .to_colon_ref()
                    .and_then(|colon_ref| colon_ref.resolve_import_subject())
            })
            .map(|import| import.get_subject().join("."));
        match defining_module_name {
            Some(defining_module_name) => self
                .modules
                .iter()
                .find(|module| module.dslx_name == defining_module_name)
                .map(Some)
                .ok_or_else(|| {
                    XlsynthError(format!(
                        "AOT typed DSLX type lowering could not find defining module `{defining_module_name}`"
                    ))
                }),
            None => Ok(None),
        }
    }

    /// Selects the `TypeInfo` that should be used to inspect a resolved type.
    ///
    /// The current function's `TypeInfo` is correct for local bits and arrays,
    /// but imported structs and enums must use the defining module's `TypeInfo`
    /// when reading fields, underlying enum types, or constant values.
    fn type_context_for_resolved_type<'a>(
        &'a self,
        current: &'a dslx::TypeInfo,
        type_annotation: Option<&dslx::TypeAnnotation>,
        ty: &dslx::Type,
    ) -> AotResult<&'a dslx::TypeInfo> {
        if let Some(module) = type_annotation
            .map(|annotation| self.defining_module_for_type_annotation(annotation))
            .transpose()?
            .flatten()
        {
            Ok(&module.type_info)
        } else if ty.is_enum() {
            self.type_info_for_enum(current, &ty.get_enum_def()?)
        } else if ty.is_struct() {
            self.type_info_for_struct(current, &ty.get_struct_def()?)
        } else {
            Ok(current)
        }
    }

    /// Returns the defining module's `TypeInfo` for a struct when it is known.
    ///
    /// Falling back to the current context keeps same-module definitions simple
    /// and lets the caller continue when a DSLX binding does not expose owner
    /// information for an otherwise local type.
    fn type_info_for_struct<'a>(
        &'a self,
        current: &'a dslx::TypeInfo,
        struct_def: &dslx::StructDef,
    ) -> AotResult<&'a dslx::TypeInfo> {
        let Some(module) = self.defining_module_for_struct(Some(current), struct_def)? else {
            return Ok(current);
        };
        Ok(&module.type_info)
    }

    /// Returns the defining module's `TypeInfo` for an enum when it is known.
    ///
    /// Enum lowering needs the owner context to evaluate discriminants and read
    /// the underlying type annotation with the same bindings DSLX typechecking
    /// used.
    fn type_info_for_enum<'a>(
        &'a self,
        current: &'a dslx::TypeInfo,
        enum_def: &dslx::EnumDef,
    ) -> AotResult<&'a dslx::TypeInfo> {
        let Some(module) = self.defining_module_for_enum(enum_def)? else {
            return Ok(current);
        };
        Ok(&module.type_info)
    }

    /// Renders the Rust bridge type path from a typechecked DSLX type alone.
    ///
    /// A concrete `dslx::Type` knows the semantic shape, definitions, fields,
    /// widths, and enum underlying bits after typechecking. It does not always
    /// preserve the caller-facing source spelling, so aliases and imported
    /// annotation paths are handled by `rust_type_path_for_resolved_type`.
    /// Imported structs and enums are rendered relative to the generated module
    /// for the local DSLX file.
    fn rust_type_for_concrete_type(
        &self,
        local_module_name: &str,
        current_type_info: &dslx::TypeInfo,
        ty: &dslx::Type,
    ) -> AotResult<String> {
        if let Some((is_signed, bit_count)) = ty.is_bits_like() {
            let signed_str = if is_signed { "S" } else { "U" };
            Ok(format!("Ir{signed_str}Bits<{bit_count}>"))
        } else if ty.is_enum() {
            let enum_def = ty.get_enum_def()?;
            let enum_name = enum_def.get_identifier();
            let defining_module = self.defining_module_for_enum(&enum_def)?;
            Ok(match defining_module {
                Some(module) if module.dslx_name != local_module_name => {
                    rust_type_path_between_dslx_modules(
                        local_module_name,
                        &module.dslx_name,
                        &enum_name,
                    )
                }
                _ => enum_name,
            })
        } else if ty.is_struct() {
            let struct_def = ty.get_struct_def()?;
            let struct_name = struct_def.get_identifier();
            let defining_module =
                self.defining_module_for_struct(Some(current_type_info), &struct_def)?;
            Ok(match defining_module {
                Some(module) if module.dslx_name != local_module_name => {
                    rust_type_path_between_dslx_modules(
                        local_module_name,
                        &module.dslx_name,
                        &struct_name,
                    )
                }
                _ => struct_name,
            })
        } else if ty.is_array() {
            let element = ty.get_array_element_type();
            let element_rust_type =
                self.rust_type_for_concrete_type(local_module_name, current_type_info, &element)?;
            Ok(format!("[{element_rust_type}; {}]", ty.get_array_size()))
        } else {
            Err(XlsynthError(format!(
                "AOT typed DSLX type lowering does not support DSLX type `{}`",
                ty.to_string()?
            )))
        }
    }

    /// Renders the Rust bridge type path from source spelling plus concrete
    /// type.
    ///
    /// In this context, resolved means the caller has both the optional source
    /// `TypeAnnotation` and the typechecked `dslx::Type`. The annotation is
    /// checked first so public signatures preserve aliases and imported paths;
    /// the concrete type fallback is used when the annotation cannot name a
    /// bridge type directly, such as synthesized array element types.
    fn rust_type_path_for_resolved_type(
        &self,
        local_module_name: &str,
        current_type_info: &dslx::TypeInfo,
        type_annotation: Option<&dslx::TypeAnnotation>,
        ty: &dslx::Type,
    ) -> AotResult<String> {
        if type_annotation.is_some() {
            return RustBridgeBuilder::rust_type_name_from_dslx_module(
                local_module_name,
                current_type_info,
                type_annotation,
                ty,
            );
        }
        self.rust_type_for_concrete_type(local_module_name, current_type_info, ty)
    }
}

/// Discovers concrete parametric structs that must be emitted outside their use
/// site.
///
/// Bridge generation normally sees only the module currently being rendered.
/// This collector walks the full typed-AOT module set first so an owner module
/// can later emit the concrete Rust struct required by a direct imported use in
/// another module. Collected entries are deduplicated by semantic definition
/// identity plus concrete Rust name; same-named declarations in sibling modules
/// must remain separate.
struct TypedConcreteParametricStructCollector<'a> {
    context: &'a TypedDslxTypeContext,
    current_module_name: String,
    structs: Vec<TypedConcreteParametricStruct>,
}

impl<'a> TypedConcreteParametricStructCollector<'a> {
    /// Creates an empty collector for one typed-AOT wrapper build.
    fn new(context: &'a TypedDslxTypeContext) -> Self {
        Self {
            context,
            current_module_name: String::new(),
            structs: Vec::new(),
        }
    }

    /// Walks one resolved DSLX type and records reachable concrete struct
    /// specializations.
    ///
    /// `current_type_info` must describe the module that wrote the annotation
    /// so caller-local parametric expressions are evaluated in the caller's
    /// context. When recursion enters struct fields, the walk switches to the
    /// defining module context for field inspection while still emitting the
    /// eventual concrete item in the owner's Rust module.
    fn collect_type(
        &mut self,
        current_module_name: &str,
        current_type_info: &dslx::TypeInfo,
        type_annotation: Option<&dslx::TypeAnnotation>,
        ty: &dslx::Type,
    ) -> AotResult<()> {
        if let Some(type_annotation) = type_annotation {
            if let Some(array_annotation) = type_annotation.to_array_type_annotation() {
                if ty.is_array() {
                    let element_annotation = array_annotation.get_element_type();
                    let element_ty = ty.get_array_element_type();
                    self.collect_type(
                        current_module_name,
                        current_type_info,
                        Some(&element_annotation),
                        &element_ty,
                    )?;
                    return Ok(());
                }
            }
            if let Some(type_ref_annotation) = type_annotation.to_type_ref_type_annotation() {
                if type_ref_annotation.get_parametric_count() > 0 && ty.is_struct() {
                    let struct_def = ty.get_struct_def()?;
                    let Some(defining_module) = self
                        .context
                        .defining_module_for_struct(Some(current_type_info), &struct_def)?
                    else {
                        return Err(XlsynthError(format!(
                            "AOT typed DSLX specialization collection could not find defining module for struct `{}`",
                            struct_def.get_identifier()
                        )));
                    };
                    let rust_name = RustBridgeBuilder::rust_type_name_from_dslx_module(
                        &defining_module.dslx_name,
                        current_type_info,
                        Some(type_annotation),
                        ty,
                    )?;
                    let lowered = lower_typed_dslx_type(
                        self.context,
                        &defining_module.dslx_name,
                        &defining_module.type_info,
                        Some(type_annotation),
                        ty,
                        rust_name.clone(),
                    )?;
                    let TypedDslxType::Struct { fields, .. } = lowered else {
                        unreachable!("parametric structs lower to struct types");
                    };
                    let already_collected = self.structs.iter().any(|existing| {
                        existing.defining_module_name == defining_module.dslx_name
                            && existing.struct_def.is_same_definition(&struct_def)
                            && existing.rust_name == rust_name
                    });
                    if !already_collected {
                        self.structs.push(TypedConcreteParametricStruct {
                            struct_def,
                            defining_module_name: defining_module.dslx_name.clone(),
                            rust_name,
                            fields,
                        });
                    }
                }
            }
        }

        if ty.is_struct() {
            let struct_def = ty.get_struct_def()?;
            let struct_type_info = self
                .context
                .type_info_for_struct(current_type_info, &struct_def)?;
            let struct_module_name = self
                .context
                .defining_module_for_struct(Some(current_type_info), &struct_def)?
                .map(|module| module.dslx_name.as_str())
                .unwrap_or(current_module_name);
            let member_count = struct_def.get_member_count();
            for index in 0..member_count {
                let member = struct_def.get_member(index);
                let field_annotation = member.get_type();
                let field_ty = if struct_def.is_parametric() {
                    ty.get_struct_member_type(index)
                } else {
                    struct_type_info.get_type_for_struct_member(&member)
                };
                let field_type_info = self.context.type_context_for_resolved_type(
                    struct_type_info,
                    Some(&field_annotation),
                    &field_ty,
                )?;
                self.collect_type(
                    struct_module_name,
                    field_type_info,
                    Some(&field_annotation),
                    &field_ty,
                )?;
            }
        } else if ty.is_array() {
            let element_ty = ty.get_array_element_type();
            self.collect_type(current_module_name, current_type_info, None, &element_ty)?;
        }
        Ok(())
    }

    /// Returns collected specializations in deterministic discovery order.
    fn into_structs(self) -> Vec<TypedConcreteParametricStruct> {
        self.structs
    }
}

/// Feeds the specialization collector from the typed bridge callbacks.
///
/// Untyped bridge callbacks and non-type-bearing members are intentionally
/// ignored: only typed structs, aliases, and function signatures can expose the
/// concrete imported instantiations this prepass must materialize.
impl BridgeBuilder for TypedConcreteParametricStructCollector<'_> {
    fn start_module(&mut self, module_name: &str) -> Result<(), XlsynthError> {
        self.current_module_name = module_name.to_string();
        Ok(())
    }

    fn end_module(&mut self, _module_name: &str) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_enum_def(
        &mut self,
        _dslx_name: &str,
        _is_signed: bool,
        _underlying_bit_count: usize,
        _members: &[(String, crate::IrValue)],
    ) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_struct_def(
        &mut self,
        _dslx_name: &str,
        _members: &[crate::dslx_bridge::StructMemberData],
    ) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_struct_def_typed(
        &mut self,
        _dslx_name: &str,
        type_info: &dslx::TypeInfo,
        members: &[crate::dslx_bridge::StructMemberData],
    ) -> Result<(), XlsynthError> {
        let module_name = self.current_module_name.clone();
        for member in members {
            self.collect_type(
                &module_name,
                type_info,
                Some(&member.type_annotation),
                &member.concrete_type,
            )?;
        }
        Ok(())
    }

    fn add_alias(
        &mut self,
        _dslx_name: &str,
        _type_annotation: &dslx::TypeAnnotation,
        _ty: &dslx::Type,
    ) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_alias_typed(
        &mut self,
        _dslx_name: &str,
        type_info: &dslx::TypeInfo,
        type_annotation: &dslx::TypeAnnotation,
        ty: &dslx::Type,
    ) -> Result<(), XlsynthError> {
        let module_name = self.current_module_name.clone();
        self.collect_type(&module_name, type_info, Some(type_annotation), ty)
    }

    fn add_constant(
        &mut self,
        _name: &str,
        _constant_def: &dslx::ConstantDef,
        _ty: &dslx::Type,
        _ir_value: &crate::IrValue,
    ) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_function_signature_typed(
        &mut self,
        _dslx_name: &str,
        type_info: &dslx::TypeInfo,
        params: &[crate::dslx_bridge::FunctionParamData],
        return_type_annotation: Option<&dslx::TypeAnnotation>,
        return_type: Option<&dslx::Type>,
    ) -> Result<(), XlsynthError> {
        let module_name = self.current_module_name.clone();
        for param in params {
            if let Some(concrete_type) = &param.concrete_type {
                self.collect_type(
                    &module_name,
                    type_info,
                    Some(&param.type_annotation),
                    concrete_type,
                )?;
            }
        }
        if let (Some(type_annotation), Some(ty)) = (return_type_annotation, return_type) {
            self.collect_type(&module_name, type_info, Some(type_annotation), ty)?;
        }
        Ok(())
    }
}

/// Collects every concrete parametric struct needed by one generated wrapper.
///
/// The traversal must cover both explicitly emitted bridge modules and the top
/// module before any module is rendered; otherwise an imported use can refer to
/// a concrete Rust struct that its defining module never emits.
fn collect_typed_concrete_parametric_structs(
    context: &TypedDslxTypeContext,
    typechecked: &TypedDslxTypecheckedModules,
) -> AotResult<Vec<TypedConcreteParametricStruct>> {
    collect_typed_concrete_parametric_structs_from_modules(
        context,
        typechecked
            .bridge_modules
            .iter()
            .chain(std::iter::once(&typechecked.top_module)),
    )
}

fn collect_typed_concrete_parametric_structs_from_modules<'a>(
    context: &TypedDslxTypeContext,
    modules: impl IntoIterator<Item = &'a dslx::TypecheckedModule>,
) -> AotResult<Vec<TypedConcreteParametricStruct>> {
    let mut collector = TypedConcreteParametricStructCollector::new(context);
    for module in modules {
        convert_imported_module(module, &mut collector)?;
    }
    Ok(collector.into_structs())
}

/// Renders one already-collected concrete parametric struct definition.
///
/// Fields are already lowered relative to the defining module, so this routine
/// only serializes the owner-local Rust item that will be inserted ahead of the
/// normal bridge output.
fn render_typed_concrete_parametric_struct(
    concrete_struct: &TypedConcreteParametricStruct,
) -> String {
    let mut lines = vec![
        "#[allow(non_camel_case_types)]".to_string(),
        "#[derive(Debug, Clone, PartialEq, Eq)]".to_string(),
        format!("pub struct {} {{", concrete_struct.rust_name),
    ];
    lines.extend(
        concrete_struct
            .fields
            .iter()
            .map(|field| format!("    pub {}: {},", field.name, field.ty.rust_type())),
    );
    lines.push("}\n".to_string());
    lines.join("\n")
}

/// Lowers one DSLX type into the semantic model used by typed AOT generation.
///
/// The caller supplies the Rust bridge type spelling for the outer type so
/// aliases and imported paths are preserved. Nested fields and array elements
/// resolve their own contexts recursively before code generation flattens them
/// to AOT leaves.
fn lower_typed_dslx_type(
    context: &TypedDslxTypeContext,
    local_module_name: &str,
    current_type_info: &dslx::TypeInfo,
    type_annotation: Option<&dslx::TypeAnnotation>,
    ty: &dslx::Type,
    rust_type: String,
) -> AotResult<TypedDslxType> {
    if let Some((is_signed, bit_count)) = ty.is_bits_like() {
        Ok(TypedDslxType::Bits {
            rust_type,
            is_signed,
            bit_count,
        })
    } else if ty.is_enum() {
        let enum_def = ty.get_enum_def()?;
        let enum_type_info = context.type_info_for_enum(current_type_info, &enum_def)?;
        let underlying = enum_type_info
            .get_type_for_type_annotation(&enum_def.get_underlying())
            .ok_or_else(|| {
                XlsynthError(format!(
                    "AOT typed DSLX type lowering could not resolve underlying type for enum `{}`",
                    enum_def.get_identifier()
                ))
            })?;
        let (is_signed, bit_count) = underlying.is_bits_like().ok_or_else(|| {
            XlsynthError(format!(
                "AOT typed DSLX type lowering expected enum `{}` to have bits-like underlying type",
                enum_def.get_identifier()
            ))
        })?;
        let variants = (0..enum_def.get_member_count())
            .map(|index| {
                let member = enum_def.get_member(index);
                let value = enum_type_info
                    .get_const_expr(&member.get_value())?
                    .convert_to_ir()?;
                let value = if is_signed {
                    value.to_i64()?.to_string()
                } else {
                    value.to_u64()?.to_string()
                };
                Ok(TypedDslxEnumVariant {
                    name: member.get_name(),
                    value,
                })
            })
            .collect::<AotResult<Vec<_>>>()?;
        Ok(TypedDslxType::Enum {
            rust_type,
            is_signed,
            bit_count,
            variants,
        })
    } else if ty.is_struct() {
        let struct_def = ty.get_struct_def()?;
        let struct_type_info = context.type_info_for_struct(current_type_info, &struct_def)?;
        let definition_member_count = struct_def.get_member_count();
        let concrete_member_count = if struct_def.is_parametric() {
            ty.get_struct_member_count()
        } else {
            definition_member_count
        };
        if concrete_member_count != definition_member_count {
            return Err(XlsynthError(format!(
                "AOT typed DSLX type lowering found {definition_member_count} definition member(s) but {concrete_member_count} concrete member type(s) for struct `{}`",
                struct_def.get_identifier()
            )));
        }
        let fields = (0..concrete_member_count)
            .map(|index| {
                let member = struct_def.get_member(index);
                let field_annotation = member.get_type();
                let field_type = if struct_def.is_parametric() {
                    ty.get_struct_member_type(index)
                } else {
                    struct_type_info.get_type_for_struct_member(&member)
                };
                let field_type_info = context.type_context_for_resolved_type(
                    struct_type_info,
                    Some(&field_annotation),
                    &field_type,
                )?;
                let rust_type = context.rust_type_path_for_resolved_type(
                    local_module_name,
                    field_type_info,
                    Some(&field_annotation),
                    &field_type,
                )?;
                Ok(TypedDslxField {
                    name: member.get_name(),
                    ty: lower_typed_dslx_type(
                        context,
                        local_module_name,
                        field_type_info,
                        Some(&field_annotation),
                        &field_type,
                        rust_type,
                    )?,
                })
            })
            .collect::<AotResult<Vec<_>>>()?;
        Ok(TypedDslxType::Struct { rust_type, fields })
    } else if ty.is_array() {
        let element = ty.get_array_element_type();
        let expanded_annotation = type_annotation
            .map(|annotation| {
                context.expand_type_alias_rhs_annotation(current_type_info, annotation, 0)
            })
            .transpose()?
            .flatten();
        let effective_type_info = expanded_annotation
            .as_ref()
            .map(|annotation| annotation.type_info)
            .unwrap_or(current_type_info);
        let effective_annotation = expanded_annotation
            .as_ref()
            .map(|annotation| &annotation.annotation)
            .or(type_annotation);
        let element_annotation = effective_annotation
            .and_then(|annotation| annotation.to_array_type_annotation())
            .map(|annotation| annotation.get_element_type());
        let element_type_info = context.type_context_for_resolved_type(
            effective_type_info,
            element_annotation.as_ref(),
            &element,
        )?;
        let element_rust_type = context.rust_type_path_for_resolved_type(
            local_module_name,
            element_type_info,
            element_annotation.as_ref(),
            &element,
        )?;
        Ok(TypedDslxType::Array {
            rust_type,
            size: ty.get_array_size(),
            element: Box::new(lower_typed_dslx_type(
                context,
                local_module_name,
                element_type_info,
                element_annotation.as_ref(),
                &element,
                element_rust_type,
            )?),
        })
    } else {
        Err(XlsynthError(format!(
            "AOT typed DSLX type lowering does not support DSLX type `{}`",
            ty.to_string()?
        )))
    }
}

/// Finds the top DSLX function selected for AOT emission.
///
/// This searches only the already-typechecked top module. Missing functions are
/// reported before AOT metadata validation so build scripts fail with the DSLX
/// function name the caller supplied.
fn find_dslx_function(
    typechecked_module: &dslx::TypecheckedModule,
    function_name: &str,
) -> AotResult<dslx::Function> {
    let module = typechecked_module.get_module();
    for index in 0..module.get_member_count() {
        if let Some(dslx::MatchableModuleMember::Function(function)) =
            module.get_member(index).to_matchable()
        {
            if function.get_identifier() == function_name {
                return Ok(function);
            }
        }
    }
    Err(XlsynthError(format!(
        "AOT typed DSLX type lowering could not find DSLX function `{function_name}`"
    )))
}

/// Builds the typed DSLX signature for the selected top function.
///
/// The result preserves public Rust bridge names and the recursive semantic
/// shape for every parameter and the return value. A return annotation is
/// required because the generated runner needs an explicit Rust return type.
fn build_typed_dslx_function_signature(
    context: &TypedDslxTypeContext,
    top_module: &dslx::TypecheckedModule,
    top: &str,
    rust_module_name: &str,
) -> AotResult<TypedAotFunctionSignature> {
    let type_info = top_module.get_type_info();
    let function = find_dslx_function(top_module, top)?;
    let params = (0..function.get_param_count())
        .map(|index| {
            let param = function.get_param(index);
            let annotation = param.get_type_annotation();
            let concrete_type = type_info
                .get_type_for_type_annotation(&annotation)
                .ok_or_else(|| {
                    XlsynthError(format!(
                        "AOT typed DSLX type lowering could not resolve type for parameter `{}`",
                        param.get_name()
                    ))
                })?;
            let param_type_info = context.type_context_for_resolved_type(
                &type_info,
                Some(&annotation),
                &concrete_type,
            )?;
            let rust_type = context.rust_type_path_for_resolved_type(
                rust_module_name,
                param_type_info,
                Some(&annotation),
                &concrete_type,
            )?;
            Ok(TypedDslxParam {
                name: param.get_name(),
                rust_type: rust_type.clone(),
                ty: lower_typed_dslx_type(
                    context,
                    rust_module_name,
                    param_type_info,
                    Some(&annotation),
                    &concrete_type,
                    rust_type,
                )?,
            })
        })
        .collect::<AotResult<Vec<_>>>()?;

    let return_annotation = function.get_return_type().ok_or_else(|| {
        XlsynthError(format!(
            "AOT typed DSLX type lowering requires function `{top}` to have an explicit return type"
        ))
    })?;
    let return_type = type_info
        .get_type_for_type_annotation(&return_annotation)
        .ok_or_else(|| {
            XlsynthError(format!(
                "AOT typed DSLX type lowering could not resolve return type for function `{top}`"
            ))
        })?;
    let return_type_info = context.type_context_for_resolved_type(
        &type_info,
        Some(&return_annotation),
        &return_type,
    )?;
    let return_rust_type = context.rust_type_path_for_resolved_type(
        rust_module_name,
        return_type_info,
        Some(&return_annotation),
        &return_type,
    )?;
    let typed_dslx_return_type = lower_typed_dslx_type(
        context,
        rust_module_name,
        return_type_info,
        Some(&return_annotation),
        &return_type,
        return_rust_type.clone(),
    )?;
    Ok(TypedAotFunctionSignature {
        params,
        return_rust_type,
        return_type: typed_dslx_return_type,
    })
}

/// Returns the Rust type spelling stored on a lowered DSLX type.
///
/// Generated helper functions use this spelling in their signatures while the
/// recursive variant data drives the actual leaf packing or decoding work.
fn typed_dslx_rust_type_name(ty: &TypedDslxType) -> &str {
    match ty {
        TypedDslxType::Bits { rust_type, .. }
        | TypedDslxType::Enum { rust_type, .. }
        | TypedDslxType::Struct { rust_type, .. }
        | TypedDslxType::Array { rust_type, .. } => rust_type,
    }
}

/// Counts the number of AOT ABI leaves produced by one lowered DSLX type.
///
/// Bits and enums each occupy one leaf. Structs concatenate field leaves in
/// declaration order, and arrays repeat the element leaf layout for every
/// element.
fn typed_dslx_leaf_count(ty: &TypedDslxType) -> usize {
    match ty {
        TypedDslxType::Bits { .. } | TypedDslxType::Enum { .. } => 1,
        TypedDslxType::Struct { fields, .. } => fields
            .iter()
            .map(|field| typed_dslx_leaf_count(&field.ty))
            .sum(),
        TypedDslxType::Array { size, element, .. } => {
            size.saturating_mul(typed_dslx_leaf_count(element))
        }
    }
}

/// Converts a lowered typed DSLX type into the structural AOT metadata shape.
///
/// This is the validation bridge between the DSLX semantic model and the
/// compiled entrypoint metadata. It intentionally drops Rust names because AOT
/// metadata only knows bits, tuples, and arrays.
fn flatten_typed_dslx_type_to_aot_type(ty: &TypedDslxType) -> AotType {
    match ty {
        TypedDslxType::Bits { bit_count, .. } | TypedDslxType::Enum { bit_count, .. } => {
            AotType::Bits {
                bit_count: *bit_count,
            }
        }
        TypedDslxType::Struct { fields, .. } => AotType::Tuple {
            elements: fields
                .iter()
                .map(|field| flatten_typed_dslx_type_to_aot_type(&field.ty))
                .collect(),
        },
        TypedDslxType::Array { size, element, .. } => AotType::Array {
            size: *size,
            element: Box::new(flatten_typed_dslx_type_to_aot_type(element)),
        },
    }
}

/// Verifies that one typed DSLX boundary type matches the compiled AOT ABI.
///
/// The label is included in diagnostics so callers can distinguish parameter,
/// field, and return mismatches without inspecting generated source.
fn validate_typed_dslx_type_matches_aot(
    label: &str,
    typed_dslx_type: &TypedDslxType,
    aot: &AotType,
) -> AotResult<()> {
    let flattened = flatten_typed_dslx_type_to_aot_type(typed_dslx_type);
    if flattened == *aot {
        Ok(())
    } else {
        Err(XlsynthError(format!(
            "AOT typed DSLX type mismatch for {label}: DSLX semantic type flattens to {flattened:?}, but AOT metadata has {aot:?}"
        )))
    }
}

/// Verifies that a typed DSLX function signature matches AOT metadata.
///
/// This check is the last line of defense before generating a public `Runner`.
/// If the DSLX lowerer and AOT compiler disagree on flattening, the build fails
/// instead of emitting a wrapper that would mispack buffers at runtime.
fn validate_typed_dslx_function_matches_aot(
    typed_signature: &TypedAotFunctionSignature,
    signature: &AotFunctionSignature,
) -> AotResult<()> {
    if typed_signature.params.len() != signature.params.len() {
        return Err(XlsynthError(format!(
            "AOT typed DSLX type mismatch: DSLX parameter count={} but AOT metadata parameter count={}",
            typed_signature.params.len(),
            signature.params.len()
        )));
    }
    for (index, (param, aot_param)) in typed_signature
        .params
        .iter()
        .zip(signature.params.iter())
        .enumerate()
    {
        validate_typed_dslx_type_matches_aot(
            &format!("input {index} `{}`", param.name),
            &param.ty,
            &aot_param.ty,
        )?;
    }
    validate_typed_dslx_type_matches_aot(
        "return",
        &typed_signature.return_type,
        &signature.return_type,
    )
}

/// Appends generated statements that pack a typed DSLX value into AOT leaves.
///
/// The generated statements write little-endian leaf bytes at offsets described
/// by entrypoint metadata layouts. Struct and array traversal must stay in lock
/// step with `typed_dslx_leaf_count` and `flatten_typed_dslx_type_to_aot_type`.
fn emit_typed_dslx_pack_statements(
    ty: &TypedDslxType,
    value_expr: &str,
    layout_name: &str,
    dst_name: &str,
    leaf_index_expr: &str,
    lines: &mut Vec<String>,
    next_loop_index: &mut usize,
) {
    match ty {
        TypedDslxType::Bits { .. } => {
            push_line(
                lines,
                format!("let encoded_bytes = ({value_expr}).to_le_bytes()?;"),
            );
            push_line(
                lines,
                format!(
                    "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &encoded_bytes);"
                ),
            );
        }
        TypedDslxType::Enum {
            rust_type,
            is_signed,
            bit_count,
            variants,
        } => {
            let scalar_type = if *is_signed { "i64" } else { "u64" };
            push_line(
                lines,
                format!("let encoded_value: {scalar_type} = match {value_expr} {{"),
            );
            for variant in variants {
                push_line(
                    lines,
                    format!("    {rust_type}::{} => {},", variant.name, variant.value),
                );
            }
            push_line(lines, "};");
            let ir_bits_wrapper_name = if *is_signed { "IrSBits" } else { "IrUBits" };
            let constructor = if *is_signed { "from_i64" } else { "from_u64" };
            push_line(
                lines,
                format!(
                    "let encoded_bits = xlsynth::{ir_bits_wrapper_name}::<{bit_count}>::{constructor}(encoded_value)?;"
                ),
            );
            push_line(lines, "let encoded_bytes = encoded_bits.to_le_bytes()?;");
            push_line(
                lines,
                format!(
                    "xlsynth::aot_runner::write_leaf_element({dst_name}, &{layout_name}[{leaf_index_expr}], &encoded_bytes);"
                ),
            );
        }
        TypedDslxType::Struct { fields, .. } => {
            let mut offset = 0usize;
            for field in fields {
                let field_leaf_base = if offset == 0 {
                    leaf_index_expr.to_string()
                } else {
                    format!("{leaf_index_expr} + {offset}")
                };
                emit_typed_dslx_pack_statements(
                    &field.ty,
                    &format!("({value_expr}).{}", field.name),
                    layout_name,
                    dst_name,
                    &field_leaf_base,
                    lines,
                    next_loop_index,
                );
                offset = offset.saturating_add(typed_dslx_leaf_count(&field.ty));
            }
        }
        TypedDslxType::Array { size, element, .. } => {
            let element_leaves = typed_dslx_leaf_count(element);
            if *size == 0 || element_leaves == 0 {
                return;
            }
            let loop_name = format!("index_{}", *next_loop_index);
            *next_loop_index += 1;
            push_line(lines, format!("for {loop_name} in 0..{size} {{"));
            let element_leaf_base = if element_leaves == 1 {
                format!("{leaf_index_expr} + {loop_name}")
            } else {
                format!("{leaf_index_expr} + {loop_name} * {element_leaves}")
            };
            emit_typed_dslx_pack_statements(
                element,
                &format!("({value_expr})[{loop_name}]"),
                layout_name,
                dst_name,
                &element_leaf_base,
                lines,
                next_loop_index,
            );
            push_line(lines, "}");
        }
    }
}

/// Renders one generated input encoder function for a typed DSLX parameter.
///
/// The encoder zeroes the destination buffer before writing leaves so padding
/// bytes in the ABI buffer do not retain stale contents between runner calls.
fn render_typed_dslx_encode_function(
    index: usize,
    ty: &TypedDslxType,
    expected_size: usize,
) -> String {
    let layout_name = format!("INPUT{index}_LAYOUT");
    let mut lines = Vec::new();
    push_line(
        &mut lines,
        "#[allow(clippy::deref_addrof, clippy::explicit_auto_deref, clippy::identity_op)]",
    );
    push_line(
        &mut lines,
        format!(
            "fn encode_input_{index}(_value: &{}, dst: &mut [u8]) -> Result<(), xlsynth::XlsynthError> {{",
            typed_dslx_rust_type_name(ty)
        ),
    );
    push_line(
        &mut lines,
        format!("debug_assert_eq!(dst.len(), {expected_size});"),
    );
    push_line(&mut lines, "dst.fill(0);");
    let mut loop_index = 0usize;
    emit_typed_dslx_pack_statements(
        ty,
        "*_value",
        &layout_name,
        "dst",
        "0usize",
        &mut lines,
        &mut loop_index,
    );
    let expected_leaves = typed_dslx_leaf_count(ty);
    push_line(
        &mut lines,
        format!("debug_assert_eq!({layout_name}.len(), {expected_leaves});"),
    );
    push_line(&mut lines, "Ok(())");
    push_line(&mut lines, "}");
    lines.join("\n")
}

/// Allocates a unique temporary identifier for generated decode code.
///
/// The prefix encodes the temporary's role for readability, while the counter
/// avoids accidental shadowing across recursive struct and array decoding.
fn next_temp(prefix: &str, next_temp_index: &mut usize) -> String {
    let name = format!("{prefix}_{}", *next_temp_index);
    *next_temp_index += 1;
    name
}

/// Appends generated statements that decode AOT leaves into a typed DSLX value.
///
/// The returned string is the generated Rust expression or temporary name that
/// holds the decoded value. Structs and arrays recursively decode their leaves
/// before constructing the Rust bridge value expected by the public runner API.
fn emit_typed_dslx_decode_statements(
    ty: &TypedDslxType,
    layout_name: &str,
    src_name: &str,
    leaf_index_expr: &str,
    lines: &mut Vec<String>,
    next_loop_index: &mut usize,
    next_temp_index: &mut usize,
) -> String {
    match ty {
        TypedDslxType::Bits {
            is_signed,
            bit_count,
            ..
        } => {
            let bytes_name = next_temp("decoded_bytes", next_temp_index);
            let value_name = next_temp("decoded_value", next_temp_index);
            let byte_count = bit_count.div_ceil(8);
            push_line(
                lines,
                format!("let mut {bytes_name} = vec![0u8; {byte_count}];"),
            );
            push_line(
                lines,
                format!(
                    "xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut {bytes_name});"
                ),
            );
            let ir_bits_wrapper_name = if *is_signed { "IrSBits" } else { "IrUBits" };
            push_line(
                lines,
                format!(
                    "let {value_name} = xlsynth::{ir_bits_wrapper_name}::<{bit_count}>::from_le_bytes(&{bytes_name})?;"
                ),
            );
            value_name
        }
        TypedDslxType::Enum {
            rust_type,
            is_signed,
            bit_count,
            variants,
        } => {
            let bytes_name = next_temp("decoded_bytes", next_temp_index);
            let bits_name = next_temp("decoded_bits", next_temp_index);
            let scalar_name = next_temp("decoded_scalar", next_temp_index);
            let value_name = next_temp("decoded_value", next_temp_index);
            let byte_count = bit_count.div_ceil(8);
            push_line(
                lines,
                format!("let mut {bytes_name} = vec![0u8; {byte_count}];"),
            );
            push_line(
                lines,
                format!(
                    "xlsynth::aot_runner::read_leaf_element({src_name}, &{layout_name}[{leaf_index_expr}], &mut {bytes_name});"
                ),
            );
            let ir_bits_wrapper_name = if *is_signed { "IrSBits" } else { "IrUBits" };
            let scalar_method = if *is_signed { "to_i64" } else { "to_u64" };
            push_line(
                lines,
                format!(
                    "let {bits_name} = xlsynth::{ir_bits_wrapper_name}::<{bit_count}>::from_le_bytes(&{bytes_name})?;"
                ),
            );
            push_line(
                lines,
                format!("let {scalar_name} = {bits_name}.{scalar_method}()?;"),
            );
            push_line(lines, format!("let {value_name} = match {scalar_name} {{"));
            for variant in variants {
                push_line(
                    lines,
                    format!("    {} => {rust_type}::{},", variant.value, variant.name),
                );
            }
            push_line(
                lines,
                format!(
                    "    value => return Err(xlsynth::XlsynthError(format!(\"AOT decode invalid enum value {{value}} for {rust_type}\"))),"
                ),
            );
            push_line(lines, "};");
            value_name
        }
        TypedDslxType::Struct { rust_type, fields } => {
            let field_values = fields
                .iter()
                .scan(0usize, |offset, field| {
                    let field_leaf_base = if *offset == 0 {
                        leaf_index_expr.to_string()
                    } else {
                        format!("{leaf_index_expr} + {}", *offset)
                    };
                    *offset = offset.saturating_add(typed_dslx_leaf_count(&field.ty));
                    Some((
                        field.name.clone(),
                        emit_typed_dslx_decode_statements(
                            &field.ty,
                            layout_name,
                            src_name,
                            &field_leaf_base,
                            lines,
                            next_loop_index,
                            next_temp_index,
                        ),
                    ))
                })
                .collect::<Vec<_>>();
            let value_name = next_temp("decoded_value", next_temp_index);
            push_line(lines, format!("let {value_name} = {rust_type} {{"));
            for (field_name, field_value) in field_values {
                push_line(lines, format!("    {field_name}: {field_value},"));
            }
            push_line(lines, "};");
            value_name
        }
        TypedDslxType::Array {
            rust_type,
            size,
            element,
        } => {
            let value_name = next_temp("decoded_value", next_temp_index);
            if *size == 0 {
                push_line(lines, format!("let {value_name}: {rust_type} = [];"));
                return value_name;
            }
            let items_name = next_temp("decoded_items", next_temp_index);
            let loop_name = format!("index_{}", *next_loop_index);
            *next_loop_index += 1;
            let element_leaves = typed_dslx_leaf_count(element);
            push_line(
                lines,
                format!("let mut {items_name} = Vec::with_capacity({size});"),
            );
            push_line(lines, format!("for {loop_name} in 0..{size} {{"));
            let element_leaf_base = if element_leaves == 1 {
                format!("{leaf_index_expr} + {loop_name}")
            } else {
                format!("{leaf_index_expr} + {loop_name} * {element_leaves}")
            };
            let element_value = emit_typed_dslx_decode_statements(
                element,
                layout_name,
                src_name,
                &element_leaf_base,
                lines,
                next_loop_index,
                next_temp_index,
            );
            push_line(lines, format!("{items_name}.push({element_value});"));
            push_line(lines, "}");
            push_line(
                lines,
                format!(
                    "let {value_name}: {rust_type} = match std::convert::TryInto::try_into({items_name}) {{"
                ),
            );
            push_line(lines, "    Ok(value) => value,");
            push_line(
                lines,
                format!(
                    "    Err(values) => return Err(xlsynth::XlsynthError(format!(\"AOT decode internal error: expected {size} array elements, got {{}}\", values.len()))),"
                ),
            );
            push_line(lines, "};");
            value_name
        }
    }
}

/// Renders the generated output decoder for the typed DSLX return value.
///
/// The decoder mirrors the input encoders: it reads bytes according to the AOT
/// output layout and reconstructs the Rust bridge type promised by the public
/// `Runner` signature.
fn render_typed_dslx_decode_function(ty: &TypedDslxType, expected_size: usize) -> String {
    let layout_name = "OUTPUT0_LAYOUT";
    let mut lines = Vec::new();
    push_line(
        &mut lines,
        "#[allow(clippy::deref_addrof, clippy::explicit_auto_deref, clippy::identity_op)]",
    );
    push_line(
        &mut lines,
        format!(
            "fn decode_output_0(src: &[u8]) -> Result<{}, xlsynth::XlsynthError> {{",
            typed_dslx_rust_type_name(ty)
        ),
    );
    push_line(
        &mut lines,
        format!("debug_assert_eq!(src.len(), {expected_size});"),
    );
    let mut loop_index = 0usize;
    let mut temp_index = 0usize;
    let value_name = emit_typed_dslx_decode_statements(
        ty,
        layout_name,
        "src",
        "0usize",
        &mut lines,
        &mut loop_index,
        &mut temp_index,
    );
    let expected_leaves = typed_dslx_leaf_count(ty);
    push_line(
        &mut lines,
        format!("debug_assert_eq!({layout_name}.len(), {expected_leaves});"),
    );
    push_line(&mut lines, format!("Ok({value_name})"));
    push_line(&mut lines, "}");
    lines.join("\n")
}

/// Produces unique generated argument names for the typed runner methods.
///
/// DSLX parameter names can collide with each other after Rust identifier
/// sanitization, or with Rust keywords. The generated names preserve readable
/// stems while guaranteeing the `run` and `run_with_events` signatures compile.
fn make_unique_typed_dslx_argument_names(params: &[TypedDslxParam]) -> Vec<String> {
    let mut used = HashSet::new();
    params
        .iter()
        .enumerate()
        .map(|(index, param)| {
            let base = sanitize_value_identifier(&param.name, &format!("arg{index}"));
            let mut candidate = base.clone();
            let mut suffix = 1usize;
            while !used.insert(candidate.clone()) {
                suffix += 1;
                candidate = format!("{base}_{suffix}");
            }
            candidate
        })
        .collect()
}

/// Renders the generated runner items inserted into the top DSLX bridge module.
///
/// The epilogue owns the linked symbol declaration, descriptor, typed
/// encode/decode helpers, and `Runner` API. Keeping it inside the top module
/// lets public signatures name bridge types without an adapter layer or extra
/// reexports.
fn render_typed_dslx_runner_epilogue(
    base_name: &str,
    proto_file_name: &str,
    metadata: &AotEntrypointMetadata,
    signature: &AotFunctionSignature,
    typed_signature: &TypedAotFunctionSignature,
) -> AotResult<String> {
    validate_signature_and_layouts(metadata, signature)?;
    validate_typed_dslx_function_matches_aot(typed_signature, signature)?;

    let link_symbol_literal = format!("{:?}", metadata.symbol);
    let symbol_ident = format!("__xlsynth_aot_linked_symbol_{base_name}");
    let input_sizes = format_usize_array(&metadata.input_buffer_sizes);
    let input_alignments = format_usize_array(&metadata.input_buffer_alignments);
    let output_sizes = format_usize_array(&metadata.output_buffer_sizes);
    let output_alignments = format_usize_array(&metadata.output_buffer_alignments);
    let input_layout_constants = render_layout_constants("INPUT", &signature.input_layouts);
    let output_layout_constants = render_layout_constants("OUTPUT", &signature.output_layouts);

    let mut helper_blocks = Vec::new();
    for (index, param) in typed_signature.params.iter().enumerate() {
        helper_blocks.push(render_typed_dslx_encode_function(
            index,
            &param.ty,
            metadata.input_buffer_sizes[index],
        ));
    }
    helper_blocks.push(render_typed_dslx_decode_function(
        &typed_signature.return_type,
        metadata.output_buffer_sizes[0],
    ));
    let helper_functions = helper_blocks.join("\n\n");

    let arg_names = make_unique_typed_dslx_argument_names(&typed_signature.params);
    let run_params = typed_signature
        .params
        .iter()
        .zip(arg_names.iter())
        .map(|(param, name)| format!("{name}: &{}", param.rust_type))
        .collect::<Vec<_>>()
        .join(", ");
    let run_signature = if run_params.is_empty() {
        "&mut self".to_string()
    } else {
        format!("&mut self, {run_params}")
    };

    let mut encode_body = String::new();
    for (index, name) in arg_names.iter().enumerate() {
        encode_body.push_str(&format!(
            "        encode_input_{index}({name}, self.inner.input_mut({index}))?;\n"
        ));
    }

    Ok(format!(
        "unsafe extern \"C\" {{\n\
    #[link_name = {link_symbol_literal}]\n\
    fn {symbol_ident}();\n\
}}\n\
\n\
const ENTRYPOINTS_PROTO: &[u8] = include_bytes!(\"{proto_file_name}\");\n\
const INPUT_BUFFER_SIZES: &[usize] = {input_sizes};\n\
const INPUT_BUFFER_ALIGNMENTS: &[usize] = {input_alignments};\n\
const OUTPUT_BUFFER_SIZES: &[usize] = {output_sizes};\n\
const OUTPUT_BUFFER_ALIGNMENTS: &[usize] = {output_alignments};\n\
\n\
{input_layout_constants}\
{output_layout_constants}\
\n\
{helper_functions}\n\
\n\
pub fn descriptor() -> xlsynth::AotEntrypointDescriptor<'static> {{\n\
    unsafe {{\n\
        xlsynth::AotEntrypointDescriptor::from_raw_parts_unchecked(\n\
            ENTRYPOINTS_PROTO,\n\
            {symbol_ident} as *const () as usize,\n\
            xlsynth::AotEntrypointMetadata {{\n\
                symbol: {link_symbol_literal}.to_string(),\n\
                input_buffer_sizes: INPUT_BUFFER_SIZES.to_vec(),\n\
                input_buffer_alignments: INPUT_BUFFER_ALIGNMENTS.to_vec(),\n\
                output_buffer_sizes: OUTPUT_BUFFER_SIZES.to_vec(),\n\
                output_buffer_alignments: OUTPUT_BUFFER_ALIGNMENTS.to_vec(),\n\
                temp_buffer_size: {temp_size},\n\
                temp_buffer_alignment: {temp_align},\n\
            }},\n\
        )\n\
    }}\n\
}}\n\
\n\
/// Reusable runner for the generated typed DSLX AOT entrypoint.\n\
///\n\
/// A runner caches the ABI buffers owned by `xlsynth::AotRunner`; create one\n\
/// runner per concurrent caller instead of sharing it across threads.\n\
pub struct Runner {{\n\
    inner: xlsynth::AotRunner<'static>,\n\
}}\n\
\n\
impl Runner {{\n\
    /// # Errors\n\
    ///\n\
    /// Returns an error if the descriptor metadata cannot initialize an AOT\n\
    /// runner.\n\
    pub fn new() -> Result<Self, xlsynth::XlsynthError> {{\n\
        Ok(Self {{\n\
            inner: xlsynth::AotRunner::new(descriptor())?,\n\
        }})\n\
    }}\n\
\n\
    /// Runs the entrypoint and returns the output together with trace/assert events.\n\
    ///\n\
    /// # Errors\n\
    ///\n\
    /// Returns an error if input packing, AOT execution, or output decoding\n\
    /// fails.\n\
    pub fn run_with_events({run_signature}) -> Result<xlsynth::AotRunResult<{return_type}>, xlsynth::XlsynthError> {{\n\
{encode_body}\
        let result = self.inner.run_with_events(|inner| decode_output_0(inner.output(0)))?;\n\
        Ok(xlsynth::AotRunResult {{\n\
            output: result.output?,\n\
            trace_messages: result.trace_messages,\n\
            assert_messages: result.assert_messages,\n\
        }})\n\
    }}\n\
\n\
    /// Runs the entrypoint and returns only the decoded output value.\n\
    ///\n\
    /// # Errors\n\
    ///\n\
    /// Returns an error if input packing, AOT execution, or output decoding\n\
    /// fails.\n\
    pub fn run({run_signature}) -> Result<{return_type}, xlsynth::XlsynthError> {{\n\
{encode_body}\
        self.inner.run()?;\n\
        decode_output_0(self.inner.output(0))\n\
    }}\n\
}}\n\
\n\
pub fn new_runner() -> Result<Runner, xlsynth::XlsynthError> {{\n\
    Runner::new()\n\
}}\n",
        return_type = typed_signature.return_rust_type.as_str(),
        temp_size = metadata.temp_buffer_size,
        temp_align = metadata.temp_buffer_alignment,
    ))
}

/// Renders the complete generated Rust module for a typed DSLX AOT wrapper.
///
/// Bridge modules are rendered first, then the top module is rendered with the
/// AOT runner epilogue appended. The generated tree is one include-able Rust
/// source file for build scripts to place under Cargo's output directory.
/// Direct imported parametric structs are collected before rendering so their
/// concrete Rust definitions can be injected once into the owning module rather
/// than being rediscovered independently by each use site.
fn render_typed_dslx_generated_module(
    spec: &TypedDslxAotBuildSpec<'_>,
    top_dslx_text: &str,
    base_name: &str,
    proto_file_name: &str,
    metadata: &AotEntrypointMetadata,
    signature: &AotFunctionSignature,
) -> AotResult<String> {
    let typechecked = typecheck_typed_dslx_modules(spec, top_dslx_text)?;
    let context = TypedDslxTypeContext::new(&typechecked);
    let top_module_name = typechecked.top_module.get_module().get_name();
    let typed_signature = build_typed_dslx_function_signature(
        &context,
        &typechecked.top_module,
        spec.top,
        &top_module_name,
    )?;
    let runner_epilogue = render_typed_dslx_runner_epilogue(
        base_name,
        proto_file_name,
        metadata,
        signature,
        &typed_signature,
    )?;
    let concrete_parametric_structs =
        collect_typed_concrete_parametric_structs(&context, &typechecked)?;
    let mut leading_items_by_module =
        concrete_parametric_structs
            .into_iter()
            .fold(BTreeMap::new(), |mut items, item| {
                items
                    .entry(item.defining_module_name.clone())
                    .or_insert_with(Vec::new)
                    .push(render_typed_concrete_parametric_struct(&item));
                items
            });

    let mut modules = Vec::with_capacity(spec.type_module_paths.len() + 1);
    for bridge_module in &typechecked.bridge_modules {
        let module_name = bridge_module.get_module().get_name();
        let mut builder = RustBridgeBuilder::new()
            .with_leading_items(
                leading_items_by_module
                    .remove(&module_name)
                    .unwrap_or_default(),
            )
            .with_deferred_parametric_struct_emission();
        convert_imported_module(bridge_module, &mut builder)?;
        modules.push(builder.module_fragment());
    }

    let mut top_builder = RustBridgeBuilder::new()
        .with_leading_items(
            leading_items_by_module
                .remove(&top_module_name)
                .unwrap_or_default(),
        )
        .with_deferred_parametric_struct_emission()
        .with_runner_items(runner_epilogue);
    convert_imported_module(&typechecked.top_module, &mut top_builder)?;
    modules.push(top_builder.module_fragment());
    if let Some((module_name, _)) = leading_items_by_module.into_iter().next() {
        return Err(XlsynthError(format!(
            "AOT typed DSLX specialization collection requires bridge module `{module_name}` to be emitted"
        )));
    }

    Ok(format!(
        "// SPDX-License-Identifier: Apache-2.0\n// Generated by xlsynth::aot_builder from DSLX build spec {:?}.\n\n{}\n",
        spec.name,
        render_rust_module_fragments(modules)
    ))
}

fn emit_typed_dslx_aot_package_with_out_dir(
    builder: &TypedDslxAotPackageBuilder<'_>,
    out_dir: &Path,
) -> AotResult<GeneratedTypedDslxAotPackage> {
    if builder.name.is_empty() {
        return Err(XlsynthError(
            "AOT invalid argument: typed DSLX package name must not be empty".to_string(),
        ));
    }
    ensure_package_specs_compatible(&builder.specs)?;

    let package_name = sanitize_identifier(builder.name);
    let mut seen_entrypoint_names = BTreeSet::new();
    let mut compiled = Vec::with_capacity(builder.specs.len());
    for spec in &builder.specs {
        let entrypoint = compile_typed_dslx_entrypoint_artifacts(spec, out_dir)?;
        if !seen_entrypoint_names.insert(entrypoint.base_name.clone()) {
            return Err(XlsynthError(format!(
                "AOT invalid argument: typed DSLX package contains duplicate entrypoint name `{}`",
                entrypoint.base_name
            )));
        }
        compiled.push(entrypoint);
    }

    let typechecked = typecheck_typed_dslx_package_modules(&builder.specs)?;
    let context = TypedDslxTypeContext::from_modules(
        typechecked.modules.iter().map(|module| &module.typechecked),
    );
    let concrete_parametric_structs = collect_typed_concrete_parametric_structs_from_modules(
        &context,
        typechecked.modules.iter().map(|module| &module.typechecked),
    )?;
    let mut leading_items_by_module =
        concrete_parametric_structs
            .into_iter()
            .fold(BTreeMap::new(), |mut items, item| {
                items
                    .entry(item.defining_module_name.clone())
                    .or_insert_with(Vec::new)
                    .push(render_typed_concrete_parametric_struct(&item));
                items
            });

    let mut modules = Vec::with_capacity(typechecked.modules.len() + compiled.len());
    for module in &typechecked.modules {
        let module_name = module.typechecked.get_module().get_name();
        let mut builder = RustBridgeBuilder::new()
            .with_leading_items(
                leading_items_by_module
                    .remove(&module_name)
                    .unwrap_or_default(),
            )
            .with_deferred_parametric_struct_emission();
        convert_imported_module(&module.typechecked, &mut builder)?;
        modules.push(builder.module_fragment());
    }
    if let Some((module_name, _)) = leading_items_by_module.into_iter().next() {
        return Err(XlsynthError(format!(
            "AOT typed DSLX specialization collection requires package module `{module_name}` to be emitted"
        )));
    }

    for entrypoint in &compiled {
        let canonical_top_path = std::fs::canonicalize(entrypoint.spec.dslx_path).map_err(|e| {
            XlsynthError(format!(
                "AOT I/O failed while resolving DSLX package top {}: {e}",
                entrypoint.spec.dslx_path.display()
            ))
        })?;
        let top_module = typechecked
            .modules
            .iter()
            .find(|module| module.canonical_path == canonical_top_path)
            .map(|module| &module.typechecked)
            .ok_or_else(|| {
                XlsynthError(format!(
                    "AOT typed DSLX package could not find top module for {}",
                    entrypoint.spec.dslx_path.display()
                ))
            })?;
        let top_module_name = top_module.get_module().get_name();
        let runner_module_name = format!("{top_module_name}.aot_{}", entrypoint.base_name);
        let typed_signature = build_typed_dslx_function_signature(
            &context,
            top_module,
            entrypoint.spec.top,
            &runner_module_name,
        )?;
        let runner_epilogue = render_typed_dslx_runner_epilogue(
            &entrypoint.base_name,
            &entrypoint.proto_file_name,
            &entrypoint.metadata,
            &entrypoint.signature,
            &typed_signature,
        )?;
        let mut runner_builder = RustBridgeBuilder::new()
            .with_leading_items(["use super::*;".to_string()])
            .with_runner_items(runner_epilogue);
        runner_builder.start_module(&runner_module_name)?;
        runner_builder.end_module(&runner_module_name)?;
        modules.push(runner_builder.module_fragment());
    }

    let rust_file = out_dir.join(format!("{package_name}_typed_dslx_aot_package.rs"));
    let generated = format!(
        "// SPDX-License-Identifier: Apache-2.0\n// Generated by xlsynth::aot_builder from typed DSLX AOT package {:?}.\n\n{}\n",
        builder.name,
        render_rust_module_fragments(modules)
    );
    write_file(&rust_file, generated.as_bytes())?;
    run_rustfmt_best_effort(&rust_file);

    Ok(GeneratedTypedDslxAotPackage {
        name: package_name,
        rust_file,
        entrypoints: compiled
            .into_iter()
            .map(|entrypoint| GeneratedTypedDslxAotEntrypoint {
                name: entrypoint.base_name,
                object_file: entrypoint.object_file,
                entrypoints_proto_file: entrypoint.proto_file,
                metadata: entrypoint.metadata,
            })
            .collect(),
    })
}

/// Renders the generated Rust wrapper source for one compiled AOT entrypoint.
fn render_generated_module(
    base_name: &str,
    proto_file_name: &str,
    metadata: &AotEntrypointMetadata,
    signature: &AotFunctionSignature,
    source_name: &str,
    top: &str,
) -> AotResult<String> {
    validate_signature_and_layouts(metadata, signature)?;

    let link_symbol_literal = format!("{:?}", metadata.symbol);
    let symbol_ident = format!("__xlsynth_aot_linked_symbol_{base_name}");
    let input_sizes = format_usize_array(&metadata.input_buffer_sizes);
    let input_alignments = format_usize_array(&metadata.input_buffer_alignments);
    let output_sizes = format_usize_array(&metadata.output_buffer_sizes);
    let output_alignments = format_usize_array(&metadata.output_buffer_alignments);

    let mut resolver = TypeResolver::default();
    let input_types = signature
        .params
        .iter()
        .enumerate()
        .map(|(index, param)| resolver.lower_type(&param.ty, &format!("Input{index}")))
        .collect::<Vec<_>>();
    let output_type = resolver.lower_type(&signature.return_type, "Output");
    let type_declarations = render_type_declarations(&resolver, &input_types, &output_type);

    let input_layout_constants = render_layout_constants("INPUT", &signature.input_layouts);
    let output_layout_constants = render_layout_constants("OUTPUT", &signature.output_layouts);

    let mut helper_blocks = Vec::new();
    for (index, input_type) in input_types.iter().enumerate() {
        helper_blocks.push(render_encode_function(
            index,
            input_type,
            metadata.input_buffer_sizes[index],
        ));
    }
    helper_blocks.push(render_decode_function(
        &output_type,
        metadata.output_buffer_sizes[0],
    ));
    let helper_functions = helper_blocks.join("\n\n");

    let arg_names = make_unique_argument_names(signature);
    let run_params = arg_names
        .iter()
        .enumerate()
        .map(|(index, name)| format!("{name}: &Input{index}"))
        .collect::<Vec<_>>()
        .join(", ");
    let run_signature = if run_params.is_empty() {
        "&mut self".to_string()
    } else {
        format!("&mut self, {run_params}")
    };

    let mut run_body = String::new();
    let mut run_with_events_body = String::new();
    for (index, name) in arg_names.iter().enumerate() {
        run_body.push_str(&format!(
            "        encode_input_{index}({name}, self.inner.input_mut({index}));\n"
        ));
        run_with_events_body.push_str(&format!(
            "        encode_input_{index}({name}, self.inner.input_mut({index}));\n"
        ));
    }
    run_body.push_str("        self.inner.run()?;\n");
    run_body.push_str("        let output = decode_output_0(self.inner.output(0));\n");
    run_body.push_str("        Ok(output)\n");

    run_with_events_body.push_str("        self.inner.run_with_events(|inner| {\n");
    run_with_events_body.push_str("            let output = decode_output_0(inner.output(0));\n");
    run_with_events_body.push_str("            output\n");
    run_with_events_body.push_str("        })\n");

    Ok(format!(
        "// SPDX-License-Identifier: Apache-2.0\n\
// Generated by xlsynth::aot_builder from build spec {source_name:?} (top={top:?}, function={function_name:?}).\n\
\n\
unsafe extern \"C\" {{\n\
    #[link_name = {link_symbol_literal}]\n\
    fn {symbol_ident}();\n\
}}\n\
\n\
const ENTRYPOINTS_PROTO: &[u8] = include_bytes!(\"{proto_file_name}\");\n\
const INPUT_BUFFER_SIZES: &[usize] = {input_sizes};\n\
const INPUT_BUFFER_ALIGNMENTS: &[usize] = {input_alignments};\n\
const OUTPUT_BUFFER_SIZES: &[usize] = {output_sizes};\n\
const OUTPUT_BUFFER_ALIGNMENTS: &[usize] = {output_alignments};\n\
\n\
{type_declarations}\
{input_layout_constants}\
{output_layout_constants}\
\n\
{helper_functions}\n\
\n\
pub fn descriptor() -> xlsynth::AotEntrypointDescriptor<'static> {{\n\
    unsafe {{\n\
        xlsynth::AotEntrypointDescriptor::from_raw_parts_unchecked(\n\
            ENTRYPOINTS_PROTO,\n\
            {symbol_ident} as *const () as usize,\n\
            xlsynth::AotEntrypointMetadata {{\n\
                symbol: {link_symbol_literal}.to_string(),\n\
                input_buffer_sizes: INPUT_BUFFER_SIZES.to_vec(),\n\
                input_buffer_alignments: INPUT_BUFFER_ALIGNMENTS.to_vec(),\n\
                output_buffer_sizes: OUTPUT_BUFFER_SIZES.to_vec(),\n\
                output_buffer_alignments: OUTPUT_BUFFER_ALIGNMENTS.to_vec(),\n\
                temp_buffer_size: {temp_size},\n\
                temp_buffer_alignment: {temp_align},\n\
            }},\n\
        )\n\
    }}\n\
}}\n\
\n\
pub struct Runner {{\n\
    inner: xlsynth::AotRunner<'static>,\n\
}}\n\
\n\
impl Runner {{\n\
    pub fn new() -> Result<Self, xlsynth::XlsynthError> {{\n\
        Ok(Self {{\n\
            inner: xlsynth::AotRunner::new(descriptor())?,\n\
        }})\n\
    }}\n\
\n\
    pub fn run_with_events({run_signature}) -> Result<xlsynth::AotRunResult<Output>, xlsynth::XlsynthError> {{\n\
{run_with_events_body}\
    }}\n\
\n\
    pub fn run({run_signature}) -> Result<Output, xlsynth::XlsynthError> {{\n\
{run_body}\
    }}\n\
}}\n\
\n\
pub fn new_runner() -> Result<Runner, xlsynth::XlsynthError> {{\n\
    Runner::new()\n\
}}\n",
        function_name = signature.function_name,
        temp_size = metadata.temp_buffer_size,
        temp_align = metadata.temp_buffer_alignment,
    ))
}

fn emit_link_archive(base_name: &str, object_file: &Path) -> AotResult<()> {
    cc::Build::new()
        .warnings(false)
        .object(object_file)
        .compile(&format!("xlsynth_aot_{base_name}"));
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aot_entrypoint_metadata::AotType;

    fn make_relative_test_root(prefix: &str) -> (tempfile::TempDir, PathBuf) {
        let tmpdir = tempfile::Builder::new()
            .prefix(prefix)
            .tempdir_in(".")
            .unwrap();
        let current_dir = std::fs::canonicalize(".").unwrap();
        let relative_root = std::fs::canonicalize(tmpdir.path())
            .unwrap()
            .strip_prefix(current_dir)
            .unwrap()
            .to_path_buf();
        (tmpdir, relative_root)
    }

    #[test]
    fn sanitize_identifier_rewrites_non_ident_chars() {
        assert_eq!(sanitize_identifier("foo-bar"), "foo_bar");
        assert_eq!(sanitize_identifier("3abc"), "_3abc");
        assert_eq!(sanitize_identifier(""), "aot_entrypoint");
    }

    #[test]
    fn sanitize_value_identifier_handles_keywords() {
        assert_eq!(sanitize_value_identifier("type", "arg"), "type_");
    }

    #[test]
    fn render_type_declarations_do_not_emit_default_impls() {
        let mut resolver = TypeResolver::default();
        let input_ty = resolver.lower_type(
            &AotType::Tuple {
                elements: vec![
                    AotType::Bits { bit_count: 8 },
                    AotType::Array {
                        size: 128,
                        element: Box::new(AotType::Bits { bit_count: 16 }),
                    },
                    AotType::Bits { bit_count: 257 },
                ],
            },
            "Input0",
        );
        let output_ty = resolver.lower_type(&AotType::Tuple { elements: vec![] }, "Output");

        let declarations = render_type_declarations(&resolver, &[input_ty], &output_ty);

        assert!(
            declarations.contains("#[derive(Debug, Clone, PartialEq, Eq)]\npub struct Input0 {")
        );
        assert!(
            declarations.contains("pub field1: [Bits16; 128],"),
            "declarations should preserve large array field types: {}",
            declarations
        );
        assert!(
            declarations.contains("pub type Bits257 = [u8; 33];"),
            "declarations should preserve wide bits byte-array aliases: {}",
            declarations
        );
        assert!(
            !declarations.contains("Default"),
            "generated declarations should not reference Default: {}",
            declarations
        );
    }

    // Negative test: rejects typed DSLX/AOT metadata mismatches.
    #[test]
    fn typed_dslx_type_validation_rejects_aot_metadata_mismatch() {
        let typed_dslx_type = TypedDslxType::Struct {
            rust_type: "ReturnType".to_string(),
            fields: vec![TypedDslxField {
                name: "value".to_string(),
                ty: TypedDslxType::Bits {
                    rust_type: "xlsynth::IrUBits<8>".to_string(),
                    is_signed: false,
                    bit_count: 8,
                },
            }],
        };
        let aot = AotType::Tuple {
            elements: vec![AotType::Bits { bit_count: 16 }],
        };

        let error =
            validate_typed_dslx_type_matches_aot("return", &typed_dslx_type, &aot).unwrap_err();
        assert!(error
            .to_string()
            .contains("AOT typed DSLX type mismatch for return"));
    }

    // Verifies: typed DSLX AOT dependency tracking follows transitive DSLX imports.
    // Catches: build scripts missing rerun-if-changed for imported modules.
    #[test]
    fn typed_dslx_aot_dependencies_follow_transitive_imports() {
        let tmpdir = xlsynth_test_helpers::make_test_tmpdir("xlsynth_aot_builder_dependencies");
        let top_path = tmpdir.path().join("top.x");
        let helper_path = tmpdir.path().join("helper.x");
        let constants_path = tmpdir.path().join("constants.x");
        let bridge_path = tmpdir.path().join("bridge.x");
        std::fs::write(
            &top_path,
            "import helper as h; pub fn frob(x: u8) -> u8 { h::inc(x) }",
        )
        .unwrap();
        std::fs::write(
            &helper_path,
            "import constants; pub fn inc(x: u8) -> u8 { x + constants::ONE }",
        )
        .unwrap();
        std::fs::write(&constants_path, "pub const ONE = u8:1;").unwrap();
        std::fs::write(&bridge_path, "pub struct Widget { value: u8 }").unwrap();

        let dslx_options = DslxConvertOptions {
            additional_search_paths: vec![tmpdir.path()],
            ..Default::default()
        };
        let spec = TypedDslxAotBuildSpec {
            name: "dependencies",
            dslx_path: &top_path,
            top: "frob",
            dslx_options,
            type_module_paths: vec![&bridge_path],
        };

        let dependencies = collect_typed_dslx_aot_dependencies(&spec).unwrap();

        assert_eq!(
            dependencies,
            BTreeSet::from([
                std::fs::canonicalize(&bridge_path).unwrap(),
                std::fs::canonicalize(&constants_path).unwrap(),
                std::fs::canonicalize(&helper_path).unwrap(),
                std::fs::canonicalize(&top_path).unwrap(),
            ])
        );
    }

    // Verifies: package bridge-module naming stays aligned with the existing
    // single-entry path for both relative and absolute search roots. Catches:
    // package-only canonicalization that collapses nested relative imports to
    // file-stem-only module names.
    #[test]
    fn typed_dslx_package_modules_match_single_entry_bridge_names_across_root_forms() {
        let (_tmpdir, relative_root) =
            make_relative_test_root("xlsynth_aot_builder_package_relative_imports");
        let relative_source_root = relative_root.join("src");
        let relative_bridge_path = relative_source_root.join("foo/widget.x");
        let relative_top_path = relative_source_root.join("top.x");
        std::fs::create_dir_all(relative_bridge_path.parent().unwrap()).unwrap();
        std::fs::write(&relative_bridge_path, "pub struct Widget { value: u8 }").unwrap();
        std::fs::write(&relative_top_path, "pub fn echo(x: u8) -> u8 { x }").unwrap();

        let absolute_source_root = std::fs::canonicalize(&relative_source_root).unwrap();
        let absolute_bridge_path = std::fs::canonicalize(&relative_bridge_path).unwrap();
        let absolute_top_path = std::fs::canonicalize(&relative_top_path).unwrap();

        for (source_root, bridge_path, top_path) in [
            (
                relative_source_root.as_path(),
                relative_bridge_path.as_path(),
                relative_top_path.as_path(),
            ),
            (
                absolute_source_root.as_path(),
                absolute_bridge_path.as_path(),
                absolute_top_path.as_path(),
            ),
        ] {
            let dslx_options = DslxConvertOptions {
                additional_search_paths: vec![source_root],
                ..Default::default()
            };
            let spec = TypedDslxAotBuildSpec {
                name: "bridge_name_parity",
                dslx_path: top_path,
                top: "echo",
                dslx_options,
                type_module_paths: vec![bridge_path],
            };
            let top_dslx_text = std::fs::read_to_string(top_path).unwrap();
            let single_entry = typecheck_typed_dslx_modules(&spec, &top_dslx_text).unwrap();
            let package = typecheck_typed_dslx_package_modules(&[spec]).unwrap();

            assert_eq!(
                single_entry
                    .bridge_modules
                    .iter()
                    .map(|module| module.get_module().get_name())
                    .chain(std::iter::once(
                        single_entry.top_module.get_module().get_name()
                    ))
                    .collect::<Vec<_>>(),
                vec!["foo.widget", "top"]
            );
            assert_eq!(
                package
                    .modules
                    .iter()
                    .map(|module| module.typechecked.get_module().get_name())
                    .collect::<Vec<_>>(),
                vec!["foo.widget", "top"]
            );
        }
    }

    // Verifies: package top modules keep search-root-relative names too.
    // Catches: same-basename top files colliding as one package-local module.
    #[test]
    fn typed_dslx_package_modules_distinguish_same_basename_tops() {
        let (_tmpdir, relative_root) =
            make_relative_test_root("xlsynth_aot_builder_package_same_basename_tops");
        let source_root = relative_root.join("src");
        let foo_top_path = source_root.join("foo/widget.x");
        let bar_top_path = source_root.join("bar/widget.x");
        std::fs::create_dir_all(foo_top_path.parent().unwrap()).unwrap();
        std::fs::create_dir_all(bar_top_path.parent().unwrap()).unwrap();
        std::fs::write(
            &foo_top_path,
            "pub struct Widget { value: u8 } pub fn left(widget: Widget) -> Widget { widget }",
        )
        .unwrap();
        std::fs::write(
            &bar_top_path,
            "pub struct Widget { value: u8 } pub fn right(widget: Widget) -> Widget { widget }",
        )
        .unwrap();

        let dslx_options = DslxConvertOptions {
            additional_search_paths: vec![source_root.as_path()],
            ..Default::default()
        };
        let left = TypedDslxAotBuildSpec {
            name: "left",
            dslx_path: &foo_top_path,
            top: "left",
            dslx_options: dslx_options.clone(),
            type_module_paths: vec![],
        };
        let right = TypedDslxAotBuildSpec {
            name: "right",
            dslx_path: &bar_top_path,
            top: "right",
            dslx_options,
            type_module_paths: vec![],
        };

        let typechecked = typecheck_typed_dslx_package_modules(&[left, right]).unwrap();

        assert_eq!(
            typechecked
                .modules
                .iter()
                .map(|module| module.typechecked.get_module().get_name())
                .collect::<Vec<_>>(),
            vec!["foo.widget", "bar.widget"]
        );
    }

    // Verifies: duplicate struct names resolve by the exact defining module.
    // Catches: bare-name owner lookup that selects the wrong imported struct.
    #[test]
    fn typed_dslx_type_lowering_uses_struct_definition_owner_when_names_collide() {
        let tmpdir =
            xlsynth_test_helpers::make_test_tmpdir("xlsynth_aot_builder_duplicate_struct_names");
        let a_path = tmpdir.path().join("a.x");
        let b_path = tmpdir.path().join("b.x");
        let top_path = tmpdir.path().join("top.x");
        std::fs::write(&a_path, "pub struct Widget { value: u8 }").unwrap();
        std::fs::write(&b_path, "pub struct Widget { value: u16 }").unwrap();
        std::fs::write(
            &top_path,
            "import a; import b; pub fn frob(widget: a::Widget) -> a::Widget { widget }",
        )
        .unwrap();

        let dslx_options = DslxConvertOptions {
            additional_search_paths: vec![tmpdir.path()],
            ..Default::default()
        };
        let spec = TypedDslxAotBuildSpec {
            name: "duplicate_struct_names",
            dslx_path: &top_path,
            top: "frob",
            dslx_options,
            type_module_paths: vec![&a_path, &b_path],
        };
        let top_dslx_text = std::fs::read_to_string(&top_path).unwrap();
        let typechecked = typecheck_typed_dslx_modules(&spec, &top_dslx_text).unwrap();
        let context = TypedDslxTypeContext::new(&typechecked);

        let typed_signature =
            build_typed_dslx_function_signature(&context, &typechecked.top_module, "frob", "top")
                .expect("duplicate struct names should resolve by defining module");

        assert_eq!(typed_signature.params.len(), 1);
        assert_eq!(typed_dslx_leaf_count(&typed_signature.params[0].ty), 1);
        assert_eq!(typed_dslx_leaf_count(&typed_signature.return_type), 1);
    }

    // Verifies: concrete specializations remain distinct when sibling imports
    // declare same-named parametric structs with the same bound values.
    // Catches: dedupe keyed only by generated Rust name.
    #[test]
    fn concrete_parametric_struct_collection_uses_struct_definition_identity_when_names_collide() {
        let tmpdir = xlsynth_test_helpers::make_test_tmpdir(
            "xlsynth_aot_builder_duplicate_parametric_struct_names",
        );
        let a_path = tmpdir.path().join("a.x");
        let b_path = tmpdir.path().join("b.x");
        let top_path = tmpdir.path().join("top.x");
        std::fs::write(&a_path, "pub struct Widget<N: u32> { value: bits[N] }").unwrap();
        std::fs::write(&b_path, "pub struct Widget<N: u32> { value: bits[N] }").unwrap();
        std::fs::write(
            &top_path,
            "import a; import b; pub fn frob(lhs: a::Widget<u32:8>, rhs: b::Widget<u32:8>) -> (a::Widget<u32:8>, b::Widget<u32:8>) { (lhs, rhs) }",
        )
        .unwrap();

        let dslx_options = DslxConvertOptions {
            additional_search_paths: vec![tmpdir.path()],
            ..Default::default()
        };
        let spec = TypedDslxAotBuildSpec {
            name: "duplicate_parametric_struct_names",
            dslx_path: &top_path,
            top: "frob",
            dslx_options,
            type_module_paths: vec![&a_path, &b_path],
        };
        let top_dslx_text = std::fs::read_to_string(&top_path).unwrap();
        let typechecked = typecheck_typed_dslx_modules(&spec, &top_dslx_text).unwrap();
        let context = TypedDslxTypeContext::new(&typechecked);

        let structs = collect_typed_concrete_parametric_structs(&context, &typechecked)
            .expect("same-named imported parametric structs should remain distinct");

        assert_eq!(structs.len(), 2);
        assert_eq!(
            structs
                .iter()
                .map(|item| (item.defining_module_name.as_str(), item.rust_name.as_str()))
                .collect::<Vec<_>>(),
            vec![("a", "Widget__N_8"), ("b", "Widget__N_8")]
        );
    }

    // Verifies: imported concrete specializations evaluate caller-written
    // parametric arguments in the importing module.
    // Catches: resolving caller-local const expressions in the defining module.
    #[test]
    fn concrete_parametric_struct_collection_uses_caller_type_info_for_imported_arguments() {
        let tmpdir = xlsynth_test_helpers::make_test_tmpdir(
            "xlsynth_aot_builder_imported_parametric_argument_context",
        );
        let imported_path = tmpdir.path().join("imported.x");
        let top_path = tmpdir.path().join("top.x");
        std::fs::write(
            &imported_path,
            "pub struct Widget<N: u32> { value: bits[N] }",
        )
        .unwrap();
        std::fs::write(
            &top_path,
            "import imported; const WIDTH = u32:4 + u32:4; pub fn frob(widget: imported::Widget<WIDTH>) -> imported::Widget<WIDTH> { widget }",
        )
        .unwrap();

        let dslx_options = DslxConvertOptions {
            additional_search_paths: vec![tmpdir.path()],
            ..Default::default()
        };
        let spec = TypedDslxAotBuildSpec {
            name: "imported_parametric_argument_context",
            dslx_path: &top_path,
            top: "frob",
            dslx_options,
            type_module_paths: vec![&imported_path],
        };
        let top_dslx_text = std::fs::read_to_string(&top_path).unwrap();
        let typechecked = typecheck_typed_dslx_modules(&spec, &top_dslx_text).unwrap();
        let context = TypedDslxTypeContext::new(&typechecked);

        let structs = collect_typed_concrete_parametric_structs(&context, &typechecked)
            .expect("caller-owned parametric arguments should resolve");

        assert_eq!(structs.len(), 1);
        assert_eq!(structs[0].defining_module_name, "imported");
        assert_eq!(structs[0].rust_name, "Widget__N_8");
    }
}