alef 0.67.6

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

use crate::core::config::ResolvedCrateConfig;
use crate::e2e::codegen::field_skip::FieldSkip;
use crate::e2e::config::{CallConfig, E2eConfig};
use crate::e2e::escape::escape_c;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::{Assertion, Fixture};
use heck::{ToPascalCase, ToSnakeCase};
use std::collections::{HashMap, HashSet};
use std::fmt::Write as FmtWrite;

/// The IR type name a C parameter carries as an opaque `AlefHandle` rather than as a literal.
/// Defined in `c::optional_arg` -- the single seam every C e2e call site checks a parameter's
/// handle-ness through, so the free-function path here and the client-method path in
/// `c/test_function.rs` cannot independently drift on the same question. ~keep
use super::optional_arg::handle_param_type_name;
use super::{
    NestedLeafOutcome, c_optional_sentinel, is_primitive_c_type, is_skipped_c_field, json_to_c,
    render_wildcard_assertion, try_emit_enum_accessor,
};

/// Emit chained FFI accessor calls for a nested resolved field path.
///
/// For a path like `metadata.document.title`, this generates:
/// ```c
/// HTMHtmlMetadata* metadata_handle = htm_conversion_result_metadata(result);
/// assert(metadata_handle != NULL);
/// HTMDocumentMetadata* doc_handle = htm_html_metadata_document(metadata_handle);
/// assert(doc_handle != NULL);
/// char* metadata_title = htm_document_metadata_title(doc_handle);
/// ```
///
/// The type chain is looked up from `fields_c_types` which maps
/// `"{parent_snake_type}.{field}"` -> `"PascalCaseType"`.
#[allow(clippy::too_many_arguments)]
pub(super) fn emit_nested_accessor(
    out: &mut String,
    prefix: &str,
    resolved: &str,
    local_var: &str,
    result_var: &str,
    fields_c_types: &HashMap<String, String>,
    fields_enum: &HashSet<String>,
    intermediate_handles: &mut Vec<(String, String)>,
    result_type_name: &str,
    raw_field: &str,
    type_defs: &[crate::core::ir::TypeDef],
    config_sources: &FieldConfigSources,
) -> anyhow::Result<Option<NestedLeafOutcome>> {
    let segments: Vec<&str> = resolved.split('.').collect();
    // cbindgen's `[export] prefix` is shouty-snake, not uppercase; re-deriving it here as
    // `to_uppercase` names types the generated header never declares for any prefix carrying an
    // internal word boundary (`SampleCore` -> `SAMPLECORE` vs the header's `SAMPLE_CORE`). ~keep
    let prefix_upper = crate::codegen::c_consumer::export_type_prefix(prefix);

    // Walk the path, starting from the root result type.
    let mut current_snake_type = result_type_name.to_snake_case();
    let mut current_handle = result_var.to_string();
    // True only while `current_snake_type` names a type the IR actually declares, which
    // is the precondition for using the IR as an oracle for the next segment. The `char*`
    // hop below sets `current_snake_type` from a *field* name rather than a type name, and
    // a `fields_c_types` value may name a C type with no IR counterpart at all; in either
    // case an IR type that happens to share the name is a coincidence, not the parent. ~keep
    let mut current_type_from_ir = type_defs.iter().any(|type_def| type_def.name == result_type_name);
    // Set to true when we've traversed a `[]` array element accessor and subsequent
    // fields must be extracted via alef_json_get_string rather than FFI function calls.
    let mut json_extract_mode = false;
    // Set to true only when that `[]` had an EMPTY key — a true wildcard ("every element"),
    // as opposed to an explicit numeric index (`[N]`) that also enables `json_extract_mode`
    // but names one concrete element. Distinguishes the two at the leaf below: an indexed
    // leaf still resolves to one scalar value, a wildcard leaf does not.
    //
    // `assertions.rs` and `test_function.rs` are both already over the repo's 1,000-line cap
    // (`file-modularization`), and this fix necessarily touches both: the mis-selection lives
    // in THIS function, and each of its three call sites (`call_patterns.rs`,
    // `test_function.rs` x2) has to learn about the new `wildcard_locals` bucket to stop
    // freeing a C local that was never declared. The new logic itself — the quantifier
    // renderer and the primitive/opaque/wildcard classification — lives in
    // `collection_wildcard.rs` instead of growing either capped file further; what remains
    // here and in `test_function.rs` is the minimum wiring needed to reach it. ~keep
    let mut is_wildcard = false;

    for (i, segment) in segments.iter().enumerate() {
        let is_leaf = i + 1 == segments.len();

        // In JSON extraction mode, the current_handle is a JSON string and all
        // segments name keys to extract via alef_json_get_string (for primitive
        // leaves) or alef_json_get_object (for intermediate object hops).
        if json_extract_mode {
            // Decompose `field` or `field[N]`/`field[]`. Numeric indexing must
            // extract the Nth element so later key lookups don't ambiguously
            // pick the first occurrence (matters for fixtures with multiple
            // array elements like `data[0]`/`data[1]`).
            let (bare_segment, bracket_key): (&str, Option<&str>) = match segment.find('[') {
                Some(pos) => (&segment[..pos], Some(segment[pos + 1..].trim_end_matches(']'))),
                None => (segment, None),
            };
            let seg_snake = bare_segment.to_snake_case();
            if is_leaf {
                // `field[].key`: `current_handle` names the ARRAY's own JSON text (the `[]`
                // branch below set it and never drilled into one element), so a scalar
                // `alef_json_get_string(current_handle, ...)` here would look up "key" as a
                // property of the array itself — never present, making every "contains"-shaped
                // assertion built from the (buggy) scalar local unsatisfiable by construction.
                // Defer to a per-element quantifier at assertion-render time instead. ~keep
                if is_wildcard && bracket_key.is_none() {
                    return Ok(Some(NestedLeafOutcome::Wildcard {
                        array_var: current_handle.clone(),
                        key_snake: seg_snake,
                    }));
                }
                let _ = writeln!(
                    out,
                    "    char* {local_var} = alef_json_get_string({current_handle}, \"{seg_snake}\");"
                );
                return Ok(None); // JSON key leaf — char*.
            }
            // Intermediate JSON key — must be an object/array value. Use the
            // object extractor so the substring includes braces/brackets and
            // later primitive lookups against it find their keys
            // (alef_json_get_string would return NULL on non-string values).
            let json_var = format!("{seg_snake}_json");
            if !intermediate_handles.iter().any(|(h, _)| h == &json_var) {
                let _ = writeln!(
                    out,
                    "    char* {json_var} = alef_json_get_object({current_handle}, \"{seg_snake}\");"
                );
                intermediate_handles.push((json_var.clone(), "free".to_string()));
            }
            // If the segment also includes a numeric index `[N]`, drill into
            // the Nth element of the extracted array; otherwise stay on the
            // object/array substring.
            if let Some(key) = bracket_key
                && let Ok(idx) = key.parse::<usize>()
            {
                let elem_var = format!("{seg_snake}_{idx}_json");
                if !intermediate_handles.iter().any(|(h, _)| h == &elem_var) {
                    let _ = writeln!(
                        out,
                        "    char* {elem_var} = alef_json_array_get_index({json_var}, {idx});"
                    );
                    intermediate_handles.push((elem_var.clone(), "free".to_string()));
                }
                current_handle = elem_var;
                continue;
            }
            current_handle = json_var;
            continue;
        }

        // Check for map access: "field[key]" or array element access: "field[]"
        if let Some(bracket_pos) = segment.find('[') {
            let field_name = &segment[..bracket_pos];
            let key = segment[bracket_pos + 1..].trim_end_matches(']');
            let field_snake = field_name.to_snake_case();
            let accessor_fn = format!("{prefix}_{current_snake_type}_{field_snake}");

            // The accessor returns a char* (JSON object/array string).
            let json_var = format!("{field_snake}_json");
            if !intermediate_handles.iter().any(|(h, _)| h == &json_var) {
                let _ = writeln!(out, "    char* {json_var} = {accessor_fn}({current_handle});");
                let _ = writeln!(out, "    assert({json_var} != NULL);");
                // Track for freeing — use prefix_free_string since it's a char*.
                intermediate_handles.push((json_var.clone(), "free_string".to_string()));
            }

            // Empty key `[]`: array-element substring access (any element matches).
            // Numeric key `[N]` (e.g. `choices[0]`, `data[1]`): extract the exact
            // Nth top-level element so subsequent key lookups don't ambiguously
            // pick the first occurrence — required for fixtures whose results
            // contain multiple array elements (e.g. `data[0].index`/`data[1].index`).
            if key.is_empty() {
                if !is_leaf {
                    current_handle = json_var;
                    json_extract_mode = true;
                    is_wildcard = true;
                    continue;
                }
                return Ok(None);
            }
            if let Ok(idx) = key.parse::<usize>() {
                let elem_var = format!("{field_snake}_{idx}_json");
                if !intermediate_handles.iter().any(|(h, _)| h == &elem_var) {
                    let _ = writeln!(
                        out,
                        "    char* {elem_var} = alef_json_array_get_index({json_var}, {idx});"
                    );
                    intermediate_handles.push((elem_var.clone(), "free".to_string()));
                }
                if !is_leaf {
                    current_handle = elem_var;
                    json_extract_mode = true;
                    continue;
                }
                // Trailing `[N]` — caller asserts on the element JSON.
                return Ok(None);
            }

            // Named map key access: extract the key value from the JSON object.
            let _ = writeln!(
                out,
                "    char* {local_var} = alef_json_get_string({json_var}, \"{key}\");"
            );
            return Ok(None); // Map access leaf — char*.
        }

        let seg_snake = segment.to_snake_case();
        let accessor_fn = format!("{prefix}_{current_snake_type}_{seg_snake}");

        // Skip any assertion that touches a field marked "skip" in fields_c_types.
        if is_skipped_c_field(fields_c_types, &current_snake_type, &seg_snake) {
            // Sentinel: no accessor emitted, assertion skipped later.
            return Ok(Some(NestedLeafOutcome::Typed("__skip__".to_string())));
        }

        if is_leaf {
            // Leaf may be a primitive scalar (uint64_t, double, ...) when
            // configured in `fields_c_types`. Otherwise default to char*.
            let lookup_key = format!("{current_snake_type}.{seg_snake}");
            if let Some(t) = fields_c_types.get(&lookup_key).filter(|t| is_primitive_c_type(t)) {
                let _ = writeln!(out, "    {t} {local_var} = {accessor_fn}({current_handle});");
                return Ok(Some(NestedLeafOutcome::Typed(t.clone())));
            }
            // Enum leaf: opaque enum pointer that needs `_to_string` conversion. Must run
            // BEFORE the opaque-struct-leaf check below: `try_emit_enum_accessor` gates
            // itself on `fields_enum` membership, but its `fields_c_types` value (the
            // enum's PascalCase type name, e.g. `DataNodeKind`) is indistinguishable in
            // shape from a struct's opaque type name -- both are non-primitive PascalCase
            // strings. Checking the opaque-struct filter first would swallow every
            // dotted-path enum leaf (it never inspects `fields_enum`) and hand back a bare
            // handle for the caller to `strcmp` against, which aborts at runtime. The flat
            // (single-segment) leaf path a few lines below in `test_function.rs` already
            // orders enum-before-opaque; this nested-path leaf must match it. ~keep
            if try_emit_enum_accessor(
                out,
                prefix,
                &prefix_upper,
                raw_field,
                &seg_snake,
                &current_snake_type,
                &accessor_fn,
                &current_handle,
                local_var,
                fields_c_types,
                fields_enum,
                intermediate_handles,
            ) {
                return Ok(None);
            }
            // Opaque struct leaf: when fields_c_types maps "{parent}.{field}" to a
            // PascalCase type name (not a primitive, not "char*", not "skip"), the
            // accessor returns a struct pointer rather than a string. Emit the typed
            // handle declaration and register it for freeing.
            if let Some(opaque_type) = fields_c_types.get(&lookup_key).filter(|t| {
                *t != "char*"
                    && *t != "skip"
                    && !is_primitive_c_type(t)
                    && t.chars().next().is_some_and(|c| c.is_uppercase())
            }) {
                let handle_var = format!("{seg_snake}_handle");
                let opaque_snake = opaque_type.to_snake_case();
                if !intermediate_handles.iter().any(|(h, _)| h == &handle_var) {
                    let _ = writeln!(
                        out,
                        "    {prefix_upper}AlefHandle {handle_var} = {accessor_fn}({current_handle});"
                    );
                    intermediate_handles.push((handle_var.clone(), opaque_snake.clone()));
                }
                // Treat the handle itself as the local_var for later assertions.
                // Map local_var → handle_var so render_assertion uses the handle name.
                if local_var != handle_var {
                    let _ = writeln!(out, "    {prefix_upper}AlefHandle {local_var} = {handle_var};");
                }
                // return type name so caller can register opaque handle cleanup
                return Ok(Some(NestedLeafOutcome::Typed(opaque_snake)));
            }
            // Every branch above proved the leaf exists — an explicit `fields_c_types`
            // declaration, or an enum registration. This default proves nothing: it emits
            // `{accessor_fn}()` on faith. When the IR knows the type the walk is standing
            // on and that type has no such field, cbindgen never generated that symbol, so
            // the assertion is rendered against a function that does not exist and the
            // failure surfaces at `cc` time inside a consumer — or, if the generated suite
            // is never compiled, not at all. Nothing upstream catches it either:
            // `FieldResolver::is_valid_for_result` only inspects a path's FIRST segment, so
            // `metadata.<anything>` passes as long as `metadata` is a real field, and the
            // `fail_on_unavailable_field_markers` scan only sees skip comments that this
            // path never writes. Fail here, matching the intermediate arm below. ~keep
            ensure_leaf_field_exists(LeafFieldCheck {
                prefix,
                accessor_fn: &accessor_fn,
                resolved,
                raw_field,
                segment,
                parent_snake_type: &current_snake_type,
                parent_is_ir_type: current_type_from_ir,
                declared_in_fields_c_types: fields_c_types.contains_key(&lookup_key),
                result_type_name,
                type_defs,
                result_fields_source: &config_sources.result_fields,
                fields_source: &config_sources.fields,
            })?;
            let _ = writeln!(out, "    char* {local_var} = {accessor_fn}({current_handle});");
        } else {
            // Intermediate field — check if it's a char* (JSON string/array) or an opaque handle.
            let lookup_key = format!("{current_snake_type}.{seg_snake}");
            let return_type_pascal = match fields_c_types
                .get(&lookup_key)
                .cloned()
                .or_else(|| resolve_intermediate_type(&current_snake_type, &seg_snake, type_defs))
            {
                Some(return_type) => return_type,
                None => {
                    // No silent fallback: deriving the C type from the field name only
                    // works when the Rust return type is the literal PascalCase of the
                    // field identifier. For accessors whose return type carries a
                    // suffix (e.g. `data` -> `DataNode`, `metadata` -> `MetadataConfig`)
                    // the guessed name does not match what cbindgen emits and the
                    // generated C fails to compile with `unknown type name`. Fail loud
                    // here so the operator declares the correct C type explicitly. ~keep
                    anyhow::bail!(
                        "{}",
                        missing_intermediate_type_diagnostic(MissingIntermediateType {
                            prefix,
                            lookup_key: &lookup_key,
                            accessor_fn: &accessor_fn,
                            resolved,
                            raw_field,
                            segment,
                            seg_snake: &seg_snake,
                            segments_walked: &segments[..=i],
                            current_snake_type: &current_snake_type,
                            result_type_name,
                            type_defs,
                            fields_source: &config_sources.fields,
                        })
                    );
                }
            };

            // Special case: intermediate char* fields (e.g. links, assets) are JSON
            // strings/arrays, not opaque handles. For a `.length` suffix, emit alef_json_array_count.
            if return_type_pascal == "char*" {
                let json_var = format!("{seg_snake}_json");
                if !intermediate_handles.iter().any(|(h, _)| h == &json_var) {
                    let _ = writeln!(out, "    char* {json_var} = {accessor_fn}({current_handle});");
                    intermediate_handles.push((json_var.clone(), "free_string".to_string()));
                }
                // If the next (and final) segment is "length", emit the count accessor.
                if i + 2 == segments.len() && segments[i + 1] == "length" {
                    let _ = writeln!(out, "    int {local_var} = alef_json_array_count({json_var});");
                    return Ok(Some(NestedLeafOutcome::Typed("int".to_string())));
                }
                current_snake_type = seg_snake.clone();
                current_type_from_ir = false;
                current_handle = json_var;
                continue;
            }

            let return_snake = return_type_pascal.to_snake_case();
            let handle_var = format!("{seg_snake}_handle");

            // Only emit the handle if we haven't already (multiple fields may
            // share the same intermediate path prefix).
            if !intermediate_handles.iter().any(|(h, _)| h == &handle_var) {
                let _ = writeln!(
                    out,
                    "    {prefix_upper}AlefHandle {handle_var} = \
                     {accessor_fn}({current_handle});"
                );
                let _ = writeln!(out, "    assert({handle_var} != 0);");
                intermediate_handles.push((handle_var.clone(), return_snake.clone()));
            }

            current_type_from_ir = type_defs.iter().any(|type_def| type_def.name == return_type_pascal);
            current_snake_type = return_snake;
            current_handle = handle_var;
        }
    }
    Ok(None)
}

