polyplugc 0.1.1

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

use super::CALL_ARENA_BUF_LEN;
use super::CodeGenerator;
use super::GeneratedFile;
use super::GeneratedFiles;
use super::collect_peer_contracts;
use super::is_native_runtime;
use super::peer_min_version;
use crate::ir::AbiBuiltin;
use crate::ir::EnumDef;
use crate::ir::EnumVariant;
use crate::ir::PrimitiveType;
use crate::ir::ResolvedBundle;
use crate::ir::ResolvedContract;
use crate::ir::ResolvedFunction;
use crate::ir::ResolvedHostContract;
use crate::ir::ResolvedParam;
use crate::ir::ResolvedPlugin;
use crate::ir::ResolvedType;
use crate::ir::ResolvedTypeRef;
use crate::ir::ValidatedIr;
use polyplug_codegen::PolyplugcError;

/// The C++ code generator.
pub(crate) struct CppGenerator;

/// AUTO-GENERATED banner emitted at the top of every C/C++-comment output file.
const CPP_FILE_HEADER: &str = "// THIS FILE IS AUTO-GENERATED BY polyplugc. DO NOT EDIT.\n";

impl CodeGenerator for CppGenerator {
    fn generate_host(
        &self,
        ir: &ValidatedIr,
        files: &mut GeneratedFiles,
    ) -> Result<(), PolyplugcError> {
        // ── File 1: types.hpp ────────────────────────────────────────────────
        let types_hpp: String = generate_types_hpp(ir);
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("host/types.hpp"),
            content: types_hpp,
            force_regenerate: false,
        });

        // ── File 2: host_callers.hpp ─────────────────────────────────────────
        let host_callers_hpp: String = generate_host_callers_hpp(ir)?;
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("host/host_callers.hpp"),
            content: host_callers_hpp,
            force_regenerate: false,
        });

        // ── File 3: manifest.toml ────────────────────────────────────────────
        let manifest_toml: String = generate_manifest_toml();
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("manifest.toml"),
            content: manifest_toml,
            force_regenerate: true,
        });

        // ── File 4: host_contracts.hpp ───────────────────────────────────────
        if !ir.host_contracts.is_empty() {
            let host_contracts_hpp: String = generate_cpp_host_contracts_file(ir);
            files.files.push(GeneratedFile {
                path: std::path::PathBuf::from("host/host_contracts.hpp"),
                content: host_contracts_hpp,
                force_regenerate: false,
            });
        }

        // ── File 5: interface_factories.hpp ─────────────────────────────────────
        if !ir.host_contracts.is_empty() {
            let interface_factories_hpp: String = generate_cpp_host_interface_factories_file(ir);
            files.files.push(GeneratedFile {
                path: std::path::PathBuf::from("host/interface_factories.hpp"),
                content: interface_factories_hpp,
                force_regenerate: false,
            });
        }

        Ok(())
    }

    fn generate_guest(
        &self,
        ir: &ValidatedIr,
        files: &mut GeneratedFiles,
    ) -> Result<(), PolyplugcError> {
        // ── File 1: types.hpp ────────────────────────────────────────────────
        let types_hpp: String = generate_types_hpp(ir);
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("guest/types.hpp"),
            content: types_hpp,
            force_regenerate: false,
        });

        // ── File 2: contracts.hpp ────────────────────────────────────────────
        let contracts_hpp: String = generate_contracts_hpp(ir);
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("guest/contracts.hpp"),
            content: contracts_hpp,
            force_regenerate: false,
        });

        // ── File 3: interfaces.hpp ──────────────────────────────────────────────
        let interfaces_hpp: String = generate_interfaces_hpp(ir)?;
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("guest/interfaces.hpp"),
            content: interfaces_hpp,
            force_regenerate: false,
        });

        // ── File 4: init.hpp ─────────────────────────────────────────────────
        let init_hpp: String = generate_init_hpp(ir)?;
        files.files.push(GeneratedFile {
            path: std::path::PathBuf::from("guest/init.hpp"),
            content: init_hpp,
            force_regenerate: false,
        });

        // --api: manifest emitted by generate_host(); --bundle: emit full discovery manifest
        if ir.bundle.is_some() {
            let manifest_toml: String = generate_bundle_manifest_cpp(ir);
            files.files.push(GeneratedFile {
                path: std::path::PathBuf::from("manifest.toml"),
                content: manifest_toml,
                force_regenerate: true,
            });
        }
        // When ir.bundle.is_none() (--api mode): NO manifest emitted here.
        // The root manifest.toml was already emitted by generate_host().

        // ── File 5: host_contracts.hpp (guest-side callers) ─────────────────────
        if !ir.host_contracts.is_empty() {
            let host_contracts_hpp: String = generate_cpp_guest_host_contracts_file(ir);
            files.files.push(GeneratedFile {
                path: std::path::PathBuf::from("guest/host_contracts.hpp"),
                content: host_contracts_hpp,
                force_regenerate: false,
            });
        }

        // ── File 6: peer_callers.hpp (guest→guest peer callers) ─────────────────
        let peer_contracts: Vec<&ResolvedContract> = collect_peer_contracts(ir);
        if !peer_contracts.is_empty() {
            let peer_callers_hpp: String = generate_cpp_peer_callers_file(ir, &peer_contracts);
            files.files.push(GeneratedFile {
                path: std::path::PathBuf::from("guest/peer_callers.hpp"),
                content: peer_callers_hpp,
                force_regenerate: false,
            });
        }

        Ok(())
    }
}

// ─── types.hpp generator ─────────────────────────────────────────────────────

fn generate_types_hpp(ir: &ValidatedIr) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n\n");
    out.push_str("namespace polyplug_generated {\n\n");

    // Emit contract ID constants
    for contract in &ir.contracts {
        let contract_upper: String = contract.name.to_uppercase().replace(['.', '-'], "_");
        out.push_str(&format!(
            "constexpr uint64_t {}_CONTRACT_ID = 0x{:016X};\n",
            contract_upper, contract.contract_id
        ));
    }
    out.push('\n');

    // Emit enums before struct types
    for e in &ir.enums {
        generate_cpp_enum(&mut out, e);
    }

    for ty in &ir.types {
        generate_cpp_type(&mut out, ty);
    }

    out.push_str("}  // namespace polyplug_generated\n");
    out
}

// ─── contracts.hpp generator ─────────────────────────────────────────────────

fn generate_contracts_hpp(ir: &ValidatedIr) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"types.hpp\"\n");
    out.push_str("#include <cstdint>\n\n");
    out.push_str("namespace polyplug_plugin {\n\n");
    out.push_str("struct RuntimeError { uint32_t code; };\n\n");

    for contract in &ir.contracts {
        generate_cpp_guest_contract_class(&mut out, contract);
    }

    out.push_str("}  // namespace polyplug_plugin\n");
    out
}

fn generate_cpp_guest_contract_class(out: &mut String, contract: &ResolvedContract) {
    let class_name: String = contract_name_to_guest_contract_class(&contract.name);
    out.push_str(&format!(
        "/// Abstract plugin base for contract `{}` (id=0x{:016X})\n",
        contract.name, contract.contract_id
    ));
    out.push_str(&format!("class {} {{\npublic:\n", class_name));
    out.push_str(&format!("    virtual ~{}() = default;\n", class_name));

    for func in &contract.functions {
        generate_cpp_guest_abstract_method(out, func);
    }

    out.push_str("};\n\n");
}

fn generate_cpp_guest_abstract_method(out: &mut String, func: &ResolvedFunction) {
    let return_type: String = func
        .returns
        .as_ref()
        .map(cpp_type_name)
        .unwrap_or_else(|| "void".to_owned());

    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let cpp_ty: String = cpp_type_name(&p.ty);
            match &p.ty {
                ResolvedTypeRef::UserDefined(_) => format!("const {}& {}", cpp_ty, p.name),
                ResolvedTypeRef::Primitive(_) | ResolvedTypeRef::AbiType(_) => {
                    format!("{} {}", cpp_ty, p.name)
                }
            }
        })
        .collect();
    let params_str: String = params.join(", ");

    out.push_str(&format!(
        "    virtual {} {}({}) = 0;\n",
        return_type, func.name, params_str
    ));
}

// ─── interfaces.hpp generator ───────────────────────────────────────────────────

fn generate_interfaces_hpp(ir: &ValidatedIr) -> Result<String, PolyplugcError> {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"contracts.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include <cstring>\n");
    out.push_str("#include <exception>\n\n");
    out.push_str("namespace polyplug_plugin {\n\n");

    if let Some(bundle) = &ir.bundle {
        for plugin in &bundle.plugins {
            for contract_impl in &plugin.implements {
                if let Some(contract) = ir.contracts.iter().find(|c| {
                    let contract_full: String =
                        format!("{}@{}.{}", c.name, c.version.major, c.version.minor);
                    &contract_full == contract_impl
                }) {
                    generate_cpp_guest_plugin_interface(
                        &mut out,
                        &plugin.name,
                        contract,
                        is_native_runtime(&bundle.loader),
                    )?;
                }
            }
        }
    } else {
        // When no bundle info, default to native dispatch
        for contract in &ir.contracts {
            generate_cpp_guest_contract_interface(&mut out, contract, true)?;
        }
    }

    out.push_str("}  // namespace polyplug_plugin\n");
    Ok(out)
}

fn generate_cpp_guest_plugin_interface(
    out: &mut String,
    plugin_name: &str,
    contract: &ResolvedContract,
    is_native: bool,
) -> Result<(), PolyplugcError> {
    let plugin_upper: String = plugin_name.to_uppercase().replace('.', "_");
    let plugin_lower: String = plugin_name.to_lowercase().replace('.', "_");
    let class_name: String = contract_name_to_guest_contract_class(&contract.name);
    let fn_count: usize = contract.functions.len();

    let state_struct: String = format!("{}InstanceState", snake_to_pascal(&plugin_lower));

    out.push_str(&format!("// Plugin: {}\n", plugin_name));
    out.push_str(&format!(
        "constexpr uint64_t {}_CONTRACT_ID = 0x{:016X}ULL;\n\n",
        plugin_upper, contract.contract_id
    ));

    emit_cpp_guest_instance_machinery(
        out,
        &plugin_upper,
        &plugin_lower,
        &class_name,
        &state_struct,
    );

    for func in &contract.functions {
        generate_cpp_guest_abi_wrapper(out, &plugin_lower, &state_struct, func)?;
    }

    out.push_str(&format!("static void* const {}_FNS[] = {{\n", plugin_upper));
    for func in &contract.functions {
        out.push_str(&format!(
            "    reinterpret_cast<void*>({0}_{1}_abi),\n",
            plugin_lower, func.name
        ));
    }
    out.push_str("};\n\n");

    out.push_str(&format!(
        "static GuestContractInterface {}_INTERFACE = {{\n",
        plugin_upper
    ));
    out.push_str(&format!("    {}_CONTRACT_ID,\n", plugin_upper));
    out.push_str(&format!(
        "    Version{{ {}U, {}U, {}U }},  // contract_version\n",
        contract.version.major, contract.version.minor, contract.version.patch
    ));
    let dispatch_type_str: &str = if is_native {
        "DispatchType::Native"
    } else {
        "DispatchType::VirtualMachine"
    };
    out.push_str(&format!("    {},\n", dispatch_type_str));
    out.push_str(&format!("    {}_create_instance,\n", plugin_upper));
    out.push_str(&format!("    {}_destroy_instance,\n", plugin_upper));
    out.push_str(&format!(
        "    DispatchMechanisms{{ .native = NativeDispatch{{ {fn_count}U, {}_FNS }} }}\n",
        plugin_upper
    ));
    out.push_str("};\n\n");

    Ok(())
}

fn generate_cpp_guest_contract_interface(
    out: &mut String,
    contract: &ResolvedContract,
    is_native: bool,
) -> Result<(), PolyplugcError> {
    let lower: String = contract_name_to_lower_snake(&contract.name);
    let upper: String = contract_name_to_upper_snake(&contract.name);
    let class_name: String = contract_name_to_guest_contract_class(&contract.name);
    let fn_count: usize = contract.functions.len();

    let state_struct: String = format!("{}InstanceState", snake_to_pascal(&lower));

    // Contract ID constant
    out.push_str(&format!(
        "constexpr uint64_t {}_CONTRACT_ID = 0x{:016X}ULL;\n\n",
        upper, contract.contract_id
    ));

    emit_cpp_guest_instance_machinery(out, &upper, &lower, &class_name, &state_struct);

    // ABI wrapper functions — one per function
    for func in &contract.functions {
        generate_cpp_guest_abi_wrapper(out, &lower, &state_struct, func)?;
    }

    // Function pointer array
    out.push_str(&format!("static void* const {}_FNS[] = {{\n", upper));
    for func in &contract.functions {
        out.push_str(&format!(
            "    reinterpret_cast<void*>({0}_{1}_abi),\n",
            lower, func.name
        ));
    }
    out.push_str("};\n\n");

    // Interface static
    out.push_str(&format!(
        "static GuestContractInterface {}_INTERFACE = {{\n",
        upper
    ));
    out.push_str(&format!("    {}_CONTRACT_ID,\n", upper));
    out.push_str(&format!(
        "    Version{{ {}U, {}U, {}U }},  // contract_version\n",
        contract.version.major, contract.version.minor, contract.version.patch
    ));
    let dispatch_type_str: &str = if is_native {
        "DispatchType::Native"
    } else {
        "DispatchType::VirtualMachine"
    };
    out.push_str(&format!("    {},\n", dispatch_type_str));
    out.push_str(&format!("    {}_create_instance,\n", upper));
    out.push_str(&format!("    {}_destroy_instance,\n", upper));
    out.push_str(&format!(
        "    DispatchMechanisms{{ .native = NativeDispatch{{ {}U, {}_FNS }} }}\n",
        fn_count, upper
    ));
    out.push_str("};\n\n");

    Ok(())
}

/// Emit the per-plugin instance machinery: the author-factory forward
/// declaration, the instance payload struct, and the real
/// `create_instance` / `destroy_instance` functions.
///
/// The implementation is constructed by the author factory on every
/// `create_instance` call and carried — together with the HostApi pointer —
/// in `GuestContractInstance.data`. No DSO-global storage is involved, so two
/// runtimes loading the same plugin DSO get fully isolated instances.
fn emit_cpp_guest_instance_machinery(
    out: &mut String,
    prefix_upper: &str,
    lower: &str,
    class_name: &str,
    state_struct: &str,
) {
    out.push_str(&format!(
        "// Author-provided factory — implement this in your plugin .cpp. Called once\n\
         // per host-created instance; ownership of the returned object transfers to\n\
         // the instance (deleted in {prefix_upper}_destroy_instance).\n\
         {class_name}* polyplug_create_{lower}(const HostApi* host);\n\n"
    ));

    out.push_str(&format!(
        "// Per-instance payload carried in GuestContractInstance.data.\n\
         struct {state_struct} {{\n\
         \x20   // Host interface captured at instance creation — routes every host call\n\
         \x20   // (allocation, logging, peer dispatch) to the runtime that owns it.\n\
         \x20   const HostApi* host;\n\
         \x20   // The author's implementation, created by polyplug_create_{lower}.\n\
         \x20   {class_name}* impl;\n\
         }};\n\n"
    ));

    out.push_str(&format!(
        "// Create a new instance: calls the author factory and heap-allocates the payload.\n\
         // Writes a null handle to *out_instance when host is null, the factory returns\n\
         // null, or it throws.\n\
         static void {prefix_upper}_create_instance(VmLoaderData loader_data, const HostApi* host, const void* args, GuestContractInstance* out_instance) noexcept {{\n\
         \x20   (void)loader_data;  // Native-dispatch contracts ignore the VM loader handle.\n\
         \x20   (void)args;  // Contract-specific init args are unused by generated glue.\n\
         \x20   if (out_instance == nullptr) return;\n\
         \x20   if (host == nullptr) {{\n\
         \x20       *out_instance = GuestContractInstance{{nullptr, 0U}};\n\
         \x20       return;\n\
         \x20   }}\n\
         \x20   try {{\n\
         \x20       {class_name}* impl = polyplug_create_{lower}(host);\n\
         \x20       if (impl == nullptr) {{\n\
         \x20           *out_instance = GuestContractInstance{{nullptr, 0U}};\n\
         \x20           return;\n\
         \x20       }}\n\
         \x20       auto* state = new {state_struct}{{host, impl}};\n\
         \x20       *out_instance = GuestContractInstance{{state, {prefix_upper}_CONTRACT_ID}};\n\
         \x20   }} catch (...) {{\n\
         \x20       *out_instance = GuestContractInstance{{nullptr, 0U}};\n\
         \x20   }}\n\
         }}\n\n"
    ));

    out.push_str(&format!(
        "// Destroy an instance created by {prefix_upper}_create_instance: deletes the\n\
         // implementation (ownership transferred from the factory) and the payload.\n\
         static void {prefix_upper}_destroy_instance(VmLoaderData loader_data, const HostApi* host, GuestContractInstance instance) noexcept {{\n\
         \x20   (void)loader_data;  // Native-dispatch contracts ignore the VM loader handle.\n\
         \x20   (void)host;  // The payload is guest-owned; no host call is needed to free it.\n\
         \x20   if (instance.data == nullptr) {{\n\
         \x20       return;\n\
         \x20   }}\n\
         \x20   auto* state = static_cast<{state_struct}*>(instance.data);\n\
         \x20   delete state->impl;\n\
         \x20   delete state;\n\
         }}\n\n"
    ));
}