fn resolve_intermediate_type(
    parent_snake: &str,
    field_snake: &str,
    type_defs: &[crate::core::ir::TypeDef],
) -> Option<String> {
    let parent = type_defs
        .iter()
        .find(|type_def| type_def.name.to_snake_case() == parent_snake)?;
    let field = parent
        .fields
        .iter()
        .find(|field| field.name.to_snake_case() == field_snake)?;
    super::named_type(&field.ty).map(str::to_string)
}

/// How deep [`find_field_path`] will search for a field name below the result type.
///
/// The bound exists to terminate on a self-referential IR, not to trade off cost -- this
/// only ever runs on the way to returning an error. Six comfortably clears the chains that
/// motivated it (a real consumer's `ScrapeResult.metadata.article.tags` is three hops); a chain
/// deeper than this just loses the "here is where the field really lives" hint, it does not
/// change the error.
const MAX_FIELD_PATH_SEARCH_DEPTH: usize = 6;

/// Where a field named `field_snake` really lives below some root type.
struct ResolvedFieldChain {
    /// The dotted path from the root type down to the field, e.g. `metadata.article.tags`.
    path: String,
    /// The IR type that actually declares the field. The C accessor symbol is built from
    /// this type, not from the root -- naming it is the difference between the diagnostic
    /// pointing at `cberg_article_metadata_tags` and at the `cberg_scrape_result_tags` that
    /// does not exist.
    owner_type: String,
}

/// Every dotted path from `root_type` down to a field whose snake_case name is
/// `field_snake`, one entry per distinct declaring type, shallowest first.
///
/// Only through `TypeRef::Named` struct fields — the same hops [`emit_nested_accessor`]
/// itself can walk, so a path this returns is one the C codegen could actually emit
/// accessors for.
///
/// More than one entry means the field name is ambiguous below `root_type`: two unrelated
/// types happen to share a field name (e.g. `kind` declared on both `DataNode`, values
/// `object`/`array`/`scalar`, and `StructureItem`, values `function`/`class`). A caller that
/// would otherwise propose a single alias fix MUST check `len() > 1` first and refuse to
/// guess — silently picking one binds the fixture to a field with a different value domain
/// instead of failing loudly. Finding this required tslp-owner to catch, by hand, a
/// generated diagnostic that suggested exactly that corrupting alias. ~keep
fn find_all_field_paths(
    root_type: &str,
    field_snake: &str,
    type_defs: &[crate::core::ir::TypeDef],
) -> Vec<ResolvedFieldChain> {
    fn walk(
        type_name: &str,
        field_snake: &str,
        type_defs: &[crate::core::ir::TypeDef],
        depth: usize,
        seen: &mut HashSet<String>,
        out: &mut Vec<ResolvedFieldChain>,
    ) {
        if depth == 0 || !seen.insert(type_name.to_string()) {
            return;
        }
        let Some(type_def) = type_defs.iter().find(|type_def| type_def.name == type_name) else {
            return;
        };
        if let Some(field) = type_def
            .fields
            .iter()
            .find(|field| field.name.to_snake_case() == field_snake)
        {
            out.push(ResolvedFieldChain {
                path: field.name.to_snake_case(),
                owner_type: type_def.name.clone(),
            });
        }
        // Keep walking nested fields even after a direct hit above: a distinct type
        // reachable through a sibling or deeper field may ALSO declare `field_snake`, and
        // that collision is exactly what this function exists to surface.
        for field in &type_def.fields {
            let Some(nested) = super::named_type(&field.ty) else {
                continue;
            };
            let before = out.len();
            walk(nested, field_snake, type_defs, depth - 1, seen, out);
            for chain in &mut out[before..] {
                chain.path = format!("{}.{}", field.name.to_snake_case(), chain.path);
            }
        }
    }

    let mut out = Vec::new();
    walk(
        root_type,
        field_snake,
        type_defs,
        MAX_FIELD_PATH_SEARCH_DEPTH,
        &mut HashSet::new(),
        &mut out,
    );
    out.sort_by_key(|chain| chain.path.matches('.').count());
    out
}

/// The dotted path from `root_type` down to a field whose snake_case name is
/// `field_snake`, when the name is declared by exactly one reachable type.
///
/// Returns `None` both when no type reachable from `root_type` has such a field AND when
/// more than one distinct type does — see [`find_all_field_paths`] for why an ambiguous
/// name cannot collapse to a single answer here. Callers that need to tell those two cases
/// apart (to phrase a different diagnostic for each) must call `find_all_field_paths`
/// directly instead of this wrapper.
///
/// Test-only: every production caller needs the ambiguous and absent cases phrased differently, so
/// they all call `find_all_field_paths`. The wrapper stays to pin the collapse rule itself. ~keep
#[cfg(test)]
fn find_field_path(
    root_type: &str,
    field_snake: &str,
    type_defs: &[crate::core::ir::TypeDef],
) -> Option<ResolvedFieldChain> {
    let mut chains = find_all_field_paths(root_type, field_snake, type_defs);
    if chains.len() == 1 { chains.pop() } else { None }
}

/// The leading segments `resolved` lost to virtual-namespace stripping, if any.
///
/// [`emit_nested_accessor`] is handed the already-stripped path (the callers in
/// `test_function.rs`/`call_patterns.rs` strip before calling), so the only surviving record
/// of a stripped prefix is that `raw_field` ends with `resolved`. Recovering it is what lets
/// the diagnostic tell "add an alias" apart from "add a type mapping": a path that lost a
/// segment is almost always a missing `[crates.e2e.fields]` alias, and declaring the C type
/// the message names would instead emit a call to a symbol that does not exist. ~keep
fn stripped_namespace_prefix<'a>(raw_field: &'a str, resolved: &str) -> Option<&'a str> {
    let prefix_len = raw_field.len().checked_sub(resolved.len())?;
    if prefix_len == 0 || !raw_field.ends_with(resolved) {
        return None;
    }
    raw_field
        .get(..prefix_len)
        .and_then(|prefix| prefix.strip_suffix('.'))
        .filter(|prefix| !prefix.is_empty())
}

/// Why `resolve_intermediate_type` could not derive a C type for `{parent_snake}.{field_snake}`.
///
/// The three ways it returns `None` need three different fixes, and the missing key alone
/// cannot tell them apart: an unknown parent type means the walk arrived somewhere it should
/// never have been (usually namespace stripping), a missing field means the path is wrong,
/// and a non-`Named` field type means the path is right but the accessor returns something
/// no opaque handle can carry. ~keep
fn why_the_type_is_unknown(parent_snake: &str, field_snake: &str, type_defs: &[crate::core::ir::TypeDef]) -> String {
    let Some(parent) = type_defs
        .iter()
        .find(|type_def| type_def.name.to_snake_case() == parent_snake)
    else {
        return format!("No IR type has the snake_case name `{parent_snake}`");
    };
    let Some(field) = parent
        .fields
        .iter()
        .find(|field| field.name.to_snake_case() == field_snake)
    else {
        return format!("Type `{}` has no field `{field_snake}`", parent.name);
    };
    if super::named_type(&field.ty).is_none() {
        return format!(
            "Field `{}.{field_snake}` is not a named struct type, so no opaque accessor type can be derived from it",
            parent.name
        );
    }
    format!("Type `{}` does have a field `{field_snake}`", parent.name)
}

/// Inputs for [`missing_intermediate_type_diagnostic`]. A struct, not a dozen positional
/// `&str`s, so two of them cannot be swapped without the compiler noticing.
struct MissingIntermediateType<'a> {
    /// The crate's FFI symbol prefix, for naming the accessor that really exists.
    prefix: &'a str,
    /// The `"{parent_snake}.{field_snake}"` key that was looked up and missed.
    lookup_key: &'a str,
    /// The C symbol the walk would call if that key were simply declared.
    accessor_fn: &'a str,
    /// The (already namespace-stripped) path being walked.
    resolved: &'a str,
    /// The fixture's own field path, before alias resolution and namespace stripping.
    raw_field: &'a str,
    segment: &'a str,
    seg_snake: &'a str,
    /// `resolved`'s segments up to and including the failing one.
    segments_walked: &'a [&'a str],
    /// The snake_case type the walk is standing on.
    current_snake_type: &'a str,
    /// The type the walk started from.
    result_type_name: &'a str,
    type_defs: &'a [crate::core::ir::TypeDef],
    /// Which `fields` (alias table) governs the call this hop belongs to — threaded
    /// through so the diagnostic can name the one config key an edit will actually reach.
    fields_source: &'a EffectiveConfigSource,
}

/// Explain a missing `fields_c_types` key in terms of the chain that produced it.
///
/// The bare "missing key `{parent}.{field}`" this replaced implied its own remedy — declare
/// that key — and the implied remedy is wrong whenever the key names a field the parent type
/// does not have. Adding it silences the failure and emits a call to a C function that was
/// never generated, which then fails at `cc` time (or, worse, links against an unrelated
/// symbol). So the message has to carry three things the key alone cannot: which prefix
/// alef stripped as a virtual namespace to arrive at this path, which symbol declaring the
/// key would conjure, and where the field really lives under the result type. ~keep
fn missing_intermediate_type_diagnostic(context: MissingIntermediateType<'_>) -> String {
    let MissingIntermediateType {
        prefix,
        lookup_key,
        accessor_fn,
        resolved,
        raw_field,
        segment,
        seg_snake,
        segments_walked,
        current_snake_type,
        result_type_name,
        type_defs,
        fields_source,
    } = context;

    let mut message = format!(
        "e2e c codegen: fields_c_types is missing key \"{lookup_key}\" (path \"{resolved}\", segment \"{segment}\"), \
         reached while walking fixture field \"{raw_field}\" from result type `{result_type_name}`. {why}, so \
         declaring \"{lookup_key}\" would make the generated test call `{accessor_fn}()`. (The old fallback guessed \
         `{guess}` from the field name, which silently miscompiled whenever the Rust return type differed, e.g. \
         `DataNode` vs `Data`.)",
        why = why_the_type_is_unknown(current_snake_type, seg_snake, type_defs),
        guess = segment.to_pascal_case(),
    );

    if let Some(namespace) = stripped_namespace_prefix(raw_field, resolved) {
        let _ = write!(
            message,
            " alef stripped the leading \"{namespace}\" from \"{raw_field}\" as a virtual namespace, because no \
             `[crates.e2e.fields]` alias maps it onto a real path and its first segment is not a `result_fields` \
             entry -- which is why the walk started at `{result_type_name}` instead of inside `{namespace}`."
        );
    }

    match find_all_field_paths(result_type_name, seg_snake, type_defs).as_slice() {
        [chain] => {
            let alias_key = match stripped_namespace_prefix(raw_field, resolved) {
                Some(namespace) => format!("{namespace}.{}", segments_walked.join(".")),
                None => segments_walked.join("."),
            };
            let real_path = &chain.path;
            let real_symbol = format!("{prefix}_{}_{seg_snake}", chain.owner_type.to_snake_case());
            // Same shadowing rule as the leaf diagnostic's alias-fix branch, `fields`
            // instead of `result_fields`: a non-empty per-call `fields` override
            // replaces the global alias table outright (`E2eConfig::effective_fields`),
            // so the alias must be spelled under whichever one actually governs this
            // call. ~keep
            let fields_key = match fields_source {
                EffectiveConfigSource::Global => "`[crates.e2e.fields]`".to_string(),
                EffectiveConfigSource::PerCall(label) => format!("`{label}.fields`"),
            };
            let _ = write!(
                message,
                " Field `{seg_snake}` does exist below `{result_type_name}`, at \"{real_path}\" -- it is declared on \
                 `{owner}`, so the accessor that really exists is `{real_symbol}()`. Fix: add \
                 \"{alias_key}\" = \"{real_path}\" under {fields_key} so the fixture path resolves to the \
                 real chain. Only add \"{lookup_key}\" to `[crates.e2e.fields_c_types]` if `{accessor_fn}()` really \
                 is in the generated header.",
                owner = chain.owner_type,
            );
        }
        [] => {
            let _ = write!(
                message,
                " No type reachable from `{result_type_name}` has a field named `{seg_snake}` either, so the \
                 fixture's field path is the thing to check first -- declaring \"{lookup_key}\" cannot make \
                 `{accessor_fn}()` exist."
            );
        }
        chains => {
            let _ = write!(
                message,
                "{}",
                ambiguous_field_name_suffix(seg_snake, result_type_name, chains, fields_source)
            );
        }
    }

    message
}

/// Describe an ambiguous field name (declared by more than one distinct type reachable from
/// `result_type_name`) without picking one for the caller.
///
/// Shared by both diagnostics that would otherwise call [`find_field_path`] and silently take
/// its `None` for "field does not exist" -- an ambiguous name is a different failure mode
/// entirely, and conflating the two is how this diagnostic once recommended a corrupting
/// fix: `find_field_path` returned whichever same-named field it found first (e.g.
/// `DataNode.kind`, values `object`/`array`/`scalar`, vs an unrelated `StructureItem.kind`,
/// values `function`/`class`), and the message confidently suggested aliasing to it. Naming
/// every candidate chain, and refusing to recommend any single one of them, is the fix: the
/// operator -- who knows which chain the fixture actually means -- has to pick. ~keep
fn ambiguous_field_name_suffix(
    seg_snake: &str,
    result_type_name: &str,
    chains: &[ResolvedFieldChain],
    fields_source: &EffectiveConfigSource,
) -> String {
    let candidates: Vec<String> = chains
        .iter()
        .map(|chain| format!("\"{}\" (declared on `{}`)", chain.path, chain.owner_type))
        .collect();
    // Same shadowing rule as every other alias-fix branch in this file: a non-empty
    // per-call `fields` override replaces the global alias table outright
    // (`E2eConfig::effective_fields`), so the manual alias this suggests has to be
    // spelled under whichever one actually governs this call. ~keep
    let fields_key = match fields_source {
        EffectiveConfigSource::Global => "`[crates.e2e.fields]`".to_string(),
        EffectiveConfigSource::PerCall(label) => format!("`{label}.fields`"),
    };
    format!(
        " Field `{seg_snake}` is declared on {count} unrelated types reachable from `{result_type_name}`, with \
         different chains: {candidates} -- alef cannot tell which one the fixture means, and guessing risks \
         binding the assertion to a field with a different value domain than intended. Fix: add \
         \"<fixture path>\" = \"<the correct chain from the list above>\" under {fields_key} yourself, \
         after checking which candidate actually matches this fixture's data.",
        count = chains.len(),
        candidates = candidates.join(", "),
    )
}