/// Convert a lowercase snake identifier to PascalCase, e.g. "my_plugin" -> "MyPlugin".
fn snake_to_pascal(s: &str) -> String {
    s.split('_')
        .map(|seg: &str| {
            let mut chars: core::str::Chars<'_> = seg.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("")
}

fn generate_cpp_guest_abi_wrapper(
    out: &mut String,
    contract_lower: &str,
    state_struct: &str,
    func: &ResolvedFunction,
) -> Result<(), PolyplugcError> {
    let fn_id: u32 = func.function_id;
    let is_void_return: bool = matches!(
        func.returns.as_ref(),
        None | Some(ResolvedTypeRef::AbiType(AbiBuiltin::Void))
    );
    let has_params: bool = !func.params.is_empty();

    out.push_str(&format!(
        "// ABI wrapper for {} (function_id = {})\n",
        func.name, fn_id
    ));
    out.push_str(&format!(
        "inline void {0}_{1}_abi(GuestContractInstance instance, const void* args, void* out, AbiError* out_err) noexcept {{\n",
        contract_lower, func.name
    ));
    out.push_str("    if (instance.data == nullptr) {\n");
    out.push_str("        static constexpr const char* null_inst_msg = \"instance is null\";\n");
    out.push_str(
        "        *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::InvalidPointer), StringView{reinterpret_cast<const uint8_t*>(null_inst_msg), 16}};\n",
    );
    out.push_str("        return;\n");
    out.push_str("    }\n");
    out.push_str("    // SAFETY: instance.data was produced by create_instance and stays valid\n");
    out.push_str("    // until destroy_instance; the host never mutates it.\n");
    out.push_str(&format!(
        "    const auto* state = static_cast<const {state_struct}*>(instance.data);\n"
    ));
    out.push_str("    try {\n");

    if has_params {
        out.push_str("        if (args == nullptr) {\n");
        out.push_str(
            "            *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::InvalidPointer), StringView{nullptr, 0}};\n",
        );
        out.push_str("            return;\n");
        out.push_str("        }\n");
    }
    if !is_void_return {
        out.push_str("        if (out == nullptr) {\n");
        out.push_str(
            "            *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::InvalidPointer), StringView{nullptr, 0}};\n",
        );
        out.push_str("            return;\n");
        out.push_str("        }\n");
    }

    // Build the call expression
    let call_expr: String = build_guest_call_expr(contract_lower, func);
    out.push_str(&call_expr);

    if is_void_return {
        // For void, emit success return (call_expr already emits the call + newline)
        out.push_str("        // SAFETY: out pointer is not dereferenced for void return per ABI contract.\n");
        out.push_str("        (void)out;\n");
        out.push_str("        *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Ok), StringView{nullptr, 0}};\n");
        out.push_str("        return;\n");
    } else {
        let ret_type: String = func
            .returns
            .as_ref()
            .map(cpp_type_name)
            .unwrap_or_else(|| "void".to_owned());
        out.push_str(&format!(
            "        // SAFETY: out is a valid void* pointing to a {ret_type} per ABI contract.\n"
        ));
        out.push_str("        // The host guarantees proper alignment and size before calling this wrapper.\n");
        out.push_str(&format!(
            "        *static_cast<{}*>(out) = result;\n",
            ret_type
        ));
        out.push_str("        *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Ok), StringView{nullptr, 0}};\n");
        out.push_str("        return;\n");
    }

    out.push_str("    } catch (const std::exception&) {\n");
    out.push_str(
        "        // The AbiError message must outlive this stack frame; the host never frees it.\n",
    );
    out.push_str(
        "        // e.what() points into the (about-to-be-destroyed) exception object, so we\n",
    );
    out.push_str("        // return a static literal instead of a dangling pointer.\n");
    out.push_str(
        "        // SAFETY: err_msg is a static constexpr string literal with known length 26.\n",
    );
    out.push_str(
        "        static constexpr const char* err_msg = \"guest threw std::exception\";\n",
    );
    out.push_str("        *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Generic), StringView{reinterpret_cast<const uint8_t*>(err_msg), 26}};\n");
    out.push_str("        return;\n");
    out.push_str("    } catch (...) {\n");
    out.push_str(
        "        // SAFETY: panic_msg is a static constexpr string literal with known length 15.\n",
    );
    out.push_str("        static constexpr const char* panic_msg = \"plugin panicked\";\n");
    out.push_str("        *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Panic), StringView{reinterpret_cast<const uint8_t*>(panic_msg), 15}};\n");
    out.push_str("        return;\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    Ok(())
}

/// Build the call-to-impl lines inside the try block.
/// For non-void, assigns `auto result = ...`. For void, just calls.
fn build_guest_call_expr(contract_lower: &str, func: &ResolvedFunction) -> String {
    let is_void_return: bool = matches!(
        func.returns.as_ref(),
        None | Some(ResolvedTypeRef::AbiType(AbiBuiltin::Void))
    );

    let result_prefix: &str = if is_void_return { "" } else { "auto result = " };

    let _ = contract_lower;

    if func.params.is_empty() {
        // No params — ignore args entirely
        return format!(
            "        // SAFETY: args is null for this function per ABI contract; no dereference needed.\n\
             (void)args;\n        {}state->impl->{}();\n",
            result_prefix, func.name
        );
    }

    if func.params.len() == 1 {
        let param: &crate::ir::ResolvedParam = &func.params[0];
        match &param.ty {
            ResolvedTypeRef::UserDefined(type_name) => {
                // Single user-defined struct param — dereference args directly
                let qualified_name: String = qualified_user_type(type_name);
                return format!(
                    "        // SAFETY: args is a valid const void* pointing to a {qualified_name} per ABI contract.\n\
             // The host guarantees proper alignment and size before calling this wrapper.\n\
             {}state->impl->{}(*static_cast<const {}*>(args));\n",
                    result_prefix, func.name, qualified_name
                );
            }
            ResolvedTypeRef::Primitive(_) | ResolvedTypeRef::AbiType(_) => {
                // Single primitive param — dereference args as the primitive type
                let cpp_ty: String = cpp_type_name(&param.ty);
                return format!(
                    "        // SAFETY: args is a valid const void* pointing to a {cpp_ty} per ABI contract.\n\
             // The host guarantees proper alignment and size before calling this wrapper.\n\
             {}state->impl->{}(*static_cast<const {}*>(args));\n",
                    result_prefix, func.name, cpp_ty
                );
            }
        }
    }

    // Multiple params — use a packed struct
    let func_name_cap: String = capitalise_first(&func.name);
    let struct_name: String = format!("{}Args", func_name_cap);

    let mut code: String = String::new();
    // SAFETY comments for generated code are required per CLAUDE.md rule 6 for all unsafe operations
    code.push_str("        // SAFETY: args is a valid const void* pointing to a packed struct layout per ABI contract.\n");
    code.push_str("        // The host guarantees proper alignment and size matching the struct definition below.\n");
    // Inline struct definition
    code.push_str(&format!("        struct {} {{", struct_name));
    for param in &func.params {
        let cpp_ty: String = cpp_type_name(&param.ty);
        code.push_str(&format!(" {} {};", cpp_ty, param.name));
    }
    code.push_str(" };\n");

    // Cast args to packed struct pointer
    code.push_str(&format!(
        "        const {name}* packed = static_cast<const {name}*>(args);\n",
        name = struct_name
    ));

    // Build call argument list
    let call_args: Vec<String> = func
        .params
        .iter()
        .map(|p| format!("packed->{}", p.name))
        .collect();
    let call_args_str: String = call_args.join(", ");

    code.push_str(&format!(
        "        {}state->impl->{}({});\n",
        result_prefix, func.name, call_args_str
    ));

    code
}

// ─── init.hpp generator ──────────────────────────────────────────────────────

fn generate_init_hpp(ir: &ValidatedIr) -> Result<String, PolyplugcError> {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"interfaces.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include \"polyplug/guest.hpp\"\n\n");

    // polyplug_abi_version
    out.push_str("extern \"C\" uint32_t polyplug_abi_version() { return 1U; }\n\n");

    // polyplug_init
    out.push_str("extern \"C\" AbiError polyplug_init(const HostApi* host, const BundleInitContext* ctx) {\n");
    out.push_str("    if (!host || !ctx) {\n");
    let init_err_msg: &str = "null parameter in polyplug_init";
    out.push_str(&format!(
        "        static constexpr const char* err_msg = \"{init_err_msg}\";\n",
    ));
    out.push_str(&format!(
        "        return AbiError{{static_cast<uint32_t>(AbiErrorCode::Generic), StringView{{reinterpret_cast<const uint8_t*>(err_msg), {len}}}}};\n",
        len = init_err_msg.len()
    ));
    out.push_str("    }\n\n");
    out.push_str(
        "    // No DSO-global state is stored here. The implementation is constructed per\n",
    );
    out.push_str("    // instance by create_instance (which calls the author factory\n");
    out.push_str(
        "    // polyplug_create_<plugin> with the HostApi pointer); init only registers\n",
    );
    out.push_str("    // the static interface tables below.\n\n");

    if let Some(bundle) = &ir.bundle {
        for plugin in &bundle.plugins {
            let plugin_upper: String = plugin.name.to_uppercase().replace('.', "_");
            let plugin_lower: String = plugin.name.to_lowercase().replace('.', "_");
            let contract_impl: &str = plugin.implements.first().map(|s| s.as_str()).unwrap_or("");
            let (contract_name, version_str): (&str, &str) = contract_impl
                .split_once('@')
                .unwrap_or((contract_impl, "1.0.0"));
            let (version_major, version_minor_patch): (&str, &str) =
                version_str.split_once('.').unwrap_or((version_str, "0"));
            let version_minor: &str = version_minor_patch.split('.').next().unwrap_or("0");
            let contract_name_full: String = format!("{}@{}", contract_name, version_major);

            let _ = &plugin_lower;
            out.push_str(&format!("    // Register plugin: {}\n", plugin.name));
            out.push_str(&format!(
                "    PluginDescriptor desc_{} = {{\n",
                plugin_upper
            ));
            out.push_str(&format!(
                "        {{ (const uint8_t*)\"{name}\", {len}U }},  // name (StringView)\n",
                name = plugin.name,
                len = plugin.name.len()
            ));
            out.push_str(&format!(
                "        {{ (const uint8_t*)\"{name}\", {len}U }},  // contract_name (StringView)\n",
                name = contract_name_full,
                len = contract_name_full.len()
            ));
            out.push_str(&format!(
                "        {{ {}U, {}U, 0U }}  // version (Version)\n",
                version_major, version_minor
            ));
            out.push_str("    };\n");

            out.push_str(&format!(
                "    AbiError err_{upper}{{}};\n    host->register_guest_contract(host, &desc_{upper}, &polyplug_plugin::{upper}_INTERFACE, &err_{upper});\n",
                upper = plugin_upper
            ));
            out.push_str(&format!(
                "    if (err_{}.code != static_cast<uint32_t>(AbiErrorCode::Ok)) return err_{};\n\n",
                plugin_upper, plugin_upper
            ));
        }
    } else {
        for contract in &ir.contracts {
            generate_init_hpp_register_guest_contract(&mut out, contract)?;
        }
    }

    out.push_str(
        "    return AbiError{static_cast<uint32_t>(AbiErrorCode::Ok), StringView{nullptr, 0}};\n",
    );
    out.push_str("}\n\n");

    Ok(out)
}

fn generate_init_hpp_register_guest_contract(
    out: &mut String,
    contract: &ResolvedContract,
) -> Result<(), PolyplugcError> {
    let upper: String = contract_name_to_upper_snake(&contract.name);
    let name_bytes: usize = contract.name.len();

    out.push_str(&format!("    // Register contract: {}\n", contract.name));

    out.push_str("    PluginDescriptor desc_");
    out.push_str(&upper);
    out.push_str(" = {\n");
    let contract_name_full: String = format!(
        "{}@{}.{}",
        contract.name, contract.version.major, contract.version.minor
    );
    let name_bytes_full: usize = contract_name_full.len();
    out.push_str(&format!(
        "        {{ (const uint8_t*)\"{name}\", {len}U }},  // name (StringView)\n",
        name = contract.name,
        len = name_bytes
    ));
    out.push_str(&format!(
        "        {{ (const uint8_t*)\"{name}\", {len}U }},  // contract_name (StringView)\n",
        name = contract_name_full,
        len = name_bytes_full
    ));
    out.push_str(&format!(
        "        {{ {}U, {}U, {}U }}  // version (Version)\n",
        contract.version.major, contract.version.minor, contract.version.patch
    ));
    out.push_str("    };\n");

    out.push_str(&format!(
        "    AbiError err_{upper}{{}};\n    host->register_guest_contract(host, &desc_{upper}, &polyplug_plugin::{upper}_INTERFACE, &err_{upper});\n",
        upper = upper
    ));
    out.push_str(&format!(
        "    if (err_{}.code != static_cast<uint32_t>(AbiErrorCode::Ok)) return err_{};\n\n",
        upper, upper
    ));

    Ok(())
}

// ─── host_callers.hpp generator ──────────────────────────────────────────────

fn generate_host_callers_hpp(ir: &ValidatedIr) -> Result<String, PolyplugcError> {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"types.hpp\"\n");
    out.push_str("#include \"polyplug/error.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include \"polyplug/runtime.hpp\"\n");
    out.push_str("#include <array>\n");
    out.push_str("#include <atomic>\n");
    out.push_str("#include <cstddef>\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include <memory>\n");
    out.push_str("#include <optional>\n\n");
    out.push_str("namespace polyplug_generated {\n\n");
    if let Some(ref bundle) = ir.bundle {
        out.push_str(&format!(
            "static constexpr uint64_t MY_BUNDLE_ID = {}ULL;\n\n",
            bundle.bundle_id
        ));
    }

    emit_cpp_revision_helper(&mut out);

    // Emit the per-caller call-arena helpers only when some contract needs one.
    if ir.contracts.iter().any(contract_needs_arena) {
        emit_cpp_call_arena_helpers(&mut out);
    }

    for contract in &ir.contracts {
        generate_cpp_host_contract(&mut out, contract)?;
    }

    out.push_str("}  // namespace polyplug_generated\n");
    Ok(out)
}

// ─── manifest.toml generator ─────────────────────────────────────────────────

fn generate_manifest_toml() -> String {
    let mut out: String = String::new();
    out.push_str("# THIS FILE IS AUTO-GENERATED BY polyplugc. DO NOT EDIT.\n");
    out.push_str("[manifest]\n");
    out.push_str("schema_version = 1\n");
    out.push_str("lang = \"cpp\"\n");
    out.push_str("generated_by = \"polyplugc\"\n");
    out
}

/// Generate a full discovery `manifest.toml` for `--bundle` invocations.
/// Called only when `ir.bundle.is_some()`.
fn generate_bundle_manifest_cpp(ir: &ValidatedIr) -> String {
    let bundle: &ResolvedBundle = match ir.bundle.as_ref() {
        Some(b) => b,
        None => return String::from("# ERROR: bundle manifest called without bundle IR\n"),
    };

    let name: &str = &bundle.name;
    let version: String = format!(
        "{}.{}.{}",
        bundle.version.major, bundle.version.minor, bundle.version.patch
    );
    // C++ native runtime uses platform-specific shared libraries from bundle.toml
    let file_field: String = super::format_manifest_file_field(&bundle.file);

    // Collect provides: all implements from all plugins, deduplicated
    let mut provides: Vec<String> = bundle
        .plugins
        .iter()
        .flat_map(|p: &ResolvedPlugin| p.implements.iter().cloned())
        .map(|impl_str: String| {
            if let Some(at_pos) = impl_str.find('@') {
                let contract_name: &str = &impl_str[..at_pos];
                let version_part: &str = &impl_str[at_pos + 1..];
                if let Some(dot_pos) = version_part.find('.') {
                    let major: &str = &version_part[..dot_pos];
                    format!("{}@{}", contract_name, major)
                } else {
                    impl_str
                }
            } else {
                impl_str
            }
        })
        .collect();
    provides.sort();
    provides.dedup();

    // Build TOML string array for provides
    let provides_toml: String = if provides.is_empty() {
        String::from("[]")
    } else {
        format!(
            "[{}]",
            provides
                .iter()
                .map(|s: &String| format!("\"{}\"", s))
                .collect::<Vec<_>>()
                .join(", ")
        )
    };

    // Build function_count inline table: only for contracts this bundle PROVIDES
    let provides_set: std::collections::HashSet<String> = provides.iter().cloned().collect();
    let fn_count_entries: Vec<String> = ir
        .contracts
        .iter()
        .filter(|c: &&ResolvedContract| {
            provides_set.contains(&format!("{}@{}", c.name, c.version.major))
        })
        .map(|c: &ResolvedContract| {
            let fn_count: u32 = c.functions.len() as u32;
            format!("\"{}@{}\" = {}", c.name, c.version.major, fn_count)
        })
        .collect();
    let function_count_toml: String = format!("{{ {} }}", fn_count_entries.join(", "));

    // Build [[dependency]] tables
    let dep_tables: String = super::emit_manifest_dependencies(&bundle.dependencies);

    let reinit: bool = bundle.needs_reinit_on_dep_reload;
    let loader: &str = "native";

    format!(
        "# THIS FILE IS AUTO-GENERATED BY polyplugc. DO NOT EDIT.\n\
name = \"{name}\"\n\
id = {bundle_id}\n\
version = \"{version}\"\n\
loader = \"{loader}\"\n\
provides = {provides_toml}\n\
function_count = {function_count_toml}\n\
needs_reinit_on_dep_reload = {reinit}\n\
{file_field}\n\
{dep_tables}",
        bundle_id = bundle.bundle_id
    )
}

// ─── Per-enum emitter ────────────────────────────────────────────────────────

fn substitute_variant_refs_cpp(
    declared_variants: &[EnumVariant],
    expr: &str,
    enum_name: &str,
    repr_cpp: &str,
) -> String {
    let declared_names: Vec<&str> = declared_variants.iter().map(|v| v.name.as_str()).collect();
    let chars: Vec<char> = expr.chars().collect();
    let len: usize = chars.len();
    let mut result: String = String::new();
    let mut i: usize = 0;
    while i < len {
        let c: char = chars[i];
        if c.is_alphabetic() || c == '_' {
            let start: usize = i;
            while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            if declared_names.contains(&ident.as_str()) {
                result.push_str(&format!(
                    "static_cast<{}>({}::{})",
                    repr_cpp, enum_name, ident
                ));
            } else {
                result.push_str(&ident);
            }
        } else {
            result.push(c);
            i += 1;
        }
    }
    result
}

fn generate_cpp_enum(out: &mut String, e: &EnumDef) {
    let repr_cpp: &str = e.repr.cpp_name();
    out.push_str(&format!("/// Enum `{}` (repr: {})\n", e.name, repr_cpp));
    out.push_str(&format!("enum class {} : {} {{\n", e.name, repr_cpp));
    for variant in &e.variants {
        let subst_value: String =
            substitute_variant_refs_cpp(&e.variants, &variant.value, &e.name, repr_cpp);
        out.push_str(&format!("    {} = {},\n", variant.name, subst_value));
    }
    out.push_str("};\n");
    if e.bitflag {
        out.push_str(&format!(
            "inline {} operator|({}  a, {} b) {{ return static_cast<{}>(static_cast<{}>(a) | static_cast<{}>(b)); }}\n",
            e.name, e.name, e.name, e.name, repr_cpp, repr_cpp
        ));
        out.push_str(&format!(
            "inline {} operator&({} a, {} b) {{ return static_cast<{}>(static_cast<{}>(a) & static_cast<{}>(b)); }}\n",
            e.name, e.name, e.name, e.name, repr_cpp, repr_cpp
        ));
        out.push_str(&format!(
            "inline {} operator~({} a) {{ return static_cast<{}>(~static_cast<{}>(a)); }}\n",
            e.name, e.name, e.name, repr_cpp
        ));
    }
    out.push('\n');
}

// ─── Per-type struct emitter ──────────────────────────────────────────────────

fn generate_cpp_type(out: &mut String, ty: &ResolvedType) {
    out.push_str(&format!("/// User-defined type `{}`\n", ty.name));
    out.push_str("struct ");
    out.push_str(&ty.name);
    out.push_str(" {\n");
    for field in &ty.fields {
        out.push_str(&format!(
            "    {} {};\n",
            cpp_types_hpp_type_name(&field.ty),
            field.name
        ));
    }
    out.push_str("};\n\n");
}

// ─── Call-arena support ────────────────────────────────────────────────────────

/// Whether a function returns a variable-size value the guest writes into the
/// call arena (a `StringView`, a `Buffer`, or any user-defined struct that may
/// embed one). Such functions receive a per-caller `CallArena`; all others pass
/// a null arena and the VM bridge falls back to per-value `host->alloc`.
///
/// Passing an arena where none is needed is harmless; passing null where one is
/// needed only loses the optimisation. The conservative `UserDefined` case keeps
/// the rule sound without resolving struct fields here. Mirrors `fn_needs_arena`
/// in `rust.rs` so every generator agrees on which functions are arena-backed.
fn fn_needs_arena(func: &ResolvedFunction) -> bool {
    matches!(
        &func.returns,
        Some(ResolvedTypeRef::AbiType(AbiBuiltin::StringView))
            | Some(ResolvedTypeRef::AbiType(AbiBuiltin::Buffer))
            | Some(ResolvedTypeRef::UserDefined(_))
    )
}

/// Whether any function on the contract needs a call arena.
fn contract_needs_arena(contract: &ResolvedContract) -> bool {
    contract.functions.iter().any(fn_needs_arena)
}

/// Emit the inline call-arena helpers used by per-caller arenas.
///
/// Emit the shared revision-load helper used by every generated caller.
///
/// `revision_ptr` is the value returned by `HostApi.revision_counter`: a pointer
/// to the runtime's registry revision counter (a Rust `AtomicU64`, layout-compatible
/// with `std::atomic<std::uint64_t>`). C++17 has no `std::atomic_ref`, so the load is
/// performed by reinterpreting the pointer as `const std::atomic<std::uint64_t>*` and
/// issuing one acquire load. A null pointer (no runtime) reads as 0, so the per-call
/// staleness check then compares the cached 0 against 0 — a no-op.
fn emit_cpp_revision_helper(out: &mut String) {
    out.push_str("/// Read the runtime's registry revision through `revision_ptr` with one\n");
    out.push_str("/// acquire atomic load. Returns 0 when the pointer is null (no runtime),\n");
    out.push_str("/// making the per-call staleness check a no-op.\n");
    out.push_str(
        "inline uint64_t polyplug_load_revision(const uint64_t* revision_ptr) noexcept {\n",
    );
    out.push_str("    if (revision_ptr == nullptr) { return 0; }\n");
    out.push_str(
        "    // SAFETY: revision_ptr was returned by HostApi.revision_counter and points at\n",
    );
    out.push_str(
        "    // the runtime's revision counter — a Rust AtomicU64, layout-compatible with\n",
    );
    out.push_str(
        "    // std::atomic<std::uint64_t> — whose address is stable for the runtime's lifetime.\n",
    );
    out.push_str(
        "    return reinterpret_cast<const std::atomic<std::uint64_t>*>(revision_ptr)->load(std::memory_order_acquire);\n",
    );
    out.push_str("}\n\n");
}

/// `CallArena` in `polyplug/abi.hpp` is a layout-only POD (no methods), so the
/// bump/overflow allocation and reset logic is emitted here. It is a direct port
/// of `polyplug_abi::CallArena::{alloc, reset}`; keeping the two in lockstep is
/// required by Rule 10 (identical ABI mechanisms across generators).
fn emit_cpp_call_arena_helpers(out: &mut String) {
    out.push_str("/// Size of each caller's inline call-arena buffer.\n");
    out.push_str("///\n");
    out.push_str("/// Variable-size VM return values (strings, buffers) are bump-allocated from\n");
    out.push_str("/// this buffer; outputs larger than it spill into host-allocated overflow\n");
    out.push_str("/// blocks that are retained across resets and freed only at teardown.\n");
    out.push_str(&format!(
        "static constexpr size_t CALL_ARENA_BUF_LEN = {CALL_ARENA_BUF_LEN};\n\n"
    ));

    out.push_str("/// Minimum size of a host-allocated overflow block, including its header.\n");
    out.push_str("static constexpr size_t POLYPLUG_OVERFLOW_BLOCK_MIN = 4096;\n");
    out.push_str("/// Alignment used for host-allocated overflow blocks.\n");
    out.push_str(
        "static constexpr size_t POLYPLUG_OVERFLOW_BLOCK_ALIGN = alignof(ArenaOverflowBlock);\n\n",
    );

    out.push_str("/// Bump-allocate `size` bytes aligned to `align` within `[from, end)`.\n");
    out.push_str("/// Returns nullptr if the request does not fit.\n");
    out.push_str(
        "inline uint8_t* polyplug_arena_bump(uint8_t* from, uint8_t* end, size_t size, size_t align) noexcept {\n",
    );
    out.push_str("    auto addr = reinterpret_cast<size_t>(from);\n");
    out.push_str("    size_t aligned = (addr + (align - 1)) & ~(align - 1);\n");
    out.push_str("    if (aligned < addr) { return nullptr; }  // overflow on alignment\n");
    out.push_str("    size_t new_cur = aligned + size;\n");
    out.push_str("    if (new_cur < aligned) { return nullptr; }  // overflow on size\n");
    out.push_str("    if (new_cur <= reinterpret_cast<size_t>(end)) {\n");
    out.push_str("        return reinterpret_cast<uint8_t*>(aligned);\n");
    out.push_str("    }\n");
    out.push_str("    return nullptr;\n");
    out.push_str("}\n\n");

    out.push_str("/// Try to bump-allocate `size`@`align` from `block`'s free region.\n");
    out.push_str("///\n");
    out.push_str("/// Advances `block->used` on success and returns the allocation pointer.\n");
    out.push_str(
        "/// Returns nullptr if the request does not fit in the block's remaining room.\n",
    );
    out.push_str(
        "inline uint8_t* polyplug_arena_serve_from_block(ArenaOverflowBlock* block, size_t size, size_t align) noexcept {\n",
    );
    out.push_str(
        "    // SAFETY: block is a valid overflow block previously allocated by polyplug_arena_alloc;\n",
    );
    out.push_str(
        "    // reading used/capacity and deriving pointers from the block base stays within\n",
    );
    out.push_str("    // the capacity-byte allocation.\n");
    out.push_str("    auto block_bytes = reinterpret_cast<uint8_t*>(block);\n");
    out.push_str("    uint8_t* from = block_bytes + block->used;\n");
    out.push_str("    uint8_t* end  = block_bytes + block->capacity;\n");
    out.push_str("    uint8_t* p = polyplug_arena_bump(from, end, size, align);\n");
    out.push_str("    if (p == nullptr) { return nullptr; }\n");
    out.push_str(
        "    // SAFETY: block is a valid chain node; writing used (a plain size_t field)\n",
    );
    out.push_str(
        "    // is in-bounds because the block was allocated with at least sizeof(ArenaOverflowBlock) bytes.\n",
    );
    out.push_str("    block->used = static_cast<size_t>(p - block_bytes) + size;\n");
    out.push_str("    return p;\n");
    out.push_str("}\n\n");

    out.push_str("/// Allocate `size` bytes aligned to `align` from `arena`.\n");
    out.push_str("///\n");
    out.push_str("/// Serves from the primary region by bumping `cur`; on exhaustion, walks the\n");
    out.push_str(
        "/// retained overflow chain for a block with spare room; if none fits, requests a\n",
    );
    out.push_str("/// fresh overflow block from the host and serves from it. Returns nullptr if\n");
    out.push_str(
        "/// `size == 0`, if `align` is not a power of two, or if a host allocation fails.\n",
    );
    out.push_str("/// The returned pointer is valid until the next polyplug_arena_reset().\n");
    out.push_str(
        "inline uint8_t* polyplug_arena_alloc(CallArena* arena, size_t size, size_t align) noexcept {\n",
    );
    out.push_str("    if (size == 0 || align == 0 || (align & (align - 1)) != 0) {\n");
    out.push_str("        return nullptr;\n");
    out.push_str("    }\n");
    out.push_str(
        "    if (uint8_t* p = polyplug_arena_bump(arena->cur, arena->end, size, align)) {\n",
    );
    out.push_str("        arena->cur = p + size;\n");
    out.push_str("        return p;\n");
    out.push_str("    }\n");
    out.push_str("    if (arena->host == nullptr) { return nullptr; }\n");
    out.push_str(
        "    // REUSE PASS: walk the retained chain; serve from the first block with room.\n",
    );
    out.push_str(
        "    for (ArenaOverflowBlock* b = arena->first_overflow; b != nullptr; b = b->next) {\n",
    );
    out.push_str(
        "        if (uint8_t* p = polyplug_arena_serve_from_block(b, size, align)) { return p; }\n",
    );
    out.push_str("    }\n");
    out.push_str("    // ALLOCATE NEW: no retained block had enough room.\n");
    out.push_str("    size_t header = sizeof(ArenaOverflowBlock);\n");
    out.push_str("    size_t needed = header + align + size;\n");
    out.push_str("    size_t capacity = needed > POLYPLUG_OVERFLOW_BLOCK_MIN ? needed : POLYPLUG_OVERFLOW_BLOCK_MIN;\n");
    out.push_str(
        "    // SAFETY: arena->host is non-null (checked above) and valid for the arena's\n",
    );
    out.push_str(
        "    // lifetime. The allocator returns a block of `capacity` bytes or nullptr.\n",
    );
    out.push_str(
        "    auto block_ptr = static_cast<uint8_t*>(arena->host->alloc(arena->host, capacity, POLYPLUG_OVERFLOW_BLOCK_ALIGN));\n",
    );
    out.push_str("    if (block_ptr == nullptr) { return nullptr; }\n");
    out.push_str("    // SAFETY: block_ptr is aligned for ArenaOverflowBlock and owns at least\n");
    out.push_str("    // `capacity >= header` bytes, so writing the header is sound.\n");
    out.push_str("    auto block = reinterpret_cast<ArenaOverflowBlock*>(block_ptr);\n");
    out.push_str("    block->next = arena->first_overflow;\n");
    out.push_str("    block->capacity = capacity;\n");
    out.push_str("    block->used = header;\n");
    out.push_str("    arena->first_overflow = block;\n");
    out.push_str("    return polyplug_arena_serve_from_block(block, size, align);\n");
    out.push_str("}\n\n");

    out.push_str(
        "/// Rewind `arena` for reuse: the primary region and every retained overflow block\n",
    );
    out.push_str(
        "/// become available again. Overflow blocks are NOT freed — they are retained for\n",
    );
    out.push_str(
        "/// reuse across calls; call polyplug_arena_free_all() at teardown to free them.\n",
    );
    out.push_str(
        "/// After reset, all pointers previously returned by polyplug_arena_alloc are invalid.\n",
    );
    out.push_str("inline void polyplug_arena_reset(CallArena* arena) noexcept {\n");
    out.push_str("    arena->cur = arena->base;\n");
    out.push_str("    ArenaOverflowBlock* block = arena->first_overflow;\n");
    out.push_str("    while (block != nullptr) {\n");
    out.push_str(
        "        // SAFETY: every block in the chain was allocated by polyplug_arena_alloc\n",
    );
    out.push_str("        // with a valid header; reading next and writing used are in-bounds.\n");
    out.push_str("        block->used = sizeof(ArenaOverflowBlock);\n");
    out.push_str("        block = block->next;\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    out.push_str("/// Free all retained overflow blocks and reset the overflow chain to empty.\n");
    out.push_str("/// Call this at teardown (destructor) to release all host-allocated memory.\n");
    out.push_str("inline void polyplug_arena_free_all(CallArena* arena) noexcept {\n");
    out.push_str("    ArenaOverflowBlock* block = arena->first_overflow;\n");
    out.push_str("    while (block != nullptr) {\n");
    out.push_str(
        "        // SAFETY: every block was allocated by polyplug_arena_alloc with a valid\n",
    );
    out.push_str("        // header; reading next/capacity before freeing is sound.\n");
    out.push_str("        ArenaOverflowBlock* next = block->next;\n");
    out.push_str("        size_t capacity = block->capacity;\n");
    out.push_str("        if (arena->host != nullptr) {\n");
    out.push_str(
        "            // SAFETY: block was allocated by host->alloc with these exact args.\n",
    );
    out.push_str(
        "            arena->host->free(arena->host, reinterpret_cast<uint8_t*>(block), capacity, POLYPLUG_OVERFLOW_BLOCK_ALIGN);\n",
    );
    out.push_str("        }\n");
    out.push_str("        block = next;\n");
    out.push_str("    }\n");
    out.push_str("    arena->first_overflow = nullptr;\n");
    out.push_str("}\n\n");

    out.push_str(
        "/// Construct a CallArena over `buf` (primary region) with `host` for overflow.\n",
    );
    out.push_str("inline CallArena polyplug_arena_new(uint8_t* buf, size_t len, const HostApi* host) noexcept {\n");
    out.push_str("    CallArena arena{};\n");
    out.push_str("    arena.cur = buf;\n");
    out.push_str("    arena.end = buf + len;\n");
    out.push_str("    arena.base = buf;\n");
    out.push_str("    arena.host = host;\n");
    out.push_str("    arena.first_overflow = nullptr;\n");
    out.push_str("    return arena;\n");
    out.push_str("}\n\n");
}

// ─── Per-contract class emitter (instance wrapper) ──────────────────────────────

fn generate_cpp_host_contract(
    out: &mut String,
    contract: &ResolvedContract,
) -> Result<(), PolyplugcError> {
    let class_name: String = contract_name_to_class(&contract.name);
    let _contract_upper: String = contract.name.to_uppercase().replace(['.', '-'], "_");
    let needs_arena: bool = contract_needs_arena(contract);

    out.push_str(&format!(
        "/// Host caller for contract `{}` (id=0x{:016X})\n",
        contract.name, contract.contract_id
    ));
    out.push_str("///\n");
    out.push_str("/// RAII wrapper that manages instance lifecycle:\n");
    out.push_str("/// - `create()`: resolves handle and calls `create_instance`\n");
    out.push_str("/// - destructor: calls `destroy_instance` to clean up\n");
    out.push_str("/// - dispatch: passes `instance_` to all method calls\n");
    if needs_arena {
        out.push_str("///\n");
        out.push_str("/// # Call-arena lifetime\n");
        out.push_str("///\n");
        out.push_str(
            "/// Methods returning variable-size values (`StringView`, `Buffer`, or structs\n",
        );
        out.push_str(
            "/// that may embed one) are non-const and reset this caller's arena at the start\n",
        );
        out.push_str(
            "/// of the call. Any view returned by such a method borrows arena memory and is\n",
        );
        out.push_str("/// valid only until the next arena-backed call on the same caller.\n");
    }
    out.push_str(&format!("class {} {{\npublic:\n", class_name));

    // Factory method: resolve handle + create_instance
    out.push_str("    /// Factory method - creates instance or nullopt if not found.\n");
    out.push_str("    /// Calls `create_instance` on the resolved interface.\n");
    out.push_str("    ///\n");
    out.push_str("    /// # Arguments\n");
    out.push_str("    /// - `handle`: Contract handle from `find_guest_contract`\n");
    out.push_str("    /// - `host`: Host interface pointer\n");
    out.push_str("    ///\n");
    out.push_str("    /// # Returns\n");
    out.push_str("    /// - `std::optional<Self>` if interface found and instance created\n");
    out.push_str("    /// - `std::nullopt` if interface not found or `create_instance` failed\n");
    out.push_str(&format!(
        "    static std::optional<{}> create(GuestContractHandle handle, const HostApi* host) noexcept {{\n",
        class_name
    ));
    out.push_str("        if (host == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    out.push_str("        // Resolve the interface from the handle via HostApi method.\n");
    out.push_str("        const GuestContractInterface* iface = host->resolve_guest_contract(host, handle);\n");
    out.push_str("        if (iface == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    out.push_str(
        "        // Create instance via host-mediated lifecycle so the runtime tracks it.\n",
    );
    out.push_str("        // A null `instance.data` is valid: stateless contracts return a null\n");
    out.push_str(
        "        // handle from `create_instance` and use it as an opaque dispatch token.\n",
    );
    out.push_str(
        "        GuestContractInstance instance{};\n        host->create_guest_instance(host, iface, nullptr, &instance);\n",
    );
    out.push_str(
        "        // Fetch the registry revision counter ONCE, then read its current value, so\n",
    );
    out.push_str(
        "        // every later call can detect a reload/unload with a direct atomic load (no\n",
    );
    out.push_str("        // call back into the runtime) and re-resolve before dispatching.\n");
    out.push_str("        const uint64_t* revision_ptr = host->revision_counter(host);\n");
    out.push_str(
        "        const uint64_t cached_revision = polyplug_load_revision(revision_ptr);\n",
    );
    out.push_str(&format!(
        "        return {}(iface, instance, host, handle, revision_ptr, cached_revision);\n",
        class_name
    ));
    out.push_str("    }\n\n");

    // Destructor: calls destroy_instance
    out.push_str("    /// Destructor - calls `destroy_instance` to clean up.\n");
    out.push_str(&format!("    ~{}() noexcept {{\n", class_name));
    if needs_arena {
        out.push_str(
            "        // Free any overflow blocks the arena still holds before destruction.\n",
        );
        out.push_str("        // arena_buf_ is null only on a moved-from caller.\n");
        out.push_str("        if (arena_buf_) {\n");
        out.push_str("            polyplug_arena_free_all(&arena_);\n");
        out.push_str("        }\n");
    }
    out.push_str(
        "        // If the registry changed since we resolved, the cached interface and\n",
    );
    out.push_str(
        "        // instance are stale — a reload/unload reclaimed their backing — so calling\n",
    );
    out.push_str(
        "        // the dead interface's destroy would be UB; the reload/unload already\n",
    );
    out.push_str("        // reclaimed the instance, so skip the destroy entirely.\n");
    out.push_str("        if (polyplug_load_revision(revision_ptr_) != cached_revision_) {\n");
    out.push_str("            return;\n");
    out.push_str("        }\n");
    out.push_str("        // Destroy instance via factory\n");
    out.push_str("        // SAFETY: instance was created by create_instance and is valid.\n");
    out.push_str("        if (instance_.data != nullptr) {\n");
    out.push_str("            host_->destroy_guest_instance(host_, interface_, instance_);\n");
    out.push_str("            instance_.data = nullptr;  // Prevent reuse after cleanup.\n");
    out.push_str("        }\n");
    out.push_str("    }\n\n");

    // Move-only (instance handles are unique)
    out.push_str("    // Move-only (instance handles are unique)\n");
    out.push_str(&format!(
        "    {}({}&& other) noexcept\n",
        class_name, class_name
    ));
    out.push_str("        : interface_(other.interface_),\n");
    out.push_str("          instance_(other.instance_),\n");
    out.push_str("          host_(other.host_),\n");
    out.push_str("          handle_(other.handle_),\n");
    out.push_str("          revision_ptr_(other.revision_ptr_),\n");
    if needs_arena {
        // The arena's interior pointers refer into *arena_buf_, a heap block whose
        // address is preserved by moving the unique_ptr, so the arena stays valid.
        out.push_str("          cached_revision_(other.cached_revision_),\n");
        out.push_str("          arena_buf_(std::move(other.arena_buf_)),\n");
        out.push_str("          arena_(other.arena_) {\n");
    } else {
        out.push_str("          cached_revision_(other.cached_revision_) {\n");
    }
    out.push_str("        other.instance_.data = nullptr;  // Prevent double-destroy.\n");
    out.push_str("    }\n");
    out.push_str(&format!(
        "    {}& operator=({}&& other) noexcept {{\n",
        class_name, class_name
    ));
    out.push_str("        if (this != &other) {\n");
    if needs_arena {
        out.push_str("            // Release this caller's overflow blocks before overwriting.\n");
        out.push_str("            if (arena_buf_) {\n");
        out.push_str("                polyplug_arena_free_all(&arena_);\n");
        out.push_str("            }\n");
    }
    out.push_str(
        "            // Destroy current instance first — but only if the registry has not\n",
    );
    out.push_str(
        "            // changed under us; a reload/unload already reclaimed a stale instance.\n",
    );
    out.push_str("            if (instance_.data != nullptr && polyplug_load_revision(revision_ptr_) == cached_revision_) {\n");
    out.push_str("                host_->destroy_guest_instance(host_, interface_, instance_);\n");
    out.push_str("            }\n");
    out.push_str("            interface_ = other.interface_; instance_ = other.instance_; host_ = other.host_; other.instance_.data = nullptr;\n");
    out.push_str("            handle_ = other.handle_; revision_ptr_ = other.revision_ptr_; cached_revision_ = other.cached_revision_;\n");
    if needs_arena {
        out.push_str(
            "            arena_buf_ = std::move(other.arena_buf_); arena_ = other.arena_;\n",
        );
    }
    out.push_str("        }\n");
    out.push_str("        return *this;\n");
    out.push_str("    }\n");
    out.push_str(&format!(
        "    {}(const {}&) = delete;\n",
        class_name, class_name
    ));
    out.push_str(&format!(
        "    {}& operator=(const {}&) = delete;\n\n",
        class_name, class_name
    ));

    out.push_str("    /// Check if this caller holds a resolved contract interface.\n");
    out.push_str("    /// Keys off the interface pointer, not `instance_.data`: stateless\n");
    out.push_str(
        "    /// contracts legitimately use a null instance as an opaque dispatch token.\n",
    );
    out.push_str(
        "    explicit operator bool() const noexcept { return interface_ != nullptr; }\n\n",
    );
    out.push_str("    /// Check if this caller holds a resolved contract interface.\n");
    out.push_str("    bool is_valid() const noexcept { return interface_ != nullptr; }\n\n");

    // reset() method: destroy and recreate
    out.push_str("    /// Destroy current instance and create a new one.\n");
    out.push_str("    /// Useful for recovering from plugin errors.\n");
    out.push_str("    void reset() noexcept {\n");
    out.push_str(
        "        // If the registry changed under us, the cached interface/instance are\n",
    );
    out.push_str(
        "        // stale (a reload/unload reclaimed their backing). revalidate() abandons\n",
    );
    out.push_str(
        "        // the dead instance and builds a fresh one on the current interface —\n",
    );
    out.push_str("        // exactly the fresh instance reset() promises — so defer to it.\n");
    out.push_str("        if (polyplug_load_revision(revision_ptr_) != cached_revision_) {\n");
    out.push_str("            revalidate();\n");
    out.push_str("            return;\n");
    out.push_str("        }\n");
    out.push_str("        if (instance_.data != nullptr) {\n");
    out.push_str("            host_->destroy_guest_instance(host_, interface_, instance_);\n");
    out.push_str("        }\n");
    out.push_str("        instance_ = GuestContractInstance{};\n");
    out.push_str("        host_->create_guest_instance(host_, interface_, nullptr, &instance_);\n");
    out.push_str("    }\n\n");

    // live_revision() + revalidate() private helpers are emitted in the private
    // section below; the public surface above references them.

    // Generate method callers
    for func in &contract.functions {
        generate_cpp_host_function(out, &class_name, func)?;
    }

    // Private members, helpers, and constructor
    out.push_str("private:\n");

    // Re-resolve the cached interface after the registry changed under us.
    out.push_str("    /// Re-resolve the cached interface after the registry changed under us.\n");
    out.push_str("    ///\n");
    out.push_str(
        "    /// A hot-reload swapped a new interface into the same slot, so the retained\n",
    );
    out.push_str(
        "    /// handle still resolves — to the new interface; an unload vacated the slot,\n",
    );
    out.push_str(
        "    /// so it resolves to null and `false` is returned (the contract is gone).\n",
    );
    out.push_str("    ///\n");
    out.push_str("    /// The old instance is ABANDONED, never destroyed: after a reload its\n");
    out.push_str(
        "    /// interface and the guest state it created are already epoch-reclaimed, so\n",
    );
    out.push_str("    /// calling the dead interface's destroy would be UB.\n");
    out.push_str("    bool revalidate() noexcept {\n");
    out.push_str("        if (host_ == nullptr) {\n");
    out.push_str("            return false;\n");
    out.push_str("        }\n");
    out.push_str("        const GuestContractInterface* iface = host_->resolve_guest_contract(host_, handle_);\n");
    out.push_str("        if (iface == nullptr) {\n");
    out.push_str("            return false;\n");
    out.push_str("        }\n");
    out.push_str("        GuestContractInstance inst{};\n");
    out.push_str("        host_->create_guest_instance(host_, iface, nullptr, &inst);\n");
    out.push_str("        interface_ = iface;\n");
    out.push_str("        instance_ = inst;\n");
    out.push_str("        cached_revision_ = polyplug_load_revision(revision_ptr_);\n");
    out.push_str("        return true;\n");
    out.push_str("    }\n\n");

    out.push_str("    /// Resolved interface pointer from the registry.\n");
    out.push_str("    const GuestContractInterface* interface_;\n");
    out.push_str("    /// Instance handle created by `create_instance`.\n");
    out.push_str("    GuestContractInstance instance_;\n");
    out.push_str("    /// Host interface pointer (needed for create/destroy_instance).\n");
    out.push_str("    const HostApi* host_;\n");
    out.push_str(
        "    /// Contract handle, retained so the cache can re-resolve after a hot-reload\n",
    );
    out.push_str(
        "    /// (which swaps a new interface into the same slot) or report a gone contract.\n",
    );
    out.push_str("    GuestContractHandle handle_;\n");
    out.push_str("    /// Pointer to the runtime's registry revision counter, fetched once via\n");
    out.push_str(
        "    /// `HostApi.revision_counter`. Polled before each dispatch (one atomic load,\n",
    );
    out.push_str("    /// no call into the runtime); null when there is no runtime.\n");
    out.push_str("    const uint64_t* revision_ptr_;\n");
    out.push_str(
        "    /// Revision value read when the interface was resolved. Compared before each\n",
    );
    out.push_str(
        "    /// dispatch against the live counter to detect a reload/unload and re-resolve,\n",
    );
    out.push_str("    /// so the cached interface pointer never dangles.\n");
    out.push_str("    uint64_t cached_revision_;\n");
    if needs_arena {
        out.push_str(
            "    /// Stable-address backing buffer for the per-call arena. Held by unique_ptr\n",
        );
        out.push_str("    /// so the arena's interior pointers survive moving the caller value.\n");
        out.push_str("    std::unique_ptr<std::array<uint8_t, CALL_ARENA_BUF_LEN>> arena_buf_;\n");
        out.push_str(
            "    /// Per-call bump arena over `arena_buf_`, reset at each arena-backed call.\n",
        );
        out.push_str("    CallArena arena_;\n");
    }
    out.push('\n');
    if needs_arena {
        out.push_str(&format!(
            "    explicit {}(const GuestContractInterface* iface, GuestContractInstance inst, const HostApi* host, GuestContractHandle handle, const uint64_t* revision_ptr, uint64_t cached_revision)\n",
            class_name
        ));
        out.push_str("        : interface_(iface), instance_(inst), host_(host), handle_(handle), revision_ptr_(revision_ptr), cached_revision_(cached_revision),\n");
        out.push_str(
            "          arena_buf_(std::make_unique<std::array<uint8_t, CALL_ARENA_BUF_LEN>>()),\n",
        );
        out.push_str(
            "          arena_(polyplug_arena_new(arena_buf_->data(), CALL_ARENA_BUF_LEN, host)) {}\n",
        );
    } else {
        out.push_str(&format!(
            "    explicit {}(const GuestContractInterface* iface, GuestContractInstance inst, const HostApi* host, GuestContractHandle handle, const uint64_t* revision_ptr, uint64_t cached_revision) noexcept\n",
            class_name
        ));
        out.push_str("        : interface_(iface), instance_(inst), host_(host), handle_(handle), revision_ptr_(revision_ptr), cached_revision_(cached_revision) {}\n");
    }
    out.push_str("};\n\n");
    Ok(())
}

// ─── Per-function method emitter (instance-based dispatch) ─────────────────────

fn generate_cpp_host_function(
    out: &mut String,
    class_name: &str,
    func: &ResolvedFunction,
) -> Result<(), PolyplugcError> {
    let return_type: String = func
        .returns
        .as_ref()
        .map(cpp_type_name)
        .unwrap_or_else(|| "void".to_owned());

    // Build parameter list string.
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| format!("{} {}", cpp_type_name(&p.ty), p.name))
        .collect();
    let params_str: String = params.join(", ");

    out.push_str(&format!(
        "    /// Call `{}` (function_id={})\n",
        func.name, func.function_id
    ));
    let needs_arena: bool = fn_needs_arena(func);
    if needs_arena {
        out.push_str(
            "    /// Returns a value borrowing this caller's arena; it stays valid until\n",
        );
        out.push_str("    /// the next arena-backed call on this caller.\n");
    }
    out.push_str(&format!(
        "    {} {}({}) {{\n",
        return_type, func.name, params_str
    ));

    // Cheap per-call staleness check: read the registry revision directly through
    // the cached pointer (one atomic load, no call into the runtime). While it
    // matches the value cached at resolve, the interface pointer is current and we
    // dispatch directly; on any change (hot-reload or unload) we re-resolve first,
    // so the cached pointer is never used once it dangles.
    out.push_str(
        "        // Per-call staleness check: re-resolve before dispatch if the registry changed,\n",
    );
    out.push_str("        // so the cached interface pointer is never used once it dangles.\n");
    out.push_str("        if (polyplug_load_revision(revision_ptr_) != cached_revision_ && !revalidate()) {\n");
    out.push_str("            static constexpr const char* err_msg = \"contract not found\";\n");
    out.push_str(
        "            polyplug::check_abi_error(AbiError{static_cast<uint32_t>(AbiErrorCode::NotFound), StringView{reinterpret_cast<const uint8_t*>(err_msg), 18}});\n",
    );
    out.push_str("        }\n");

    if needs_arena {
        out.push_str(
            "        // Reset the arena at call start: frees the previous call's overflow\n",
        );
        out.push_str(
            "        // blocks and rewinds the primary region, invalidating prior views.\n",
        );
        out.push_str("        polyplug_arena_reset(&arena_);\n");
    }

    // Determine args_ptr expression.
    let args_ptr_code: String = build_args_ptr_code(class_name, func);
    out.push_str(&args_ptr_code);

    let fn_id: u32 = func.function_id;

    let is_void_return: bool = matches!(
        func.returns.as_ref(),
        None | Some(ResolvedTypeRef::AbiType(AbiBuiltin::Void))
    );

    // SAFETY: Check interface validity
    let null_iface_msg: &str = "interface is null";
    out.push_str("        // SAFETY: interface_ is valid for the lifetime of this wrapper.\n");
    out.push_str("        if (!interface_) {\n");
    out.push_str(&format!(
        "            static constexpr const char* err_msg = \"{null_iface_msg}\";\n"
    ));
    out.push_str(&format!(
        "            polyplug::check_abi_error(AbiError{{static_cast<uint32_t>(AbiErrorCode::InvalidPointer), StringView{{reinterpret_cast<const uint8_t*>(err_msg), {len}}}}});\n",
        len = null_iface_msg.len()
    ));
    out.push_str("        }\n");

    let out_ptr_expr: &str = if is_void_return {
        out.push_str("        void* out_ptr = nullptr;\n");
        "out_ptr"
    } else {
        out.push_str(&format!("        {} out{{}};\n", return_type));
        out.push_str("        void* out_ptr = &out;\n");
        "out_ptr"
    };

    // Dispatch via the resolved interface, branching on its dispatch type so
    // native and VM-backed guests are both supported (ABI parity with rust.rs).
    out.push_str("        AbiError err{};\n");
    out.push_str("        switch (interface_->dispatch_type) {\n");
    out.push_str("            case DispatchType::Native: {\n");
    // Function-id bounds check against the native dispatch table — emitted
    // inside the Native arm only: on a VM interface `dispatch.native.function_count`
    // aliases bits of `dispatch.vm.call` through the union (garbage). The VM-side
    // loader enforces its own bounds (FunctionNotAvailable). The count lives in
    // `dispatch.native.function_count` — there is no top-level `function_count`
    // field on GuestContractInterface.
    let fn_unavailable_msg: &str = "function not available in interface";
    out.push_str(&format!(
        "                if ({}U >= interface_->dispatch.native.function_count) {{\n",
        fn_id
    ));
    out.push_str(&format!(
        "                    static constexpr const char* err_msg = \"{fn_unavailable_msg}\";\n"
    ));
    out.push_str(&format!(
        "                    polyplug::check_abi_error(AbiError{{static_cast<uint32_t>(AbiErrorCode::FunctionNotAvailable), StringView{{reinterpret_cast<const uint8_t*>(err_msg), {len}}}}});\n",
        len = fn_unavailable_msg.len()
    ));
    out.push_str("                }\n");
    out.push_str(&format!(
        "                auto fn_ = reinterpret_cast<void(*)(GuestContractInstance, const void*, void*, AbiError*)>(interface_->dispatch.native.functions[{}U]);\n",
        fn_id
    ));
    out.push_str("                // SAFETY: instance_ is the token returned by create_instance and is valid.\n");
    out.push_str("                // args_ptr/out_ptr match the ABI contract for this function.\n");
    out.push_str(&format!(
        "                fn_(instance_, args_ptr, {}, &err);\n",
        out_ptr_expr
    ));
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("            case DispatchType::VirtualMachine: {\n");
    // Arena-backed functions hand the guest this caller's per-call arena so it can
    // write variable-size returns without a per-value host->alloc; other functions
    // pass nullptr and the VM bridge falls back to per-value host allocation.
    let arena_arg: &str = if needs_arena { "&arena_" } else { "nullptr" };
    out.push_str(&format!(
        "                (interface_->dispatch.vm.call)(interface_->dispatch.vm.loader_data, instance_, {}U, args_ptr, {}, {}, &err);\n",
        fn_id, out_ptr_expr, arena_arg
    ));
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("        }\n");
    out.push_str("        polyplug::check_abi_error(err);\n");
    if !is_void_return {
        out.push_str("        return out;\n");
    }

    out.push_str("    }\n\n");
    Ok(())
}

/// Build the `args_ptr` preamble lines for a function body.
///
/// Returns the lines (indented 8 spaces) that set up `args_ptr`.
fn build_args_ptr_code(class_name: &str, func: &ResolvedFunction) -> String {
    if func.params.is_empty() {
        // No args — pass nullptr.
        return "        const void* args_ptr = nullptr;\n".to_owned();
    }

    if func.params.len() == 1 {
        let param: &ResolvedParam = &func.params[0];
        match &param.ty {
            ResolvedTypeRef::UserDefined(_) => {
                // User-defined struct: pass pointer directly.
                return format!("        const void* args_ptr = &{};\n", param.name);
            }
            ResolvedTypeRef::Primitive(_) | ResolvedTypeRef::AbiType(_) => {
                // Single primitive: store in local and pass pointer.
                let cpp_ty: String = cpp_type_name(&param.ty);
                return format!(
                    "        const {cpp_ty} local_{name} = {name};\n        const void* args_ptr = &local_{name};\n",
                    cpp_ty = cpp_ty,
                    name = param.name
                );
            }
        }
    }

    // Multiple params: pack into a generated args struct.
    // Capitalise the function name for the struct name.
    let func_name_cap: String = capitalise_first(&func.name);
    let struct_name: String = format!("{}{}{}", class_name, func_name_cap, "Args");

    let mut code: String = String::new();
    // Inline struct definition.
    code.push_str(&format!("        struct {} {{", struct_name));
    for param in &func.params {
        let cpp_ty: String = cpp_type_name(&param.ty);
        code.push_str(&format!(" {} {};", cpp_ty, param.name));
    }
    code.push_str(" };\n");

    // Initialise the struct.
    let field_inits: Vec<String> = func.params.iter().map(|p| p.name.clone()).collect();
    code.push_str(&format!(
        "        {} args_val{{ {} }};\n",
        struct_name,
        field_inits.join(", ")
    ));
    code.push_str("        const void* args_ptr = &args_val;\n");
    code
}

// ─── Utility helpers ──────────────────────────────────────────────────────────

/// Fully qualified C++ spelling for a contract-defined type.
///
/// Every generated file other than `types.hpp` references contract-defined
/// types through this spelling so an unqualified name can never become
/// ambiguous with a global declared by `polyplug/abi.hpp` (e.g. a contract
/// `LogLevel` enum vs the ABI's global `::LogLevel`).
fn qualified_user_type(name: &str) -> String {
    format!("polyplug_generated::{name}")
}

/// C++ type name with contract-defined types fully qualified as
/// `polyplug_generated::<Type>`. Used everywhere except `types.hpp` field
/// emission (see `cpp_types_hpp_type_name`).
/// C++ spelling of an ABI type as used everywhere the raw ABI representation is
/// required: `types.hpp` fields, host trait params/returns, host thunk arguments,
/// and the guest caller's packed arg structs. The ergonomic guest-caller param /
/// return spellings (borrowed `std::string_view` / `std::span`) live in their own
/// functions because they differ from this ABI spelling.
fn cpp_type_name(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::Primitive(p) => p.cpp_name().to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => "StringView".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => "Buffer".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Ptr) => "void*".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Void) => "void".to_owned(),
        ResolvedTypeRef::UserDefined(name) => qualified_user_type(name),
    }
}