/// Where a per-call-overridable e2e config collection (`result_fields`, `fields`, ...)
/// actually came from for a given call: the per-call override, or the global
/// `[crates.e2e]` default that only applies when the call declares no override of its
/// own.
///
/// Exists so a diagnostic can name the ONE config key an edit will actually reach.
/// Every `E2eConfig::effective_*` method (`effective_result_fields`, `effective_fields`,
/// ...) REPLACES the global collection outright when a call's own collection is
/// non-empty — it never merges the two — so a message that always names the global key
/// is actively wrong for every call with an override. That exact wrongness shipped once
/// already for `result_fields`: it told a consumer with a per-call override to edit the
/// global key, they did, nothing changed, and they filed it as a codegen blocker. The
/// same shape lived on, unfixed, in every diagnostic that names `[crates.e2e.fields]` —
/// this type is shared by both so the two checks cannot drift onto different resolution
/// logic the way the two hand-rolled versions of it did before this. ~keep
pub(super) enum EffectiveConfigSource {
    /// The global `[crates.e2e]` collection is what's in effect for this call.
    Global,
    /// A per-call override is what's in effect, named by its TOML table path (e.g.
    /// `"[crates.e2e.calls.crawl]"`, or the unnamed default `"[crates.e2e.call]"`).
    PerCall(String),
}

/// Determine which instance of a per-call-overridable collection governs `call`: pass
/// `call_has_override` as `!call.result_fields.is_empty()`, `!call.fields.is_empty()`,
/// etc. — whichever collection the caller is resolving — since that emptiness check is
/// the only part of [`E2eConfig::effective_result_fields`]/[`E2eConfig::effective_fields`]
/// (and siblings) that differs per collection; the "which key names it" logic that
/// follows is identical for all of them.
///
/// `call` is matched against `e2e_config.calls`/`e2e_config.call` by pointer identity
/// rather than by name, because a caller that reached `call` through
/// `resolve_call_for_fixture`'s `select_when` auto-routing does not get the matched key
/// back — the resolved `&CallConfig` reference is the only thing both the explicit-name
/// path and the auto-routed path have in common. ~keep
pub(super) fn describe_effective_config_source(
    e2e_config: &E2eConfig,
    call: &CallConfig,
    call_has_override: bool,
) -> EffectiveConfigSource {
    if !call_has_override {
        return EffectiveConfigSource::Global;
    }
    match e2e_config
        .calls
        .iter()
        .find(|(_, candidate)| std::ptr::eq(*candidate, call))
    {
        Some((name, _)) => EffectiveConfigSource::PerCall(format!("[crates.e2e.calls.{name}]")),
        None => EffectiveConfigSource::PerCall("[crates.e2e.call]".to_string()),
    }
}

/// The `result_fields` and `fields` sources actually in effect for one call, resolved
/// once per fixture and threaded through every nested-field diagnostic for it. Bundled
/// rather than passed as two loose parameters so a diagnostic that needs both (the leaf
/// diagnostic proposes a `result_fields` fix on one path and a `fields` alias fix on
/// another) cannot accidentally receive one resolved against a different call than the
/// other. ~keep
pub(super) struct FieldConfigSources {
    pub result_fields: EffectiveConfigSource,
    pub fields: EffectiveConfigSource,
}

impl FieldConfigSources {
    pub(super) fn resolve(e2e_config: &E2eConfig, call: &CallConfig) -> Self {
        Self {
            result_fields: describe_effective_config_source(e2e_config, call, !call.result_fields.is_empty()),
            fields: describe_effective_config_source(e2e_config, call, !call.fields.is_empty()),
        }
    }
}

/// Inputs for [`ensure_leaf_field_exists`]. A struct, not a handful of positional
/// `&str`s, for the same reason [`MissingIntermediateType`] is one.
pub(super) struct LeafFieldCheck<'a> {
    /// The crate's FFI symbol prefix, for naming the accessor that really exists.
    pub prefix: &'a str,
    /// The C symbol the caller is about to emit for this leaf.
    pub accessor_fn: &'a str,
    /// The (alias-resolved, already namespace-stripped) path being walked.
    pub resolved: &'a str,
    /// The fixture's own field path, before alias resolution and namespace stripping.
    pub raw_field: &'a str,
    /// The leaf segment itself, in its fixture spelling.
    pub segment: &'a str,
    /// The snake_case name of the type the accessor will be called on.
    pub parent_snake_type: &'a str,
    /// Whether `parent_snake_type` really names an IR type. False after a `char*` hop,
    /// where it holds a *field* name, and for a result type the IR does not model — in
    /// both cases an IR type sharing the name is a coincidence, not the parent.
    pub parent_is_ir_type: bool,
    /// Whether the operator declared this exact leaf in `[crates.e2e.fields_c_types]`.
    /// An explicit declaration is a claim that the accessor exists, and stays authoritative.
    pub declared_in_fields_c_types: bool,
    /// The type the walk started from.
    pub result_type_name: &'a str,
    pub type_defs: &'a [crate::core::ir::TypeDef],
    /// Which `result_fields` set governs the call this leaf belongs to — threaded through
    /// so the diagnostic can name the one config key an edit will actually reach.
    pub result_fields_source: &'a EffectiveConfigSource,
    /// Which `fields` (alias table) governs the call this leaf belongs to — same reason
    /// as `result_fields_source`, for the diagnostic's alias-fix branches.
    pub fields_source: &'a EffectiveConfigSource,
}

/// Reject a leaf field the IR positively says the parent type does not have.
///
/// The C accessor for a leaf is `{prefix}_{parent_snake}_{leaf_snake}`, built from a name
/// rather than looked up, so nothing but the IR can tell a real accessor from a fabricated
/// one. Default-allow everywhere the IR cannot answer: silence is not evidence of absence,
/// and this is a hard generation failure. ~keep
pub(super) fn ensure_leaf_field_exists(check: LeafFieldCheck<'_>) -> anyhow::Result<()> {
    if !check.parent_is_ir_type || check.declared_in_fields_c_types || check.resolved.contains('[') {
        return Ok(());
    }
    let seg_snake = check.segment.to_snake_case();
    let Some(parent) = check
        .type_defs
        .iter()
        .find(|type_def| type_def.name.to_snake_case() == check.parent_snake_type)
    else {
        return Ok(());
    };
    if parent
        .fields
        .iter()
        .any(|field| field.name.to_snake_case() == seg_snake)
    {
        return Ok(());
    }
    anyhow::bail!(
        "{}",
        unknown_leaf_field_diagnostic(UnknownLeafField {
            prefix: check.prefix,
            accessor_fn: check.accessor_fn,
            resolved: check.resolved,
            raw_field: check.raw_field,
            segment: check.segment,
            seg_snake: &seg_snake,
            parent_type: &parent.name,
            result_type_name: check.result_type_name,
            type_defs: check.type_defs,
            result_fields_source: check.result_fields_source,
            fields_source: check.fields_source,
        })
    )
}

/// Inputs for [`unknown_leaf_field_diagnostic`], resolved from a [`LeafFieldCheck`].
struct UnknownLeafField<'a> {
    prefix: &'a str,
    accessor_fn: &'a str,
    resolved: &'a str,
    raw_field: &'a str,
    segment: &'a str,
    seg_snake: &'a str,
    /// The IR type the walk is standing on, in its declared PascalCase spelling.
    parent_type: &'a str,
    result_type_name: &'a str,
    type_defs: &'a [crate::core::ir::TypeDef],
    result_fields_source: &'a EffectiveConfigSource,
    fields_source: &'a EffectiveConfigSource,
}

/// Explain a leaf segment that names no field of the type the walk arrived at.
///
/// The intermediate arm can at least offer "declare the C type"; a leaf cannot, because the
/// leaf accessor is emitted from the parent type and the field name alone. So the only
/// honest remedies are the alias that reconnects the fixture path to the real chain, or
/// fixing the fixture path — and the message has to say which, by looking up where the field
/// really lives. Same three facts as [`missing_intermediate_type_diagnostic`], same
/// resolution machinery, different remedy. ~keep
fn unknown_leaf_field_diagnostic(context: UnknownLeafField<'_>) -> String {
    let UnknownLeafField {
        prefix,
        accessor_fn,
        resolved,
        raw_field,
        segment,
        seg_snake,
        parent_type,
        result_type_name,
        type_defs,
        result_fields_source,
        fields_source,
    } = context;

    let mut message = format!(
        "e2e c codegen: fixture field \"{raw_field}\" (path \"{resolved}\") ends at segment \"{segment}\", but IR \
         type `{parent_type}` has no field `{seg_snake}`. The walk was about to emit `{accessor_fn}()`, a C symbol \
         no binding generates, so this assertion would have been rendered against a function that does not exist. \
         Nothing upstream rejects it: the field-availability oracle (`FieldResolver::is_valid_for_result`) only \
         inspects a path's FIRST segment, which is a real field here."
    );

    let namespace = stripped_namespace_prefix(raw_field, resolved);
    if let Some(namespace) = namespace {
        let _ = write!(
            message,
            " alef stripped the leading \"{namespace}\" from \"{raw_field}\" as a virtual namespace, because no \
             `[crates.e2e.fields]` alias maps it onto a real path and its first segment is not a `result_fields` \
             entry -- which is why the walk started at `{result_type_name}` instead of inside `{namespace}`."
        );
    }

    let chains = find_all_field_paths(result_type_name, seg_snake, type_defs);
    let chain = match chains.as_slice() {
        [chain] => chain,
        [] => {
            let _ = write!(
                message,
                " No type reachable from `{result_type_name}` has a field named `{seg_snake}` either, so the \
                 fixture's field path is the thing to fix -- there is no config entry that can spell a chain which \
                 does not exist."
            );
            return message;
        }
        chains => {
            let _ = write!(
                message,
                "{}",
                ambiguous_field_name_suffix(seg_snake, result_type_name, chains, fields_source)
            );
            return message;
        }
    };

    let real_path = &chain.path;
    let real_symbol = format!("{prefix}_{}_{seg_snake}", chain.owner_type.to_snake_case());
    let _ = write!(
        message,
        " Field `{seg_snake}` does exist below `{result_type_name}`, at \"{real_path}\" -- it is declared on \
         `{owner}`, so the accessor that really exists is `{real_symbol}()`.",
        owner = chain.owner_type,
    );

    // Two different config bugs produce this, and they take opposite fixes. When the real
    // chain starts with the prefix that was stripped, the fixture path was right all along
    // and the stripping was the mistake -- an alias would be an identity mapping and change
    // nothing, because `namespace_stripped_path` consults only `result_fields`. Otherwise the
    // fixture path genuinely names a chain that does not exist and needs an alias. ~keep
    match namespace.filter(|namespace| real_path.starts_with(&format!("{namespace}."))) {
        Some(namespace) => {
            // `result_fields` here means whichever set `effective_result_fields` actually
            // resolved for THIS call -- a non-empty per-call override replaces the global
            // default outright (see `E2eConfig::effective_result_fields`), so naming the
            // global key when a per-call override shadows it sends an edit nowhere: a
            // consumer followed exactly that instruction, edited the global key, and it
            // changed nothing because their call had its own `result_fields`. ~keep
            let result_fields_key = match result_fields_source {
                EffectiveConfigSource::Global => "`[crates.e2e].result_fields`".to_string(),
                EffectiveConfigSource::PerCall(label) => format!("`{label}.result_fields`"),
            };
            let _ = write!(
                message,
                " Fix: add \"{namespace}\" to {result_fields_key} so alef stops treating it as a virtual \
                 namespace prefix and walks it as the real field it is. An alias here would be an identity mapping \
                 and would not stop the stripping."
            );
        }
        None => {
            // Same shadowing rule, `[crates.e2e.fields]` instead of `.result_fields`: a
            // non-empty per-call `fields` override replaces the global alias table
            // outright (`E2eConfig::effective_fields`), so the alias must be spelled
            // under whichever one actually governs this call. ~keep
            let fields_key = match fields_source {
                EffectiveConfigSource::Global => "`[crates.e2e.fields]`".to_string(),
                EffectiveConfigSource::PerCall(label) => format!("`{label}.fields`"),
            };
            let _ = write!(
                message,
                " Fix: add \"{raw_field}\" = \"{real_path}\" under {fields_key} so the fixture path \
                 resolves to the real chain."
            );
        }
    }

    message
}

/// The three-state view of the target's declared parameters this file renders against.
///
/// Defined in [`crate::e2e::codegen::call_ir`] because every backend needs the same three
/// states; the C-specific part is what this file *does* with them, not the states. ~keep
pub(super) use crate::e2e::codegen::call_ir::TargetParams;

/// The `alef.toml` key whose `args` list governs this fixture's call, named so every
/// diagnostic below points the operator at the table they actually have to edit -- the
/// per-call `[crates.e2e.calls.<name>]` one when the fixture selects a named call, the
/// default `[crates.e2e.call]` otherwise. ~keep
fn args_config_key(fixture: &Fixture) -> String {
    match fixture.call.as_deref() {
        Some(name) => format!("[crates.e2e.calls.{name}].args"),
        None => "[crates.e2e.call].args".to_string(),
    }
}

/// Fixture "{id}" calls `{function_name}` with no configured `args`, but the target's IR
/// signature declares real parameters -- an authoring gap, not a zero-argument call. ~keep
fn missing_args_for_known_params_diagnostic(
    fixture: &Fixture,
    function_name: &str,
    params: &[crate::core::ir::ParamDef],
) -> String {
    let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
    let call_key = args_config_key(fixture);
    format!(
        "e2e c codegen: fixture \"{id}\" calls `{function_name}` with no configured `args`, but the Rust core \
         signature for `{function_name}` declares {count} parameter(s): {joined_names}. With no `args` \
         configured, alef used to splice the fixture's whole `input` JSON as a single C string literal \
         regardless of what the target actually takes, which does not compile against anything but a lone \
         string parameter. Fix: add an `args` entry under `{call_key}` for each parameter, mapping it to the \
         fixture input field that supplies it.",
        id = fixture.id,
        count = params.len(),
        joined_names = names.join(", "),
    )
}

/// Fixture "{id}" calls `{function_name}` with no configured `args`, and alef cannot resolve
/// the target's IR signature at all -- refuse rather than guess whether that is a genuine
/// zero-argument call or a missing `args` configuration. ~keep
fn missing_args_unresolvable_signature_diagnostic(fixture: &Fixture, function_name: &str) -> String {
    let call_key = args_config_key(fixture);
    format!(
        "e2e c codegen: fixture \"{id}\" calls `{function_name}` with no configured `args`, and alef could not \
         resolve `{function_name}` against the Rust core IR, so it cannot tell a genuine zero-argument call from \
         a missing `args` configuration -- guessing risks splicing the fixture's whole `input` JSON as one C \
         literal against a target that takes real, typed parameters. Fix: configure `args` under `{call_key}`, \
         one entry per parameter `{function_name}` actually takes. If it genuinely takes none, check that this \
         call's `function` name (and any per-language override) matches a real core function or method name -- \
         an unresolvable name is why alef cannot confirm that on its own.",
        id = fixture.id,
    )
}

/// How much of the offending literal [`handle_param_type_mismatch_diagnostic`] quotes back.
///
/// The value is named so the operator can find the `args` entry that produced it, but a
/// fixture `input` can be arbitrarily large and the diagnostic is not a place to reprint it. ~keep
const MAX_DIAGNOSTIC_VALUE_CHARS: usize = 80;

/// Fixture "{id}" maps an `args` entry onto a parameter the C ABI exports as an opaque
/// handle, but the fixture value lowers to a plain C literal. ~keep
fn handle_param_type_mismatch_diagnostic(
    fixture: &Fixture,
    function_name: &str,
    arg: &crate::e2e::config::ArgMapping,
    param: &crate::core::ir::ParamDef,
    param_type: &crate::core::ir::TypeDef,
    rendered: &str,
) -> String {
    let call_key = args_config_key(fixture);
    let quoted: String = rendered.chars().take(MAX_DIAGNOSTIC_VALUE_CHARS).collect();
    let elided = if quoted.len() < rendered.len() { "..." } else { "" };
    let type_name = &param_type.name;
    let mut message = format!(
        "e2e c codegen: fixture \"{id}\" maps `args` entry \"{arg_name}\" (type = \"{arg_type}\", field = \
         \"{field}\") onto parameter `{param_name}` of `{function_name}`, which the Rust core declares as \
         `{type_name}` and the C ABI exports as `AlefHandle` -- an unsigned integer handle, not a pointer or \
         a string. The fixture value lowers to the C literal {quoted}{elided}, and passing a literal where a \
         handle is expected does not compile (`incompatible pointer to integer conversion`). A handle only \
         exists once something constructs it, and alef will not fabricate one.",
        id = fixture.id,
        arg_name = arg.name,
        arg_type = arg.arg_type,
        field = arg.field,
        param_name = param.name,
    );
    if arg.arg_type == "json_object" {
        let _ = write!(
            message,
            " This entry already declares `type = \"json_object\"`, so the gap is on alef's side: this call \
             path rendered the arguments without constructing any typed handle first (the `returns_void` \
             snippet path in `c/test_function.rs` passes an empty handle map, unlike the free-function path, \
             which emits the `from_json` construction ahead of the call). Until that path constructs handles, \
             this fixture needs an extension-owned documentation recipe for C, or a documented \
             `coverage_exceptions` entry."
        );
    } else if param_type.has_serde {
        let _ = write!(
            message,
            " Fix: set `type = \"json_object\"` and `element_type = \"{type_name}\"` on that entry under \
             {call_key}, so alef constructs the handle with the generated `from_json` helper and passes that \
             instead of the literal."
        );
    } else {
        let _ = write!(
            message,
            " `{type_name}` derives no serde, so the FFI crate exports no `from_json` constructor for it and \
             `type = \"json_object\"` would name a symbol that does not exist. This fixture needs an \
             extension-owned documentation recipe for C, or a documented `coverage_exceptions` entry."
        );
    }
    message
}

/// Refuse an argument whose lowering contradicts the type of the parameter it lands in.
///
/// The sibling refusal above covers the ABSENCE of `args` -- "no args configured, do not
/// fabricate an argument list". This covers the opposite case, which nothing checked: `args`
/// are present, so the arity is satisfied and no refusal fires, but the value is rendered by
/// `json_to_c` with no reference whatsoever to what the parameter is declared to be. A fixture
/// `input` object lowered that way becomes a C string literal, and against a parameter the FFI
/// exports as `AlefHandle` that is an int-conversion error, not a working call.
///
/// The check is deliberately narrow, because a false refusal deletes published documentation:
/// it fires only when the IR both names the parameter's type and carries a `TypeDef` for it.
/// An IR enum is an `EnumDef`, never a `TypeDef`, and enum-typed `Named` parameters cross as
/// `i32` rather than as a handle -- so a name that matches no `TypeDef` cannot be proven to be
/// a handle and is left alone. Parameter matching follows `resolve_call_info`'s `element_type`
/// backfill in `c.rs` exactly (by name, else positionally); the two must agree about which
/// parameter an `args` entry fills or they would be reasoning about different parameters. ~keep
fn ensure_arg_matches_param_type(
    fixture: &Fixture,
    function_name: &str,
    arg: &crate::e2e::config::ArgMapping,
    index: usize,
    params: &[crate::core::ir::ParamDef],
    type_defs: &[crate::core::ir::TypeDef],
    rendered: &str,
) -> anyhow::Result<()> {
    let Some(param) = TargetParams::Known(params).param_for(&arg.name, index) else {
        return Ok(());
    };
    let Some(type_name) = handle_param_type_name(&param.ty) else {
        return Ok(());
    };
    let Some(param_type) = type_defs.iter().find(|type_def| type_def.name == type_name) else {
        return Ok(());
    };
    anyhow::bail!(
        "{}",
        handle_param_type_mismatch_diagnostic(fixture, function_name, arg, param, param_type, rendered)
    )
}

/// Build the C argument string for the function call.
/// When `has_options_handle` is true, json_object args are replaced with
/// the `options_handle` pointer (which was constructed via `from_json`).
///
/// `target_params` decides what an empty `args` renders as: a genuinely zero-argument target
/// (`TargetParams::Known(&[])`) emits `""` (an empty call), anything else refuses rather than
/// fabricate an argument list the target's real parameters (or the emitter's ignorance of
/// them) cannot justify. See [`TargetParams`].
///
/// It also decides whether a *present* argument may be rendered at all: a satisfied argument
/// count is not a satisfied argument type, so every value that would be lowered by `json_to_c`
/// is checked against the parameter it fills -- see [`ensure_arg_matches_param_type`].
#[allow(clippy::too_many_arguments)]
pub(super) fn build_args_string_c(
    input: &serde_json::Value,
    args: &[crate::e2e::config::ArgMapping],
    typed_arg_handles: &HashMap<String, String>,
    config: &ResolvedCrateConfig,
    type_defs: &[crate::core::ir::TypeDef],
    fixture: &Fixture,
    function_name: &str,
    target_params: TargetParams<'_>,
) -> anyhow::Result<String> {
    if args.is_empty() {
        return match target_params {
            TargetParams::Known([]) => Ok(String::new()),
            TargetParams::Known(params) => {
                anyhow::bail!(
                    "{}",
                    missing_args_for_known_params_diagnostic(fixture, function_name, params)
                )
            }
            TargetParams::IrAbsent => Ok(json_to_c(input)),
            TargetParams::Unresolvable => {
                anyhow::bail!(
                    "{}",
                    missing_args_unresolvable_signature_diagnostic(fixture, function_name)
                )
            }
        };
    }

    // The parameters a rendered argument can be checked against, if any. `IrAbsent` and
    // `Unresolvable` learned nothing about the target, so they license no type claim -- the
    // same asymmetry the empty-`args` match above encodes. ~keep
    let known_params = target_params.known();

    let mut parts: Vec<String> = Vec::new();

    for (index, arg) in args.iter().enumerate() {
        // Handle test_backend args: emit the stub and use it.
        if arg.arg_type == "test_backend" {
            // A `test_backend` arg fills a C trait-bridge vtable-pointer parameter.
            // There is no fixture-supplied value to fall back to: an unregistered
            // trait has no vtable to point at, and `emit_test_backend` panics rather
            // than hand back a placeholder for `parts` to splice in as an
            // expression — splicing either would emit C that cannot compile. Unlike a non-null-typed
            // target language, C's type system would happily accept a `NULL` fallback
            // here too (any pointer type admits it), so the compiler can't be relied on
            // to catch a bad default the way it can elsewhere — fail loud here instead,
            // matching every other "cannot render this" case in this file (see
            // `resolve_intermediate_type`'s `None` arm above, and the assertion-type
            // panics below). ~keep
            let Some(trait_name) = &arg.trait_name else {
                panic!(
                    "C e2e generator: fixture `{}` declares a `test_backend` arg `{}` with no `trait_name` configured; cannot generate a C stub without knowing which trait to implement",
                    fixture.id, arg.name
                );
            };
            let Some(trait_bridge) = config.trait_bridges.iter().find(|tb| tb.trait_name == *trait_name) else {
                panic!(
                    "C e2e generator: fixture `{}` requires trait `{trait_name}` for its `test_backend` arg `{}`, but no `[[crates.trait_bridges]]` entry named `{trait_name}` is configured",
                    fixture.id, arg.name
                );
            };
            let mut methods: Vec<&crate::core::ir::MethodDef> = type_defs
                .iter()
                .find(|t| t.name == *trait_name)
                .map(|t| t.methods.iter().collect())
                .unwrap_or_default();
            if let Some(super_trait) = &trait_bridge.super_trait
                && let Some(super_type) = type_defs.iter().find(|t| &t.rust_path == super_trait)
            {
                for method in &super_type.methods {
                    if !methods.iter().any(|m| m.name == method.name) {
                        methods.push(method);
                    }
                }
            }
            // `emit_test_backend` panics rather than return a placeholder when the C
            // test-backend emitter is unimplemented — see `TestBackendEmission`'s and
            // `trait_bridge_snippet::emit_test_backend`'s doc comments. ~keep
            let emission = crate::e2e::codegen::emit_test_backend("c", trait_bridge, &methods, fixture, &[]);
            parts.push(emission.arg_expr);
            continue;
        }

        let val = crate::e2e::codegen::resolve_field(input, &arg.field);
        match val {
            // ~keep Explicit null on optional arg → pass the type-appropriate "none"
            // sentinel: `0` for a scalar `AlefHandle` arg, `NULL` for a real pointer.
            v if v.is_null() && arg.optional => parts.push(c_optional_sentinel(&arg.arg_type).to_string()),
            // Missing required fields resolve to null; skip them so malformed
            // fixture configuration does not crash generation.
            v if v.is_null() => {}
            v => {
                // For json_object args, use the options_handle pointer
                // instead of the raw JSON string.
                if let Some(handle) = typed_arg_handles.get(&arg.name) {
                    parts.push(handle.clone())
                } else {
                    let rendered = json_to_c(v);
                    // `json_to_c` answers only to the shape of the JSON value; nothing above
                    // has consulted the parameter this expression lands in. This is the one
                    // point where both facts are in hand. ~keep
                    if let Some(params) = known_params {
                        ensure_arg_matches_param_type(
                            fixture,
                            function_name,
                            arg,
                            index,
                            params,
                            type_defs,
                            &rendered,
                        )?;
                    }
                    parts.push(rendered)
                }
            }
        }
    }

    Ok(parts.join(", "))
}