/// C++ type name as spelled inside `namespace polyplug_generated` itself
/// (`types.hpp` struct fields only): contract-defined types stay unqualified
/// because they are declared as siblings in the same namespace.
fn cpp_types_hpp_type_name(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::UserDefined(name) => name.clone(),
        ResolvedTypeRef::Primitive(_) | ResolvedTypeRef::AbiType(_) => cpp_type_name(ty),
    }
}

fn contract_name_to_class(name: &str) -> String {
    // Convert "image.decode" -> "ImageDecodeContract"
    name.split('.')
        .map(|p| {
            let mut chars: core::str::Chars<'_> = p.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("")
        + "Contract"
}

/// Convert "test.add" → "TestAddPlugin"
fn contract_name_to_guest_contract_class(name: &str) -> String {
    name.split('.')
        .map(|p| {
            let mut chars: core::str::Chars<'_> = p.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("")
        + "GuestContract"
}

/// Convert "test.add" → "test_add"
fn contract_name_to_lower_snake(name: &str) -> String {
    name.replace('.', "_")
}

/// Convert "test.add" → "TEST_ADD"
fn contract_name_to_upper_snake(name: &str) -> String {
    name.replace('.', "_").to_uppercase()
}

fn capitalise_first(s: &str) -> String {
    let mut chars: core::str::Chars<'_> = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

// ─── Host Contract Trait Generation ───────────────────────────────────────────

/// Convert host contract name to C++ abstract class name.
fn host_contract_name_to_cpp_trait(name: &str) -> String {
    let name_without_prefix: &str = name.strip_prefix("host.").unwrap_or(name);

    let pascal: String = name_without_prefix
        .split('.')
        .map(|p| {
            let mut chars: core::str::Chars<'_> = p.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("");

    if pascal.starts_with("Host") {
        pascal
    } else {
        "Host".to_owned() + &pascal
    }
}

/// Generate the abstract class definition for one host contract.
fn generate_cpp_host_contract_trait(out: &mut String, contract: &ResolvedHostContract) {
    let class_name: String = host_contract_name_to_cpp_trait(&contract.name);
    out.push_str(&format!(
        "/// Host abstract class for contract `{}` (id=0x{:016X})\n",
        contract.name, contract.contract_id
    ));
    out.push_str("/// Hosts implement this class to provide functionality to plugins.\n");
    out.push_str(&format!("class {} {{\npublic:\n", class_name));
    out.push_str(&format!("    virtual ~{}() = default;\n", class_name));

    for func in &contract.functions {
        generate_cpp_host_trait_method(out, func);
    }

    out.push_str("};\n\n");
}

// ─── Guest Host Contract Caller Generation ─────────────────────────────────────

/// Convert host contract name to C++ guest caller class name.
/// e.g. "host.logger" -> "HostLoggerContract", "host.fs.reader" -> "HostFsReaderContract"
fn host_contract_name_to_cpp_caller(name: &str) -> String {
    let name_without_prefix: &str = name.strip_prefix("host.").unwrap_or(name);

    let pascal: String = name_without_prefix
        .split('.')
        .map(|p| {
            let mut chars: core::str::Chars<'_> = p.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("");

    if pascal.starts_with("Host") {
        pascal + "Contract"
    } else {
        "Host".to_owned() + &pascal + "Contract"
    }
}

/// Generate C++ guest-side type name for caller method parameters.
/// For guest callers, we use ergonomic C++ types:
/// - StringView -> std::string_view (borrowed view)
/// - Buffer -> Buffer (ABI type, passed by value)
/// - UserDefined -> const polyplug_generated::TypeName& (passed by const reference)
/// - Primitives -> T (passed by value)
fn cpp_guest_caller_param_type_name(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::Primitive(p) => p.cpp_name().to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => "std::string_view".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => "Buffer".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Ptr) => "void*".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Void) => "void".to_owned(),
        ResolvedTypeRef::UserDefined(name) => format!("const {}&", qualified_user_type(name)),
    }
}

/// Generate C++ guest-side return type name for caller methods.
/// Returns ergonomic borrowed-view types for host-owned memory:
/// - StringView -> std::string_view (borrowed view into host-owned memory)
/// - Buffer -> std::span<const std::uint8_t> (borrowed view into host-owned memory)
/// - UserDefined -> polyplug_generated::TypeName (by value)
/// - Primitives -> T (by value)
fn cpp_guest_caller_return_type_name(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::Primitive(p) => p.cpp_name().to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => "std::string_view".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => "std::span<const std::uint8_t>".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Ptr) => "void*".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Void) => "void".to_owned(),
        ResolvedTypeRef::UserDefined(name) => qualified_user_type(name),
    }
}

/// Generate one guest-side host contract caller class.
fn generate_cpp_guest_host_contract_caller(out: &mut String, contract: &ResolvedHostContract) {
    let class_name: String = host_contract_name_to_cpp_caller(&contract.name);

    out.push_str(&format!(
        "/// Guest caller for host contract `{}` (id=0x{:016X})\n",
        contract.name, contract.contract_id
    ));
    out.push_str("/// Plugins use this class to call host-provided functionality.\n");
    out.push_str(&format!("class {} {{\npublic:\n", class_name));

    // Factory method - from_host
    out.push_str("    /// Factory method - creates caller from HostApi or nullopt if not found.\n");
    out.push_str(&format!(
        "    static std::optional<{}> from_host(const HostApi* host, uint32_t min_version = 0) noexcept {{\n",
        class_name
    ));
    out.push_str("        if (host == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    // Get the instance first
    out.push_str(&format!(
        "        HostContractInstance instance = host->get_host_contract(host, 0x{:016X}ULL, min_version);\n",
        contract.contract_id
    ));
    out.push_str("        if (instance.data == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    // Resolve the interface for dispatch metadata
    out.push_str(&format!(
        "        const HostContractInterface* interface = host->resolve_host_contract_interface(host, 0x{:016X}ULL, min_version);\n",
        contract.contract_id
    ));
    out.push_str("        if (interface == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    out.push_str(&format!(
        "        return {}(host, interface, instance);\n",
        class_name
    ));
    out.push_str("    }\n\n");

    // is_valid method
    out.push_str("    /// Check if caller is valid (interface and instance are non-null).\n");
    out.push_str("    bool is_valid() const noexcept { return interface_ != nullptr && instance_.data != nullptr; }\n\n");

    // Explicit bool conversion
    out.push_str("    /// Explicit bool conversion for validity check.\n");
    out.push_str("    explicit operator bool() const noexcept { return interface_ != nullptr && instance_.data != nullptr; }\n\n");

    // Methods for each function
    for func in &contract.functions {
        generate_cpp_guest_host_contract_method(out, func, &class_name);
    }

    // Private section
    out.push_str("private:\n");
    out.push_str(&format!(
        "    explicit {}(const HostApi* host, const HostContractInterface* interface, HostContractInstance instance) noexcept\n",
        class_name
    ));
    out.push_str("        : host_(host), interface_(interface), instance_(instance) {}\n\n");
    out.push_str("    // Host interface captured in from_host — used for failure logging.\n");
    out.push_str("    // No DSO-global host storage exists; the pointer flows per caller.\n");
    out.push_str("    const HostApi* host_;\n");
    out.push_str("    const HostContractInterface* interface_;\n");
    out.push_str("    HostContractInstance instance_;\n");
    out.push_str("};\n\n");
}

/// Emit the shared `detail::log_call_failure` helper used by guest-side
/// noexcept callers (guest→host and peer) to funnel call failures through the
/// host logging funnel (`HostApi::log`) before returning a default value.
///
/// The emitted text is byte-identical wherever it appears (ODR-clean across
/// translation units) and wrapped in a preprocessor guard so a TU including
/// BOTH generated headers sees exactly one definition.
fn emit_cpp_log_call_failure_helper(out: &mut String) {
    out.push_str("#ifndef POLYPLUG_GENERATED_LOG_CALL_FAILURE\n");
    out.push_str("#define POLYPLUG_GENERATED_LOG_CALL_FAILURE\n");
    out.push_str("namespace detail {\n\n");
    out.push_str("/// Log a failed cross-boundary call through the host logging funnel\n");
    out.push_str("/// (level 1 = Error) before the caller returns its default value.\n");
    out.push_str("inline void log_call_failure(const HostApi* host, const char* scope, const char* what, uint32_t code) noexcept {\n");
    out.push_str("    if (host == nullptr) {\n");
    out.push_str("        return;\n");
    out.push_str("    }\n");
    out.push_str("    char message[96];\n");
    out.push_str("    const int written = std::snprintf(message, sizeof(message), \"%s failed: code=%u\", what, code);\n");
    out.push_str(
        "    const std::size_t length = written > 0 ? static_cast<std::size_t>(written) : 0U;\n",
    );
    out.push_str("    host->log(host, 1U,\n");
    out.push_str(
        "              StringView{reinterpret_cast<const uint8_t*>(scope), std::strlen(scope)},\n",
    );
    out.push_str("              StringView{reinterpret_cast<const uint8_t*>(message), length});\n");
    out.push_str("}\n\n");
    out.push_str("}  // namespace detail\n");
    out.push_str("#endif  // POLYPLUG_GENERATED_LOG_CALL_FAILURE\n\n");
}

/// Generate one method for a guest-side host contract caller.
fn generate_cpp_guest_host_contract_method(
    out: &mut String,
    func: &ResolvedFunction,
    class_name: &str,
) {
    let fn_id: u32 = func.function_id;

    let return_type: String = func
        .returns
        .as_ref()
        .map(cpp_guest_caller_return_type_name)
        .unwrap_or_else(|| "void".to_owned());

    // Build parameter list
    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| format!("{} {}", cpp_guest_caller_param_type_name(&p.ty), p.name))
        .collect();
    let params_str: String = params.join(", ");

    out.push_str(&format!(
        "    /// Call host contract function `{}` (function_id={})\n",
        func.name, fn_id
    ));
    out.push_str(&format!(
        "    {} {}({}) noexcept {{\n",
        return_type, func.name, params_str
    ));

    let what: String = format!("{}.{}", class_name, func.name);
    let default_return: String = if func.returns.is_some() {
        format!("return {}{{}};", return_type)
    } else {
        "return;".to_owned()
    };

    // Null interface check — log the failure through the host funnel before
    // returning the default (the caller is noexcept, so we cannot throw).
    out.push_str("        if (interface_ == nullptr) {\n");
    out.push_str(&format!(
        "            detail::log_call_failure(host_, \"guest.host_caller\", \"{what}\", static_cast<uint32_t>(AbiErrorCode::InvalidPointer));\n"
    ));
    out.push_str(&format!("            {default_return}\n"));
    out.push_str("        }\n\n");

    // Build args_ptr setup
    emit_cpp_guest_host_contract_args_setup(out, func, class_name);

    // Build out_ptr setup
    emit_cpp_guest_host_contract_out_setup(out, &func.returns);

    // Dispatch call
    out.push_str("        AbiError err{};\n");
    out.push_str("        switch (interface_->dispatch_type) {\n");
    out.push_str("            case DispatchType::Native: {\n");
    // Function-id bounds check belongs to the Native arm only: on a VM interface
    // `dispatch.native.function_count` aliases bits of `dispatch.vm.call` through
    // the union. The VM-side loader enforces its own bounds (FunctionNotAvailable).
    out.push_str(&format!(
        "                if ({fn_id}U >= interface_->dispatch.native.function_count) {{\n"
    ));
    out.push_str(&format!(
        "                    detail::log_call_failure(host_, \"guest.host_caller\", \"{what}\", static_cast<uint32_t>(AbiErrorCode::FunctionNotAvailable));\n"
    ));
    out.push_str(&format!("                    {default_return}\n"));
    out.push_str("                }\n");
    out.push_str(&format!(
        "                auto fn_ = reinterpret_cast<void(*)(HostContractInstance, const void*, void*, AbiError*)>(interface_->dispatch.native.functions[{fn_id}U]);\n"
    ));
    out.push_str("                fn_(instance_, args_ptr, out_ptr, &err);\n");
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("            case DispatchType::VirtualMachine: {\n");
    // The vm.call expects a GuestContractInstance; a host contract has no guest
    // instance, so pass a null one (matches rust.rs). The host-contract instance
    // is conveyed to the native thunk via the Native branch, not the VM bridge.
    out.push_str(&format!(
        "                (interface_->dispatch.vm.call)(interface_->dispatch.vm.loader_data, GuestContractInstance{{}}, {fn_id}U, args_ptr, out_ptr, nullptr, &err);\n"
    ));
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("        }\n\n");

    // Error handling — funnel the failure through the host logging funnel
    // (with the error code) before returning the default; the caller is
    // noexcept, so we cannot throw.
    out.push_str("        if (err.code != static_cast<uint32_t>(AbiErrorCode::Ok)) {\n");
    out.push_str(&format!(
        "            detail::log_call_failure(host_, \"guest.host_caller\", \"{what}\", err.code);\n"
    ));
    out.push_str(&format!("            {default_return}\n"));
    out.push_str("        }\n\n");

    // Return result
    if let Some(ret_ty) = &func.returns {
        let expr: String = cpp_guest_caller_return_expr(ret_ty);
        out.push_str(&format!("        return {};\n", expr));
    }

    out.push_str("    }\n\n");
}

/// Emit the args_ptr setup for a C++ guest host contract method.
fn emit_cpp_guest_host_contract_args_setup(
    out: &mut String,
    func: &ResolvedFunction,
    class_name: &str,
) {
    if func.params.is_empty() {
        out.push_str("        const void* args_ptr = nullptr;\n");
        return;
    }

    if func.params.len() == 1 {
        let param: &crate::ir::ResolvedParam = &func.params[0];
        match &param.ty {
            ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => {
                // std::string_view -> StringView conversion
                out.push_str(&format!(
                    "        StringView {}_view{{ reinterpret_cast<const uint8_t*>({}.data()), {}.size() }};\n",
                    param.name, param.name, param.name
                ));
                out.push_str(&format!(
                    "        const void* args_ptr = &{}_view;\n",
                    param.name
                ));
            }
            ResolvedTypeRef::UserDefined(_) => {
                // User-defined struct - pass pointer directly
                out.push_str(&format!(
                    "        const void* args_ptr = &{};\n",
                    param.name
                ));
            }
            ResolvedTypeRef::Primitive(_) | ResolvedTypeRef::AbiType(_) => {
                // Primitive or other ABI type - store in local and pass pointer
                let cpp_ty: String = cpp_type_name(&param.ty);
                out.push_str(&format!(
                    "        const {cpp_ty} local_{name} = {name};\n",
                    cpp_ty = cpp_ty,
                    name = param.name
                ));
                out.push_str(&format!(
                    "        const void* args_ptr = &local_{name};\n",
                    name = param.name
                ));
            }
        }
        return;
    }

    // Multiple params: pack into inline struct
    let func_name_cap: String = capitalise_first(&func.name);
    let struct_name: String = format!("{}{}Args", class_name, func_name_cap);

    out.push_str(&format!("        struct {} {{", struct_name));
    for param in &func.params {
        let cpp_ty: String = cpp_type_name(&param.ty);
        out.push_str(&format!(" {} {};", cpp_ty, param.name));
    }
    out.push_str(" };\n");

    // Initialize struct fields
    let field_inits: Vec<String> = func
        .params
        .iter()
        .map(|p| match &p.ty {
            ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => {
                format!(
                    "StringView{{ reinterpret_cast<const uint8_t*>({}.data()), {}.size() }}",
                    p.name, p.name
                )
            }
            _ => p.name.clone(),
        })
        .collect();

    out.push_str(&format!(
        "        {} args_val{{ {} }};\n",
        struct_name,
        field_inits.join(", ")
    ));
    out.push_str("        const void* args_ptr = &args_val;\n");
}

/// Get the raw ABI type name for the `out` local in a guest caller method.
/// This is always the ABI struct (StringView/Buffer), never the ergonomic view type,
/// because the host writes into this local via the void* out_ptr.
fn cpp_guest_caller_out_local_type_name(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => "StringView".to_owned(),
        ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => "Buffer".to_owned(),
        _ => cpp_guest_caller_return_type_name(ty),
    }
}

/// Build the return expression for a guest caller method given the filled `out` local.
/// For StringView/Buffer, constructs a borrowed view into host-owned memory.
/// For all other types, returns `out` directly.
fn cpp_guest_caller_return_expr(ty: &ResolvedTypeRef) -> String {
    match ty {
        ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => {
            // Borrowed view into host-owned memory, valid until the next call on this caller.
            // A null/empty StringView (ptr=null, len=0) is a legal ABI return; constructing a
            // std::string_view from a null pointer is UB before C++26, so route through the
            // SDK's null-safe polyplug::to_string_view helper.
            "polyplug::to_string_view(out)".to_owned()
        }
        ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => {
            // Borrowed view into host-owned memory, valid until the next call on this caller.
            // A null/empty Buffer (ptr=null, len=0) is a legal ABI return; guard the null
            // pointer explicitly rather than constructing a span from it.
            "out.ptr ? std::span<const std::uint8_t>(out.ptr, out.len) : std::span<const std::uint8_t>{}".to_owned()
        }
        _ => "out".to_owned(),
    }
}

/// Emit the out_ptr setup for a C++ guest host contract method.
/// The `out` local is always the raw ABI type so the host can write into it via void*.
fn emit_cpp_guest_host_contract_out_setup(out: &mut String, returns: &Option<ResolvedTypeRef>) {
    if let Some(ret_ty) = returns {
        let abi_ty: String = cpp_guest_caller_out_local_type_name(ret_ty);
        out.push_str(&format!("        {} out{{}};\n", abi_ty));
        out.push_str("        void* out_ptr = &out;\n");
    } else {
        out.push_str("        void* out_ptr = nullptr;\n");
    }
}

/// Generate all guest-side host contract callers into a single file.
fn generate_cpp_guest_host_contracts_file(ir: &ValidatedIr) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str(
        "// Re-generate with: polyplugc generate --bundle bundle.toml --lang cpp --out <dir>\n",
    );
    out.push_str("#pragma once\n");
    out.push_str("#include \"types.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include \"polyplug/guest.hpp\"\n");
    out.push_str("#include <cstddef>\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include <cstdio>\n");
    out.push_str("#include <cstring>\n");
    out.push_str("#include <optional>\n");
    out.push_str("#include <string_view>\n\n");
    out.push_str("namespace polyplug_plugin {\n\n");
    emit_cpp_log_call_failure_helper(&mut out);

    for contract in &ir.host_contracts {
        generate_cpp_guest_host_contract_caller(&mut out, contract);
    }

    for contract in &ir.host_contracts {
        let class_name: String = host_contract_name_to_cpp_caller(&contract.name);
        let const_name: String = class_name.to_uppercase() + "_ID";
        out.push_str(&format!(
            "/// Contract ID constant for `{}` (FNV-1a of \"host_contract:{}@{}\")\n",
            contract.name, contract.name, contract.version.major
        ));
        out.push_str(&format!(
            "constexpr uint64_t {} = 0x{:016X}ULL;\n\n",
            const_name, contract.contract_id
        ));
    }

    out.push_str("}  // namespace polyplug_plugin\n");
    out
}

/// Generate one pure virtual method for a host contract function.
fn generate_cpp_host_trait_method(out: &mut String, func: &ResolvedFunction) {
    let return_type: String = func
        .returns
        .as_ref()
        .map(cpp_type_name)
        .unwrap_or_else(|| "void".to_owned());

    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| {
            let cpp_ty: String = cpp_type_name(&p.ty);
            match &p.ty {
                ResolvedTypeRef::UserDefined(_) => format!("const {}& {}", cpp_ty, p.name),
                ResolvedTypeRef::AbiType(_) => format!("{} {}", cpp_ty, p.name),
                ResolvedTypeRef::Primitive(_) => format!("{} {}", cpp_ty, p.name),
            }
        })
        .collect();
    let params_str: String = params.join(", ");

    out.push_str(&format!(
        "    virtual {} {}({}) = 0;\n",
        return_type, func.name, params_str
    ));
}