#[allow(clippy::too_many_arguments)]
pub(super) fn render_assertion(
    out: &mut String,
    assertion: &Assertion,
    result_var: &str,
    ffi_prefix: &str,
    _field_resolver: &FieldResolver,
    accessed_fields: &[(String, String, bool)],
    primitive_locals: &HashMap<String, String>,
    opaque_handle_locals: &HashMap<String, String>,
    wildcard_locals: &HashMap<String, (String, String)>,
) {
    // Skip assertions on fields that don't exist on the result type.
    if let Some(f) = &assertion.field
        && !f.is_empty()
        && !_field_resolver.is_valid_for_result(f)
    {
        let _ = writeln!(
            out,
            "    // skipped: {}",
            FieldSkip::NotAvailableOnResultType.message(f)
        );
        return;
    }

    let field_expr = match &assertion.field {
        Some(f) if !f.is_empty() => {
            // Use the local variable extracted from the opaque handle.
            accessed_fields
                .iter()
                .find(|(k, _, _)| k == f)
                .map(|(_, local, _)| local.clone())
                .unwrap_or_else(|| result_var.to_string())
        }
        _ => result_var.to_string(),
    };

    // `field[].key`: the extraction phase declared no scalar local for it (see
    // `emit_nested_accessor`'s wildcard leaf), only registered `array_var`/`key_snake` here.
    // Render the per-element quantifier and stop — none of the scalar branches below apply.
    if let Some((array_var, key_snake)) = wildcard_locals.get(&field_expr) {
        render_wildcard_assertion(out, assertion, array_var, key_snake);
        return;
    }

    // If the field was marked with the "__skip__" sentinel (fields_c_types = "skip"),
    // the accessor was never emitted — skip the assertion silently.
    if primitive_locals.get(&field_expr).is_some_and(|t| t == "__skip__") {
        let _ = writeln!(
            out,
            "    // skipped: {}",
            FieldSkip::NotAvailableInCFfi.message(&field_expr)
        );
        return;
    }

    let field_is_primitive = primitive_locals.contains_key(&field_expr);
    let field_primitive_type = primitive_locals.get(&field_expr).cloned();
    // Opaque-handle fields (e.g. `usage` → SAMPLELLMUsage*, or an enum field a missing
    // `fields_enum`/IR-enum declaration failed to route through `try_emit_enum_accessor`)
    // cannot be treated as C strings — `strlen`/`strcmp`/`strstr`/`regexec` on a scalar
    // `AlefHandle` (`uint64_t`) is undefined behavior at best and a type error at worst.
    // Every string-shaped assertion arm below guards on this flag and falls back to a
    // non-zero existence check (matching the sentinel the handle actually uses) rather
    // than emitting a comparison against a value the ABI carries as an integer. ~keep
    let field_is_opaque_handle = opaque_handle_locals.contains_key(&field_expr);
    // Map-access fields are extracted via `alef_json_get_string` and end up
    // as char*. When the assertion expects a numeric or boolean value, we
    // emit a parsed/literal comparison rather than `strcmp`.
    let field_is_map_access = if let Some(f) = &assertion.field {
        accessed_fields.iter().any(|(k, _, m)| k == f && *m)
    } else {
        false
    };

    // Check if the assertion field is optional — used to emit conditional assertions
    // for optional numeric fields (returns 0 when None, so 0 == "not set").
    // Check both the raw field name and its resolved alias.
    let assertion_field_is_optional = assertion
        .field
        .as_deref()
        .map(|f| {
            if f.is_empty() {
                return false;
            }
            if _field_resolver.is_optional(f) {
                return true;
            }
            // Also check the resolved alias (e.g. "robots.crawl_delay" → "crawl_delay").
            let resolved = _field_resolver.resolve(f);
            _field_resolver.is_optional(resolved)
        })
        .unwrap_or(false);

    match assertion.assertion_type.as_str() {
        "equals" => {
            if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                if field_is_primitive {
                    let cmp_val = if field_primitive_type.as_deref() == Some("bool") {
                        match expected.as_bool() {
                            Some(true) => "1".to_string(),
                            Some(false) => "0".to_string(),
                            None => c_val,
                        }
                    } else {
                        c_val
                    };
                    // For optional numeric fields, treat 0 as "not set" and allow it.
                    // This mirrors Go's nil-pointer check for optional fields. Excludes a
                    // boolean equals-assertion even when `field_primitive_type` spells the
                    // field's real C type as `int32_t` rather than the literal string `bool`
                    // (bool crosses the FFI ABI as `int32_t`, and `primitive_field_inference`'s
                    // IR-derived entries record that exact spelling): `false` (`0`) is a real,
                    // legitimate value for a boolean field, not an "unset" sentinel, so a
                    // `equals: false` assertion against an optional bool field must never pass
                    // merely because 0 also means "not set" for an unrelated numeric optional. ~keep
                    let is_numeric =
                        field_primitive_type.as_deref().map(|t| t != "bool").unwrap_or(false) && !expected.is_boolean();
                    if assertion_field_is_optional && is_numeric {
                        let _ = writeln!(
                            out,
                            "    assert(({field_expr} == 0 || {field_expr} == {cmp_val}) && \"equals assertion failed\");"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "    assert({field_expr} == {cmp_val} && \"equals assertion failed\");"
                        );
                    }
                } else if field_is_opaque_handle {
                    if expected.is_number() {
                        // A numeric expected value compares exactly against the handle.
                        let _ = writeln!(
                            out,
                            "    assert({field_expr} == {c_val} && \"equals assertion failed\");"
                        );
                    } else {
                        // A string expected value against a handle means the field should
                        // have been routed through `try_emit_enum_accessor` and wasn't;
                        // `field_expr == "..."` would compile as a pointer comparison that
                        // always lies, so weaken to existence instead of emitting that.
                        let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
                    }
                } else if expected.is_string() {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && strcmp({field_expr}, {c_val}) == 0 && \"equals assertion failed\");"
                    );
                } else if field_is_map_access && expected.is_boolean() {
                    let lit = match expected.as_bool() {
                        Some(true) => "\"true\"",
                        _ => "\"false\"",
                    };
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && strcmp({field_expr}, {lit}) == 0 && \"equals assertion failed\");"
                    );
                } else if field_is_map_access && expected.is_number() {
                    if expected.is_f64() {
                        let _ = writeln!(
                            out,
                            "    assert({field_expr} != NULL && atof({field_expr}) == {c_val} && \"equals assertion failed\");"
                        );
                    } else {
                        let _ = writeln!(
                            out,
                            "    assert({field_expr} != NULL && atoll({field_expr}) == {c_val} && \"equals assertion failed\");"
                        );
                    }
                } else {
                    let _ = writeln!(
                        out,
                        "    assert(strcmp({field_expr}, {c_val}) == 0 && \"equals assertion failed\");"
                    );
                }
            }
        }
        "contains" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                let _ = writeln!(
                    out,
                    "    assert({field_expr} != NULL && strstr({field_expr}, {c_val}) != NULL && \"expected to contain substring\");"
                );
            }
        }
        "contains_all" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(values) = &assertion.values {
                for val in values {
                    let c_val = json_to_c(val);
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && strstr({field_expr}, {c_val}) != NULL && \"expected to contain substring\");"
                    );
                }
            }
        }
        "not_contains" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                let _ = writeln!(
                    out,
                    "    assert({field_expr} != NULL && strstr({field_expr}, {c_val}) == NULL && \"expected non-null value without substring\");"
                );
            }
        }
        "not_empty" => {
            if field_is_opaque_handle {
                // ~keep Opaque handle: `strlen` on a scalar `AlefHandle` (uint64_t) is a
                // type error, not just UB on a struct pointer. Weaken to a
                // non-zero check — strictly weaker than the original intent but
                // matches the handle's actual "none" sentinel (`0`, not `NULL`).
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else {
                // A `char*` leaf can hold plain text OR the serialized JSON text of a
                // collection field (e.g. `alef_json_array_count`'s own input) — an empty
                // collection serializes as the two-byte string "[]"/"{}", not "", so `strlen`
                // alone reads it as non-empty. `c/scalar_or_collection_empty.jinja` accepts
                // either empty form. ~keep
                let condition = crate::e2e::template_env::render(
                    "c/scalar_or_collection_empty.jinja",
                    minijinja::context! { field_expr => field_expr, negate => true, allow_null => false },
                );
                let _ = writeln!(
                    out,
                    "    assert({} && \"expected non-empty value\");",
                    condition.trim_end()
                );
            }
        }
        "is_empty" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} == 0 && \"expected null handle\");");
            } else if assertion_field_is_optional || !field_is_primitive {
                // Optional string fields may return NULL — treat NULL as empty.
                let condition = crate::e2e::template_env::render(
                    "c/scalar_or_collection_empty.jinja",
                    minijinja::context! { field_expr => field_expr, negate => false, allow_null => true },
                );
                let _ = writeln!(out, "    assert({} && \"expected empty value\");", condition.trim_end());
            } else {
                let condition = crate::e2e::template_env::render(
                    "c/scalar_or_collection_empty.jinja",
                    minijinja::context! { field_expr => field_expr, negate => false, allow_null => false },
                );
                let _ = writeln!(out, "    assert({} && \"expected empty value\");", condition.trim_end());
            }
        }
        "contains_any" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(values) = &assertion.values {
                let _ = writeln!(out, "    {{");
                let _ = writeln!(out, "        int found = 0;");
                for val in values {
                    let c_val = json_to_c(val);
                    let _ = writeln!(
                        out,
                        "        if (strstr({field_expr}, {c_val}) != NULL) {{ found = 1; }}"
                    );
                }
                let _ = writeln!(
                    out,
                    "        assert(found && \"expected to contain at least one of the specified values\");"
                );
                let _ = writeln!(out, "    }}");
            }
        }
        "greater_than" => {
            if let Some(val) = &assertion.value {
                let c_val = json_to_c(val);
                if field_is_map_access && val.is_number() && !field_is_primitive {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && atof({field_expr}) > {c_val} && \"expected greater than\");"
                    );
                } else {
                    let _ = writeln!(out, "    assert({field_expr} > {c_val} && \"expected greater than\");");
                }
            }
        }
        "less_than" => {
            if let Some(val) = &assertion.value {
                let c_val = json_to_c(val);
                if field_is_map_access && val.is_number() && !field_is_primitive {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && atof({field_expr}) < {c_val} && \"expected less than\");"
                    );
                } else {
                    let _ = writeln!(out, "    assert({field_expr} < {c_val} && \"expected less than\");");
                }
            }
        }
        "greater_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let c_val = json_to_c(val);
                if field_is_map_access && val.is_number() && !field_is_primitive {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && atof({field_expr}) >= {c_val} && \"expected greater than or equal\");"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} >= {c_val} && \"expected greater than or equal\");"
                    );
                }
            }
        }
        "less_than_or_equal" => {
            if let Some(val) = &assertion.value {
                let c_val = json_to_c(val);
                if field_is_map_access && val.is_number() && !field_is_primitive {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} != NULL && atof({field_expr}) <= {c_val} && \"expected less than or equal\");"
                    );
                } else {
                    let _ = writeln!(
                        out,
                        "    assert({field_expr} <= {c_val} && \"expected less than or equal\");"
                    );
                }
            }
        }
        "starts_with" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                let _ = writeln!(
                    out,
                    "    assert(strncmp({field_expr}, {c_val}, strlen({c_val})) == 0 && \"expected to start with\");"
                );
            }
        }
        "ends_with" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                let _ = writeln!(out, "    assert(strlen({field_expr}) >= strlen({c_val}) && ");
                let _ = writeln!(
                    out,
                    "           strcmp({field_expr} + strlen({field_expr}) - strlen({c_val}), {c_val}) == 0 && \"expected to end with\");"
                );
            }
        }
        "min_length" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(
                    out,
                    "    assert(strlen({field_expr}) >= {n} && \"expected minimum length\");"
                );
            }
        }
        "max_length" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(
                    out,
                    "    assert(strlen({field_expr}) <= {n} && \"expected maximum length\");"
                );
            }
        }
        "count_min" => {
            if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(out, "    {{");
                let _ = writeln!(out, "        /* count_min: count top-level JSON array elements */");
                let _ = writeln!(
                    out,
                    "        assert({field_expr} != NULL && \"expected non-null collection JSON\");"
                );
                let _ = writeln!(out, "        int elem_count = alef_json_array_count({field_expr});");
                let _ = writeln!(
                    out,
                    "        assert(elem_count >= {n} && \"expected at least {n} elements\");"
                );
                let _ = writeln!(out, "    }}");
            }
        }
        "count_equals" => {
            if let Some(val) = &assertion.value
                && let Some(n) = val.as_u64()
            {
                let _ = writeln!(out, "    {{");
                let _ = writeln!(out, "        /* count_equals: count elements in array */");
                let _ = writeln!(
                    out,
                    "        assert({field_expr} != NULL && \"expected non-null collection JSON\");"
                );
                let _ = writeln!(out, "        int elem_count = alef_json_array_count({field_expr});");
                let _ = writeln!(out, "        assert(elem_count == {n} && \"expected {n} elements\");");
                let _ = writeln!(out, "    }}");
            }
        }
        "is_true" => {
            let _ = writeln!(out, "    assert({field_expr});");
        }
        "is_false" => {
            let _ = writeln!(out, "    assert(!{field_expr});");
        }
        "method_result" => {
            if let Some(method_name) = &assertion.method {
                render_method_result_assertion(
                    out,
                    result_var,
                    ffi_prefix,
                    method_name,
                    assertion.args.as_ref(),
                    assertion.return_type.as_deref(),
                    assertion.check.as_deref().unwrap_or("is_true"),
                    assertion.value.as_ref(),
                );
            } else {
                panic!("C e2e generator: method_result assertion missing 'method' field");
            }
        }
        "matches_regex" => {
            if field_is_opaque_handle {
                let _ = writeln!(out, "    assert({field_expr} != 0 && \"expected non-null handle\");");
            } else if let Some(expected) = &assertion.value {
                let c_val = json_to_c(expected);
                let _ = writeln!(out, "    {{");
                let _ = writeln!(out, "        regex_t _re;");
                let _ = writeln!(
                    out,
                    "        assert(regcomp(&_re, {c_val}, REG_EXTENDED) == 0 && \"regex compile failed\");"
                );
                let _ = writeln!(
                    out,
                    "        assert(regexec(&_re, {field_expr}, 0, NULL, 0) == 0 && \"expected value to match regex\");"
                );
                let _ = writeln!(out, "        regfree(&_re);");
                let _ = writeln!(out, "    }}");
            }
        }
        "not_error" => {
            // Already handled — the NULL check above covers this.
        }
        "error" => {
            // Handled at the test function level.
        }
        other => {
            panic!("C e2e generator: unsupported assertion type: {other}");
        }
    }
}

/// Render a `method_result` assertion in C.
///
/// Dispatches generically using `{ffi_prefix}_{method_name}` for the FFI call.
/// The `return_type` fixture field controls how the return value is handled:
/// - `"string"` — the method returns a heap-allocated `char*`; the generator
///   emits a scoped block that asserts, then calls `free()`.
/// - absent/other — treated as a primitive integer (or pointer-as-bool); the
///   assertion is emitted inline without any heap management.
#[allow(clippy::too_many_arguments)]
fn render_method_result_assertion(
    out: &mut String,
    result_var: &str,
    ffi_prefix: &str,
    method_name: &str,
    args: Option<&serde_json::Value>,
    return_type: Option<&str>,
    check: &str,
    value: Option<&serde_json::Value>,
) {
    let call_expr = build_c_method_call(result_var, ffi_prefix, method_name, args);

    if return_type == Some("string") {
        // Heap-allocated char* return: emit a scoped block, assert, then free.
        let _ = writeln!(out, "    {{");
        let _ = writeln!(out, "        char* _method_result = {call_expr};");
        if check == "is_error" {
            let _ = writeln!(
                out,
                "        assert(_method_result == NULL && \"expected method to return error\");"
            );
            let _ = writeln!(out, "    }}");
            return;
        }
        let _ = writeln!(
            out,
            "        assert(_method_result != NULL && \"method_result returned NULL\");"
        );
        match check {
            "contains" => {
                if let Some(val) = value {
                    let c_val = json_to_c(val);
                    let _ = writeln!(
                        out,
                        "        assert(strstr(_method_result, {c_val}) != NULL && \"method_result contains assertion failed\");"
                    );
                }
            }
            "equals" => {
                if let Some(val) = value {
                    let c_val = json_to_c(val);
                    let _ = writeln!(
                        out,
                        "        assert(strcmp(_method_result, {c_val}) == 0 && \"method_result equals assertion failed\");"
                    );
                }
            }
            "is_true" => {
                let _ = writeln!(
                    out,
                    "        assert(_method_result != NULL && strlen(_method_result) > 0 && \"method_result is_true assertion failed\");"
                );
            }
            "count_min" => {
                if let Some(val) = value {
                    let n = val.as_u64().unwrap_or(0);
                    let _ = writeln!(out, "        int _elem_count = alef_json_array_count(_method_result);");
                    let _ = writeln!(
                        out,
                        "        assert(_elem_count >= {n} && \"method_result count_min assertion failed\");"
                    );
                }
            }
            other_check => {
                panic!("C e2e generator: unsupported method_result check type for string return: {other_check}");
            }
        }
        let _ = writeln!(out, "        free(_method_result);");
        let _ = writeln!(out, "    }}");
        return;
    }

    // Primitive (integer / pointer-as-bool) return: inline assert, no heap management.
    match check {
        "equals" => {
            if let Some(val) = value {
                let c_val = json_to_c(val);
                let _ = writeln!(
                    out,
                    "    assert({call_expr} == {c_val} && \"method_result equals assertion failed\");"
                );
            }
        }
        "is_true" => {
            let _ = writeln!(
                out,
                "    assert({call_expr} && \"method_result is_true assertion failed\");"
            );
        }
        "is_false" => {
            let _ = writeln!(
                out,
                "    assert(!{call_expr} && \"method_result is_false assertion failed\");"
            );
        }
        "greater_than_or_equal" => {
            if let Some(val) = value {
                let n = val.as_u64().unwrap_or(0);
                let _ = writeln!(
                    out,
                    "    assert({call_expr} >= {n} && \"method_result >= {n} assertion failed\");"
                );
            }
        }
        "count_min" => {
            if let Some(val) = value {
                let n = val.as_u64().unwrap_or(0);
                let _ = writeln!(
                    out,
                    "    assert({call_expr} >= {n} && \"method_result count_min assertion failed\");"
                );
            }
        }
        other_check => {
            panic!("C e2e generator: unsupported method_result check type: {other_check}");
        }
    }
}