/// Generate all host contract traits into a single file.
fn generate_cpp_host_contracts_file(ir: &ValidatedIr) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"types.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include <cstdint>\n\n");
    out.push_str("namespace polyplug_host {\n\n");

    for contract in &ir.host_contracts {
        generate_cpp_host_contract_trait(&mut out, contract);
    }

    for contract in &ir.host_contracts {
        let trait_name: String = host_contract_name_to_cpp_trait(&contract.name);
        let const_name: String = trait_name.to_uppercase() + "_CONTRACT_ID";
        out.push_str(&format!(
            "/// Contract ID constant for `{}` (FNV-1a of \"host_contract:{}@{}\")\n",
            contract.name, contract.name, contract.version.major
        ));
        out.push_str(&format!(
            "constexpr uint64_t {} = 0x{:016X}ULL;\n\n",
            const_name, contract.contract_id
        ));
    }

    out.push_str("}  // namespace polyplug_host\n");
    out
}

// ─── Host Interface Factories Generation ─────────────────────────────────────────

/// Generate all host-side interface factories into a single file.
fn generate_cpp_host_interface_factories_file(ir: &ValidatedIr) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str("// Re-generate with: polyplugc generate --api api.toml --lang cpp --out <dir>\n");
    out.push_str("#pragma once\n");
    out.push_str("#include \"host_contracts.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include <memory>\n\n");
    out.push_str("namespace polyplug_host {\n\n");

    for contract in &ir.host_contracts {
        generate_cpp_host_interface_factory(&mut out, contract);
    }

    out.push_str("}  // namespace polyplug_host\n");
    out
}