/// Build a C call expression for a `method_result` assertion.
///
/// Uses generic dispatch: `{ffi_prefix}_{method_name}(result_var, args...)`.
/// Args from the fixture JSON object are emitted as positional C arguments in
/// insertion order, using best-effort type conversion (strings → C string literals,
/// numbers and booleans → verbatim literals).
fn build_c_method_call(
    result_var: &str,
    ffi_prefix: &str,
    method_name: &str,
    args: Option<&serde_json::Value>,
) -> String {
    let extra_args = if let Some(args_val) = args {
        args_val
            .as_object()
            .map(|obj| {
                obj.values()
                    .map(|v| match v {
                        serde_json::Value::String(s) => format!("\"{}\"", escape_c(s)),
                        serde_json::Value::Bool(true) => "1".to_string(),
                        serde_json::Value::Bool(false) => "0".to_string(),
                        serde_json::Value::Number(n) => n.to_string(),
                        serde_json::Value::Null => "NULL".to_string(),
                        other => format!("\"{}\"", escape_c(&other.to_string())),
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default()
    } else {
        String::new()
    };

    if extra_args.is_empty() {
        format!("{ffi_prefix}_{method_name}({result_var})")
    } else {
        format!("{ffi_prefix}_{method_name}({result_var}, {extra_args})")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{FieldDef, ParamDef, TypeDef, TypeRef};

    /// The neutral `FieldConfigSources` most tests want: neither `result_fields` nor
    /// `fields` has a per-call override in effect, so every diagnostic falls back to
    /// naming the global keys — the shape every test that isn't specifically exercising
    /// the per-call branch expects.
    fn global_sources() -> FieldConfigSources {
        FieldConfigSources {
            result_fields: EffectiveConfigSource::Global,
            fields: EffectiveConfigSource::Global,
        }
    }

    /// IR-oracle wiring regression (alef task #64): a field that is IR-reachable
    /// (present, non-`binding_excluded`, on some IR type) but missing from the
    /// hand-maintained `result_fields` config must still render a real assertion,
    /// not a "skipped: field not available" comment — `c.rs` (both the main-suite
    /// and snippet resolver construction sites) now threads
    /// `FieldResolver::ir_field_sets(type_defs)` into `with_ir_fields`. ~keep
    #[test]
    fn c_ir_reachable_field_absent_from_result_fields_is_not_skipped() {
        let reachable: HashSet<String> = ["data".to_string()].into_iter().collect();
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        )
        .with_ir_fields(reachable, HashSet::new(), HashSet::new());
        let assertion = Assertion {
            assertion_type: "equals".to_string(),
            field: Some("data".to_string()),
            value: Some(serde_json::Value::String("hello".to_string())),
            ..Default::default()
        };
        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            "sample",
            &resolver,
            &[],
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        );
        assert!(!out.contains("skipped"), "got: {out}");
    }

    /// The negative-control half of the same regression: `internal_diagnostics`
    /// represents a field carrying `#[doc(hidden)]` or `#[cfg_attr(alef,
    /// alef(skip))]` in the real struct (a genuine `binding_excluded` field) —
    /// NOT `#[serde(skip)]`, which alone does not exclude a field from the
    /// binding surface. Even though it is listed in `result_fields` (a stale/
    /// wrong config entry), the IR must still win and reject it. ~keep
    #[test]
    fn c_ir_excluded_field_present_in_result_fields_is_still_skipped() {
        let result_fields: HashSet<String> = ["internal_diagnostics".to_string()].into_iter().collect();
        let excluded: HashSet<String> = ["internal_diagnostics".to_string()].into_iter().collect();
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &result_fields,
            &HashSet::new(),
            &HashSet::new(),
        )
        .with_ir_fields(HashSet::new(), excluded, HashSet::new());
        let assertion = Assertion {
            assertion_type: "equals".to_string(),
            field: Some("internal_diagnostics".to_string()),
            value: Some(serde_json::Value::String("hello".to_string())),
            ..Default::default()
        };
        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            "sample",
            &resolver,
            &[],
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        );
        assert!(out.contains("skipped"), "got: {out}");
    }

    /// Task 1c backstop: even after the enum-vs-opaque-handle classification gap is
    /// fixed elsewhere, a field `render_assertion` is told is a genuine opaque handle
    /// must never be compared via `strcmp` — the ABI carries it as a scalar `uint64_t`
    /// `AlefHandle`, and `strcmp` on that is undefined behavior, not merely wrong. A
    /// numeric `equals` value must compare exactly instead.
    #[test]
    fn equals_assertion_on_opaque_handle_compares_numerically_not_via_strcmp() {
        let reachable: HashSet<String> = ["status".to_string()].into_iter().collect();
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        )
        .with_ir_fields(reachable, HashSet::new(), HashSet::new());
        let assertion = Assertion {
            assertion_type: "equals".to_string(),
            field: Some("status".to_string()),
            value: Some(serde_json::json!(2)),
            ..Default::default()
        };
        let accessed_fields = [("status".to_string(), "status".to_string(), false)];
        let mut opaque_handle_locals = HashMap::new();
        opaque_handle_locals.insert("status".to_string(), "batch_status".to_string());

        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            "sample",
            &resolver,
            &accessed_fields,
            &HashMap::new(),
            &opaque_handle_locals,
            &HashMap::new(),
        );

        assert!(out.contains("status == 2"), "got: {out}");
        assert!(!out.contains("strcmp"), "must not strcmp a uint64_t handle: {out}");
    }

    /// Negative control / companion: a string expected value against an opaque handle
    /// means the field should have matched `try_emit_enum_accessor` and didn't. Rather
    /// than emit `status == "completed"` — a pointer comparison against a string literal
    /// that compiles cleanly and always lies — this weakens to an honest existence check,
    /// mirroring the precedent already established for `not_empty`/`is_empty`.
    #[test]
    fn equals_assertion_on_opaque_handle_with_string_value_falls_back_to_existence_check() {
        let reachable: HashSet<String> = ["status".to_string()].into_iter().collect();
        let resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        )
        .with_ir_fields(reachable, HashSet::new(), HashSet::new());
        let assertion = Assertion {
            assertion_type: "equals".to_string(),
            field: Some("status".to_string()),
            value: Some(serde_json::Value::String("completed".to_string())),
            ..Default::default()
        };
        let accessed_fields = [("status".to_string(), "status".to_string(), false)];
        let mut opaque_handle_locals = HashMap::new();
        opaque_handle_locals.insert("status".to_string(), "batch_status".to_string());

        let mut out = String::new();
        render_assertion(
            &mut out,
            &assertion,
            "result",
            "sample",
            &resolver,
            &accessed_fields,
            &HashMap::new(),
            &opaque_handle_locals,
            &HashMap::new(),
        );

        assert!(out.contains("status != 0"), "got: {out}");
        assert!(
            !out.contains("strcmp"),
            "must not compare a uint64_t handle to a string literal: {out}"
        );
    }

    #[test]
    fn nested_optional_handle_type_comes_from_ir_when_config_mapping_is_absent() {
        let types = [
            TypeDef {
                name: "ExtractionResult".into(),
                fields: vec![FieldDef {
                    name: "summary".into(),
                    ty: TypeRef::Optional(Box::new(TypeRef::Named("ExtractionSummary".into()))),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "ExtractionSummary".into(),
                fields: vec![FieldDef {
                    name: "processed".into(),
                    ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U64),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
        ];
        let mut output = String::new();
        let mut handles = Vec::new();

        emit_nested_accessor(
            &mut output,
            "sample",
            "summary.processed",
            "summary_processed",
            "result",
            &HashMap::from([("extraction_summary.processed".into(), "uint64_t".into())]),
            &HashSet::new(),
            &mut handles,
            "ExtractionResult",
            "summary.processed",
            &types,
            &global_sources(),
        )
        .expect("every hop resolves");

        assert!(output.contains("SAMPLEAlefHandle summary_handle"), "{output}");
        assert!(output.contains("sample_extraction_result_summary(result)"), "{output}");
        assert!(output.contains("uint64_t summary_processed"), "{output}");
    }

    /// The crawlberg shape: `ScrapeResult.metadata -> PageMetadata.article ->
    /// ArticleMetadata.tags`, asserted by a fixture as `article.tags.length`. With no
    /// `article.*` alias configured, `article` is stripped as a virtual namespace before
    /// this function is called, so the walk starts on `ScrapeResult` and looks for a field
    /// `tags` that lives two hops further down. ~keep
    fn crawlberg_article_types() -> Vec<TypeDef> {
        vec![
            TypeDef {
                name: "ScrapeResult".into(),
                fields: vec![FieldDef {
                    name: "metadata".into(),
                    ty: TypeRef::Optional(Box::new(TypeRef::Named("PageMetadata".into()))),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "PageMetadata".into(),
                fields: vec![FieldDef {
                    name: "article".into(),
                    ty: TypeRef::Optional(Box::new(TypeRef::Named("ArticleMetadata".into()))),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "ArticleMetadata".into(),
                fields: vec![FieldDef {
                    name: "tags".into(),
                    ty: TypeRef::Vec(Box::new(TypeRef::String)),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
        ]
    }

    fn walk_crawlberg_article_tags() -> anyhow::Error {
        walk_crawlberg_article_tags_with_sources(&global_sources())
    }

    fn walk_crawlberg_article_tags_with_sources(config_sources: &FieldConfigSources) -> anyhow::Error {
        let mut output = String::new();
        let mut handles = Vec::new();
        emit_nested_accessor(
            &mut output,
            "cberg",
            "tags.length",
            "article_tags_length",
            "result",
            &HashMap::new(),
            &HashSet::new(),
            &mut handles,
            "ScrapeResult",
            "article.tags.length",
            &crawlberg_article_types(),
            config_sources,
        )
        .expect_err("`tags` is not a field of ScrapeResult")
    }

    /// A consumer config gap must surface as an error, not a process-killing panic.
    #[test]
    fn missing_intermediate_type_returns_an_error_instead_of_panicking() {
        let message = walk_crawlberg_article_tags().to_string();
        assert!(message.contains("fields_c_types"), "{message}");
        assert!(message.contains("scrape_result.tags"), "{message}");
        assert!(message.contains("tags.length"), "{message}");
    }

    /// Every fact the old panic carried must survive the conversion.
    #[test]
    fn missing_intermediate_type_keeps_the_original_panic_facts() {
        let message = walk_crawlberg_article_tags().to_string();
        assert!(message.contains("path \"tags.length\""), "{message}");
        assert!(message.contains("segment \"tags\""), "{message}");
        assert!(message.contains("`Tags`"), "guessed-name rationale is gone: {message}");
        assert!(message.contains("`DataNode` vs `Data`"), "{message}");
    }

    /// The point of the rewrite. The message must not leave "add the key it named" as the
    /// obvious remedy, because that key would emit `cberg_scrape_result_tags()` -- a symbol
    /// no backend generates. It has to name the stripped namespace, the real chain, and the
    /// alias that reconnects them.
    #[test]
    fn missing_intermediate_type_names_the_real_chain_not_the_phantom_key() {
        let message = walk_crawlberg_article_tags().to_string();

        assert!(
            message.contains("Type `ScrapeResult` has no field `tags`"),
            "must say why the key is missing: {message}"
        );
        assert!(
            message.contains("stripped the leading \"article\""),
            "must name the namespace stripping that produced the path: {message}"
        );
        assert!(
            message.contains("cberg_scrape_result_tags()"),
            "must name the C symbol declaring the key would conjure: {message}"
        );
        assert!(
            message.contains("cberg_article_metadata_tags()"),
            "must name the C symbol that really exists: {message}"
        );
        assert!(
            message.contains("\"metadata.article.tags\""),
            "must name the real resolved chain: {message}"
        );
        assert!(
            message.contains("\"article.tags\" = \"metadata.article.tags\""),
            "must spell the alias that fixes it: {message}"
        );
        assert!(
            message.contains("[crates.e2e.fields]"),
            "must name the alias table, not just fields_c_types: {message}"
        );
    }

    /// The `fields` sibling of the `result_fields` fix: a non-empty per-call `fields`
    /// override REPLACES the global alias table outright (`E2eConfig::effective_fields`),
    /// so when a per-call override is what's in effect, the alias-fix must name that
    /// call's own key -- never the global one, which an edit would not reach.
    #[test]
    fn missing_intermediate_type_names_the_per_call_fields_when_that_is_what_shadows() {
        let sources = FieldConfigSources {
            result_fields: EffectiveConfigSource::Global,
            fields: EffectiveConfigSource::PerCall("[crates.e2e.calls.scrape]".to_string()),
        };
        let message = walk_crawlberg_article_tags_with_sources(&sources).to_string();

        assert!(
            message.contains("\"article.tags\" = \"metadata.article.tags\" under `[crates.e2e.calls.scrape].fields`"),
            "must name the per-call key that actually governs this call: {message}"
        );
        assert!(
            !message.contains("under `[crates.e2e.fields]`"),
            "must not point at the global key when a per-call override shadows it: {message}"
        );
    }

    /// The other half of the diagnostic: when the field genuinely does not exist anywhere
    /// under the result type, there is no alias to suggest and the message must say so
    /// rather than inventing a chain.
    #[test]
    fn missing_intermediate_type_says_so_when_no_type_carries_the_field() {
        let mut output = String::new();
        let mut handles = Vec::new();
        let error = emit_nested_accessor(
            &mut output,
            "cberg",
            "nowhere.length",
            "nowhere_length",
            "result",
            &HashMap::new(),
            &HashSet::new(),
            &mut handles,
            "ScrapeResult",
            "nowhere.length",
            &crawlberg_article_types(),
            &global_sources(),
        )
        .expect_err("`nowhere` is not a field of anything");

        let message = error.to_string();
        assert!(
            message.contains("No type reachable from `ScrapeResult` has a field named `nowhere`"),
            "{message}"
        );
        assert!(
            !message.contains("under `[crates.e2e.fields]`"),
            "must not suggest an alias it cannot spell: {message}"
        );
        assert!(
            !message.contains("stripped the leading"),
            "nothing was stripped here: {message}"
        );
    }

    #[test]
    fn stripped_namespace_prefix_recovers_only_a_real_stripped_prefix() {
        assert_eq!(
            stripped_namespace_prefix("article.tags.length", "tags.length"),
            Some("article")
        );
        assert_eq!(
            stripped_namespace_prefix("interaction.action_results[0].x", "action_results[0].x"),
            Some("interaction")
        );
        assert_eq!(stripped_namespace_prefix("tags.length", "tags.length"), None);
        assert_eq!(
            stripped_namespace_prefix("metadata.title", "something.else"),
            None,
            "a raw field that does not end with the resolved path was not produced by stripping"
        );
    }

    #[test]
    fn find_field_path_returns_the_shallowest_chain_and_its_declaring_type() {
        let types = crawlberg_article_types();

        let tags = find_field_path("ScrapeResult", "tags", &types).expect("tags is reachable");
        assert_eq!(tags.path, "metadata.article.tags");
        assert_eq!(
            tags.owner_type, "ArticleMetadata",
            "the C accessor symbol is built from the declaring type, not the root"
        );

        let metadata = find_field_path("ScrapeResult", "metadata", &types).expect("metadata is a direct field");
        assert_eq!(metadata.path, "metadata");
        assert_eq!(metadata.owner_type, "ScrapeResult");

        assert!(find_field_path("ScrapeResult", "nowhere", &types).is_none());
    }

    /// The `pipeline_regeneration_gate` shape: `CompletionResponse.metadata -> Metadata`,
    /// `Metadata.document -> Document`, `Document.title`. `Metadata` deliberately has NO
    /// `title` field, so `metadata.title` only resolves through the
    /// `"metadata.title" = "metadata.document.title"` alias. ~keep
    fn completion_response_types() -> Vec<TypeDef> {
        vec![
            TypeDef {
                name: "CompletionResponse".into(),
                fields: vec![
                    FieldDef {
                        name: "id".into(),
                        ty: TypeRef::String,
                        ..FieldDef::default()
                    },
                    FieldDef {
                        name: "metadata".into(),
                        ty: TypeRef::Named("Metadata".into()),
                        ..FieldDef::default()
                    },
                ],
                ..TypeDef::default()
            },
            TypeDef {
                name: "Metadata".into(),
                fields: vec![FieldDef {
                    name: "document".into(),
                    ty: TypeRef::Named("Document".into()),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "Document".into(),
                fields: vec![FieldDef {
                    name: "title".into(),
                    ty: TypeRef::String,
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
        ]
    }

    fn completion_response_c_types() -> HashMap<String, String> {
        HashMap::from([
            ("completion_response.metadata".to_string(), "Metadata".to_string()),
            ("metadata.document".to_string(), "Document".to_string()),
        ])
    }

    fn walk_completion_response(
        resolved: &str,
        raw_field: &str,
        fields_c_types: &HashMap<String, String>,
    ) -> anyhow::Result<(String, Option<NestedLeafOutcome>)> {
        walk_completion_response_with_sources(resolved, raw_field, fields_c_types, &global_sources())
    }

    fn walk_completion_response_with_sources(
        resolved: &str,
        raw_field: &str,
        fields_c_types: &HashMap<String, String>,
        config_sources: &FieldConfigSources,
    ) -> anyhow::Result<(String, Option<NestedLeafOutcome>)> {
        let mut output = String::new();
        let mut handles = Vec::new();
        let leaf = emit_nested_accessor(
            &mut output,
            "gatelib",
            resolved,
            "metadata_title",
            "result",
            fields_c_types,
            &HashSet::new(),
            &mut handles,
            "CompletionResponse",
            raw_field,
            &completion_response_types(),
            config_sources,
        )?;
        Ok((output, leaf))
    }

    /// The decisive case. Dropping the `[crates.e2e.fields]` alias leaves the fixture
    /// asserting `metadata.title`, whose leaf names no field of `Metadata`. Before this
    /// check the walk emitted `gatelib_metadata_title(metadata_handle)` — a symbol cbindgen
    /// never generates — and generation reported success, so the assertion was lost with no
    /// error, no warning and no skip comment for the
    /// `ALEF_E2E_STRICT_FIELD_AVAILABILITY` scan to find. ~keep
    #[test]
    fn unknown_leaf_field_is_an_error_not_a_phantom_accessor() {
        let error = walk_completion_response("metadata.title", "metadata.title", &completion_response_c_types())
            .expect_err("`title` is not a field of `Metadata`");

        let message = error.to_string();
        assert!(
            message.contains("IR type `Metadata` has no field `title`"),
            "must name the type and the field it lacks: {message}"
        );
        assert!(
            message.contains("gatelib_metadata_title()"),
            "must name the phantom symbol it refused to emit: {message}"
        );
        assert!(
            message.contains("only inspects a path's FIRST segment"),
            "must say why nothing upstream caught it: {message}"
        );
    }

    /// The remedy has to be spelled out, not implied: the fix for this shape is the alias,
    /// and the message must carry both sides of it.
    #[test]
    fn unknown_leaf_field_diagnostic_spells_the_alias_that_fixes_it() {
        let message = walk_completion_response("metadata.title", "metadata.title", &completion_response_c_types())
            .expect_err("`title` is not a field of `Metadata`")
            .to_string();

        assert!(
            message.contains("\"metadata.title\" = \"metadata.document.title\""),
            "must spell the alias that reconnects the fixture path: {message}"
        );
        assert!(
            message.contains("`[crates.e2e.fields]`"),
            "must name the table the alias goes in: {message}"
        );
        assert!(
            message.contains("gatelib_document_title()"),
            "must name the accessor that really exists: {message}"
        );
    }

    /// The `fields` sibling of the per-call `result_fields` test above: a per-call `fields`
    /// override REPLACES the global alias table outright, so the leaf diagnostic's alias-fix
    /// branch must name that call's own key too -- not just the intermediate-hop diagnostic's
    /// identical branch tested above.
    #[test]
    fn unknown_leaf_field_diagnostic_names_the_per_call_fields_when_that_is_what_shadows() {
        let sources = FieldConfigSources {
            result_fields: EffectiveConfigSource::Global,
            fields: EffectiveConfigSource::PerCall("[crates.e2e.calls.complete]".to_string()),
        };
        let message = walk_completion_response_with_sources(
            "metadata.title",
            "metadata.title",
            &completion_response_c_types(),
            &sources,
        )
        .expect_err("`title` is not a field of `Metadata`")
        .to_string();

        assert!(
            message.contains(
                "\"metadata.title\" = \"metadata.document.title\" under `[crates.e2e.calls.complete].fields`"
            ),
            "must name the per-call key that actually governs this call: {message}"
        );
        assert!(
            !message.contains("`[crates.e2e.fields]`"),
            "must not point at the global key when a per-call override shadows it: {message}"
        );
    }

    /// Positive control: with the alias in place the very same fixture field resolves, and
    /// the leaf still renders its accessor. The fix must not turn every nested assertion
    /// into a failure.
    #[test]
    fn resolvable_leaf_still_renders_its_accessor() {
        let (output, leaf) = walk_completion_response(
            "metadata.document.title",
            "metadata.title",
            &completion_response_c_types(),
        )
        .expect("every hop and the leaf resolve");

        assert_eq!(
            leaf, None,
            "a plain string leaf is a char*, not a primitive or a handle"
        );
        assert!(
            output.contains("char* metadata_title = gatelib_document_title(document_handle);"),
            "{output}"
        );
    }

    /// A leaf the operator declared in `[crates.e2e.fields_c_types]` is an explicit claim
    /// that the accessor exists, and stays authoritative — the IR check only governs the
    /// undeclared default. Without this escape hatch a field reached through a C type the
    /// IR does not model would become ungeneratable.
    #[test]
    fn explicitly_declared_leaf_type_overrides_the_ir_check() {
        let mut fields_c_types = completion_response_c_types();
        fields_c_types.insert("metadata.title".to_string(), "char*".to_string());

        let (output, _) = walk_completion_response("metadata.title", "metadata.title", &fields_c_types)
            .expect("an explicit fields_c_types declaration is authoritative");

        assert!(
            output.contains("char* metadata_title = gatelib_metadata_title(metadata_handle);"),
            "{output}"
        );
    }

    /// Default-allow guard: when the walk is standing on a type the IR does not declare,
    /// the IR cannot say whether the leaf exists, and silence must not be read as absence.
    #[test]
    fn leaf_on_a_type_the_ir_does_not_declare_is_not_rejected() {
        let mut output = String::new();
        let mut handles = Vec::new();
        emit_nested_accessor(
            &mut output,
            "gatelib",
            "metadata.title",
            "metadata_title",
            "result",
            &HashMap::from([("unmodelled_result.metadata".to_string(), "AlsoUnmodelled".to_string())]),
            &HashSet::new(),
            &mut handles,
            "UnmodelledResult",
            "metadata.title",
            &completion_response_types(),
            &global_sources(),
        )
        .expect("an unmodelled parent type must not be treated as proof the leaf is absent");

        assert!(
            output.contains("char* metadata_title = gatelib_also_unmodelled_title(metadata_handle);"),
            "{output}"
        );
    }

    /// The shape found shipped in `tree-sitter-language-pack/e2e/c/test_data_extraction.c`:
    /// `ProcessResult.data -> DataNode.kind`, asserted as `data.kind`, with `data` absent
    /// from `result_fields`. Stripping reduces the path to the bare leaf `kind`, which the
    /// availability oracle accepts because `kind` is IR-reachable on *some* type, and the
    /// flat branch then emits `ts_pack_process_result_kind()` — a symbol the generated
    /// header does not declare. ~keep
    fn ts_pack_types() -> Vec<TypeDef> {
        vec![
            TypeDef {
                name: "ProcessResult".into(),
                fields: vec![
                    FieldDef {
                        name: "language".into(),
                        ty: TypeRef::String,
                        ..FieldDef::default()
                    },
                    FieldDef {
                        name: "data".into(),
                        ty: TypeRef::Named("DataNode".into()),
                        ..FieldDef::default()
                    },
                ],
                ..TypeDef::default()
            },
            TypeDef {
                name: "DataNode".into(),
                fields: vec![FieldDef {
                    name: "kind".into(),
                    ty: TypeRef::String,
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
        ]
    }

    fn check_ts_pack_stripped_leaf(
        declared_in_fields_c_types: bool,
        result_fields_source: &EffectiveConfigSource,
    ) -> anyhow::Result<()> {
        let types = ts_pack_types();
        ensure_leaf_field_exists(LeafFieldCheck {
            prefix: "ts_pack",
            accessor_fn: "ts_pack_process_result_kind",
            resolved: "kind",
            raw_field: "data.kind",
            segment: "kind",
            parent_snake_type: "process_result",
            parent_is_ir_type: true,
            declared_in_fields_c_types,
            result_type_name: "ProcessResult",
            type_defs: &types,
            result_fields_source,
            // Irrelevant to what this helper's callers assert on -- all of them exercise
            // the namespace-stripped-identity branch, which only reads
            // `result_fields_source`. Global is the neutral default. ~keep
            fields_source: &EffectiveConfigSource::Global,
        })
    }

    #[test]
    fn namespace_stripped_leaf_that_is_not_a_result_type_field_is_rejected() {
        let message = check_ts_pack_stripped_leaf(false, &EffectiveConfigSource::Global)
            .expect_err("`kind` is a field of `DataNode`, not of `ProcessResult`")
            .to_string();

        assert!(
            message.contains("IR type `ProcessResult` has no field `kind`"),
            "must name the type the accessor would have been called on: {message}"
        );
        assert!(
            message.contains("stripped the leading \"data\""),
            "must name the stripping that produced the bare leaf: {message}"
        );
        assert!(
            message.contains("ts_pack_data_node_kind()"),
            "must name the accessor that really exists: {message}"
        );
    }

    /// The remedy differs from the aliasable case and the message must not confuse them: an
    /// alias here would be `"data.kind" = "data.kind"`, an identity mapping that leaves
    /// `namespace_stripped_path` (which reads `result_fields`, not the alias table) stripping
    /// exactly as before. This is the global-in-effect case: no per-call override, so the
    /// global key really is the one an edit reaches.
    #[test]
    fn stripped_leaf_diagnostic_names_result_fields_not_an_identity_alias() {
        let message = check_ts_pack_stripped_leaf(false, &EffectiveConfigSource::Global)
            .expect_err("`kind` is a field of `DataNode`, not of `ProcessResult`")
            .to_string();

        assert!(
            message.contains("add \"data\" to `[crates.e2e].result_fields`"),
            "must name the config entry that stops the stripping: {message}"
        );
        assert!(
            !message.contains("\"data.kind\" = \"data.kind\""),
            "must not suggest an identity alias that changes nothing: {message}"
        );
    }

    /// The defect this type exists to prevent: a per-call `result_fields` override
    /// REPLACES the global default outright (`E2eConfig::effective_result_fields`), so
    /// when a per-call override is what's in effect, the "Fix:" must name that call's own
    /// key -- never the global one, which a consumer reported editing to no effect
    /// because their call's per-call list is what actually governed the walk.
    #[test]
    fn stripped_leaf_diagnostic_names_the_per_call_result_fields_when_that_is_what_shadows() {
        let source = EffectiveConfigSource::PerCall("[crates.e2e.calls.crawl]".to_string());
        let message = check_ts_pack_stripped_leaf(false, &source)
            .expect_err("`kind` is a field of `DataNode`, not of `ProcessResult`")
            .to_string();

        assert!(
            message.contains("add \"data\" to `[crates.e2e.calls.crawl].result_fields`"),
            "must name the per-call key that actually governs this call: {message}"
        );
        assert!(
            !message.contains("`[crates.e2e].result_fields`"),
            "must not point at the global key when a per-call override shadows it: {message}"
        );
    }

    /// The unnamed default call (`[crates.e2e.call]`) can also carry its own
    /// `result_fields` override -- it is looked up the same way a named call is, just
    /// with no entry in `e2e_config.calls` to match by pointer. The message must still
    /// name it, not fall back to claiming it's the global key.
    #[test]
    fn describe_effective_config_source_names_the_unnamed_default_call() {
        let e2e_config = E2eConfig::default();
        let call = CallConfig {
            result_fields: HashSet::from(["pages".to_string()]),
            ..CallConfig::default()
        };

        let source = describe_effective_config_source(&e2e_config, &call, !call.result_fields.is_empty());

        match source {
            EffectiveConfigSource::PerCall(label) => assert_eq!(label, "[crates.e2e.call]"),
            EffectiveConfigSource::Global => panic!("call_has_override == true must never resolve to Global"),
        }
    }

    /// The common case: a named call in `[crates.e2e.calls]` with its own override must be
    /// identified by that name, so the operator can find the exact TOML table to edit.
    #[test]
    fn describe_effective_config_source_names_a_call_matched_by_pointer_identity() {
        let mut e2e_config = E2eConfig::default();
        let crawl_call = CallConfig {
            result_fields: HashSet::from(["pages".to_string()]),
            ..CallConfig::default()
        };
        e2e_config.calls.insert("crawl".to_string(), crawl_call);

        let source = describe_effective_config_source(&e2e_config, &e2e_config.calls["crawl"], true);

        match source {
            EffectiveConfigSource::PerCall(label) => assert_eq!(label, "[crates.e2e.calls.crawl]"),
            EffectiveConfigSource::Global => panic!("call_has_override == true must never resolve to Global"),
        }
    }

    /// `call_has_override == false` always resolves to the global default, regardless of
    /// whether `call` is named or the unnamed default call -- the caller-computed
    /// emptiness check is authoritative, the function never re-derives it.
    #[test]
    fn describe_effective_config_source_is_global_when_the_caller_says_there_is_no_override() {
        let e2e_config = E2eConfig::default();
        let call = CallConfig {
            result_fields: HashSet::from(["pages".to_string()]),
            ..CallConfig::default()
        };

        assert!(matches!(
            describe_effective_config_source(&e2e_config, &call, false),
            EffectiveConfigSource::Global
        ));
    }

    /// `FieldConfigSources::resolve` is the one place production code should call this
    /// from: it derives `call_has_override` itself, once per collection, so the two
    /// checks (`result_fields`, `fields`) cannot drift onto different emptiness logic.
    #[test]
    fn field_config_sources_resolve_derives_each_collection_independently() {
        let mut e2e_config = E2eConfig::default();
        let call = CallConfig {
            result_fields: HashSet::from(["pages".to_string()]),
            // `fields` left empty: only `result_fields` has a per-call override.
            ..CallConfig::default()
        };
        e2e_config.calls.insert("crawl".to_string(), call);

        let sources = FieldConfigSources::resolve(&e2e_config, &e2e_config.calls["crawl"]);

        assert!(
            matches!(sources.result_fields, EffectiveConfigSource::PerCall(ref label) if label == "[crates.e2e.calls.crawl]")
        );
        assert!(matches!(sources.fields, EffectiveConfigSource::Global));
    }

    #[test]
    fn explicitly_declared_flat_leaf_type_overrides_the_ir_check() {
        check_ts_pack_stripped_leaf(true, &EffectiveConfigSource::Global)
            .expect("an explicit fields_c_types declaration is authoritative");
    }

    /// The full `ProcessResult.data -> DataNode.kind` shape once `data` is correctly
    /// registered in `result_fields` and `fields_c_types` names both hops (`data` ->
    /// `DataNode`, and the enum leaf `kind` -> `DataNodeKind`) — the "config already correct
    /// and complete" state a fixture author reaches after following `ts_pack_types`'s
    /// diagnostic. `data` is `Optional<Named>` here, matching the real IR (`pub data:
    /// Option<DataNode>`), not the bare `Named` `ts_pack_types` uses — this is the actual
    /// shape `emit_nested_accessor` must walk through the `Option`. ~keep
    fn ts_pack_types_with_optional_data_and_enum_kind() -> Vec<TypeDef> {
        vec![
            TypeDef {
                name: "ProcessResult".into(),
                fields: vec![FieldDef {
                    name: "data".into(),
                    ty: TypeRef::Optional(Box::new(TypeRef::Named("DataNode".into()))),
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "DataNode".into(),
                fields: vec![
                    FieldDef {
                        name: "kind".into(),
                        ty: TypeRef::Named("DataNodeKind".into()),
                        ..FieldDef::default()
                    },
                    FieldDef {
                        name: "children".into(),
                        ty: TypeRef::Vec(Box::new(TypeRef::Named("DataNode".into()))),
                        ..FieldDef::default()
                    },
                ],
                ..TypeDef::default()
            },
        ]
    }

    /// Both halves of the ts-pack fix at once: the walk must go through the `Option<DataNode>`
    /// hop AND land on the enum branch, not the opaque-struct branch, for the `DataNodeKind`
    /// leaf. Before the branch-ordering fix, this leaf matched the opaque-struct filter first
    /// (`DataNodeKind` is PascalCase, non-primitive, not `char*`/`skip`) and emitted a bare
    /// handle the caller would `strcmp` against instead of a `_to_string`-converted `char*`.
    #[test]
    fn dotted_path_through_optional_field_reaches_enum_leaf() {
        let types = ts_pack_types_with_optional_data_and_enum_kind();
        let fields_c_types = HashMap::from([
            ("process_result.data".to_string(), "DataNode".to_string()),
            ("data_node.kind".to_string(), "DataNodeKind".to_string()),
        ]);
        let fields_enum: HashSet<String> = ["data.kind".to_string()].into_iter().collect();
        let mut output = String::new();
        let mut handles = Vec::new();

        let result = emit_nested_accessor(
            &mut output,
            "ts_pack",
            "data.kind",
            "data_kind",
            "result",
            &fields_c_types,
            &fields_enum,
            &mut handles,
            "ProcessResult",
            "data.kind",
            &types,
            &global_sources(),
        )
        .expect("the Option<DataNode> hop and the enum leaf both resolve");

        assert_eq!(
            result, None,
            "an enum leaf returns Ok(None) (render_assertion reads it as a plain char*), not \
             Ok(Some(opaque_type)) -- a Some here would mean the opaque-struct branch fired instead"
        );
        assert!(
            output.contains("data_handle = ts_pack_process_result_data(result)"),
            "must walk into the Option<DataNode> field via the FFI accessor: {output}"
        );
        assert!(
            output.contains("ts_pack_data_node_kind_to_string("),
            "must convert the enum leaf via its _to_string accessor, proving the enum branch \
             (not the opaque-struct branch) fired: {output}"
        );
        assert!(
            !output.contains("AlefHandle data_kind = kind_handle"),
            "must not fall through to the opaque-struct branch's bare handle assignment: {output}"
        );
    }

    /// Two unrelated types below the same result type declaring a field with the same name
    /// (`DataNode.kind`, values object/array/scalar, vs `StructureItem.kind`, values
    /// function/class) must not collapse into a single confident alias suggestion — this is
    /// the tslp scenario that motivated the fix: the pre-fix diagnostic would have proposed
    /// exactly `"data.kind" = "structure.kind"`, silently rebinding the assertion to the
    /// wrong field.
    #[test]
    fn ambiguous_leaf_field_name_does_not_suggest_a_specific_alias() {
        let types = vec![
            TypeDef {
                name: "ProcessResult".into(),
                fields: vec![
                    FieldDef {
                        name: "data".into(),
                        ty: TypeRef::Named("DataNode".into()),
                        ..FieldDef::default()
                    },
                    FieldDef {
                        name: "structure".into(),
                        ty: TypeRef::Named("StructureItem".into()),
                        ..FieldDef::default()
                    },
                ],
                ..TypeDef::default()
            },
            TypeDef {
                name: "DataNode".into(),
                fields: vec![FieldDef {
                    name: "kind".into(),
                    ty: TypeRef::String,
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
            TypeDef {
                name: "StructureItem".into(),
                fields: vec![FieldDef {
                    name: "kind".into(),
                    ty: TypeRef::String,
                    ..FieldDef::default()
                }],
                ..TypeDef::default()
            },
        ];

        let message = ensure_leaf_field_exists(LeafFieldCheck {
            prefix: "ts_pack",
            accessor_fn: "ts_pack_process_result_kind",
            resolved: "kind",
            raw_field: "data.kind",
            segment: "kind",
            parent_snake_type: "process_result",
            parent_is_ir_type: true,
            declared_in_fields_c_types: false,
            result_type_name: "ProcessResult",
            type_defs: &types,
            result_fields_source: &EffectiveConfigSource::Global,
            fields_source: &EffectiveConfigSource::Global,
        })
        .expect_err("`kind` is not a field of `ProcessResult` itself")
        .to_string();

        assert!(
            !message.contains("\"data.kind\" = \"structure.kind\""),
            "must never suggest binding DataNode.kind's field onto the unrelated \
             StructureItem.kind: {message}"
        );
        assert!(
            message.contains("\"data.kind\""),
            "must still name the ambiguous candidate chain rooted at `data`: {message}"
        );
        assert!(
            message.contains("\"structure.kind\""),
            "must still name the ambiguous candidate chain rooted at `structure`: {message}"
        );
        assert!(
            message.contains("DataNode") && message.contains("StructureItem"),
            "must name both declaring types so the operator can tell them apart: {message}"
        );
    }

    fn test_backend_arg(trait_name: &str) -> crate::e2e::config::ArgMapping {
        crate::e2e::config::ArgMapping {
            name: "backend".into(),
            field: "backend".into(),
            arg_type: "test_backend".into(),
            optional: false,
            owned: false,
            element_type: None,
            go_type: None,
            vec_inner_is_ref: false,
            trait_name: Some(trait_name.to_string()),
        }
    }

    /// Pin: a `test_backend` arg whose trait IS registered still panics today,
    /// because `c::emit_test_backend` (`trait_bridge_snippet.rs`) is unimplemented —
    /// see its doc comment for why. `emit_test_backend` panics before ever handing
    /// `build_args_string_c` a value, so there is no sentinel left to accidentally
    /// splice into the call's argument list. This is the regression guard: it fails
    /// if that panic is ever replaced with a placeholder return and the call site
    /// stops checking it.
    #[test]
    #[should_panic(expected = "test-backend emitter is unimplemented")]
    fn registered_test_backend_trait_panics_because_c_backend_is_unimplemented() {
        use crate::core::config::TraitBridgeConfig;

        let bridge = TraitBridgeConfig {
            trait_name: "SampleBackend".into(),
            ..TraitBridgeConfig::default()
        };
        let config = ResolvedCrateConfig {
            trait_bridges: vec![bridge],
            ..ResolvedCrateConfig::default()
        };
        let fixture = Fixture {
            id: "register_sample_backend".into(),
            ..Fixture::default()
        };
        let args = vec![test_backend_arg("SampleBackend")];

        let _ = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "register_sample_backend",
            TargetParams::IrAbsent,
        );
    }

    /// An unregistered trait (no matching `[[crates.trait_bridges]]` entry) has no
    /// vtable to point at — generation must fail loudly instead of falling back to
    /// `NULL`. Unlike Kotlin's non-null interface parameter, nothing in C's type
    /// system would catch a bad `NULL` default at compile time, so this loud check
    /// is the only thing standing between a misconfigured `alef.toml` and either an
    /// uncompilable comment or a `NULL` vtable pointer reaching generated C.
    #[test]
    #[should_panic(expected = "no `[[crates.trait_bridges]]` entry")]
    fn unregistered_test_backend_trait_panics_instead_of_falling_back_to_null() {
        let config = ResolvedCrateConfig::default();
        let fixture = Fixture {
            id: "register_sample_backend".into(),
            ..Fixture::default()
        };
        let args = vec![test_backend_arg("SampleBackend")];

        let _ = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "register_sample_backend",
            TargetParams::IrAbsent,
        );
    }

    /// Regression for the bug that shipped a `char[37]` literal against a
    /// `TS_PACKAlefHandle` (an `int32_t`) parameter: with no `args` configured, alef
    /// used to splice the fixture's whole `input` JSON as a single C string literal
    /// regardless of the target's real parameters, which cannot compile against
    /// anything the target actually takes. A genuinely zero-argument target
    /// (`TargetParams::Known(&[])`) is the one case that must keep emitting an empty
    /// argument list rather than refuse. ~keep
    #[test]
    fn should_emit_empty_parens_when_args_unconfigured_and_target_takes_no_parameters() {
        let fixture = Fixture {
            id: "list_ocr_backends".into(),
            input: serde_json::json!({"cache_dir": "/tmp/sample_cache"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();

        let result = build_args_string_c(
            &fixture.input,
            &[],
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "list_ocr_backends",
            TargetParams::Known(&[]),
        )
        .expect("a genuinely zero-argument target must not fail generation");

        assert_eq!(
            result, "",
            "a zero-argument call must emit `()`, not a fabricated literal"
        );
    }

    /// The actual defect this guards: `ts_pack_configure` takes one typed parameter
    /// (`config`, an opaque handle), but the fixture configured no `args`. Splicing the
    /// whole fixture `input` JSON as one C string literal produced
    /// `ts_pack_configure("{\"cache_dir\":...}")` against `int32_t
    /// ts_pack_configure(TS_PACKAlefHandle config)` -- an incompatible
    /// pointer-to-integer conversion that does not compile. The emitter must refuse
    /// with a diagnostic instead of guessing an argument it cannot construct. ~keep
    #[test]
    fn should_refuse_when_args_unconfigured_and_target_takes_a_typed_parameter() {
        let fixture = Fixture {
            id: "pack_configure_defaults".into(),
            input: serde_json::json!({"cache_dir": "/tmp/sample_cache"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();
        let params = [ParamDef {
            name: "config".into(),
            ..ParamDef::default()
        }];

        let error = build_args_string_c(
            &fixture.input,
            &[],
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "ts_pack_configure",
            TargetParams::Known(&params),
        )
        .expect_err("a known non-empty parameter list must not be papered over with a JSON literal")
        .to_string();

        assert!(
            !error.contains("cache_dir"),
            "must not leak the fixture JSON into a diagnostic that replaces splicing it: {error}"
        );
        assert!(error.contains("ts_pack_configure"), "must name the call: {error}");
        assert!(error.contains("config"), "must name the unfilled parameter: {error}");
        assert!(error.contains("args"), "must point at the `args` config knob: {error}");
    }

    /// When the IR signature cannot be resolved at all, the emitter has no basis to
    /// tell a genuine zero-argument call from an authoring gap -- refuse rather than
    /// guess, per the same principle `ResultTypeName::require` applies to result types.
    #[test]
    fn should_refuse_when_args_unconfigured_and_target_signature_is_unresolvable() {
        let fixture = Fixture {
            id: "mystery_call".into(),
            input: serde_json::json!({"cache_dir": "/tmp/sample_cache"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();

        let error = build_args_string_c(
            &fixture.input,
            &[],
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "mystery_fn",
            TargetParams::Unresolvable,
        )
        .expect_err("an unresolvable signature must not fall back to guessing")
        .to_string();

        assert!(error.contains("mystery_fn"), "must name the call: {error}");
        assert!(error.contains("args"), "must point at the `args` config knob: {error}");
    }

    /// The boundary between the two refusing cases and the one that must not refuse.
    ///
    /// `IrAbsent` means no IR was consulted at all -- the main e2e test-file emitter has no
    /// `CallIr`, and several snippet entry points render without one. Nothing was learned, so
    /// nothing can be concluded, and this keeps the pre-existing behaviour instead of failing.
    /// Collapsing it back into `Unresolvable` would fail generation for every IR-less caller,
    /// which is a far wider blast radius than the defect this guards, and it would put this
    /// half of the fix in direct contradiction with `unresolved_result_type_name`, which
    /// classifies an absent IR as `Unverified` for exactly the same reason. Both halves must
    /// agree on what an absent IR licenses, or one of them is wrong. ~keep
    #[test]
    fn should_keep_prior_behaviour_when_there_is_no_ir_to_consult() {
        let fixture = Fixture {
            id: "no_ir".into(),
            input: serde_json::json!({"cache_dir": "/tmp/sample_cache"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();

        let rendered = build_args_string_c(
            &fixture.input,
            &[],
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "sample_fn",
            TargetParams::IrAbsent,
        )
        .expect("an absent IR must not fail generation on a path that never had a signature");

        assert_eq!(
            rendered,
            json_to_c(&fixture.input),
            "with no IR consulted the emitter must render exactly what it rendered before"
        );
    }

    /// The load-bearing control: a call WITH properly configured `args` must keep
    /// emitting them, unchanged, real typed literal and all. Without this test, a fix
    /// that makes the empty-`args` path refuse (or always emit `()`) everywhere would
    /// pass the two tests above and look correct while quietly breaking every snippet
    /// that already configures `args` correctly -- the two failure modes above only
    /// ever trigger on `args.is_empty()`, so nothing else in this suite would catch a
    /// regression that clobbers the non-empty path too. ~keep
    #[test]
    fn should_still_emit_configured_args_unchanged_when_args_are_present() {
        let fixture = Fixture {
            id: "chat_basic".into(),
            input: serde_json::json!({"text": "hello"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();
        let args = vec![crate::e2e::config::ArgMapping {
            name: "text".into(),
            field: "text".into(),
            arg_type: "string".into(),
            optional: false,
            owned: false,
            element_type: None,
            go_type: None,
            vec_inner_is_ref: false,
            trait_name: None,
        }];

        // `TargetParams::Unresolvable` on purpose: an unresolved signature licenses no claim
        // about any parameter's type, so a configured `args` list must render exactly as it
        // always did. (A resolved signature does license one -- see
        // `should_refuse_a_string_literal_configured_against_a_handle_parameter` and its
        // correctly-typed control below.)
        let result = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "chat",
            TargetParams::Unresolvable,
        )
        .expect("configured args must still render");

        assert_eq!(
            result, "\"hello\"",
            "a configured string arg must still emit its real typed literal"
        );
    }

    fn string_arg(name: &str, field: &str) -> crate::e2e::config::ArgMapping {
        crate::e2e::config::ArgMapping {
            name: name.into(),
            field: field.into(),
            arg_type: "string".into(),
            optional: false,
            owned: false,
            element_type: None,
            go_type: None,
            vec_inner_is_ref: false,
            trait_name: None,
        }
    }

    /// The other half of the same defect. The refusals above all key on `args.is_empty()` --
    /// "no args configured, do not fabricate an argument list". This is the opposite case:
    /// `args` are present, so the arity is satisfied and nothing refuses, but the entry's type
    /// contradicts the parameter's. `json_to_c` stringifies the JSON object and the emitter
    /// splices a `char[]` literal into a parameter the C ABI exports as `AlefHandle` -- the
    /// same `-Wint-conversion` failure, reached without ever passing through the empty-`args`
    /// guard. ~keep
    #[test]
    fn should_refuse_a_string_literal_configured_against_a_handle_parameter() {
        let fixture = Fixture {
            id: "configure_cache_dir".into(),
            input: serde_json::json!({"config": {"cache_dir": "/tmp/sample_cache"}}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();
        let args = vec![string_arg("config", "config")];
        let params = [ParamDef {
            name: "config".into(),
            ty: TypeRef::Named("SampleConfig".into()),
            ..ParamDef::default()
        }];
        let type_defs = [TypeDef {
            name: "SampleConfig".into(),
            has_serde: true,
            ..TypeDef::default()
        }];

        let error = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &type_defs,
            &fixture,
            "sample_configure",
            TargetParams::Known(&params),
        )
        .expect_err("a JSON object must not be lowered into a handle parameter")
        .to_string();

        assert!(error.contains("sample_configure"), "must name the call: {error}");
        assert!(error.contains("`config`"), "must name the parameter: {error}");
        assert!(
            error.contains("AlefHandle"),
            "must name the parameter's C type: {error}"
        );
        assert!(
            error.contains("cache_dir"),
            "must quote the offending value so the operator can find the entry: {error}"
        );
        assert!(
            error.contains("json_object"),
            "must name the configuration that constructs the handle: {error}"
        );
    }

    /// The false-refusal boundary, and the reason this check cannot simply reject every JSON
    /// object. A `Vec<Named>` parameter does NOT cross the C ABI as a handle -- `type_map`'s
    /// `c_param_type` maps it to `*const c_char`, a JSON string -- so the stringified literal
    /// is exactly the right lowering there. Refusing it would delete correct, compiling
    /// documentation, which is why `handle_param_type_name` deliberately does not unwrap
    /// through `Vec` the way `c.rs`'s `named_type` does. ~keep
    #[test]
    fn should_not_refuse_a_json_literal_against_a_vec_parameter() {
        let fixture = Fixture {
            id: "rank_documents".into(),
            input: serde_json::json!({"documents": ["alpha", "beta"]}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();
        let args = vec![string_arg("documents", "documents")];
        let params = [ParamDef {
            name: "documents".into(),
            ty: TypeRef::Vec(Box::new(TypeRef::Named("Document".into()))),
            ..ParamDef::default()
        }];
        let type_defs = [TypeDef {
            name: "Document".into(),
            has_serde: true,
            ..TypeDef::default()
        }];

        let rendered = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &type_defs,
            &fixture,
            "sample_rank",
            TargetParams::Known(&params),
        )
        .expect("a JSON-string parameter must keep rendering its literal");

        assert_eq!(
            rendered,
            json_to_c(&fixture.input["documents"]),
            "a `Vec<T>` parameter crosses as a JSON `const char *`, so the literal is correct"
        );
    }

    /// A parameter type the IR names but carries no `TypeDef` for cannot be proven to be a
    /// handle: an IR enum is an `EnumDef`, never a `TypeDef`, and enum-typed `Named` parameters
    /// cross as `i32`. Refusing on the name alone would reject every enum argument on evidence
    /// the emitter does not have, so an unmatched name leaves the rendering untouched. ~keep
    #[test]
    fn should_not_refuse_a_named_parameter_the_ir_carries_no_type_def_for() {
        let fixture = Fixture {
            id: "set_level".into(),
            input: serde_json::json!({"level": "debug"}),
            ..Fixture::default()
        };
        let config = ResolvedCrateConfig::default();
        let args = vec![string_arg("level", "level")];
        let params = [ParamDef {
            name: "level".into(),
            ty: TypeRef::Named("LogLevel".into()),
            ..ParamDef::default()
        }];

        let rendered = build_args_string_c(
            &fixture.input,
            &args,
            &HashMap::new(),
            &config,
            &[],
            &fixture,
            "sample_set_level",
            TargetParams::Known(&params),
        )
        .expect("a name with no `TypeDef` behind it licenses no claim about the C type");

        assert_eq!(rendered, "\"debug\"", "the rendering must be left exactly as it was");
    }
}