/// Generate interface factories for one host contract.
fn generate_cpp_host_interface_factory(out: &mut String, contract: &ResolvedHostContract) {
    let trait_name: String = host_contract_name_to_cpp_trait(&contract.name);
    let factory_name: String = format!(
        "create_{}_interface",
        contract.name.replace('.', "_").to_lowercase()
    );
    let factory_vm_name: String = format!(
        "create_{}_interface_vm",
        contract.name.replace('.', "_").to_lowercase()
    );
    let fn_count: usize = contract.functions.len();
    let contract_id: u64 = contract.contract_id;
    let major: u32 = contract.version.major;
    let minor: u32 = contract.version.minor;
    let patch: u32 = contract.version.patch;
    let singleton: bool = contract.singleton;

    // NATIVE dispatch factory
    out.push_str(&format!(
        "/// Create a host contract interface for `{}` with NATIVE dispatch.\n",
        contract.name
    ));
    out.push_str("///\n");
    out.push_str("/// Takes ownership of the implementation and creates a 'static interface.\n");
    out.push_str("/// The implementation must inherit from the abstract class.\n");
    out.push_str("///\n");
    out.push_str("/// # Memory\n");
    out.push_str("/// The returned interface pointer is valid for the lifetime of the program.\n");
    out.push_str("/// The implementation unique_ptr is released and managed internally.\n");
    out.push_str("template<typename T>\n");
    out.push_str(&format!(
        "const HostContractInterface* {}(std::unique_ptr<T> impl) noexcept {{\n",
        factory_name
    ));
    out.push_str("    T* impl_ptr = impl.release();\n\n");

    // Generate thunks for each function
    for func in &contract.functions {
        generate_cpp_host_thunk(out, func, &contract.name, &trait_name);
    }

    // Static function pointer array. NativeDispatch::functions is `void* const*`,
    // so the thunk lambdas are stored as type-erased `void*` (matching the guest
    // interfaces.hpp pattern) and reinterpreted at the dispatch site.
    out.push_str(&format!(
        "    static void* const FUNCTIONS[{}] = {{\n",
        fn_count
    ));
    for func in &contract.functions {
        let thunk_name: String = format!(
            "{}_{}_thunk",
            contract.name.replace('.', "_").to_lowercase(),
            func.name
        );
        out.push_str(&format!(
            "        reinterpret_cast<void*>({}),\n",
            thunk_name
        ));
    }
    out.push_str("    };\n\n");

    // create_instance stub for host-side factory (captureless lambda → fn ptr).
    out.push_str("    // create_instance stub - host owns the singleton instance lifecycle\n");
    out.push_str(
        "    static constexpr HostContractInterface_create_instance_fn create_instance_stub =\n",
    );
    out.push_str(
        "        +[](const HostContractInterface* self, const void* /*args*/, HostContractInstance* out_instance) noexcept -> void {\n",
    );
    out.push_str("        if (out_instance == nullptr) return;\n");
    out.push_str("        // Write the registrant-owned user_data as the instance; the thunks\n");
    out.push_str("        // recover the implementation from it (no mutable static state — the\n");
    out.push_str("        // interface itself is heap-allocated per factory call).\n");
    out.push_str("        *out_instance = HostContractInstance{self->user_data};\n");
    out.push_str("    };\n\n");

    // destroy_instance stub for host-side factory (captureless lambda → fn ptr).
    out.push_str("    // destroy_instance stub - host owns the singleton instance lifecycle\n");
    out.push_str(
        "    static constexpr HostContractInterface_destroy_instance_fn destroy_instance_stub =\n",
    );
    out.push_str("        +[](const HostContractInterface* /*this*/, HostContractInstance /*instance*/) noexcept -> void {\n");
    if singleton {
        out.push_str(
            "        // Singleton: no-op, the implementation lives for program lifetime\n",
        );
    } else {
        out.push_str(
            "        // Multi-instance: not supported in host-side factory, use custom factory\n",
        );
    }
    out.push_str("    };\n\n");

    // Heap-allocated interface, intentionally leaked (Box::leak semantics): the
    // registered interface must stay valid for the program lifetime, and a fresh
    // allocation per call keeps the factory re-entrant — a `static` here would
    // silently alias every registration after the first onto the first impl.
    out.push_str("    auto* iface = new HostContractInterface{\n");
    out.push_str(&format!(
        "        0x{contract_id:016X}ULL,  // contract_id\n"
    ));
    out.push_str(&format!(
        "        Version{{{major}U, {minor}U, {patch}U}},  // contract_version\n"
    ));
    out.push_str(&format!("        {},  // singleton\n", singleton));
    out.push_str("        DispatchType::Native,  // dispatch_type\n");
    out.push_str("        nullptr,  // runtime (set by polyplug during registration)\n");
    out.push_str("        nullptr,  // user_data (set below to the registrant-owned impl)\n");
    out.push_str("        create_instance_stub,  // create_instance\n");
    out.push_str("        destroy_instance_stub,  // destroy_instance\n");
    out.push_str("        DispatchMechanisms{ .native = NativeDispatch{\n");
    out.push_str(&format!("            {fn_count}U,  // function_count\n"));
    out.push_str("            FUNCTIONS,  // functions\n");
    out.push_str("        } },  // dispatch.native\n");
    out.push_str("    };  // dispatch\n\n");
    out.push_str(
        "    // Route the implementation through user_data; create_instance reads it via `this`.\n",
    );
    out.push_str("    iface->user_data = static_cast<void*>(impl_ptr);\n");
    out.push_str("    return iface;\n");
    out.push_str("}\n\n");

    // VM dispatch factory
    out.push_str(&format!(
        "/// Create a host contract interface for `{}` with VM dispatch.\n",
        contract.name
    ));
    out.push_str("///\n");
    out.push_str("/// Used when the host implementation is in a VM language (Python, Lua, JS).\n");
    out.push_str("///\n");
    out.push_str("/// # Arguments\n");
    out.push_str("/// * `loader_data` - Opaque pointer to VM-specific data\n");
    out.push_str("/// * `dispatch_fn` - Function to call for each contract function\n");
    out.push_str("///\n");
    out.push_str("/// # Memory\n");
    out.push_str("/// The returned interface pointer is valid for the lifetime of the program.\n");
    out.push_str(&format!(
        "const HostContractInterface* {}(\n",
        factory_vm_name
    ));
    out.push_str("    void* loader_data,\n");
    out.push_str("    VmDispatch_call_fn dispatch_fn\n");
    out.push_str(") noexcept {\n");

    // create_instance stub for VM factory (captureless lambda → fn ptr).
    out.push_str("    // create_instance stub - VM loader owns instance lifecycle\n");
    out.push_str(
        "    static constexpr HostContractInterface_create_instance_fn vm_create_instance_stub =\n",
    );
    out.push_str(
        "        +[](const HostContractInterface* /*this*/, const void* /*args*/, HostContractInstance* out_instance) noexcept -> void {\n",
    );
    out.push_str("        if (out_instance == nullptr) return;\n");
    out.push_str("        // VM dispatch: instance managed by VM loader, write placeholder\n");
    out.push_str("        *out_instance = HostContractInstance{nullptr};\n");
    out.push_str("    };\n\n");

    // destroy_instance stub for VM factory (captureless lambda → fn ptr).
    out.push_str("    // destroy_instance stub - VM loader owns instance lifecycle\n");
    out.push_str("    static constexpr HostContractInterface_destroy_instance_fn vm_destroy_instance_stub =\n");
    out.push_str("        +[](const HostContractInterface* /*this*/, HostContractInstance /*instance*/) noexcept -> void {\n");
    out.push_str("        // VM dispatch: instance managed by VM loader, no-op here\n");
    out.push_str("    };\n\n");

    // Heap-allocated interface, intentionally leaked (Box::leak semantics): a
    // `static` local here would bind to the FIRST call's `loader_data` /
    // `dispatch_fn` forever and silently alias every later registration.
    out.push_str("    auto* iface = new HostContractInterface{\n");
    out.push_str(&format!(
        "        0x{contract_id:016X}ULL,  // contract_id\n"
    ));
    out.push_str(&format!(
        "        Version{{{major}U, {minor}U, {patch}U}},  // contract_version\n"
    ));
    out.push_str(&format!("        {},  // singleton\n", singleton));
    out.push_str("        DispatchType::VirtualMachine,  // dispatch_type\n");
    out.push_str("        nullptr,  // runtime (set by polyplug during registration)\n");
    out.push_str("        loader_data,  // user_data (registrant-owned VM bridge data)\n");
    out.push_str("        vm_create_instance_stub,  // create_instance\n");
    out.push_str("        vm_destroy_instance_stub,  // destroy_instance\n");
    // `dispatch` is a union; the VM variant is not the first member, so it must
    // be set via a designated initializer. `loader_data` is a VmLoaderData.
    out.push_str("        DispatchMechanisms{ .vm = VmDispatch{\n");
    out.push_str("            dispatch_fn,  // call\n");
    out.push_str("            VmLoaderData{loader_data},  // loader_data\n");
    out.push_str("        } },  // dispatch.vm\n");
    out.push_str("    };  // dispatch\n");
    out.push_str("    return iface;\n");
    out.push_str("}\n\n");
}

/// Generate a thunk function for a host contract function.
fn generate_cpp_host_thunk(
    out: &mut String,
    func: &ResolvedFunction,
    contract_name: &str,
    trait_name: &str,
) {
    let thunk_name: String = format!(
        "{}_{}_thunk",
        contract_name.replace('.', "_").to_lowercase(),
        func.name
    );
    let has_return: bool = func.returns.is_some();

    // Emit the thunk as a captureless lambda. C++ forbids defining a named
    // function inside another function body, but a captureless lambda decays to
    // a plain function pointer. The implementation is recovered from the instance
    // token, which create_instance sets from the interface's user_data (no static).
    out.push_str(&format!(
        "    static constexpr auto {} = +[](HostContractInstance instance, const void* args, void* out, AbiError* out_err) noexcept -> void {{\n",
        thunk_name
    ));
    out.push_str(&format!(
        "        auto* impl = static_cast<{}*>(instance.data);\n",
        trait_name
    ));
    out.push_str("        if (impl == nullptr) {\n");
    out.push_str("            *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Panic), StringView{nullptr, 0}};\n");
    out.push_str("            return;\n");
    out.push_str("        }\n");
    out.push_str("        try {\n");

    // Generate argument extraction
    if !func.params.is_empty() {
        generate_cpp_host_thunk_args(out, func);
    } else {
        out.push_str("            (void)args;\n");
    }

    // Generate the trait method call
    generate_cpp_host_thunk_call(out, func, has_return);

    // Handle return value
    if has_return {
        let ret_ty: String = func
            .returns
            .as_ref()
            .map(cpp_type_name)
            .unwrap_or_else(|| "void".to_owned());
        out.push_str(&format!(
            "            *static_cast<{}*>(out) = result;\n",
            ret_ty
        ));
    } else {
        out.push_str("            (void)out;\n");
    }

    out.push_str("            *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Ok), StringView{nullptr, 0}};\n");
    out.push_str("        } catch (...) {\n");
    out.push_str("            *out_err = AbiError{static_cast<uint32_t>(AbiErrorCode::Panic), StringView{nullptr, 0}};\n");
    out.push_str("        }\n");
    out.push_str("    };\n\n");
}

/// Generate argument extraction for a host thunk.
fn generate_cpp_host_thunk_args(out: &mut String, func: &ResolvedFunction) {
    if func.params.len() == 1 {
        let param: &crate::ir::ResolvedParam = &func.params[0];
        let ty_name: String = cpp_type_name(&param.ty);
        match &param.ty {
            ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => {
                // Pass the raw StringView through to the impl: the generated
                // abstract method takes StringView (rule 9 — UTF-8 boundary).
                out.push_str(&format!(
                    "            StringView {} = *static_cast<const StringView*>(args);\n",
                    param.name
                ));
            }
            ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => {
                out.push_str(&format!(
                    "            Buffer {}_buf = *static_cast<const Buffer*>(args);\n",
                    param.name
                ));
                out.push_str(&format!(
                    "            (void){}_buf;  // Buffer handling depends on use case\n",
                    param.name
                ));
            }
            ResolvedTypeRef::UserDefined(_) => {
                out.push_str(&format!(
                    "            const {}& {} = *static_cast<const {}*>(args);\n",
                    ty_name, param.name, ty_name
                ));
            }
            _ => {
                out.push_str(&format!(
                    "            {} {} = *static_cast<const {}*>(args);\n",
                    ty_name, param.name, ty_name
                ));
            }
        }
    } else {
        // Multiple params - use arg-pack struct
        let pack_struct: String = format!("{}Args", func.name.to_uppercase());
        out.push_str(&format!("            struct {} {{\n", pack_struct));
        for param in &func.params {
            let cpp_ty: String = cpp_type_name(&param.ty);
            out.push_str(&format!("                {} {};\n", cpp_ty, param.name));
        }
        out.push_str("            };\n");
        out.push_str(&format!(
            "            const {}* packed = static_cast<const {}*>(args);\n",
            pack_struct, pack_struct
        ));
        // Extract each param from the packed struct
        for param in &func.params {
            match &param.ty {
                ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => {
                    // Pass the raw StringView through to the impl (rule 9).
                    out.push_str(&format!(
                        "            StringView {} = packed->{};\n",
                        param.name, param.name
                    ));
                }
                ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => {
                    out.push_str(&format!(
                        "            Buffer {} = packed->{}; (void){};\n",
                        param.name, param.name, param.name
                    ));
                }
                _ => {
                    let cpp_ty: String = cpp_type_name(&param.ty);
                    out.push_str(&format!(
                        "            {} {} = packed->{};\n",
                        cpp_ty, param.name, param.name
                    ));
                }
            }
        }
    }
}

/// Generate the trait method call inside a host thunk.
fn generate_cpp_host_thunk_call(out: &mut String, func: &ResolvedFunction, has_return: bool) {
    let call_args: String = if func.params.is_empty() {
        String::new()
    } else if func.params.len() == 1 {
        let param: &crate::ir::ResolvedParam = &func.params[0];
        match &param.ty {
            ResolvedTypeRef::AbiType(AbiBuiltin::StringView) => param.name.clone(),
            ResolvedTypeRef::AbiType(AbiBuiltin::Buffer) => param.name.clone(),
            ResolvedTypeRef::UserDefined(_) => param.name.clone(),
            _ => param.name.clone(),
        }
    } else {
        func.params
            .iter()
            .map(|p| p.name.clone())
            .collect::<Vec<_>>()
            .join(", ")
    };

    if has_return {
        let ret_ty: String = func
            .returns
            .as_ref()
            .map(cpp_type_name)
            .unwrap_or_else(|| "void".to_owned());
        out.push_str(&format!(
            "            {} result = impl->{}({});\n",
            ret_ty, func.name, call_args
        ));
    } else {
        out.push_str(&format!(
            "            impl->{}({});\n",
            func.name, call_args
        ));
    }
}

// Suppress unused import warning
const _: fn() = || {
    let _ = cpp_type_name(&ResolvedTypeRef::Primitive(PrimitiveType::U8));
};

// ─── Peer caller collection helpers ──────────────────────────────────────────

// ─── Peer callers file generator ─────────────────────────────────────────────

/// Generate the full `guest/peer_callers.hpp` file for all peer contracts.
fn generate_cpp_peer_callers_file(ir: &ValidatedIr, peers: &[&ResolvedContract]) -> String {
    let mut out: String = String::new();
    out.push_str(CPP_FILE_HEADER);
    out.push_str(
        "// Re-generate with: polyplugc generate --bundle bundle.toml --lang cpp --out <dir>\n",
    );
    out.push_str("#pragma once\n");
    out.push_str("#include \"types.hpp\"\n");
    out.push_str("#include \"polyplug/guest.hpp\"\n");
    out.push_str("#include \"polyplug/abi.hpp\"\n");
    out.push_str("#include <array>\n");
    out.push_str("#include <atomic>\n");
    out.push_str("#include <cstddef>\n");
    out.push_str("#include <cstdint>\n");
    out.push_str("#include <cstdio>\n");
    out.push_str("#include <cstring>\n");
    out.push_str("#include <memory>\n");
    out.push_str("#include <optional>\n\n");
    out.push_str("namespace polyplug_plugin {\n\n");
    emit_cpp_log_call_failure_helper(&mut out);
    emit_cpp_revision_helper(&mut out);

    // Emit arena helpers only when at least one peer contract needs the arena.
    let any_needs_arena: bool = peers
        .iter()
        .any(|c: &&ResolvedContract| contract_needs_arena(c));
    if any_needs_arena {
        emit_cpp_call_arena_helpers(&mut out);
    }

    for contract in peers {
        let min_ver: u32 = peer_min_version(ir, contract.contract_id);
        generate_cpp_peer_caller(&mut out, contract, min_ver);
    }

    out.push_str("}  // namespace polyplug_plugin\n");
    out
}

/// Generate one `…Peer` class for a single peer guest contract.
///
/// The class mirrors the host caller (`generate_cpp_host_contract`) with two
/// differences:
/// 1. The factory (`resolve(host)`) takes the per-instance `HostApi*` (the
///    author-factory parameter / instance payload — no DSO-global storage),
///    then calls `find_guest_contract` / `resolve_guest_contract` /
///    `create_instance`.
/// 2. Per-method dispatch goes DIRECTLY through the cached interface (branch on
///    `dispatch_type`; Native indexes `dispatch.native.functions`, VM calls
///    `dispatch.vm.call`) — the same path as the host->guest caller, never a
///    host-mediated round-trip.
fn generate_cpp_peer_caller(out: &mut String, contract: &ResolvedContract, min_version: u32) {
    let class_name: String = format!("{}Peer", contract_name_to_class(&contract.name));
    let needs_arena: bool = contract_needs_arena(contract);

    out.push_str(&format!(
        "/// Peer caller for guest contract `{}` (id=0x{:016X})\n",
        contract.name, contract.contract_id
    ));
    out.push_str("///\n");
    out.push_str(
        "/// Dispatches directly through the cached peer interface — the same near-bare-metal\n",
    );
    out.push_str(
        "/// path as the host->guest caller; no host-mediated round-trip, no per-call registry\n",
    );
    out.push_str(
        "/// resolve, no epoch pin. The declared dependency keeps the peer alive; a hot-reload\n",
    );
    out.push_str("/// is caught by the cached revision counter.\n");
    out.push_str("/// Use `resolve(host)` to obtain an instance; returns `std::nullopt` when\n");
    out.push_str("/// the contract is not registered or the host interface is null.\n");
    if needs_arena {
        out.push_str("///\n");
        out.push_str("/// # Call-arena lifetime\n");
        out.push_str("///\n");
        out.push_str(
            "/// Methods returning variable-size values (`StringView`, `Buffer`, or structs\n",
        );
        out.push_str(
            "/// that may embed one) are non-const and reset this caller's arena at the start\n",
        );
        out.push_str(
            "/// of the call. Any view returned by such a method borrows arena memory and is\n",
        );
        out.push_str("/// valid only until the next arena-backed call on the same caller.\n");
    }
    out.push_str(&format!("class {} {{\npublic:\n", class_name));

    // ── resolve(host) factory ───────────────────────────────────────────────
    out.push_str("    /// Discover and resolve the peer contract through the host.\n");
    out.push_str("    ///\n");
    out.push_str("    /// `host` is the per-instance HostApi pointer handed to the author\n");
    out.push_str("    /// factory (`polyplug_create_<plugin>`) — no DSO-global host exists.\n");
    out.push_str("    ///\n");
    out.push_str("    /// Returns `std::nullopt` if the host interface is null, the contract\n");
    out.push_str("    /// is not registered, or `resolve_guest_contract` returns null.\n");
    out.push_str(&format!(
        "    static std::optional<{}> resolve(const HostApi* host) noexcept {{\n",
        class_name
    ));
    out.push_str("        if (host == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    out.push_str(&format!(
        "        GuestContractHandle handle = host->find_guest_contract(host, 0x{:016X}ULL, {}U);\n",
        contract.contract_id, min_version
    ));
    out.push_str("        // Pass the handle straight to resolve_guest_contract; it rejects\n");
    out.push_str("        // stale/invalid handles and returns nullptr — do not inspect fields.\n");
    out.push_str(
        "        const GuestContractInterface* iface = host->resolve_guest_contract(host, handle);\n",
    );
    out.push_str("        if (iface == nullptr) {\n");
    out.push_str("            return std::nullopt;\n");
    out.push_str("        }\n");
    out.push_str("        // A null `instance.data` is valid: stateless contracts return a null\n");
    out.push_str(
        "        // handle from `create_instance` and use it as an opaque dispatch token.\n",
    );
    out.push_str(
        "        // Route creation through the host so the runtime tracks the instance.\n",
    );
    out.push_str(
        "        GuestContractInstance instance{};\n        host->create_guest_instance(host, iface, nullptr, &instance);\n",
    );
    out.push_str(
        "        // Fetch the registry revision counter ONCE, then read its current value, so\n",
    );
    out.push_str(
        "        // every later call can detect a reload/unload with a direct atomic load and\n",
    );
    out.push_str("        // re-resolve before dispatching.\n");
    out.push_str("        const uint64_t* revision_ptr = host->revision_counter(host);\n");
    out.push_str(
        "        const uint64_t cached_revision = polyplug_load_revision(revision_ptr);\n",
    );
    out.push_str(&format!(
        "        return {}(iface, instance, host, handle, revision_ptr, cached_revision);\n",
        class_name
    ));
    out.push_str("    }\n\n");

    // ── Destructor ──────────────────────────────────────────────────────────
    out.push_str("    /// Destructor - calls `destroy_instance` to clean up.\n");
    out.push_str(&format!("    ~{}() noexcept {{\n", class_name));
    if needs_arena {
        out.push_str(
            "        // Free any overflow blocks the arena still holds before destruction.\n",
        );
        out.push_str("        // arena_buf_ is null only on a moved-from caller.\n");
        out.push_str("        if (arena_buf_) {\n");
        out.push_str("            polyplug_arena_reset(&arena_);\n");
        out.push_str("        }\n");
    }
    out.push_str(
        "        // If the registry changed since we resolved, the cached interface and\n",
    );
    out.push_str(
        "        // instance are stale — a reload/unload reclaimed their backing — so calling\n",
    );
    out.push_str(
        "        // the dead interface's destroy would be UB; the reload/unload already\n",
    );
    out.push_str("        // reclaimed the instance, so skip the destroy entirely.\n");
    out.push_str("        if (polyplug_load_revision(revision_ptr_) != cached_revision_) {\n");
    out.push_str("            return;\n");
    out.push_str("        }\n");
    out.push_str(
        "        // SAFETY: instance was created by create_instance on the resolved interface.\n",
    );
    out.push_str("        // We guard on instance.data to skip the call for stateless (null-data) contracts.\n");
    out.push_str("        if (instance_.data != nullptr) {\n");
    out.push_str("            host_->destroy_guest_instance(host_, iface_, instance_);\n");
    out.push_str("            instance_.data = nullptr;  // Prevent reuse after cleanup.\n");
    out.push_str("        }\n");
    out.push_str("    }\n\n");

    // ── Move-only ───────────────────────────────────────────────────────────
    out.push_str("    // Move-only (instance handles are unique)\n");
    out.push_str(&format!(
        "    {}({}&& other) noexcept\n",
        class_name, class_name
    ));
    out.push_str("        : iface_(other.iface_),\n");
    out.push_str("          instance_(other.instance_),\n");
    out.push_str("          host_(other.host_),\n");
    out.push_str("          handle_(other.handle_),\n");
    out.push_str("          revision_ptr_(other.revision_ptr_),\n");
    if needs_arena {
        out.push_str("          cached_revision_(other.cached_revision_),\n");
        out.push_str("          arena_buf_(std::move(other.arena_buf_)),\n");
        out.push_str("          arena_(other.arena_) {\n");
    } else {
        out.push_str("          cached_revision_(other.cached_revision_) {\n");
    }
    out.push_str("        other.instance_.data = nullptr;  // Prevent double-destroy.\n");
    out.push_str("    }\n");
    out.push_str(&format!(
        "    {}& operator=({}&& other) noexcept {{\n",
        class_name, class_name
    ));
    out.push_str("        if (this != &other) {\n");
    if needs_arena {
        out.push_str("            if (arena_buf_) {\n");
        out.push_str("                polyplug_arena_reset(&arena_);\n");
        out.push_str("            }\n");
    }
    out.push_str(
        "            // Destroy current instance first — but only if the registry has not\n",
    );
    out.push_str(
        "            // changed under us; a reload/unload already reclaimed a stale instance.\n",
    );
    out.push_str("            if (instance_.data != nullptr && polyplug_load_revision(revision_ptr_) == cached_revision_) {\n");
    out.push_str("                host_->destroy_guest_instance(host_, iface_, instance_);\n");
    out.push_str("            }\n");
    out.push_str(
        "            iface_ = other.iface_; instance_ = other.instance_; host_ = other.host_; other.instance_.data = nullptr;\n",
    );
    out.push_str("            handle_ = other.handle_; revision_ptr_ = other.revision_ptr_; cached_revision_ = other.cached_revision_;\n");
    if needs_arena {
        out.push_str(
            "            arena_buf_ = std::move(other.arena_buf_); arena_ = other.arena_;\n",
        );
    }
    out.push_str("        }\n");
    out.push_str("        return *this;\n");
    out.push_str("    }\n");
    out.push_str(&format!(
        "    {}(const {}&) = delete;\n",
        class_name, class_name
    ));
    out.push_str(&format!(
        "    {}& operator=(const {}&) = delete;\n\n",
        class_name, class_name
    ));

    // ── Validity checks ─────────────────────────────────────────────────────
    out.push_str("    /// Check if this peer holds a resolved (non-null) interface.\n");
    out.push_str("    /// Keys off the interface pointer, not `instance_.data`: stateless\n");
    out.push_str(
        "    /// contracts legitimately use a null instance as an opaque dispatch token.\n",
    );
    out.push_str("    explicit operator bool() const noexcept { return iface_ != nullptr; }\n\n");
    out.push_str("    /// Check if this peer holds a resolved (non-null) interface.\n");
    out.push_str("    bool is_valid() const noexcept { return iface_ != nullptr; }\n\n");

    // ── Per-method peer callers ─────────────────────────────────────────────
    for func in &contract.functions {
        generate_cpp_peer_fn_caller(out, &class_name, func);
    }

    // ── Private members, helpers, and constructor ───────────────────────────
    out.push_str("private:\n");

    // Re-resolve the cached peer interface after the registry changed under us.
    out.push_str(
        "    /// Re-resolve the cached peer interface after the registry changed under us.\n",
    );
    out.push_str("    ///\n");
    out.push_str(
        "    /// A hot-reload swapped a new interface into the same slot, so the retained\n",
    );
    out.push_str(
        "    /// handle still resolves — to the new interface; an unload vacated the slot,\n",
    );
    out.push_str("    /// so it resolves to null and `false` is returned (the peer is gone).\n");
    out.push_str("    ///\n");
    out.push_str("    /// The old instance is ABANDONED, never destroyed: after a reload its\n");
    out.push_str(
        "    /// interface and the guest state it created are already epoch-reclaimed, so\n",
    );
    out.push_str("    /// calling the dead interface's destroy would be UB. Dispatch then goes\n");
    out.push_str("    /// straight through the freshly resolved interface pointer.\n");
    out.push_str("    bool revalidate() noexcept {\n");
    out.push_str("        if (host_ == nullptr) {\n");
    out.push_str("            return false;\n");
    out.push_str("        }\n");
    out.push_str("        const GuestContractInterface* iface = host_->resolve_guest_contract(host_, handle_);\n");
    out.push_str("        if (iface == nullptr) {\n");
    out.push_str("            return false;\n");
    out.push_str("        }\n");
    out.push_str("        GuestContractInstance inst{};\n");
    out.push_str("        host_->create_guest_instance(host_, iface, nullptr, &inst);\n");
    out.push_str("        iface_ = iface;\n");
    out.push_str("        instance_ = inst;\n");
    out.push_str("        cached_revision_ = polyplug_load_revision(revision_ptr_);\n");
    out.push_str("        return true;\n");
    out.push_str("    }\n\n");

    out.push_str("    /// Resolved interface pointer for the peer contract.\n");
    out.push_str("    const GuestContractInterface* iface_;\n");
    out.push_str("    /// Instance handle created from the peer interface.\n");
    out.push_str("    GuestContractInstance instance_;\n");
    out.push_str(
        "    /// Host interface pointer used for instance lifecycle (create/destroy) and\n    /// re-resolve — NOT for dispatch, which goes straight through the interface.\n",
    );
    out.push_str("    const HostApi* host_;\n");
    out.push_str(
        "    /// Peer contract handle, retained so the cache can re-resolve after a hot-reload\n",
    );
    out.push_str(
        "    /// (which swaps a new interface into the same slot) or report a gone contract.\n",
    );
    out.push_str("    GuestContractHandle handle_;\n");
    out.push_str("    /// Pointer to the runtime's registry revision counter, fetched once via\n");
    out.push_str(
        "    /// `HostApi.revision_counter`. Polled before each dispatch (one atomic load,\n",
    );
    out.push_str("    /// no call into the runtime); null when there is no runtime.\n");
    out.push_str("    const uint64_t* revision_ptr_;\n");
    out.push_str(
        "    /// Revision value read when the peer was resolved. Compared before each dispatch\n",
    );
    out.push_str(
        "    /// against the live counter to detect a reload/unload and re-resolve, so the\n",
    );
    out.push_str("    /// cached interface pointer and instance never dangle.\n");
    out.push_str("    uint64_t cached_revision_;\n");
    if needs_arena {
        out.push_str(
            "    /// Stable-address backing buffer for the per-call arena. Held by unique_ptr\n",
        );
        out.push_str("    /// so the arena's interior pointers survive moving the caller value.\n");
        out.push_str("    std::unique_ptr<std::array<uint8_t, CALL_ARENA_BUF_LEN>> arena_buf_;\n");
        out.push_str(
            "    /// Per-call bump arena over `arena_buf_`, reset at each arena-backed call.\n",
        );
        out.push_str("    CallArena arena_;\n");
    }
    out.push('\n');
    if needs_arena {
        out.push_str(&format!(
            "    explicit {}(const GuestContractInterface* iface, GuestContractInstance inst, const HostApi* host, GuestContractHandle handle, const uint64_t* revision_ptr, uint64_t cached_revision)\n",
            class_name
        ));
        out.push_str("        : iface_(iface), instance_(inst), host_(host), handle_(handle), revision_ptr_(revision_ptr), cached_revision_(cached_revision),\n");
        out.push_str(
            "          arena_buf_(std::make_unique<std::array<uint8_t, CALL_ARENA_BUF_LEN>>()),\n",
        );
        out.push_str(
            "          arena_(polyplug_arena_new(arena_buf_->data(), CALL_ARENA_BUF_LEN, host)) {}\n",
        );
    } else {
        out.push_str(&format!(
            "    explicit {}(const GuestContractInterface* iface, GuestContractInstance inst, const HostApi* host, GuestContractHandle handle, const uint64_t* revision_ptr, uint64_t cached_revision) noexcept\n",
            class_name
        ));
        out.push_str("        : iface_(iface), instance_(inst), host_(host), handle_(handle), revision_ptr_(revision_ptr), cached_revision_(cached_revision) {}\n");
    }
    out.push_str("};\n\n");
}

/// Generate one per-method peer caller body.
///
/// Dispatches directly through the cached peer interface — the same near-bare-metal
/// path as the host->guest caller; no host-mediated round-trip, no per-call registry
/// resolve, no epoch pin. The declared dependency keeps the peer alive; a hot-reload
/// is caught by the cached revision counter (which re-resolves the interface).
/// Marshalling is identical to the host caller (`generate_cpp_host_function`):
/// raw ABI types (StringView/Buffer) are returned; variable-size returns reset
/// and pass the caller's arena; the dispatch switch branches on `dispatch_type`
/// (Native indexes `dispatch.native.functions`, VM calls `dispatch.vm.call`).
fn generate_cpp_peer_fn_caller(out: &mut String, class_name: &str, func: &ResolvedFunction) {
    let fn_id: u32 = func.function_id;
    let needs_arena: bool = fn_needs_arena(func);

    let return_type: String = func
        .returns
        .as_ref()
        .map(cpp_type_name)
        .unwrap_or_else(|| "void".to_owned());

    let params: Vec<String> = func
        .params
        .iter()
        .map(|p| format!("{} {}", cpp_type_name(&p.ty), p.name))
        .collect();
    let params_str: String = params.join(", ");

    // Not const: the per-call staleness check may invoke revalidate(), which
    // re-resolves the interface/instance and updates the cached revision.
    let self_qual: &str = "";

    out.push_str(&format!(
        "    /// Call peer function `{}` (function_id={}) via direct interface dispatch.\n",
        func.name, fn_id
    ));
    if needs_arena {
        out.push_str(
            "    /// Returns a value borrowing this caller's arena; it stays valid until\n",
        );
        out.push_str("    /// the next arena-backed call on this caller.\n");
    }
    out.push_str(&format!(
        "    {} {}({}){} {{\n",
        return_type, func.name, params_str, self_qual
    ));

    // Interface null-guard.
    out.push_str("        if (iface_ == nullptr) {\n");
    if func.returns.is_some() {
        out.push_str(&format!("            return {}{{}};\n", return_type));
    } else {
        out.push_str("            return;\n");
    }
    out.push_str("        }\n");

    // Per-call staleness check: re-resolve before dispatch if the registry changed
    // (hot-reload or unload of the peer), so the cached interface and instance are
    // never used once they dangle. This caller is noexcept, so a gone peer funnels
    // through the host log and returns a zero-initialised value.
    out.push_str("        if (polyplug_load_revision(revision_ptr_) != cached_revision_ && !revalidate()) {\n");
    out.push_str(&format!(
        "            detail::log_call_failure(host_, \"guest.peer_caller\", \"{class_name}.{fn_name}\", static_cast<uint32_t>(AbiErrorCode::NotFound));\n",
        fn_name = func.name
    ));
    if func.returns.is_some() {
        out.push_str(&format!("            return {}{{}};\n", return_type));
    } else {
        out.push_str("            return;\n");
    }
    out.push_str("        }\n");

    if needs_arena {
        out.push_str(
            "        // Reset the arena at call start: frees the previous call's overflow\n",
        );
        out.push_str(
            "        // blocks and rewinds the primary region, invalidating prior views.\n",
        );
        out.push_str("        polyplug_arena_reset(&arena_);\n");
    }

    // args_ptr — reuse the same helper as the host caller.
    let args_ptr_code: String = build_args_ptr_code(class_name, func);
    out.push_str(&args_ptr_code);

    // out_ptr
    let is_void_return: bool = matches!(
        func.returns.as_ref(),
        None | Some(ResolvedTypeRef::AbiType(AbiBuiltin::Void))
    );
    if is_void_return {
        out.push_str("        void* out_ptr = nullptr;\n");
    } else {
        out.push_str(&format!("        {} out{{}};\n", return_type));
        out.push_str("        void* out_ptr = &out;\n");
    }

    // Dispatch DIRECTLY through the cached peer interface, branching on its
    // dispatch type — the exact same near-bare-metal path as the host->guest
    // caller (no host-mediated round-trip, no per-call registry resolve, no
    // epoch pin). The declared dependency keeps the peer alive; a hot-reload is
    // caught by the per-call revision check above (which re-resolves iface_).
    out.push_str("        AbiError err{};\n");
    out.push_str("        switch (iface_->dispatch_type) {\n");
    out.push_str("            case DispatchType::Native: {\n");
    // Function-id bounds check against the native dispatch table — emitted inside
    // the Native arm only: on a VM interface `dispatch.native.function_count`
    // aliases bits of `dispatch.vm.call` through the union (garbage). The VM-side
    // loader enforces its own bounds (FunctionNotAvailable).
    out.push_str(&format!(
        "                if ({}U >= iface_->dispatch.native.function_count) {{\n",
        fn_id
    ));
    out.push_str(&format!(
        "                    detail::log_call_failure(host_, \"guest.peer_caller\", \"{class_name}.{fn_name}\", static_cast<uint32_t>(AbiErrorCode::FunctionNotAvailable));\n",
        fn_name = func.name
    ));
    if func.returns.is_some() {
        out.push_str(&format!(
            "                    return {}{{}};\n",
            return_type
        ));
    } else {
        out.push_str("                    return;\n");
    }
    out.push_str("                }\n");
    out.push_str(&format!(
        "                auto fn_ = reinterpret_cast<void(*)(GuestContractInstance, const void*, void*, AbiError*)>(iface_->dispatch.native.functions[{}U]);\n",
        fn_id
    ));
    out.push_str("                // SAFETY: instance_ is the token returned by create_instance and is valid.\n");
    out.push_str("                // args_ptr/out_ptr match the ABI contract for this function.\n");
    out.push_str("                fn_(instance_, args_ptr, out_ptr, &err);\n");
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("            case DispatchType::VirtualMachine: {\n");
    // Arena-backed functions hand the peer this caller's per-call arena so it can
    // write variable-size returns without a per-value host->alloc; other functions
    // pass nullptr and the VM bridge falls back to per-value host allocation.
    let arena_arg: &str = if needs_arena { "&arena_" } else { "nullptr" };
    out.push_str(&format!(
        "                (iface_->dispatch.vm.call)(iface_->dispatch.vm.loader_data, instance_, {}U, args_ptr, out_ptr, {}, &err);\n",
        fn_id, arena_arg
    ));
    out.push_str("                break;\n");
    out.push_str("            }\n");
    out.push_str("        }\n");

    // Error handling — guest-side peer callers cannot throw (noexcept), so the
    // failure is funnelled through the host logging funnel (with the error code)
    // before returning a zero-initialised value.
    out.push_str("        if (err.code != static_cast<uint32_t>(AbiErrorCode::Ok)) {\n");
    out.push_str(&format!(
        "            detail::log_call_failure(host_, \"guest.peer_caller\", \"{class_name}.{fn_name}\", err.code);\n",
        fn_name = func.name
    ));
    if func.returns.is_some() {
        out.push_str(&format!("            return {}{{}};\n", return_type));
    } else {
        out.push_str("            return;\n");
    }
    out.push_str("        }\n");

    if !is_void_return {
        out.push_str("        return out;\n");
    }

    out.push_str("    }\n\n");
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    #![allow(clippy::unwrap_used)]

    use super::*;
    use crate::ir::ReprType;
    use crate::ir::ResolvedDependency;
    use crate::ir::ResolvedParam;
    use crate::ir::Version;

    #[test]
    fn class_name_conversion() {
        assert_eq!(
            contract_name_to_class("image.decode"),
            "ImageDecodeContract"
        );
    }

    #[test]
    fn plugin_class_name_conversion() {
        assert_eq!(
            contract_name_to_guest_contract_class("test.add"),
            "TestAddGuestContract"
        );
    }

    #[test]
    fn lower_snake_conversion() {
        assert_eq!(contract_name_to_lower_snake("test.add"), "test_add");
    }

    #[test]
    fn upper_snake_conversion() {
        assert_eq!(contract_name_to_upper_snake("test.add"), "TEST_ADD");
    }

    #[test]
    fn generate_host_empty_ir() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        // Now produces 3 files: types.hpp, host_callers.hpp, manifest.toml
        assert!(!files.files.is_empty());
        // At least one file contains the AUTO-GENERATED header
        assert!(
            files
                .files
                .iter()
                .any(|f| f.content.contains("AUTO-GENERATED"))
        );
    }

    #[test]
    fn generate_guest_empty_ir() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");
        // Produces 4 files (bundle=None, so no manifest): types.hpp, contracts.hpp, interfaces.hpp, init.hpp
        assert_eq!(files.files.len(), 4);
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f| f.path.to_string_lossy().to_string())
            .collect();
        assert!(names.contains(&"guest/types.hpp".to_owned()));
        assert!(names.contains(&"guest/contracts.hpp".to_owned()));
        assert!(names.contains(&"guest/interfaces.hpp".to_owned()));
        assert!(names.contains(&"guest/init.hpp".to_owned()));
    }

    #[test]
    fn generate_cpp_enum_non_bitflag() {
        let e: EnumDef = EnumDef {
            name: "PixelFormat".to_owned(),
            repr: ReprType::U32,
            bitflag: false,
            variants: vec![
                EnumVariant {
                    name: "Unknown".to_owned(),
                    value: "0".to_owned(),
                },
                EnumVariant {
                    name: "Rgba8".to_owned(),
                    value: "1".to_owned(),
                },
            ],
        };
        let mut out: String = String::new();
        generate_cpp_enum(&mut out, &e);
        assert!(
            out.contains("enum class PixelFormat : uint32_t"),
            "missing enum class: {out}"
        );
        assert!(
            out.contains("Unknown = 0"),
            "missing Unknown variant: {out}"
        );
        assert!(
            !out.contains("operator|"),
            "non-bitflag should not have operator|: {out}"
        );
    }

    #[test]
    fn generate_cpp_enum_bitflag() {
        let e: EnumDef = EnumDef {
            name: "ImageFlags".to_owned(),
            repr: ReprType::U32,
            bitflag: true,
            variants: vec![
                EnumVariant {
                    name: "None".to_owned(),
                    value: "0".to_owned(),
                },
                EnumVariant {
                    name: "Compressed".to_owned(),
                    value: "1".to_owned(),
                },
            ],
        };
        let mut out: String = String::new();
        generate_cpp_enum(&mut out, &e);
        assert!(
            out.contains("enum class ImageFlags : uint32_t"),
            "missing enum class: {out}"
        );
        assert!(out.contains("operator|"), "missing operator|: {out}");
        assert!(out.contains("operator&"), "missing operator&: {out}");
        assert!(out.contains("operator~"), "missing operator~: {out}");
        assert!(
            out.contains("static_cast<uint32_t>"),
            "missing static_cast: {out}"
        );
    }

    #[test]
    fn generate_cpp_host_contract_has_factory_method() {
        let contract = ResolvedContract {
            name: "test.add".to_owned(),
            contract_id: 0x123456789ABCDEF0,
            version: Version {
                major: 1,
                minor: 0,
                patch: 0,
            },
            functions: vec![ResolvedFunction {
                name: "add".to_owned(),
                function_id: 0,
                params: vec![
                    ResolvedParam {
                        name: "a".to_owned(),
                        ty: ResolvedTypeRef::Primitive(PrimitiveType::I32),
                    },
                    ResolvedParam {
                        name: "b".to_owned(),
                        ty: ResolvedTypeRef::Primitive(PrimitiveType::I32),
                    },
                ],
                returns: Some(ResolvedTypeRef::Primitive(PrimitiveType::I32)),
            }],
        };

        let mut out: String = String::new();
        generate_cpp_host_contract(&mut out, &contract).unwrap();

        // Check for instance-based factory method. The handle is the typed
        // GuestContractHandle (a u32 index struct), never a raw u64.
        assert!(
            out.contains("static std::optional<TestAddContract> create(GuestContractHandle handle, const HostApi* host) noexcept"),
            "missing factory method: {out}"
        );

        // Validity must key off the resolved interface pointer, not instance_.data:
        // stateless contracts legitimately return a null instance handle.
        assert!(
            out.contains("return interface_ != nullptr;"),
            "validity check must key off interface_, not instance_.data: {out}"
        );

        // Function-id bounds check must read the native dispatch table's count
        // (there is no top-level function_count field on GuestContractInterface)
        // and must live INSIDE the Native dispatch arm: on a VM interface,
        // dispatch.native.function_count aliases bits of dispatch.vm.call
        // through the union, so a pre-branch check reads garbage.
        let native_arm_pos: usize = out
            .find("case DispatchType::Native: {")
            .expect("missing Native dispatch arm");
        let bounds_check_pos: usize = out
            .find("interface_->dispatch.native.function_count")
            .expect("bounds check must use dispatch.native.function_count");
        assert!(
            bounds_check_pos > native_arm_pos,
            "bounds check must be inside the Native dispatch arm, not before the branch: {out}"
        );

        // Dispatch must branch on the interface's dispatch type for ABI parity.
        assert!(
            out.contains("switch (interface_->dispatch_type)"),
            "dispatch must branch on dispatch_type: {out}"
        );

        // Check for instance member (not PluginGuard)
        assert!(
            out.contains("GuestContractInstance instance_"),
            "missing instance member: {out}"
        );

        // Check for interface and host members
        assert!(
            out.contains("const GuestContractInterface* interface_"),
            "missing interface member: {out}"
        );
        assert!(
            out.contains("const HostApi* host_"),
            "missing host member: {out}"
        );

        // Check lifecycle methods
        assert!(
            out.contains("bool is_valid() const noexcept"),
            "missing is_valid method: {out}"
        );
        assert!(
            out.contains("explicit operator bool() const noexcept"),
            "missing operator bool: {out}"
        );
        assert!(
            out.contains("void reset() noexcept"),
            "missing reset method: {out}"
        );

        // Check destructor calls host-mediated destroy_guest_instance
        assert!(
            out.contains("~TestAddContract() noexcept"),
            "missing destructor: {out}"
        );
        assert!(
            out.contains("host_->destroy_guest_instance(host_, interface_, instance_)"),
            "missing destroy_guest_instance call in destructor: {out}"
        );

        // Check factory calls host-mediated create_guest_instance via out-param
        assert!(
            out.contains("host->create_guest_instance(host, iface, nullptr, &instance)"),
            "missing create_guest_instance call in factory: {out}"
        );

        // Check move constructor (not default, explicit transfer)
        assert!(
            out.contains("TestAddContract(TestAddContract&& other) noexcept"),
            "missing move constructor: {out}"
        );
        assert!(
            out.contains("other.instance_.data = nullptr"),
            "missing nulling of moved-from instance: {out}"
        );
        assert!(
            out.contains("TestAddContract(const TestAddContract&) = delete"),
            "missing deleted copy constructor: {out}"
        );

        // Check private constructor (threads the retained handle + revision counter
        // so the per-call staleness check can re-resolve after a reload/unload).
        assert!(
            out.contains("explicit TestAddContract(const GuestContractInterface* iface, GuestContractInstance inst, const HostApi* host, GuestContractHandle handle, const uint64_t* revision_ptr, uint64_t cached_revision) noexcept"),
            "missing private constructor: {out}"
        );

        // Check dispatch uses instance_ and passes &err as out-param
        assert!(
            out.contains("fn_(instance_, args_ptr,") && out.contains(", &err)"),
            "dispatch must call fn_ with instance_, args_ptr, out_ptr, &err: {out}"
        );

        // Check revision-counter dangle protection: the caller stores the handle +
        // revision pointer, performs a per-call staleness check that re-resolves on
        // change, and the destructor skips destroy once the revision has moved.
        assert!(
            out.contains("const uint64_t* revision_ptr_;")
                && out.contains("uint64_t cached_revision_;"),
            "missing revision_ptr_/cached_revision_ members: {out}"
        );
        assert!(
            out.contains("GuestContractHandle handle_;"),
            "missing retained contract handle_ member: {out}"
        );
        assert!(
            out.contains("host->revision_counter(host)"),
            "factory must fetch the revision counter once: {out}"
        );
        assert!(
            out.contains("bool revalidate() noexcept"),
            "missing revalidate() helper: {out}"
        );
        assert!(
            out.contains(
                "if (polyplug_load_revision(revision_ptr_) != cached_revision_ && !revalidate())"
            ),
            "dispatch must re-resolve before use when the revision changed: {out}"
        );
        assert!(
            out.contains("if (polyplug_load_revision(revision_ptr_) != cached_revision_) {\n            return;\n        }"),
            "destructor must skip destroy when the revision changed: {out}"
        );
    }

    #[test]
    fn host_contract_name_to_cpp_trait_conversion() {
        assert_eq!(host_contract_name_to_cpp_trait("host.logger"), "HostLogger");
        assert_eq!(
            host_contract_name_to_cpp_trait("host.fs.reader"),
            "HostFsReader"
        );
        assert_eq!(
            host_contract_name_to_cpp_trait("host.HostLogger"),
            "HostLogger"
        );
        assert_eq!(host_contract_name_to_cpp_trait("logger"), "HostLogger");
    }

    #[test]
    fn cpp_type_name_mappings() {
        assert_eq!(
            cpp_type_name(&ResolvedTypeRef::Primitive(PrimitiveType::U32)),
            "uint32_t"
        );
        assert_eq!(
            cpp_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::StringView)),
            "StringView"
        );
        assert_eq!(
            cpp_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::Buffer)),
            "Buffer"
        );
        assert_eq!(
            cpp_type_name(&ResolvedTypeRef::UserDefined("MyStruct".to_owned())),
            "polyplug_generated::MyStruct"
        );
    }

    #[test]
    fn generate_cpp_host_contract_trait_produces_class() {
        let contract = ResolvedHostContract {
            name: "host.logger".to_owned(),
            contract_id: 0x1234_5678_9ABC_DEF0_u64,
            version: Version {
                major: 1,
                minor: 0,
                patch: 0,
            },
            singleton: false,
            functions: vec![
                ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![ResolvedParam {
                        name: "message".to_owned(),
                        ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                    }],
                    returns: None,
                },
                ResolvedFunction {
                    name: "logf".to_owned(),
                    function_id: 1,
                    params: vec![
                        ResolvedParam {
                            name: "level".to_owned(),
                            ty: ResolvedTypeRef::Primitive(PrimitiveType::U32),
                        },
                        ResolvedParam {
                            name: "format".to_owned(),
                            ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                        },
                    ],
                    returns: None,
                },
            ],
        };
        let mut out: String = String::new();
        generate_cpp_host_contract_trait(&mut out, &contract);
        assert!(out.contains("class HostLogger"), "missing class: {out}");
        assert!(
            out.contains("virtual ~HostLogger() = default"),
            "missing virtual destructor: {out}"
        );
        assert!(
            out.contains("virtual void log(StringView message) = 0"),
            "missing log method: {out}"
        );
        assert!(
            out.contains("virtual void logf(uint32_t level, StringView format) = 0"),
            "missing logf method: {out}"
        );
    }

    #[test]
    fn generate_cpp_host_contracts_file_produces_file() {
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![ResolvedParam {
                        name: "message".to_owned(),
                        ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                    }],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let out: String = generate_cpp_host_contracts_file(&ir);
        assert!(out.contains("AUTO-GENERATED"), "missing header: {out}");
        assert!(out.contains("class HostLogger"), "missing class: {out}");
        assert!(
            out.contains("HOSTLOGGER_CONTRACT_ID"),
            "missing constant: {out}"
        );
        assert!(
            out.contains("namespace polyplug_host"),
            "missing namespace: {out}"
        );
    }

    #[test]
    fn generate_host_with_host_contracts_produces_host_contracts_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            names.contains(&"host/host_contracts.hpp".to_owned()),
            "missing host_contracts.hpp: {names:?}"
        );
    }

    #[test]
    fn generate_host_without_host_contracts_no_host_contracts_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            !names.contains(&"host/host_contracts.hpp".to_owned()),
            "unexpected host_contracts.hpp: {names:?}"
        );
    }

    #[test]
    fn host_contract_name_to_cpp_caller_conversion() {
        assert_eq!(
            host_contract_name_to_cpp_caller("host.logger"),
            "HostLoggerContract"
        );
        assert_eq!(
            host_contract_name_to_cpp_caller("host.fs.reader"),
            "HostFsReaderContract"
        );
        assert_eq!(
            host_contract_name_to_cpp_caller("host.HostLogger"),
            "HostLoggerContract"
        );
        assert_eq!(
            host_contract_name_to_cpp_caller("logger"),
            "HostLoggerContract"
        );
    }

    #[test]
    fn cpp_guest_caller_param_type_name_mappings() {
        assert_eq!(
            cpp_guest_caller_param_type_name(&ResolvedTypeRef::Primitive(PrimitiveType::U32)),
            "uint32_t"
        );
        assert_eq!(
            cpp_guest_caller_param_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::StringView)),
            "std::string_view"
        );
        assert_eq!(
            cpp_guest_caller_param_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::Buffer)),
            "Buffer"
        );
        assert_eq!(
            cpp_guest_caller_param_type_name(&ResolvedTypeRef::UserDefined("MyStruct".to_owned())),
            "const polyplug_generated::MyStruct&"
        );
    }

    #[test]
    fn cpp_guest_caller_return_type_name_mappings() {
        assert_eq!(
            cpp_guest_caller_return_type_name(&ResolvedTypeRef::Primitive(PrimitiveType::U32)),
            "uint32_t"
        );
        assert_eq!(
            cpp_guest_caller_return_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::StringView)),
            "std::string_view"
        );
        assert_eq!(
            cpp_guest_caller_return_type_name(&ResolvedTypeRef::AbiType(AbiBuiltin::Buffer)),
            "std::span<const std::uint8_t>"
        );
        assert_eq!(
            cpp_guest_caller_return_type_name(&ResolvedTypeRef::UserDefined("MyStruct".to_owned())),
            "polyplug_generated::MyStruct"
        );
    }

    #[test]
    fn cpp_guest_caller_return_expr_is_null_safe() {
        // A null/empty StringView/Buffer return is legal at the ABI boundary; constructing a
        // std::string_view from a null pointer is UB before C++26, so the emitted return must
        // route through the SDK's null-safe to_string_view, and the span must guard the pointer.
        let sv_expr: String =
            cpp_guest_caller_return_expr(&ResolvedTypeRef::AbiType(AbiBuiltin::StringView));
        assert_eq!(sv_expr, "polyplug::to_string_view(out)");
        assert!(
            !sv_expr.contains("std::string_view(reinterpret_cast"),
            "StringView return must not build string_view from raw ptr (UB on null): {sv_expr}"
        );

        let buf_expr: String =
            cpp_guest_caller_return_expr(&ResolvedTypeRef::AbiType(AbiBuiltin::Buffer));
        assert!(
            buf_expr.contains("out.ptr ?"),
            "Buffer return must guard the null pointer before building a span: {buf_expr}"
        );
    }

    #[test]
    fn generate_cpp_guest_host_contract_caller_produces_class() {
        let contract = ResolvedHostContract {
            name: "host.logger".to_owned(),
            contract_id: 0x1234_5678_9ABC_DEF0_u64,
            version: Version {
                major: 1,
                minor: 0,
                patch: 0,
            },
            singleton: false,
            functions: vec![ResolvedFunction {
                name: "log".to_owned(),
                function_id: 0,
                params: vec![ResolvedParam {
                    name: "message".to_owned(),
                    ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                }],
                returns: None,
            }],
        };
        let mut out: String = String::new();
        generate_cpp_guest_host_contract_caller(&mut out, &contract);
        assert!(
            out.contains("class HostLoggerContract"),
            "missing class: {out}"
        );
        assert!(
            out.contains("const HostContractInterface* interface_"),
            "missing interface member: {out}"
        );
        assert!(
            out.contains("HostContractInstance instance_"),
            "missing instance member: {out}"
        );
        assert!(
            out.contains("static std::optional<HostLoggerContract> from_host"),
            "missing from_host method: {out}"
        );
        assert!(
            out.contains("void log(std::string_view message) noexcept"),
            "missing log method: {out}"
        );
        assert!(
            out.contains("bool is_valid() const noexcept"),
            "missing is_valid method: {out}"
        );
    }

    #[test]
    fn generate_cpp_guest_host_contracts_file_produces_file() {
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let out: String = generate_cpp_guest_host_contracts_file(&ir);
        assert!(out.contains("AUTO-GENERATED"), "missing header: {out}");
        assert!(
            out.contains("class HostLoggerContract"),
            "missing class: {out}"
        );
        assert!(
            out.contains("HOSTLOGGERCONTRACT_ID"),
            "missing constant: {out}"
        );
        assert!(
            out.contains("namespace polyplug_plugin"),
            "missing namespace: {out}"
        );
    }

    #[test]
    fn generate_guest_with_host_contracts_produces_guest_host_contracts_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            names.contains(&"guest/host_contracts.hpp".to_owned()),
            "missing guest/host_contracts.hpp: {names:?}"
        );
    }

    #[test]
    fn generate_guest_without_host_contracts_no_guest_host_contracts_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            !names.contains(&"guest/host_contracts.hpp".to_owned()),
            "unexpected guest/host_contracts.hpp: {names:?}"
        );
    }

    #[test]
    fn generate_host_with_host_contracts_produces_interface_factories_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            names.contains(&"host/interface_factories.hpp".to_owned()),
            "missing interface_factories.hpp: {names:?}"
        );
    }

    #[test]
    fn generate_host_without_host_contracts_no_interface_factories_file() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            !names.contains(&"host/interface_factories.hpp".to_owned()),
            "unexpected interface_factories.hpp: {names:?}"
        );
    }

    #[test]
    fn generate_cpp_host_interface_factories_file_produces_file() {
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x1234_5678_9ABC_DEF0_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: false,
                functions: vec![ResolvedFunction {
                    name: "log".to_owned(),
                    function_id: 0,
                    params: vec![ResolvedParam {
                        name: "message".to_owned(),
                        ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                    }],
                    returns: None,
                }],
            }],
            bundle: None,
        };
        let out: String = generate_cpp_host_interface_factories_file(&ir);
        assert!(out.contains("AUTO-GENERATED"), "missing header: {out}");
        assert!(
            out.contains("template<typename T>"),
            "missing template: {out}"
        );
        assert!(
            out.contains("create_host_logger_interface"),
            "missing NATIVE factory: {out}"
        );
        assert!(
            out.contains("create_host_logger_interface_vm"),
            "missing VM factory: {out}"
        );
        assert!(
            out.contains("std::unique_ptr<T> impl"),
            "missing unique_ptr param: {out}"
        );
        assert!(
            out.contains("VmDispatch_call_fn dispatch_fn"),
            "missing dispatch_fn param: {out}"
        );
        assert!(
            out.contains("namespace polyplug_host"),
            "missing namespace: {out}"
        );
    }

    #[test]
    fn generate_cpp_host_interface_factory_produces_native_and_vm_factories() {
        let contract = ResolvedHostContract {
            name: "host.logger".to_owned(),
            contract_id: 0x1234_5678_9ABC_DEF0_u64,
            version: Version {
                major: 1,
                minor: 0,
                patch: 0,
            },
            singleton: false,
            functions: vec![ResolvedFunction {
                name: "log".to_owned(),
                function_id: 0,
                params: vec![ResolvedParam {
                    name: "message".to_owned(),
                    ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                }],
                returns: None,
            }],
        };
        let mut out: String = String::new();
        generate_cpp_host_interface_factory(&mut out, &contract);
        assert!(
            out.contains("template<typename T>"),
            "missing template: {out}"
        );
        assert!(
            out.contains("const HostContractInterface* create_host_logger_interface"),
            "missing NATIVE factory: {out}"
        );
        assert!(
            out.contains("std::unique_ptr<T> impl"),
            "missing unique_ptr: {out}"
        );
        assert!(
            out.contains("T* impl_ptr = impl.release();"),
            "implementation must be released into a local, not a static: {out}"
        );
        assert!(
            out.contains("iface->user_data = static_cast<void*>(impl_ptr);"),
            "implementation must be routed through user_data, not a static: {out}"
        );
        assert!(
            !out.contains("s_impl"),
            "host factory must not hold the implementation in a static: {out}"
        );
        // The interface must be heap-allocated per call (Box::leak semantics):
        // a `static HostContractInterface` would alias every registration after
        // the first onto the first call's impl/loader_data.
        assert!(
            out.contains("auto* iface = new HostContractInterface{"),
            "factory must heap-allocate the interface per call: {out}"
        );
        assert!(
            !out.contains("static HostContractInterface s_interface"),
            "factory must not hold the interface in a static: {out}"
        );
        assert!(
            out.contains("static void* const FUNCTIONS"),
            "missing function array: {out}"
        );
        assert!(
            out.contains("host_logger_log_thunk"),
            "missing thunk: {out}"
        );
        assert!(
            out.contains("create_host_logger_interface_vm"),
            "missing VM factory: {out}"
        );
        assert!(
            out.contains("VmDispatch_call_fn dispatch_fn"),
            "missing dispatch_fn: {out}"
        );
        assert!(
            out.contains("create_instance_stub"),
            "missing create_instance stub: {out}"
        );
        assert!(
            out.contains("destroy_instance_stub"),
            "missing destroy_instance stub: {out}"
        );
    }

    /// A declared [[dependency]] whose contract_id matches a contract in ir.contracts
    /// must produce a PeerCallers class in guest/peer_callers.hpp.
    #[test]
    fn peer_caller_emitted_for_declared_dependency() {
        let contract_id: u64 = 0xDEAD_BEEF_1234_5678_u64;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![ResolvedContract {
                name: "pipeline.Validator".to_owned(),
                contract_id,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                functions: vec![ResolvedFunction {
                    name: "validate".to_owned(),
                    function_id: 0,
                    params: vec![ResolvedParam {
                        name: "input".to_owned(),
                        ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                    }],
                    returns: Some(ResolvedTypeRef::AbiType(AbiBuiltin::StringView)),
                }],
            }],
            host_contracts: vec![],
            bundle: Some(ResolvedBundle {
                name: "cpp_transformer".to_owned(),
                bundle_id: 0xAAAA_BBBB_CCCC_DDDD_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                loader: "native".to_owned(),
                file: polyplug_codegen::ResolvedBundleFile::Single("test.so".to_owned()),
                plugins: vec![ResolvedPlugin {
                    name: "transformer".to_owned(),
                    implements: vec!["data.Transformer@1".to_owned()],
                    optional: vec![],
                }],
                dependencies: vec![ResolvedDependency::ByContract {
                    contract: "pipeline.Validator".to_owned(),
                    contract_id,
                    min_version: 1,
                }],
                needs_reinit_on_dep_reload: false,
            }),
        };

        let generator: CppGenerator = CppGenerator;
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");

        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            names.contains(&"guest/peer_callers.hpp".to_owned()),
            "expected guest/peer_callers.hpp, got: {names:?}"
        );

        let peer_file: &GeneratedFile = files
            .files
            .iter()
            .find(|f: &&GeneratedFile| f.path.to_string_lossy() == "guest/peer_callers.hpp")
            .expect("peer_callers.hpp must be present");

        assert!(
            peer_file.content.contains("PipelineValidatorContractPeer"),
            "expected peer class name in output:\n{}",
            peer_file.content
        );
        // Peer caller dispatches DIRECTLY through the cached interface (same path
        // as the host->guest caller), branching on dispatch type.
        assert!(
            peer_file.content.contains("switch (iface_->dispatch_type)"),
            "peer caller must branch on dispatch type:\n{}",
            peer_file.content
        );
        assert!(
            peer_file
                .content
                .contains("iface_->dispatch.native.functions"),
            "peer caller Native arm must index dispatch.native.functions:\n{}",
            peer_file.content
        );
        assert!(
            peer_file.content.contains("iface_->dispatch.vm.call"),
            "peer caller VM arm must call dispatch.vm.call:\n{}",
            peer_file.content
        );
        assert!(
            peer_file.content.contains("find_guest_contract"),
            "resolve() must call find_guest_contract:\n{}",
            peer_file.content
        );
        assert!(
            peer_file.content.contains("resolve_guest_contract"),
            "resolve() must call resolve_guest_contract:\n{}",
            peer_file.content
        );
        assert!(
            peer_file
                .content
                .contains("resolve(const HostApi* host) noexcept"),
            "resolve(host) must take the per-instance HostApi pointer:\n{}",
            peer_file.content
        );
        assert!(
            peer_file.content.contains("AUTO-GENERATED"),
            "missing AUTO-GENERATED header:\n{}",
            peer_file.content
        );
    }

    /// Without a bundle (or without a matching dependency), no peer_callers.hpp
    /// must be emitted.
    #[test]
    fn no_peer_callers_without_dependencies() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = ValidatedIr {
            types: vec![],
            enums: vec![],
            contracts: vec![ResolvedContract {
                name: "pipeline.Validator".to_owned(),
                contract_id: 0xDEAD_BEEF_1234_5678_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                functions: vec![],
            }],
            host_contracts: vec![],
            bundle: None,
        };
        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");
        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        assert!(
            !names.contains(&"guest/peer_callers.hpp".to_owned()),
            "must NOT emit peer_callers.hpp without a bundle: {names:?}"
        );
    }

    /// Build an IR whose contract defines a `LogLevel` enum colliding with the
    /// global `::LogLevel` declared by `polyplug/abi.hpp`, plus a struct
    /// embedding it, a guest contract and a host contract using it, and a
    /// bundle dependency — so every generated file kind is exercised.
    fn collision_ir() -> ValidatedIr {
        ValidatedIr {
            types: vec![crate::ir::ResolvedType {
                name: "LogMessage".to_owned(),
                fields: vec![crate::ir::ResolvedField {
                    name: "level".to_owned(),
                    ty: ResolvedTypeRef::UserDefined("LogLevel".to_owned()),
                }],
            }],
            enums: vec![EnumDef {
                name: "LogLevel".to_owned(),
                repr: ReprType::U32,
                bitflag: false,
                variants: vec![
                    EnumVariant {
                        name: "Debug".to_owned(),
                        value: "0".to_owned(),
                    },
                    EnumVariant {
                        name: "Error".to_owned(),
                        value: "1".to_owned(),
                    },
                ],
            }],
            contracts: vec![ResolvedContract {
                name: "pipeline.decoder".to_owned(),
                contract_id: 0x1111_2222_3333_4444_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                functions: vec![ResolvedFunction {
                    name: "describe".to_owned(),
                    function_id: 0,
                    params: vec![ResolvedParam {
                        name: "level".to_owned(),
                        ty: ResolvedTypeRef::UserDefined("LogLevel".to_owned()),
                    }],
                    returns: Some(ResolvedTypeRef::AbiType(AbiBuiltin::StringView)),
                }],
            }],
            host_contracts: vec![ResolvedHostContract {
                name: "host.logger".to_owned(),
                contract_id: 0x5555_6666_7777_8888_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                singleton: true,
                functions: vec![ResolvedFunction {
                    name: "log_with_level".to_owned(),
                    function_id: 0,
                    params: vec![
                        ResolvedParam {
                            name: "level".to_owned(),
                            ty: ResolvedTypeRef::UserDefined("LogLevel".to_owned()),
                        },
                        ResolvedParam {
                            name: "message".to_owned(),
                            ty: ResolvedTypeRef::AbiType(AbiBuiltin::StringView),
                        },
                    ],
                    returns: None,
                }],
            }],
            bundle: Some(crate::ir::ResolvedBundle {
                name: "decoder_bundle".to_owned(),
                bundle_id: 0x9999_AAAA_BBBB_CCCC_u64,
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
                loader: "native".to_owned(),
                file: polyplug_codegen::ResolvedBundleFile::Single("test.so".to_owned()),
                plugins: vec![crate::ir::ResolvedPlugin {
                    name: "decoder".to_owned(),
                    implements: vec!["pipeline.decoder@1.0".to_owned()],
                    optional: vec![],
                }],
                dependencies: vec![ResolvedDependency::ByContract {
                    contract: "pipeline.decoder".to_owned(),
                    contract_id: 0x1111_2222_3333_4444_u64,
                    min_version: 1,
                }],
                needs_reinit_on_dep_reload: false,
            }),
        }
    }

    /// Find one generated file's content by path.
    fn file_content<'a>(files: &'a GeneratedFiles, name: &str) -> &'a str {
        files
            .files
            .iter()
            .find(|f: &&GeneratedFile| f.path.to_string_lossy() == name)
            .map(|f: &GeneratedFile| f.content.as_str())
            .expect("generated file missing")
    }

    /// Defect: a blanket `using namespace polyplug_generated;` made unqualified
    /// contract-type references ambiguous against globals declared by
    /// `polyplug/abi.hpp` (contract `LogLevel` vs the ABI's `::LogLevel`), so
    /// every TU including a generated header failed to compile. No generated
    /// file may ever blanket-import the generated namespace.
    #[test]
    fn generated_files_never_blanket_import_polyplug_generated() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = collision_ir();

        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");

        let names: Vec<String> = files
            .files
            .iter()
            .map(|f: &GeneratedFile| f.path.to_string_lossy().to_string())
            .collect();
        // The collision IR must exercise every generated file kind.
        for expected in [
            "host/types.hpp",
            "host/host_callers.hpp",
            "host/host_contracts.hpp",
            "host/interface_factories.hpp",
            "guest/types.hpp",
            "guest/contracts.hpp",
            "guest/interfaces.hpp",
            "guest/init.hpp",
            "guest/host_contracts.hpp",
            "guest/peer_callers.hpp",
        ] {
            assert!(
                names.contains(&expected.to_owned()),
                "collision IR must produce {expected}: {names:?}"
            );
        }

        for file in &files.files {
            assert!(
                !file.content.contains("using namespace polyplug_generated"),
                "{} must not blanket-import polyplug_generated:\n{}",
                file.path.display(),
                file.content
            );
        }
    }

    /// Contract-defined types must be referenced fully qualified
    /// (`polyplug_generated::<Type>`) in every generated file, so unqualified
    /// names can never collide with `polyplug/abi.hpp` globals. Only the type
    /// DEFINITIONS in `types.hpp` (inside `namespace polyplug_generated`)
    /// stay unqualified.
    #[test]
    fn contract_types_emitted_fully_qualified() {
        let generator: CppGenerator = CppGenerator;
        let ir: ValidatedIr = collision_ir();

        let mut files: GeneratedFiles = GeneratedFiles::default();
        generator
            .generate_host(&ir, &mut files)
            .expect("generate_host");
        generator
            .generate_guest(&ir, &mut files)
            .expect("generate_guest");

        // types.hpp IS namespace polyplug_generated — definitions stay unqualified.
        let types_hpp: &str = file_content(&files, "host/types.hpp");
        assert!(
            types_hpp.contains("enum class LogLevel : uint32_t"),
            "missing enum definition in types.hpp:\n{types_hpp}"
        );
        assert!(
            types_hpp.contains("    LogLevel level;\n"),
            "struct field inside polyplug_generated must stay unqualified:\n{types_hpp}"
        );
        assert!(
            !types_hpp.contains("polyplug_generated::LogLevel"),
            "types.hpp must not self-qualify its own definitions:\n{types_hpp}"
        );

        // Host-side abstract class (namespace polyplug_host).
        let host_contracts: &str = file_content(&files, "host/host_contracts.hpp");
        assert!(
            host_contracts.contains(
                "virtual void log_with_level(const polyplug_generated::LogLevel& level, StringView message) = 0;"
            ),
            "host trait method must qualify contract types:\n{host_contracts}"
        );

        // Host-side thunks (namespace polyplug_host).
        let factories: &str = file_content(&files, "host/interface_factories.hpp");
        assert!(
            factories.contains("polyplug_generated::LogLevel"),
            "host thunk arg extraction must qualify contract types:\n{factories}"
        );

        // Host callers (namespace polyplug_generated — qualified for parity).
        let host_callers: &str = file_content(&files, "host/host_callers.hpp");
        assert!(
            host_callers.contains("polyplug_generated::LogLevel level"),
            "host caller params must qualify contract types:\n{host_callers}"
        );

        // Guest-side host-contract caller (namespace polyplug_plugin).
        let guest_host_contracts: &str = file_content(&files, "guest/host_contracts.hpp");
        assert!(
            guest_host_contracts.contains("const polyplug_generated::LogLevel& level"),
            "guest caller params must qualify contract types:\n{guest_host_contracts}"
        );
        assert!(
            guest_host_contracts.contains(" polyplug_generated::LogLevel level;"),
            "guest caller packed-args fields must qualify contract types:\n{guest_host_contracts}"
        );

        // Guest abstract contract classes (namespace polyplug_plugin).
        let contracts_hpp: &str = file_content(&files, "guest/contracts.hpp");
        assert!(
            contracts_hpp.contains("const polyplug_generated::LogLevel& level"),
            "guest abstract method params must qualify contract types:\n{contracts_hpp}"
        );

        // Guest ABI wrappers (namespace polyplug_plugin).
        let interfaces_hpp: &str = file_content(&files, "guest/interfaces.hpp");
        assert!(
            interfaces_hpp.contains("static_cast<const polyplug_generated::LogLevel*>(args)"),
            "guest ABI wrapper casts must qualify contract types:\n{interfaces_hpp}"
        );

        // Peer callers (namespace polyplug_plugin).
        let peer_callers: &str = file_content(&files, "guest/peer_callers.hpp");
        assert!(
            peer_callers.contains("polyplug_generated::LogLevel level"),
            "peer caller params must qualify contract types:\n{peer_callers}"
        );

        // The C++17 atomic read idiom over the Rust AtomicU64 (no std::atomic_ref)
        // must be emitted by the shared revision helper in BOTH caller files, so the
        // per-call staleness check reads the live counter with an acquire load.
        let atomic_idiom: &str = "reinterpret_cast<const std::atomic<std::uint64_t>*>(revision_ptr)->load(std::memory_order_acquire)";
        assert!(
            host_callers.contains("#include <atomic>") && host_callers.contains(atomic_idiom),
            "host_callers.hpp must include <atomic> and emit the acquire-load idiom:\n{host_callers}"
        );
        assert!(
            peer_callers.contains("#include <atomic>") && peer_callers.contains(atomic_idiom),
            "peer_callers.hpp must include <atomic> and emit the acquire-load idiom:\n{peer_callers}"
        );
        // The peer caller must also re-resolve before dispatch and guard its destroy.
        assert!(
            peer_callers.contains(
                "if (polyplug_load_revision(revision_ptr_) != cached_revision_ && !revalidate())"
            ),
            "peer dispatch must re-resolve before use when the revision changed:\n{peer_callers}"
        );
        assert!(
            peer_callers.contains("bool revalidate() noexcept"),
            "peer caller must have a revalidate() helper:\n{peer_callers}"
        );
    }
}