alef 0.66.0

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
//! C e2e test generator using assert.h and a Makefile.
//!
//! Generates `e2e/c/Makefile`, per-category `test_{category}.c` files,
//! a `main.c` test runner, a `test_runner.h` header, and a
//! `download_ffi.sh` script for downloading prebuilt FFI libraries from
//! GitHub releases.

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::hash::{self, CommentStyle};
use crate::e2e::config::{CallConfig, E2eConfig};
use crate::e2e::escape::{escape_c, sanitize_filename};
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::{Fixture, FixtureGroup};
use anyhow::Result;
use heck::{ToPascalCase, ToSnakeCase};
use std::collections::{HashMap, HashSet};
use std::fmt::Write as FmtWrite;
use std::path::PathBuf;

use super::E2eCodegen;

/// C e2e code generator.
pub struct CCodegen;

/// Returns true when `t` is a primitive C scalar type (uint64_t, int32_t, double,
/// etc.) that should be emitted as a typed local variable rather than a heap
/// `char*` accessor result.
pub(crate) fn is_primitive_c_type(t: &str) -> bool {
    matches!(
        t,
        "uint8_t"
            | "uint16_t"
            | "uint32_t"
            | "uint64_t"
            | "int8_t"
            | "int16_t"
            | "int32_t"
            | "int64_t"
            | "uintptr_t"
            | "intptr_t"
            | "size_t"
            | "ssize_t"
            | "double"
            | "float"
            | "bool"
            | "int"
    )
}

/// Returns `true` when `fields_c_types["{parent}.{field}"]` is the magic
/// sentinel `"skip"` — the C codegen should omit any assertion that touches
/// this field rather than emitting a call to a non-existent FFI function.
fn is_skipped_c_field(fields_c_types: &HashMap<String, String>, parent_snake: &str, field_snake: &str) -> bool {
    let key = format!("{parent_snake}.{field_snake}");
    fields_c_types.get(&key).is_some_and(|t| t == "skip")
}

/// Field names whose declared `fields_c_types` type is a real IR enum, derived from the
/// IR rather than authored in config. `fields_enum` membership is `try_emit_enum_accessor`'s
/// gate (see below): a field absent from it falls through to `infer_opaque_handle_type`,
/// whose match condition (non-primitive, non-`char*`) is a strict superset of the enum
/// arm's — so a genuinely enum-typed field that a config entry simply forgot to list
/// silently renders as an opaque handle instead, and `render_assertion` then emits
/// `strcmp()` against a `uint64_t`. Returning these field names lets the caller union
/// them into the effective `fields_enum` set so the IR can independently satisfy the
/// gate — an override, not the sole source of truth. ~keep
fn enum_fields_from_ir(
    fields_c_types: &HashMap<String, String>,
    enums: &[crate::core::ir::EnumDef],
) -> HashSet<String> {
    fields_c_types
        .iter()
        .filter(|(_, type_name)| enums.iter().any(|e| &e.name == *type_name))
        .filter_map(|(key, _)| key.rsplit('.').next().map(str::to_string))
        .collect()
}

/// The single seam deciding the C "none" sentinel for an omitted optional argument -- `0`
/// for the scalar `AlefHandle` handle representation, `NULL` for a real pointer. See
/// `c::optional_arg` for the full rationale; re-exported here (rather than imported at every
/// use site) so the submodules keep naming it `super::c_optional_sentinel`. ~keep
use optional_arg::{c_optional_sentinel, resolve_optional_sentinel};

/// Infer the opaque-handle PascalCase return type for a bare-field accessor.
///
/// Returns `Some(pascal_type)` when the accessor `{prefix}_{parent}_{field}`
/// returns a pointer to an opaque struct (e.g. `SAMPLELLMUsage*`) rather than
/// a `char*` or primitive scalar.
///
/// Detection strategy:
/// 1. Direct lookup `fields_c_types["{parent}.{field}"]` — if present and
///    NOT a primitive AND NOT `char*`, treat as an opaque handle of that
///    PascalCase type.
/// 2. Inferred lookup — when ANY key in `fields_c_types` starts with
///    `"{field}."` (the snake_case of `field` as a parent type), the field
///    must be a struct whose nested fields are mapped. Default the struct
///    type to `field.to_pascal_case()`. This mirrors the fallback used by
///    `emit_nested_accessor` for intermediate segments.
///
/// Returns `None` when the field looks like a `char*` string accessor.
fn infer_opaque_handle_type(
    fields_c_types: &HashMap<String, String>,
    parent_snake_type: &str,
    field_snake: &str,
) -> Option<String> {
    let lookup_key = format!("{parent_snake_type}.{field_snake}");
    if let Some(t) = fields_c_types.get(&lookup_key) {
        if !is_primitive_c_type(t) && t != "char*" {
            return Some(t.clone());
        }
        // Primitive or explicit char* — caller handles those paths.
        return None;
    }
    // Inferred: nested keys exist with `field_snake` as the parent type prefix.
    let nested_prefix = format!("{field_snake}.");
    if fields_c_types.keys().any(|k| k.starts_with(&nested_prefix)) {
        return Some(field_snake.to_pascal_case());
    }
    None
}

/// Try to emit an enum-aware field accessor: when `raw_field`/`resolved_field`
/// is registered in `fields_enum` AND `fields_c_types[parent.field]` resolves
/// to a non-primitive PascalCase type name, treat the accessor return as an
/// opaque enum pointer and convert it to `char*` via the FFI's
/// `{prefix}_{enum_snake}_to_string` accessor.
///
/// Without this, the C codegen would default-declare the accessor result as
/// `char* status = {prefix}_batch_object_status(result);` and string-compare
/// it — but the FFI returns `SAMPLELLMBatchStatus*` (an opaque enum struct
/// pointer), not a C string. The mismatch causes immediate `Abort trap: 6` /
/// `strcmp(NULL,...)` failures in every assertion that targets an enum field.
///
/// Returns `true` when an accessor was emitted (caller must NOT emit the
/// default `char*` declaration). When emitted, the opaque-enum handle is
/// pushed to `intermediate_handles` so the existing cleanup loop frees it via
/// `{prefix}_{enum_snake}_free(...)` after the test body runs.
#[allow(clippy::too_many_arguments)]
fn try_emit_enum_accessor(
    out: &mut String,
    prefix: &str,
    prefix_upper: &str,
    raw_field: &str,
    resolved_field: &str,
    parent_snake_type: &str,
    accessor_fn: &str,
    parent_handle: &str,
    local_var: &str,
    fields_c_types: &HashMap<String, String>,
    fields_enum: &HashSet<String>,
    intermediate_handles: &mut Vec<(String, String)>,
) -> bool {
    if !(fields_enum.contains(raw_field) || fields_enum.contains(resolved_field)) {
        return false;
    }
    let lookup_key = format!("{parent_snake_type}.{resolved_field}");
    let Some(enum_pascal) = fields_c_types.get(&lookup_key) else {
        return false;
    };
    if is_primitive_c_type(enum_pascal) || enum_pascal == "char*" {
        return false;
    }
    let enum_snake = enum_pascal.to_snake_case();
    let handle_var = format!("{local_var}_handle");
    let _ = writeln!(
        out,
        "    {prefix_upper}AlefHandle {handle_var} = {accessor_fn}({parent_handle});"
    );
    let _ = writeln!(out, "    assert({handle_var} != 0);");
    let _ = writeln!(
        out,
        "    char* {local_var} = {prefix}_{enum_snake}_to_string({handle_var});"
    );
    intermediate_handles.push((handle_var, enum_snake));
    true
}

impl E2eCodegen for CCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
        functions: &[crate::core::ir::FunctionDef],
        errors: &[crate::core::ir::ErrorDef],
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
        let ir = CallIr { functions, type_defs };

        let mut files = Vec::new();

        // Resolve default call config with overrides.
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let result_var = call.effective_result_var();
        let prefix = overrides
            .and_then(|o| o.prefix.as_ref())
            .cloned()
            .or_else(|| config.ffi.as_ref().and_then(|ffi| ffi.prefix.as_ref()).cloned())
            .unwrap_or_default();
        let header = overrides
            .and_then(|o| o.header.as_ref())
            .cloned()
            .unwrap_or_else(|| config.ffi_header_name());

        // Resolve package config.
        let c_pkg = e2e_config.resolve_package("c");
        // lib_name is the actual Rust library name (for linking)
        let lib_name = config.ffi_lib_name();

        // ffi_pkg_name is the release artifact package name (for downloads).
        // Derived from lib_name (for example, "sample_ffi" stays "sample_ffi") because
        // the publish workflow stages tarballs as "${lib_name}-v${VERSION}-${TRIPLE}.tar.gz".
        // The explicit e2e package name is a fallback for edge cases where the release
        // artifact name differs from the library name.
        let ffi_pkg_name = c_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| lib_name.clone());

        // Filter active groups (with non-skipped fixtures).
        let active_groups: Vec<(&FixtureGroup, Vec<&Fixture>)> = groups
            .iter()
            .filter_map(|group| {
                let active: Vec<&Fixture> = group
                    .fixtures
                    .iter()
                    .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                    .filter(|f| f.visitor.is_none())
                    .collect();
                if active.is_empty() { None } else { Some((group, active)) }
            })
            .collect();

        // Collect active visitor fixtures (flattened across all groups).
        let visitor_fixtures: Vec<&Fixture> = groups
            .iter()
            .flat_map(|group| group.fixtures.iter())
            .filter(|f| super::should_include_fixture(f, lang, e2e_config))
            .filter(|f| f.visitor.is_some())
            .filter(|f| c_visitor_fixture_has_typed_call(f, e2e_config, ir))
            .collect();

        // Resolve FFI crate path for local repo builds.
        // Default to `../../crates/{name}-ffi` derived from the crate name so that
        // projects with named FFI crates resolve to `../../crates/{name}-ffi/include/`
        // rather than the generic (incorrect) `../../crates/ffi`.
        // When `[crates.output] ffi` is set explicitly, derive the crate path from
        // that value so that renamed FFI crates (e.g. `parser-core-core-ffi`) resolve
        // correctly without any hardcoded special cases.
        let ffi_crate_path = c_pkg
            .as_ref()
            .and_then(|p| p.path.as_ref())
            .cloned()
            .unwrap_or_else(|| config.ffi_crate_path());

        // Generate Makefile.
        let mut category_names: Vec<String> = active_groups
            .iter()
            .map(|(g, _)| sanitize_filename(&g.category))
            .collect();
        if !visitor_fixtures.is_empty() {
            category_names.push("visitor".to_string());
        }
        let needs_mock_server = active_groups
            .iter()
            .flat_map(|(_, fixtures)| fixtures.iter())
            .any(|f| f.needs_mock_server());
        files.push(GeneratedFile {
            path: output_base.join("Makefile"),
            content: render_makefile(&category_names, &header, &ffi_crate_path, &lib_name, needs_mock_server),
            generated_header: true,
        });

        // Generate download_ffi.sh for downloading prebuilt FFI from GitHub releases.
        let github_repo = config.github_repo();
        let version = config.resolved_version().unwrap_or_else(|| "0.0.0".to_string());
        files.push(GeneratedFile {
            path: output_base.join("download_ffi.sh"),
            content: render_download_script(&github_repo, &version, &ffi_pkg_name),
            generated_header: true,
        });

        // Generate test_runner.h.
        files.push(GeneratedFile {
            path: output_base.join("test_runner.h"),
            content: render_test_runner_header(&active_groups, &visitor_fixtures),
            generated_header: true,
        });

        // Generate main.c.
        files.push(GeneratedFile {
            path: output_base.join("main.c"),
            content: render_main_c(&active_groups, &visitor_fixtures, &e2e_config.env),
            generated_header: true,
        });

        // Generate .gitignore so locally-built binaries and mock-server pipe
        // artifacts are never accidentally checked in. A committed macOS Mach-O
        // `run_tests` binary will fail Linux CI with `Exec format error`.
        files.push(GeneratedFile {
            path: output_base.join(".gitignore"),
            content: render_gitignore(),
            generated_header: false,
        });

        let field_resolver = FieldResolver::new(
            &e2e_config.fields,
            &e2e_config.fields_optional,
            &e2e_config.result_fields,
            &e2e_config.fields_array,
            &std::collections::HashSet::new(),
        );

        // Generate per-category test files.
        // Each fixture may reference a named call config (fixture.call), so we pass
        // e2e_config to render_test_file so it can resolve per-fixture call settings.
        for (group, active) in &active_groups {
            let filename = format!("test_{}.c", sanitize_filename(&group.category));
            let content = render_test_file(
                &group.category,
                active,
                &header,
                &prefix,
                result_var,
                e2e_config,
                lang,
                &field_resolver,
                config,
                type_defs,
                enums,
                errors,
                ir,
            )?;
            files.push(GeneratedFile {
                path: output_base.join(filename),
                content,
                generated_header: true,
            });
        }

        // Generate test_visitor.c if there are visitor fixtures.
        if !visitor_fixtures.is_empty() {
            files.push(GeneratedFile {
                path: output_base.join("test_visitor.c"),
                content: render_visitor_test_file(&visitor_fixtures, &header, &prefix, e2e_config, config, ir)?,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn render_snippet_body(
        &self,
        fixture: &Fixture,
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        _enums: &[crate::core::ir::EnumDef],
    ) -> Result<String> {
        render_c_snippet(fixture, e2e_config, config, type_defs, &[])
    }

    fn render_snippet_body_with_functions(
        &self,
        fixture: &Fixture,
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        _enums: &[crate::core::ir::EnumDef],
        functions: &[crate::core::ir::FunctionDef],
        _errors: &[crate::core::ir::ErrorDef],
    ) -> Result<String> {
        render_c_snippet(fixture, e2e_config, config, type_defs, functions)
    }

    fn language_name(&self) -> &'static str {
        "c"
    }
}

fn render_c_snippet(
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    config: &ResolvedCrateConfig,
    type_defs: &[crate::core::ir::TypeDef],
    functions: &[crate::core::ir::FunctionDef],
) -> Result<String> {
    let ir = CallIr { functions, type_defs };
    let mut info = resolve_fixture_call_info(fixture, e2e_config, config, "c", ir);
    let call = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    let prefix = call
        .overrides
        .get("c")
        .and_then(|value| value.prefix.clone())
        .or_else(|| config.ffi.as_ref().and_then(|value| value.prefix.clone()))
        .unwrap_or_else(|| config.ffi_prefix());
    if info.client_factory.is_none()
        && info.c_engine_factory.is_none()
        && !prefix.is_empty()
        && !info.function_name.starts_with(&format!("{prefix}_"))
    {
        info.function_name = crate::codegen::naming::abi_symbol(&prefix, &info.function_name);
    }
    let header = call
        .overrides
        .get("c")
        .and_then(|value| value.header.clone())
        .unwrap_or_else(|| config.ffi_header_name());
    let (ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields) = FieldResolver::ir_field_sets(type_defs);
    let resolver = FieldResolver::new(
        e2e_config.effective_fields(call),
        e2e_config.effective_fields_optional(call),
        e2e_config.effective_result_fields(call),
        e2e_config.effective_fields_array(call),
        e2e_config.effective_fields_method_calls(call),
    )
    .with_ir_fields(ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields);
    test_function::render_snippet_body(test_function::SnippetContext {
        fixture,
        e2e_config,
        header: &header,
        prefix: &prefix,
        info: &info,
        field_resolver: &resolver,
        config,
        type_defs,
        ir,
    })
}

/// Resolve per-call-config C-specific settings for a given call config and lang.
struct ResolvedCallInfo {
    function_name: String,
    /// Not a `String`: a call whose result type nothing real names must fail at the point the
    /// emitter needs the name, not silently become a PascalCased call name. Paths that never
    /// name a result type — `returns_void` calls, streaming adapters, the `raw_c_result_type`
    /// scalar path — never call [`ResultTypeName::require`] and are unaffected. ~keep
    result_type_name: ResultTypeName,
    options_type_name: String,
    client_factory: Option<String>,
    args: Vec<crate::e2e::config::ArgMapping>,
    raw_c_result_type: Option<String>,
    c_free_fn: Option<String>,
    c_engine_factory: Option<String>,
    result_is_option: bool,
    returns_void: bool,
    /// When `true`, the FFI signature for this method follows the byte-buffer
    /// out-pointer pattern: `int32_t fn(this, req, uint8_t** out_ptr,
    /// uintptr_t* out_len, uintptr_t* out_cap)`. The C codegen emits out-param
    /// declarations, a status-code check, and `<prefix>_free_bytes` rather
    /// than treating the result as an opaque response handle.
    result_is_bytes: bool,
    streaming: Option<bool>,
    /// Per-language `extra_args` from call overrides — verbatim trailing
    /// arguments appended after the configured `args`. The C codegen passes
    /// `NULL` for absent optional pointers via this mechanism.
    extra_args: Vec<String>,
}

/// The core-IR seam this backend resolves calls through, shared with every other e2e backend.
///
/// These lived here until each backend needed them; the definitions and their rationale are now
/// in [`super::call_ir`]. Re-exported rather than re-imported at every use site so the `c`
/// submodules keep naming them `super::CallIr` / `super::named_type`. ~keep
pub(super) use super::call_ir::{CallIr, TargetParams, named_type};

fn resolve_call_info(
    call: &CallConfig,
    lang: &str,
    ir: CallIr<'_>,
    trait_bridge_registry_identity: Option<&str>,
) -> ResolvedCallInfo {
    let overrides = call.overrides.get(lang);
    let function_name = overrides
        .and_then(|o| o.function.as_ref())
        .cloned()
        .unwrap_or_else(|| call.function.clone());
    // Fall back to the *base* (non-C-overridden) function name when no explicit
    // result_type is set.  Using the C-overridden name (e.g. "htm_convert") would
    // produce a doubled-prefix type like `HTMHtmConvert*`; the base name
    // ("convert") yields the correct `HTMConvert*` shape.
    let result_type_name = overrides
        .and_then(|o| o.result_type.as_ref())
        .cloned()
        .inspect(|configured| warn_if_result_type_override_disables_verification(configured, call, lang))
        .or_else(|| resolve_ir_result_type(call, lang, ir))
        .map(ResultTypeName::Resolved)
        .unwrap_or_else(|| unresolved_result_type_name(call, lang, ir, trait_bridge_registry_identity));
    let options_type_name = overrides
        .and_then(|o| o.options_type.as_deref())
        .or(call.options_type.as_deref())
        .unwrap_or_default()
        .to_string();
    let client_factory = overrides.and_then(|o| o.client_factory.as_ref()).cloned();
    let raw_c_result_type = overrides
        .and_then(|o| o.raw_c_result_type.clone())
        .or_else(|| return_shape::resolve_raw_c_result_type(call, lang, ir));
    let c_free_fn = overrides.and_then(|o| o.c_free_fn.clone());
    let c_engine_factory = overrides.and_then(|o| o.c_engine_factory.clone());
    let result_is_option = overrides
        .and_then(|o| if o.result_is_option { Some(true) } else { None })
        .unwrap_or(call.result_is_option);
    let returns_void = call.returns_void;
    // result_is_bytes is read from either the call-level config (preferred —
    // the byte-buffer FFI shape is identical across languages that use the
    // same FFI crate) or the per-language override (back-compat with the
    // pattern used by Java / PHP / etc.).
    let result_is_bytes = call.result_is_bytes || overrides.is_some_and(|o| o.result_is_bytes);
    let extra_args = overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
    let mut args = call.args.clone();
    // `ir` is the Rust core's IR, so this lookup wants the Rust identity and must NOT
    // resolve `overrides.c.function` — that names a prefixed C export (`samplellm_chat`), not
    // the Rust function (`chat`). `core_lookup_name` keeps the base name as the key and only
    // supplies a fallback when the base names nothing at all, which stops the key degrading
    // to `""` and silently deriving arg/result types from the empty string. ~keep
    let core_lookup_name = call.core_lookup_name(lang);
    if let Some(signature) = core_lookup_name.as_deref().and_then(|name| ir.signature(name)) {
        for (index, arg) in args.iter_mut().enumerate() {
            if arg.element_type.is_some() || arg.arg_type != "json_object" {
                continue;
            }
            let parameter = signature
                .params
                .iter()
                .find(|parameter| parameter.name == arg.name)
                .or_else(|| signature.params.get(index));
            arg.element_type = parameter
                .and_then(|parameter| named_type(&parameter.ty))
                .map(str::to_string);
        }
    }
    ResolvedCallInfo {
        function_name,
        result_type_name,
        options_type_name,
        client_factory,
        args,
        raw_c_result_type,
        c_free_fn,
        c_engine_factory,
        result_is_option,
        returns_void,
        result_is_bytes,
        streaming: call.streaming_enabled(),
        extra_args,
    }
}

/// Name the type a call's result handle points at, read from the core IR.
///
/// The declared return type is already the `Ok` type: the extractor splits `Result<T, E>`
/// into `return_type = T` plus a separate `error_type`, so a fallible
/// `fn complete(..) -> Result<CompletionResponse, String>` resolves to `CompletionResponse`.
///
/// The named type is reached through [`named_type`], the recursive unwrapper this module
/// already uses for argument element types — a second, one-level-deep match sitting beside it
/// answered `None` for `Result<Vec<Model>, E>` and every other nesting, and every `None` here
/// lands on [`unresolved_result_type_name`].
///
/// The lookup goes through [`CallIr::signature`], so a call naming an inherent or trait method
/// resolves too; `ApiSurface::functions` alone would answer `None` for every one of them.
fn resolve_ir_result_type(call: &CallConfig, lang: &str, ir: CallIr<'_>) -> Option<String> {
    let lookup_name = call.core_lookup_name(lang)?;
    let signature = ir.signature(&lookup_name)?;
    named_type(signature.return_type).map(str::to_string)
}

/// Warn when a per-language `result_type` override names a primitive/pointer C spelling
/// (`char*`, `int32_t`, `uintptr_t`, ...) rather than the PascalCase IR struct name the field
/// doc describes.
///
/// `overrides.result_type` short-circuits [`resolve_call_info`]'s `.or_else()` chain before
/// both `resolve_ir_result_type` and [`unresolved_result_type_name`] ever run — so unlike the
/// unresolvable-call case those two cover (which now fails generation, per the `~keep` above), a
/// primitive spelling typed into `result_type` reaches no diagnostic at all. It still becomes
/// `result_type_name`, which is both the accessor prefix and the `parent_is_ir_type` flag
/// `ensure_leaf_field_exists` reads — no IR type is ever named `"char*"`, so nested-field
/// verification silently turns off for the call, exactly as it would via the fallback path,
/// but invisibly. A call whose result genuinely carries no named fields has a documented way
/// to say so (`result_is_bytes` / `result_is_simple` / the Zig-only `result_is_json_struct`,
/// all checked at [`unresolved_result_type_name`]) — `result_type` is not it. ~keep
fn warn_if_result_type_override_disables_verification(configured: &str, call: &CallConfig, lang: &str) {
    if is_primitive_c_type(configured) || configured == "char*" || configured.ends_with('*') {
        tracing::warn!(
            call = %call.function,
            language = %lang,
            result_type = %configured,
            "call/override declares `result_type` as a primitive/pointer C spelling rather than \
             a PascalCase IR type name, which disables nested-field verification for this call \
             because no IR type will ever match this name — if the result genuinely carries no \
             named fields to verify, declare that with `result_is_bytes` / `result_is_simple` \
             instead"
        );
    }
}

/// Stands in for a call whose name is empty in both the base config and the per-language
/// override, so a diagnostic never interpolates to nothing. ~keep
const UNNAMED_CALL_DIAGNOSTIC: &str = "<call with no configured name>";

/// The result type a C call will be emitted against, together with what backs the name.
///
/// The emitter builds three different things out of this one name — the accessor prefix
/// (`{prefix}_{result_snake}_{leaf}`), the cleanup call (`{prefix}_{result_snake}_free`), and
/// the `parent_is_ir_type` flag `ensure_leaf_field_exists` reads. Handing all three a
/// PascalCased *call* name, as this module did before, was self-concealing: the fabricated
/// type matched no IR type, so `ensure_leaf_field_exists` default-allowed every leaf under it
/// and the very check that would have caught the fabrication was switched off by the
/// fabrication. Carrying the outcome rather than a bare `String` forces the emitter to ask for
/// the name through [`ResultTypeName::require`], and asking is where an unresolvable one turns
/// into a generation error instead of a guess. ~keep
pub(super) enum ResultTypeName {
    /// Backed by something real: an explicit `result_type` call override, or the declared
    /// return type the core IR gives for this call.
    Resolved(String),
    /// Derived from the call name in a case where nothing downstream reads it as a claim that
    /// a type of that name exists:
    ///
    /// - No IR was supplied at all (unit tests and the visitor call sites construct a
    ///   [`CallIr`] from empty slices deliberately). `type_defs` is then empty, so every
    ///   IR-keyed check has no data either way and none is lost by the derived name.
    /// - The call/override already declares the result carries no named fields
    ///   (`result_is_bytes` / `result_is_simple` / the Zig-only `result_is_json_struct`), which
    ///   is the config's own statement that there is no named type and no nested field.
    /// - The call resolves to a trait-bridge registry function (`register_fn` / `unregister_fn`
    ///   / `clear_fn` on `[[crates.trait_bridges]]`). Those are FFI exports the backend
    ///   generates itself, not core IR functions, so they never resolve against `ir` — and a
    ///   registry register/unregister/clear operation returns a status code, not a named
    ///   response type, so there is no result to verify in the first place.
    ///
    /// The three cases are NOT interchangeable at the point the emitter decides what the call
    /// returns, so the basis travels with the name -- see [`UnverifiedBasis`]. ~keep
    Unverified { name: String, basis: UnverifiedBasis },
    /// The IR was available, the call resolves to nothing in it (absent, or ambiguous per
    /// [`CallIr::signature`]), and no config declaration says the result has no named type.
    /// There is nothing real to name here, so emitting fails rather than inventing one.
    Unresolvable { call: String, language: String },
}

/// Why a [`ResultTypeName::Unverified`] name is not backed by a real type.
///
/// The three cases answer "what does this call return" differently, and collapsing them into a
/// bare name is what let a failed type lookup masquerade as a positive statement that the call
/// returns an owned opaque handle. That inference is unsound in both directions: it emitted
/// `{PREFIX}AlefHandle result = f(...)` for an `i32` status and then passed the status to
/// `{prefix}_..._free`, which frees an alef `Box` -- heap corruption in the emitted C, reached
/// by every call whose result type failed to resolve, not only by trait bridges. Mirrors
/// `assertions::TargetParams`, which splits the same ambiguity on the argument axis. ~keep
pub(super) enum UnverifiedBasis {
    /// No IR was supplied at all (unit tests and the visitor call sites construct a [`CallIr`]
    /// from empty slices deliberately), so nothing was consulted and nothing was learned.
    ///
    /// Nothing contradicts the pre-existing opaque-handle derivation either, and refusing here
    /// would fail every IR-less caller -- a far larger blast radius than the defect being
    /// fixed. Same trade, and same reasoning, as `assertions::TargetParams::IrAbsent`; the
    /// two halves of one rule must agree on what an absent IR licenses. ~keep
    IrAbsent,
    /// The call/override declares the result carries no named fields (`result_is_bytes` /
    /// `result_is_simple` / the Zig-only `result_is_json_struct`).
    ///
    /// This is the config's own statement that the result is NOT a named struct, so it is
    /// positive evidence against the opaque-handle shape rather than mere silence. Paths that
    /// only need something to call the result by (the byte-buffer out-pointer shape) keep
    /// working through [`ResultTypeName::require`]; paths that would bind the result to a
    /// handle and free it are refused by [`ResultTypeName::require_owned_handle`]. ~keep
    DeclaredNonStruct,
    /// The call resolves to a trait-bridge registry function (`register_fn` / `unregister_fn` /
    /// `clear_fn` on `[[crates.trait_bridges]]`).
    ///
    /// Alef generates these exports itself, so their C return shape is known rather than
    /// guessed: `register_fn_header.jinja`, `unregister_fn.jinja` and `clear_fn.jinja` all
    /// declare `-> i32`, with `0` for success and `1` for failure. There is no result handle at
    /// all, which is why they never resolve against the core IR -- and why binding one to
    /// `{PREFIX}AlefHandle` and freeing it was never a naming slip. ~keep
    TraitBridgeRegistry,
}

impl ResultTypeName {
    /// The name to emit, or the generation error that replaces the name this used to invent.
    ///
    /// This resolves against the core IR, not against the header the run is about to emit,
    /// because the emitted symbol set is not reachable from here: neither
    /// [`E2eCodegen::generate`] nor either snippet entry point receives it — they receive IR
    /// slices (`type_defs`, `enums`, `functions`) and nothing else. Checking a result type
    /// against the symbols that will actually exist would mean threading
    /// `cli::pipeline::generate::header_freshness::scan_generated_ffi_source`'s
    /// `BTreeMap<symbol, Option<cfg>>` down into the generator. Until that is threaded, the IR
    /// is the only real thing available to resolve against, and failing loudly beats a
    /// plausible wrong name. ~keep
    pub(super) fn require(&self) -> Result<&str> {
        match self {
            Self::Resolved(name) | Self::Unverified { name, .. } => Ok(name),
            Self::Unresolvable { call, language } => anyhow::bail!(
                "C e2e codegen cannot name the result type of call `{call}` for language \
                 `{language}`: it resolves to no core IR function or method with a named return \
                 type. Naming it after the call would emit `{{prefix}}_{{result}}_{{field}}` \
                 accessors and a `{{prefix}}_{{result}}_free` cleanup for a type the generated \
                 header never declares, and would switch nested-field verification off for this \
                 fixture because no IR type matches an invented name. Fix by setting \
                 `result_type` on the call's `{language}` override to the real type, or by \
                 declaring the result carries no named fields (`result_is_bytes` / \
                 `result_is_simple`)."
            ),
        }
    }

    /// The name to emit on a path that binds the call's result to `{PREFIX}AlefHandle` and
    /// hands it to `{prefix}_{result_snake}_free`.
    ///
    /// Deliberately stricter than [`require`](Self::require). `require` answers "what is this
    /// result called", which the byte-buffer and streaming shapes ask without ever taking
    /// ownership of a handle. This answers a different question -- "may this result be owned
    /// and freed as an alef `Box`" -- and the failure to resolve a type name is never an
    /// affirmative answer to it. Passing a non-handle to a generated `_free` corrupts the heap
    /// in the emitted C, so the two `Unverified` bases that positively contradict the handle
    /// shape refuse here even though they still have a usable name. ~keep
    pub(super) fn require_owned_handle(&self) -> Result<&str> {
        let name = self.require()?;
        match self {
            Self::Unverified {
                basis: UnverifiedBasis::DeclaredNonStruct,
                ..
            } => anyhow::bail!(
                "C e2e codegen would bind the result of a call it cannot name to an opaque \
                 handle and free it with `{{prefix}}_{{result}}_free`, but the call already \
                 declares its result carries no named fields (`result_is_bytes` / \
                 `result_is_simple` / `result_is_json_struct`) -- so there is no handle to own \
                 and the free would be passed a value that was never an alef `Box`. Fix by \
                 setting `raw_c_result_type` on the call's `c` override to the C spelling the \
                 export actually returns (`char*`, `int32_t`, `uintptr_t`, ...), or by setting \
                 `result_type` to the real handle type if the result IS a named struct."
            ),
            Self::Unverified {
                basis: UnverifiedBasis::TraitBridgeRegistry,
                ..
            } => anyhow::bail!(
                "C e2e codegen would bind the result of trait-bridge registry export \
                 `{name}` to an opaque handle and free it, but `register_fn` / `unregister_fn` \
                 / `clear_fn` exports return an `i32` status code (see \
                 `src/backends/ffi/templates/`), not a handle. The status-code emission in \
                 `test_function.rs` should have claimed this call before any handle path did."
            ),
            Self::Resolved(_) | Self::Unverified { .. } | Self::Unresolvable { .. } => Ok(name),
        }
    }

    /// True when the C export this call names returns an `i32` status code rather than a
    /// result the emitted test could own, assert on, or free.
    ///
    /// Positive knowledge, not a fallback: the only calls that answer `true` are trait-bridge
    /// registry exports, which alef generates from its own templates and which all declare
    /// `-> i32`. Every branch that presupposes a different return shape -- a client method, an
    /// engine factory, an opaque handle -- must consult this first, because a wrong shape here
    /// is not a cosmetic mismatch: it emits a free for a value that is not a heap allocation. ~keep
    pub(super) fn returns_status_code(&self) -> bool {
        matches!(
            self,
            Self::Unverified {
                basis: UnverifiedBasis::TraitBridgeRegistry,
                ..
            }
        )
    }
}

/// Classify a call whose result type neither config nor the IR named.
///
/// `trait_bridge_registry_identity` is the derived C identity
/// ([`crate::e2e::codegen::recipe::trait_bridge_derived_c_identity`]'s second tuple element,
/// e.g. `"clear_validator"`) when the caller has already matched this call against a
/// `[[crates.trait_bridges]]` `register_fn` / `unregister_fn` / `clear_fn`, or `None` for an
/// ordinary call. It is threaded in rather than recomputed here because the match needs
/// `ResolvedCrateConfig` and the fixture, neither of which this function (or [`resolve_call_info`],
/// its only caller) otherwise takes — widening this signature to the whole config just to run a
/// lookup already available at the call site would be a worse trade than one extra parameter.
///
/// Three of the four arms still derive a name from the call, and all three are cases where the
/// derived name is provably not read as a type claim — see [`ResultTypeName::Unverified`]. The
/// fourth is the authoring gap: the IR was there to consult, the call is not in it, nothing
/// declares that it has no named result, and it does not name a trait-bridge registry function
/// either. That one used to warn and hand back the invented name anyway, which is how a suite
/// could be generated with field verification off for a fixture and nothing but a log line said
/// so. It is now an error, raised where the name would have been emitted. ~keep
fn unresolved_result_type_name(
    call: &CallConfig,
    lang: &str,
    ir: CallIr<'_>,
    trait_bridge_registry_identity: Option<&str>,
) -> ResultTypeName {
    let result_type = call.function.to_pascal_case();
    // Checked BEFORE `ir.is_absent()`, unlike the other two arms: a registry export is matched
    // against `[[crates.trait_bridges]]` config, which is available whether or not any IR is,
    // so an absent IR tells us strictly less about this call than the config already does.
    // Ordering it second made an IR-less run classify a bridge call as `IrAbsent` -- "nothing
    // is known" -- when its return shape is in fact fully known, and `IrAbsent` is the one
    // basis that still licenses the opaque-handle path. That is how a status code reached
    // `{prefix}_..._free`. ~keep
    //
    // A registry register/unregister/clear export is generated by the FFI backend itself
    // (`src/backends/ffi/trait_bridge/registration.rs`), never appears in the core IR, and
    // returns an `i32` status code -- there is no named response type it could ever resolve
    // to, so this is not the authoring gap the `Unresolvable` arm below exists to catch. The
    // derived identity (not `call.function`, which is legitimately blank when the call names
    // itself only per language -- exactly the shape a bridge call takes) keeps the name real
    // and non-empty rather than collapsing to the degenerate `{prefix}__free` a blank
    // PascalCase produced before `fallback_result_type_name` was removed. ~keep
    if let Some(identity) = trait_bridge_registry_identity {
        let result_type = identity.to_pascal_case();
        tracing::debug!(
            call = %call.function,
            language = %lang,
            %result_type,
            "call resolves to a trait-bridge registry function (register_fn / unregister_fn / \
             clear_fn), which is a generated FFI export with no core IR counterpart and no named \
             result to verify"
        );
        return ResultTypeName::Unverified {
            name: result_type,
            basis: UnverifiedBasis::TraitBridgeRegistry,
        };
    }
    if ir.is_absent() {
        tracing::debug!(
            call = %call.function,
            language = %lang,
            %result_type,
            "no core IR available to this generator; result type derived from the call name"
        );
        return ResultTypeName::Unverified {
            name: result_type,
            basis: UnverifiedBasis::IrAbsent,
        };
    }
    if call_declares_non_struct_result(call, lang) {
        tracing::debug!(
            call = %call.function,
            language = %lang,
            %result_type,
            "call did not resolve to a core IR function or method with a named return type, but \
             the call/override already declares the result carries no named fields \
             (result_is_bytes / result_is_simple / result_is_json_struct) — there is no named \
             type to set and no nested field for the derived type to hide"
        );
        return ResultTypeName::Unverified {
            name: result_type,
            basis: UnverifiedBasis::DeclaredNonStruct,
        };
    }
    // WARN, not ERROR: whether this is fatal depends on which emission path the call takes. A
    // `raw_c_result_type` call — `char*` derived from a `Vec<String>` return, say — renders
    // correctly without ever naming a result type, so classifying here is "degraded but
    // continuing". The unrecoverable case is reported by [`ResultTypeName::require`] at the point
    // of use, where there is enough context to say what would otherwise have been emitted. ~keep
    // Name the call by the symbol this language actually emits, not by the raw base `function`.
    // The base is legitimately empty when a call names itself only per language, and a diagnostic
    // whose whole job is to tell an author which call to fix is worse than useless when it
    // interpolates to the empty string. ~keep
    let call_name = call.effective_function(lang).unwrap_or(UNNAMED_CALL_DIAGNOSTIC);
    tracing::warn!(
        call = %call_name,
        language = %lang,
        "call did not resolve to a core IR function or method with a named return type and \
         declares no non-struct result; there is no real type to name, so any emission path that \
         needs one now fails rather than inventing it — set `result_type` on the call override"
    );
    ResultTypeName::Unresolvable {
        call: call_name.to_string(),
        language: lang.to_string(),
    }
}

/// True when the call/override already declares that the result carries no named fields to
/// verify: `result_is_bytes` (raw byte buffer), `result_is_simple` (a bare scalar), or the
/// Zig-only `result_is_json_struct` escape hatch (an opaque JSON blob the Zig generator parses
/// and verifies structurally, not through named-field lookup). [`unresolved_result_type_name`]'s
/// error arm exists to catch a genuine authoring gap — a call that SHOULD have resolved to a named
/// IR type but didn't, so no real type can be named — and none of these three flags describe that
/// gap: they are the config's own declaration that there is no named type and no nested field to
/// check, which is what makes the derived PascalCase name provably unread as a type claim there.
/// Checking only `result_is_bytes` would fail generation on every declared-simple or
/// declared-json-struct call, which is the same false alarm with a much larger blast radius. ~keep
fn call_declares_non_struct_result(call: &CallConfig, lang: &str) -> bool {
    if call.result_is_simple || call.result_is_bytes {
        return true;
    }
    call.overrides
        .get(lang)
        .is_some_and(|o| o.result_is_simple || o.result_is_bytes || o.result_is_json_struct)
}

/// Resolve call info for a fixture, with fallback to default call's client_factory.
///
/// Named call configs (e.g. `[e2e.calls.embed]`) may not repeat the `client_factory`
/// setting. We fall back to the default `[e2e.call]` override's client_factory so that
/// all methods on the same client use the same pattern.
fn resolve_fixture_call_info(
    fixture: &Fixture,
    e2e_config: &E2eConfig,
    config: &ResolvedCrateConfig,
    lang: &str,
    ir: CallIr<'_>,
) -> ResolvedCallInfo {
    let call = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );

    // `trait_bridge_derived_c_identity` derives the C ABI symbol the FFI backend
    // actually generates for a trait-bridge registry operation, rather than trusting
    // the raw `fixture.call` config text (`register_fn`/`unregister_fn`/`clear_fn`),
    // which can diverge from it for `unregister`/`clear` (see that function's doc
    // comment for the exact derivation rule). A fixture author who set
    // `skip.languages` for `lang` has already declared that this generator cannot
    // speak for it, so this fallback must not run for a skipped fixture.
    // `src/e2e/snippets/mod.rs` applies an equivalent guard before it ever calls into
    // this generator, but this check must not depend on that upstream filtering having
    // happened -- a caller that reaches this function directly (as this module's own
    // unit tests, and the compiled e2e test-file path via `render_test_file`, both do)
    // must get the same protection on its own terms.
    //
    // Computed once, up front: both the function-name fallback below and the
    // result-type classification inside `resolve_call_info` need the same match, and a
    // registry function's `function_name` may already be non-empty (an explicit
    // per-language override, as a well-formed config sets) while its result type is
    // still unresolvable against the core IR -- the two fallbacks are independent, so
    // neither can be conditioned on the other having fired. ~keep
    let skipped_for_lang = fixture.skip.as_ref().is_some_and(|skip| skip.should_skip(lang));
    let trait_bridge_identity = (!skipped_for_lang)
        .then(|| crate::e2e::codegen::recipe::trait_bridge_derived_c_identity(config, fixture))
        .flatten();

    let mut info = resolve_call_info(
        call,
        lang,
        ir,
        trait_bridge_identity.as_ref().map(|(_, name)| name.as_str()),
    );

    if info.function_name.is_empty()
        && let Some((operation, derived_name)) = trait_bridge_identity
    {
        info.function_name = derived_name;
        // `unregister`/`clear` C exports always take a trailing `out_error` out-param
        // that the shared, language-agnostic `[crates.e2e.calls.*]` args config has no
        // way to express (other bindings surface it via an exception/error-return
        // mechanism instead). `register` needs no such treatment here: register-shaped
        // fixtures require vtable/user_data wiring this generic void-call fallback does
        // not build, so they never reach this branch as a `returns_void` call in
        // practice. See `unregister_fn.jinja` / `clear_fn.jinja` for the ABI shapes.
        if matches!(
            operation,
            crate::e2e::codegen::recipe::TraitBridgeRegistryOperation::Unregister
                | crate::e2e::codegen::recipe::TraitBridgeRegistryOperation::Clear
        ) {
            info.extra_args.push("NULL".to_string());
        }
    }

    let default_overrides = e2e_config.call.overrides.get(lang);

    // Neither factory fallback may reach a status-code export. Both describe how to obtain a
    // receiver for a *method* call, and a trait-bridge registry export is a free function on
    // the registry with no receiver at all -- inheriting a default `client_factory` makes the
    // emitter call `{prefix}_default_client_clear_{trait}(client, ...)`, a symbol the header
    // never declares, and (in a docs snippet) prefaces it with an `API key must be set` guard
    // for a purely local registry operation. The inheritance is a convenience for suites where
    // every call really is a method on one client; it is not evidence about a call whose shape
    // is already known. ~keep
    let returns_status_code = info.result_type_name.returns_status_code();

    // Fallback: if the named call has no client_factory override, inherit from the
    // default call config so all calls use the same client pattern.
    if info.client_factory.is_none()
        && !returns_status_code
        && let Some(factory) = default_overrides.and_then(|o| o.client_factory.as_ref())
    {
        info.client_factory = Some(factory.clone());
    }

    // Fallback: if the named call has no c_engine_factory override, inherit from the
    // default call config so all calls use the same engine pattern.
    if info.c_engine_factory.is_none()
        && !returns_status_code
        && let Some(factory) = default_overrides.and_then(|o| o.c_engine_factory.as_ref())
    {
        info.c_engine_factory = Some(factory.clone());
    }

    info
}

fn c_visitor_fixture_has_typed_call(fixture: &Fixture, e2e_config: &E2eConfig, ir: CallIr<'_>) -> bool {
    let call = e2e_config.resolve_call_for_fixture(
        fixture.call.as_deref(),
        &fixture.id,
        &fixture.resolved_category(),
        &fixture.tags,
        &fixture.input,
    );
    // `None`: this predicate only reads `info.options_type_name`, never `result_type_name`,
    // so a trait-bridge identity would be inert here even if computed. ~keep
    let info = resolve_call_info(call, "c", ir, None);
    let has_function = call
        .overrides
        .get("c")
        .and_then(|override_config| override_config.function.as_deref())
        .is_some_and(|function| !function.is_empty());
    has_function && !info.options_type_name.is_empty()
}

mod assertions;
mod call_patterns;
#[cfg(test)]
mod client_factory_optional_arg_tests;
#[cfg(test)]
mod collection_empty_assertion_tests;
mod collection_wildcard;
mod docs_input;
mod enum_field_inference;
mod ffi_constructors;
mod optional_arg;
mod primitive_field_inference;
mod project;
mod return_shape;
mod runner;
#[cfg(test)]
mod snippet_regressions;
#[cfg(test)]
mod std_arg_tests;
mod streaming;
mod test_function;
mod trait_bridge_snippet;
mod visitor;
mod void_call_status;
#[cfg(test)]
mod wildcard_collection_regression_tests;

use assertions::{
    FieldConfigSources, LeafFieldCheck, build_args_string_c, emit_nested_accessor, ensure_leaf_field_exists,
    render_assertion,
};
use collection_wildcard::{NestedLeafOutcome, classify_nested_leaf, render_wildcard_assertion};
// Test-only: the tests here and in `snippet_regressions` (which pulls this scope in via
// `use super::*`) construct sources explicitly to pin which config key a diagnostic names, while
// non-test code only ever goes through `FieldConfigSources`. Importing it unconditionally would be
// an unused import, which this repo's clippy config escalates to a build failure. ~keep
#[cfg(test)]
use assertions::EffectiveConfigSource;
use call_patterns::{render_bytes_test_function, render_engine_factory_test_function};
use enum_field_inference::enum_fields_c_types_from_ir;
use primitive_field_inference::primitive_fields_c_types_from_ir;
use project::{render_download_script, render_gitignore, render_makefile};
use runner::{render_main_c, render_test_runner_header};
use streaming::{
    render_c_diagnostic_skip, render_streaming_test_function, resolve_c_client_owner_type, resolve_c_streaming_adapter,
    validate_c_snippet_metadata,
};
use test_function::render_test_function_impl;
use visitor::render_visitor_test_file;

#[allow(clippy::too_many_arguments)]
fn render_test_file(
    category: &str,
    fixtures: &[&Fixture],
    header: &str,
    prefix: &str,
    result_var: &str,
    e2e_config: &E2eConfig,
    lang: &str,
    field_resolver: &FieldResolver,
    config: &ResolvedCrateConfig,
    type_defs: &[crate::core::ir::TypeDef],
    enums: &[crate::core::ir::EnumDef],
    errors: &[crate::core::ir::ErrorDef],
    ir: CallIr<'_>,
) -> anyhow::Result<String> {
    let mut out = String::new();
    out.push_str(&hash::header(CommentStyle::Block));
    let _ = writeln!(out, "/* E2e tests for category: {category} */");
    let _ = writeln!(out);
    let _ = writeln!(out, "#include <assert.h>");
    let _ = writeln!(out, "#include <stdint.h>");
    let _ = writeln!(out, "#include <string.h>");
    let _ = writeln!(out, "#include <stdio.h>");
    let _ = writeln!(out, "#include <stdlib.h>");
    let _ = writeln!(out, "#include \"{header}\"");
    let _ = writeln!(out, "#include \"test_runner.h\"");
    let _ = writeln!(out);

    // Extend the operator-declared `fields_c_types` with entries the IR itself proves are
    // enum-typed, before any per-fixture derivation runs. Neither input varies per fixture
    // (`type_defs`/`enums` are the whole crate's IR), so this is computed once. Config always
    // wins: `or_insert` never overwrites an operator's own declaration, including one that
    // deliberately names a different accessor shape (e.g. `"skip"` or `"char*"`). ~keep
    let mut effective_fields_c_types = e2e_config.fields_c_types.clone();
    for (key, type_name) in enum_fields_c_types_from_ir(type_defs, enums) {
        effective_fields_c_types.entry(key).or_insert(type_name);
    }
    // Same precedence for plain scalar leaf fields (`bool`/`u32`/`f64`/...) that never got a
    // `fields_c_types` entry either — see `primitive_field_inference` module docs. ~keep
    for (key, type_name) in primitive_fields_c_types_from_ir(type_defs) {
        effective_fields_c_types.entry(key).or_insert(type_name);
    }

    for (i, fixture) in fixtures.iter().enumerate() {
        // Visitor fixtures are filtered out before render_test_file is called.
        // This guard is a safety net in case a fixture reaches here unexpectedly.
        if fixture.visitor.is_some() {
            panic!(
                "C e2e generator: visitor pattern not supported for fixture: {}",
                fixture.id
            );
        }

        // `ir`, not an empty slice: `resolve_call_info` derives `result_type_name` from the
        // declared return type here, and `result_type_name` is what `parent_is_ir_type` — and
        // through it `ensure_leaf_field_exists` — reads. Passing an empty slice would make
        // every call unresolvable-but-excused (`CallIr::is_absent`), which is how a suite used
        // to be generated with field verification off and nothing but a log line saying so. ~keep
        let call_info = resolve_fixture_call_info(fixture, e2e_config, config, lang, ir);

        // Effective enum fields for this fixture: merge global e2e_config.fields_enum
        // (HashSet) with the per-call C override's enum_fields (HashMap keys). This
        // mirrors Ruby/Java's pattern: global = always-enum-typed paths; per-call =
        // context-dependent paths (BatchObject.status is BatchStatus, but
        // ResponseObject.status is plain String).
        let mut effective_fields_enum = e2e_config.fields_enum.clone();
        let fixture_call = e2e_config.resolve_call_for_fixture(
            fixture.call.as_deref(),
            &fixture.id,
            &fixture.resolved_category(),
            &fixture.tags,
            &fixture.input,
        );
        if let Some(co) = fixture_call.overrides.get(lang) {
            for k in co.enum_fields.keys() {
                effective_fields_enum.insert(k.clone());
            }
        }
        // `fields_enum` above is config-declared and can miss a field the IR itself
        // already proves is enum-shaped — union in every field whose `fields_c_types`
        // entry names a real IR enum so a missing declaration falls back to IR truth
        // instead of silently falling through to the opaque-handle arm (which emits
        // `strcmp()` against a `uint64_t` handle). This only ever ADDS field names: an
        // explicit config entry the IR check doesn't independently confirm (e.g. a
        // synthetic field with no `fields_c_types` entry) still passes through untouched.
        // Reads `effective_fields_c_types`, not the raw config map, so a field the IR-derived
        // pass above declared (no config entry at all) is also recognized as enum-shaped here. ~keep
        effective_fields_enum.extend(enum_fields_from_ir(&effective_fields_c_types, enums));

        // Per-call field resolver: overrides the top-level resolver when this call
        // declares its own result_fields / fields / fields_optional / fields_array.
        // Without this, `pages.length` on a `crawl` call would skip because the
        // default `result_fields` (configured for the top-level `scrape` call)
        // does not contain `pages`.
        let (ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields) =
            FieldResolver::ir_field_sets(type_defs);
        let per_call_field_resolver = FieldResolver::new(
            e2e_config.effective_fields(fixture_call),
            e2e_config.effective_fields_optional(fixture_call),
            e2e_config.effective_result_fields(fixture_call),
            e2e_config.effective_fields_array(fixture_call),
            &std::collections::HashSet::new(),
        )
        .with_ir_fields(ir_reachable_fields, ir_known_excluded_fields, ir_optional_fields);
        let _ = field_resolver; // top-level resolver retained for compat; per-call wins
        let field_resolver = &per_call_field_resolver;

        // Which `result_fields`/`fields` collections govern THIS fixture's call, by the
        // identical shadowing rule `effective_result_fields`/`effective_fields` just
        // applied above — a nested-field diagnostic must name the same key that actually
        // shaped `field_resolver`, or it sends an operator's edit to a config key their
        // call ignores. ~keep
        let config_sources = FieldConfigSources::resolve(e2e_config, fixture_call);

        // `out` accumulates every fixture's rendered function in this file, so the
        // strict-availability scan below must only look at the text THIS fixture's
        // own render appended — scanning the whole buffer would misattribute an
        // earlier fixture's skip comment to this fixture's id.
        let fixture_start = out.len();
        // What the core IR says about this fixture's target parameters -- the identical
        // resolution `render_snippet_body` performs, so the doc-snippet path and the real
        // e2e-test-file emitter (which also drives `test_apps/`) agree on one call's declared
        // signature instead of this path always rendering `IrAbsent`. See `c::optional_arg`. ~keep
        let target_params = if crate::e2e::codegen::recipe::trait_bridge_derived_c_identity(config, fixture).is_some() {
            TargetParams::Known(&[])
        } else {
            TargetParams::resolve(fixture_call, lang, ir)
        };
        render_test_function_impl(
            &mut out,
            fixture,
            prefix,
            &call_info.function_name,
            result_var,
            &call_info.args,
            field_resolver,
            &effective_fields_c_types,
            &effective_fields_enum,
            &call_info.result_type_name,
            &call_info.options_type_name,
            call_info.client_factory.as_deref(),
            call_info.raw_c_result_type.as_deref(),
            call_info.c_free_fn.as_deref(),
            call_info.c_engine_factory.as_deref(),
            call_info.result_is_option,
            call_info.result_is_bytes,
            call_info.streaming,
            &call_info.extra_args,
            config,
            type_defs,
            errors,
            false,
            &config_sources,
            target_params,
        )?;
        crate::e2e::codegen::fail_on_unavailable_field_markers(
            &out[fixture_start..],
            "c",
            &fixture.id,
            &fixture.assertions,
        );
        crate::e2e::codegen::fail_on_unsupported_assertion_type_markers(&out[fixture_start..], "c", &fixture.id);
        if i + 1 < fixtures.len() {
            let _ = writeln!(out);
        }
    }

    Ok(out)
}

#[allow(clippy::too_many_arguments)]
/// Convert a `serde_json::Value` to a C literal string.
fn json_to_c(value: &serde_json::Value) -> String {
    match value {
        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())),
    }
}

/// Emit a test backend stub.
pub fn emit_test_backend(
    trait_bridge: &crate::core::config::TraitBridgeConfig,
    methods: &[&crate::core::ir::MethodDef],
    fixture: &crate::e2e::fixture::Fixture,
) -> super::TestBackendEmission {
    trait_bridge_snippet::emit_test_backend(trait_bridge, methods, fixture)
}

#[cfg(test)]
mod snippet_tests {
    use super::*;

    #[test]
    fn snippet_keeps_header_and_call_without_test_harness() {
        let fixture = Fixture {
            id: "count".into(),
            description: "Count".into(),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "sample_count".into();
        e2e.call.result_var = "result".into();
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };
        let rendered = CCodegen
            .render_snippet_body(&fixture, &e2e, &config, &[], &[])
            .expect("snippet renders");
        assert!(rendered.contains("#include \""));
        assert!(rendered.contains("sample_count("));
        assert!(rendered.contains("int main(void)"));
        assert!(!rendered.contains("void test_"));
        assert!(!rendered.contains("assert("));
        assert!(rendered.contains("_free(result)"), "{rendered}");
    }

    /// A crate IR that names one function, so `CallIr::is_absent()` is false and the generator
    /// genuinely had something to resolve against. The fixture's call is not that function.
    fn unrelated_ir() -> [crate::core::ir::FunctionDef; 1] {
        [crate::core::ir::FunctionDef {
            name: "unrelated".into(),
            return_type: crate::core::ir::TypeRef::Named("Unrelated".into()),
            ..crate::core::ir::FunctionDef::default()
        }]
    }

    /// The defect this pair pins: `list_ocr_backends` was PascalCased into `ListOcrBackends`,
    /// a type the generated header never declares, and the snippet then spelled it into a
    /// `{prefix}_{result}_free` call for a family that has no `_free` member — while the
    /// invented name simultaneously switched `ensure_leaf_field_exists` off, because
    /// `parent_is_ir_type` can only be true for a name the IR actually declares. An
    /// unresolvable result type must therefore produce an ERROR here, not a snippet: the
    /// emitted symbol set is not reachable from this generator (see `ResultTypeName::require`),
    /// so there is nothing better than the IR to resolve against and nothing at all to guess
    /// from. The positive control below shares this shape exactly apart from the IR entry, so
    /// this test cannot pass by making every render fail. ~keep
    #[test]
    fn should_refuse_to_emit_a_snippet_whose_result_type_resolves_to_nothing_real() {
        let fixture = Fixture {
            id: "list_backends".into(),
            description: "List backends".into(),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "sample_list_backends".into();
        e2e.call.result_var = "result".into();
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };

        let error = render_c_snippet(&fixture, &e2e, &config, &[], &unrelated_ir())
            .expect_err("a result type nothing real names must fail generation, not emit a snippet");

        let message = format!("{error:#}");
        assert!(
            message.contains("sample_list_backends"),
            "the failure must name the call an operator has to fix: {message}"
        );
        assert!(
            message.contains("result_type"),
            "the failure must name the config key that fixes it: {message}"
        );
        assert!(
            !message.contains("SampleListBackends"),
            "the failure must not hand back the PascalCased call name as if it were a type: {message}"
        );
    }

    /// Positive control for the test above, identical apart from the IR declaring the call.
    /// A resolvable result type must still render, and must render *through the same emission
    /// path* — the opaque-handle path whose `{prefix}_{result_snake}_free` is exactly the symbol
    /// the fabricated name used to corrupt. Without this, the failure test above would be
    /// satisfied by an emitter that refused everything. ~keep
    #[test]
    fn should_still_emit_a_snippet_when_the_ir_names_the_result_type() {
        let fixture = Fixture {
            id: "list_backends".into(),
            description: "List backends".into(),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "sample_list_backends".into();
        e2e.call.result_var = "result".into();
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };
        let functions = [crate::core::ir::FunctionDef {
            name: "sample_list_backends".into(),
            return_type: crate::core::ir::TypeRef::Named("BackendList".into()),
            ..crate::core::ir::FunctionDef::default()
        }];

        let rendered =
            render_c_snippet(&fixture, &e2e, &config, &[], &functions).expect("a call the IR names must still render");

        assert!(rendered.contains("sample_list_backends("), "{rendered}");
        assert!(
            rendered.contains("sample_backend_list_free(result)"),
            "cleanup must be derived from the IR-declared type, not the call name: {rendered}"
        );
        assert!(
            !rendered.contains("sample_list_backends_free"),
            "the call-name-derived cleanup symbol must never appear: {rendered}"
        );
    }

    /// `clear_fn = "clear_sample_backends"` (plural, human-written config text) on a
    /// trait named `SampleBackend` (singular). `registration.rs` derives the exported
    /// symbol from the trait name's snake_case form, discarding the config text's
    /// spelling, so the real ABI symbol is `sample_clear_sample_backend` (singular) --
    /// and it takes a trailing `out_error` out-param (`clear_fn.jinja`), so the call
    /// site must pass `NULL`. This fails against the pre-fix code, which trusted
    /// `fixture.call`'s raw text verbatim and emitted the argument-less, plural,
    /// nonexistent `sample_clear_sample_backends()`.
    #[test]
    fn trait_bridge_operation_uses_declared_abi_identity() {
        let fixture = Fixture {
            id: "clear_sample_backends".into(),
            description: "Clear registered sample backends".into(),
            call: Some("clear_sample_backends".into()),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.calls.insert(
            "clear_sample_backends".into(),
            CallConfig {
                returns_result: false,
                returns_void: true,
                ..CallConfig::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            trait_bridges: vec![crate::core::config::TraitBridgeConfig {
                trait_name: "SampleBackend".into(),
                clear_fn: Some("clear_sample_backends".into()),
                ..Default::default()
            }],
            ..ResolvedCrateConfig::default()
        };

        let rendered = render_c_snippet(&fixture, &e2e, &config, &[], &[]).expect("C snippet renders");

        assert!(rendered.contains("sample_clear_sample_backend(NULL)"), "{rendered}");
        assert!(!rendered.contains("sample_clear_sample_backends("), "{rendered}");
        assert!(!rendered.contains("has no function identity"), "{rendered}");
    }

    /// `unregister_fn`'s C export always takes a trailing `out_error` out-param
    /// (`unregister_fn.jinja`) in addition to the configured `name` argument, but the
    /// shared, language-agnostic call args config (`args = [{ name, field, type }]`)
    /// has no way to express a C-only out-param. This fails against the pre-fix code:
    /// the void-call branch built its argument list purely from `info.args` and never
    /// consulted `info.extra_args`, so it emitted `sample_unregister_sample_backend(name)`
    /// -- one argument short of the real two-argument ABI signature.
    #[test]
    fn trait_bridge_unregister_appends_out_error_out_param() {
        let fixture = Fixture {
            id: "unregister_sample_backend".into(),
            description: "Unregister a sample backend".into(),
            call: Some("unregister_sample_backend".into()),
            input: serde_json::json!({ "name": "nonexistent-backend" }),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.calls.insert(
            "unregister_sample_backend".into(),
            CallConfig {
                returns_result: false,
                returns_void: true,
                args: vec![crate::core::config::e2e::ArgMapping {
                    name: "name".into(),
                    field: "input.name".into(),
                    arg_type: "string".into(),
                    optional: false,
                    owned: false,
                    element_type: None,
                    go_type: None,
                    vec_inner_is_ref: false,
                    trait_name: None,
                }],
                ..CallConfig::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            trait_bridges: vec![crate::core::config::TraitBridgeConfig {
                trait_name: "SampleBackend".into(),
                unregister_fn: Some("unregister_sample_backend".into()),
                ..Default::default()
            }],
            ..ResolvedCrateConfig::default()
        };

        let rendered = render_c_snippet(&fixture, &e2e, &config, &[], &[]).expect("C snippet renders");

        assert!(
            rendered.contains("sample_unregister_sample_backend(\"nonexistent-backend\", NULL)"),
            "{rendered}"
        );
    }

    /// `resolve_fixture_call_info` must not trust `trait_bridge_function_identity`'s
    /// raw-config-text-derived symbol name for a fixture that declares
    /// `skip.languages = ["c"]` -- exactly the shape of the 13 fixtures fixed in
    /// `8ddaa0559` (via `src/e2e/snippets/mod.rs`'s equivalent guard). This exercises
    /// the resolver directly, independent of the prefixing/template logic that
    /// `render_c_snippet` layers on top, so a regression here is unambiguous: it can
    /// only mean the skip check stopped gating the fallback.
    #[test]
    fn resolve_fixture_call_info_ignores_naive_identity_when_skipped_for_lang() {
        let fixture = Fixture {
            id: "clear_sample_backends".into(),
            call: Some("clear_sample_backends".into()),
            skip: Some(crate::e2e::fixture::SkipDirective {
                languages: vec!["c".into()],
                reason: None,
            }),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.calls.insert(
            "clear_sample_backends".into(),
            CallConfig {
                returns_result: false,
                returns_void: true,
                ..CallConfig::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            trait_bridges: vec![crate::core::config::TraitBridgeConfig {
                trait_name: "SampleBackend".into(),
                clear_fn: Some("clear_sample_backends".into()),
                ..Default::default()
            }],
            ..ResolvedCrateConfig::default()
        };

        let info = resolve_fixture_call_info(&fixture, &e2e, &config, "c", CallIr::default());

        assert_eq!(
            info.function_name, "",
            "skip.languages = [\"c\"] must block the naive identity fallback, leaving no function \
             configured rather than a symbol name that may not exist"
        );
    }

    /// End-to-end counterpart of the resolver-level test above: a fixture skipped for
    /// `c` must not produce a snippet that calls the config-text-derived symbol name.
    /// `render_c_snippet` is exercised directly (not through
    /// `src/e2e/snippets/mod.rs`'s gate) so this proves the C generator's own
    /// invariant, not just the upstream caller's filtering.
    #[test]
    fn trait_bridge_operation_skipped_for_c_does_not_trust_naive_identity() {
        let fixture = Fixture {
            id: "clear_sample_backends".into(),
            description: "Clear registered sample backends".into(),
            call: Some("clear_sample_backends".into()),
            skip: Some(crate::e2e::fixture::SkipDirective {
                languages: vec!["c".into()],
                reason: Some("c FFI export does not match the configured clear_fn text".into()),
            }),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.calls.insert(
            "clear_sample_backends".into(),
            CallConfig {
                returns_result: false,
                returns_void: true,
                ..CallConfig::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            trait_bridges: vec![crate::core::config::TraitBridgeConfig {
                trait_name: "SampleBackend".into(),
                clear_fn: Some("clear_sample_backends".into()),
                ..Default::default()
            }],
            ..ResolvedCrateConfig::default()
        };

        let rendered = render_c_snippet(&fixture, &e2e, &config, &[], &[]).expect("C snippet renders");

        assert!(
            !rendered.contains("sample_clear_sample_backends("),
            "skipped fixture must not call the naive-identity symbol: {rendered}"
        );
        assert!(rendered.contains("sample_();"), "{rendered}");
    }

    #[test]
    fn expected_error_snippet_checks_the_native_null_result() {
        let mut fixture = Fixture {
            id: "invalid".into(),
            description: "Invalid".into(),
            ..Fixture::default()
        };
        fixture.assertions.push(crate::e2e::fixture::Assertion {
            assertion_type: "error".into(),
            ..Default::default()
        });
        let mut e2e = E2eConfig::default();
        e2e.call.function = "sample_parse".into();
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };
        let rendered = CCodegen
            .render_snippet_body(&fixture, &e2e, &config, &[], &[])
            .expect("snippet renders");
        assert!(rendered.contains("!= 0) { return EXIT_FAILURE; }"), "{rendered}");
        assert!(!rendered.contains("assert("));
    }

    #[test]
    fn engine_factory_snippet_reuses_native_call_preparation() {
        let fixture = Fixture {
            id: "engine_call".into(),
            description: "Engine call".into(),
            input: serde_json::json!({ "url": "https://example.test" }),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "sample_scrape".into();
        e2e.call.result_var = "result".into();
        e2e.call.overrides.insert(
            "c".into(),
            crate::core::config::e2e::CallOverride {
                c_engine_factory: Some("EngineConfig".into()),
                ..Default::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };

        let rendered = CCodegen
            .render_snippet_body(&fixture, &e2e, &config, &[], &[])
            .expect("engine-factory snippet renders");

        assert!(rendered.contains("create_engine"), "{rendered}");
        assert!(rendered.contains("sample_scrape(engine"), "{rendered}");
        assert!(rendered.contains("crawl_engine_handle_free(engine)"), "{rendered}");
    }

    #[test]
    fn simple_result_snippet_uses_prefixed_string_api() {
        let fixture = Fixture {
            id: "list_formats".into(),
            description: "List formats".into(),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "list_formats".into();
        e2e.call.result_var = "result".into();
        e2e.call.result_is_simple = true;
        e2e.call.overrides.insert(
            "c".into(),
            crate::core::config::e2e::CallOverride {
                raw_c_result_type: Some("char*".into()),
                ..Default::default()
            },
        );
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };

        let rendered = CCodegen
            .render_snippet_body(&fixture, &e2e, &config, &[], &[])
            .expect("simple-result snippet renders");

        assert!(rendered.contains("char* result = sample_list_formats();"), "{rendered}");
        assert!(rendered.contains("sample_free_string(result);"), "{rendered}");
        assert!(!rendered.contains("SAMPLEListFormats"), "{rendered}");
    }

    #[test]
    fn scalar_result_snippets_preserve_numeric_types_without_string_cleanup() {
        for raw_type in ["int32_t", "bool"] {
            let fixture = Fixture {
                id: "count_formats".into(),
                description: "Count formats".into(),
                ..Fixture::default()
            };
            let mut e2e = E2eConfig::default();
            e2e.call.function = "count_formats".into();
            e2e.call.result_var = "result".into();
            e2e.call.result_is_simple = true;
            e2e.call.overrides.insert(
                "c".into(),
                crate::core::config::e2e::CallOverride {
                    raw_c_result_type: Some(raw_type.into()),
                    ..Default::default()
                },
            );
            let config = ResolvedCrateConfig {
                name: "sample".into(),
                ..ResolvedCrateConfig::default()
            };

            let rendered = CCodegen
                .render_snippet_body(&fixture, &e2e, &config, &[], &[])
                .expect("numeric-result snippet renders");

            assert!(
                rendered.contains(&format!("{raw_type} result = sample_count_formats();")),
                "{rendered}"
            );
            assert!(!rendered.contains("free_string"), "{rendered}");
        }
    }

    #[test]
    fn raw_result_error_snippet_fails_on_unexpected_success() {
        for (raw_type, expected_failure_check) in [
            ("char*", "if (result != 0) { return EXIT_FAILURE; }"),
            ("int32_t", "if (result != 0) { return EXIT_FAILURE; }"),
            ("uintptr_t", "assert(sample_last_error_code() != 0"),
        ] {
            let mut fixture = Fixture {
                id: "invalid_input".into(),
                description: "Invalid input".into(),
                ..Fixture::default()
            };
            fixture.assertions.push(crate::e2e::fixture::Assertion {
                assertion_type: "error".into(),
                ..Default::default()
            });
            let mut e2e = E2eConfig::default();
            e2e.call.function = "parse_input".into();
            e2e.call.result_var = "result".into();
            e2e.call.result_is_simple = true;
            e2e.call.overrides.insert(
                "c".into(),
                crate::core::config::e2e::CallOverride {
                    raw_c_result_type: Some(raw_type.into()),
                    ..Default::default()
                },
            );
            let config = ResolvedCrateConfig {
                name: "sample".into(),
                ..ResolvedCrateConfig::default()
            };

            let rendered = CCodegen
                .render_snippet_body(&fixture, &e2e, &config, &[], &[])
                .expect("raw-result error snippet renders");

            assert!(
                rendered.contains(expected_failure_check),
                "raw_type={raw_type}: {rendered}"
            );
        }
    }

    /// Identifiers a snippet guard may name without a preceding local declaration. ~keep
    const GUARD_FREE_IDENTIFIERS: &[&str] = &["NULL", "EXIT_FAILURE", "EXIT_SUCCESS", "true", "false", "sizeof"];

    /// The condition of an `if (...)` guard, paren-balanced so a call inside it does not
    /// terminate the scan early.
    fn guard_condition(line: &str) -> Option<&str> {
        let rest = line.trim().strip_prefix("if (")?;
        let mut depth = 1usize;
        for (index, character) in rest.char_indices() {
            match character {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(&rest[..index]);
                    }
                }
                _ => {}
            }
        }
        None
    }

    /// Identifiers a condition reads as values: call names, string-literal contents and
    /// numeric literals are excluded.
    fn condition_identifiers(condition: &str) -> Vec<String> {
        let characters: Vec<char> = condition.chars().collect();
        let mut identifiers = Vec::new();
        let mut index = 0;
        let mut in_string = false;
        while index < characters.len() {
            let character = characters[index];
            if in_string {
                index += if character == '\\' { 2 } else { 1 };
                if character == '"' {
                    in_string = false;
                }
                continue;
            }
            if character == '"' {
                in_string = true;
                index += 1;
                continue;
            }
            if character.is_alphabetic() || character == '_' {
                let start = index;
                while index < characters.len() && (characters[index].is_alphanumeric() || characters[index] == '_') {
                    index += 1;
                }
                if characters.get(index) != Some(&'(') {
                    identifiers.push(characters[start..index].iter().collect());
                }
                continue;
            }
            index += 1;
        }
        identifiers
    }

    /// The variable a statement declares. Deliberately reimplemented here rather than shared
    /// with `test_function::declared_variable`: a checker that reuses the emitter's own
    /// heuristic cannot fail when that heuristic is what is wrong. ~keep
    fn declared_name(line: &str) -> Option<String> {
        let statement = line.trim().trim_end_matches(';');
        let declarator = statement.split('=').next()?.trim();
        if declarator.contains(['(', ')', '{', '}', '!', '<', '>', ',', '#'])
            || declarator.split_whitespace().count() < 2
        {
            return None;
        }
        let last = declarator.split_whitespace().next_back()?;
        let name = last.trim_start_matches('*').split('[').next()?;
        (!name.is_empty()).then(|| name.to_string())
    }

    fn guard_uses_before_declaration(snippet: &str) -> Vec<String> {
        let mut declared: HashSet<String> = HashSet::new();
        let mut violations = Vec::new();
        for line in snippet.lines() {
            if let Some(condition) = guard_condition(line) {
                for identifier in condition_identifiers(condition) {
                    if !GUARD_FREE_IDENTIFIERS.contains(&identifier.as_str()) && !declared.contains(&identifier) {
                        violations.push(format!("`{identifier}` read by guard `{}`", line.trim()));
                    }
                }
            }
            if let Some(name) = declared_name(line) {
                declared.insert(name);
            }
        }
        violations
    }

    fn error_fixture(id: &str) -> Fixture {
        let mut fixture = Fixture {
            id: id.into(),
            description: "Expected to fail".into(),
            ..Fixture::default()
        };
        fixture.assertions.push(crate::e2e::fixture::Assertion {
            assertion_type: "error".into(),
            ..Default::default()
        });
        fixture
    }

    /// Property, not string: whatever a generated C snippet's `if (...)` guards read must
    /// already be declared above them, because a snippet is a standalone translation unit and
    /// a use-before-declaration is a hard compile error, not a failing assertion.
    ///
    /// The checker is a whole-snippet scan, so it also covers the `free`-guards the
    /// engine-factory and client paths emit — not just the error-path failure guard. ~keep
    #[test]
    fn every_guard_identifier_in_a_generated_snippet_is_declared_before_it_is_read() {
        let sample = || ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };

        let mut client_e2e = E2eConfig::default();
        client_e2e.call.function = "chat".into();
        client_e2e.call.overrides.insert(
            "c".into(),
            crate::core::config::e2e::CallOverride {
                client_factory: Some("create_client".into()),
                ..Default::default()
            },
        );
        let client_config = ResolvedCrateConfig {
            adapters: vec![
                serde_json::from_value(serde_json::json!({
                    "name": "chat",
                    "pattern": "async_method",
                    "core_path": "sample::chat",
                    "owner_type": "DefaultClient"
                }))
                .expect("client adapter config"),
            ],
            ..sample()
        };

        let mut raw_e2e = E2eConfig::default();
        raw_e2e.call.function = "parse_input".into();
        raw_e2e.call.result_var = "result".into();
        raw_e2e.call.result_is_simple = true;
        raw_e2e.call.overrides.insert(
            "c".into(),
            crate::core::config::e2e::CallOverride {
                raw_c_result_type: Some("char*".into()),
                ..Default::default()
            },
        );

        let mut handle_e2e = E2eConfig::default();
        handle_e2e.call.function = "sample_parse".into();

        let cases: Vec<(&str, Fixture, E2eConfig, ResolvedCrateConfig)> = vec![
            (
                "client-factory error",
                error_fixture("chat_auth_401"),
                client_e2e,
                client_config,
            ),
            ("raw-result error", error_fixture("parse_invalid"), raw_e2e, sample()),
            (
                "opaque-handle error",
                error_fixture("parse_failed"),
                handle_e2e,
                sample(),
            ),
        ];

        for (label, fixture, e2e, config) in cases {
            let rendered = render_c_snippet(&fixture, &e2e, &config, &[], &[]).expect("snippet renders");
            let violations = guard_uses_before_declaration(&rendered);
            assert!(
                violations.is_empty(),
                "{label}: guard reads an undeclared identifier: {violations:?}\n{rendered}"
            );
        }
    }

    /// Negative control for the checker above. This is the exact shape alef 0.60.0 published for
    /// every error fixture with a client factory: the client-construction assertion was rewritten
    /// into the result guard, so the guard named a variable declared on the next line. A checker
    /// that cannot see this defect proves nothing about the snippets that pass it. ~keep
    #[test]
    fn guard_checker_rejects_the_historic_use_before_declaration_snippet() {
        let historic = concat!(
            "int main(void) {\n",
            "    SAMPLEDefaultClient* client = sample_create_client(\"test-key\", NULL);\n",
            "    if (result != NULL) { return EXIT_FAILURE; }\n",
            "    SAMPLEBatchObject* result = sample_default_client_cancel_batch(client, \"batch-1\");\n",
            "    sample_default_client_free(client);\n",
            "    if (result != NULL) { return EXIT_FAILURE; }\n",
            "    return EXIT_SUCCESS;\n",
            "}\n",
        );

        let violations = guard_uses_before_declaration(historic);

        assert_eq!(violations.len(), 1, "{violations:?}");
        assert!(violations[0].contains("`result`"), "{violations:?}");
    }

    #[test]
    fn raw_result_test_function_asserts_failure_per_result_type() {
        // Direct test of the real e2e-test-file emitter (render_test_function_impl),
        // which is where the defect lived: for raw_c_result_type functions
        // (char*/int32_t/uintptr_t), an "error"-only fixture previously emitted
        // no assertion at all, so a call that unexpectedly SUCCEEDED still made
        // the generated test pass. Assert the exact failing construct per type.
        let cases: &[(&str, &str)] = &[
            ("char*", "assert(result == NULL && \"expected call to fail\");"),
            ("int32_t", "assert(result < 0 && \"expected call to fail\");"),
            (
                "uintptr_t",
                "assert(sample_last_error_code() != 0 && \"expected call to fail\");",
            ),
        ];
        for (raw_type, expected_assert) in cases {
            let mut fixture = Fixture {
                id: "invalid_input".into(),
                description: "Invalid input".into(),
                ..Fixture::default()
            };
            fixture.assertions.push(crate::e2e::fixture::Assertion {
                assertion_type: "error".into(),
                ..Default::default()
            });
            let config = ResolvedCrateConfig {
                name: "sample".into(),
                ..ResolvedCrateConfig::default()
            };
            let field_resolver = FieldResolver::new(
                &HashMap::new(),
                &HashSet::new(),
                &HashSet::new(),
                &HashSet::new(),
                &HashSet::new(),
            );

            let mut out = String::new();
            render_test_function_impl(
                &mut out,
                &fixture,
                "sample",
                "sample_parse_input",
                "result",
                &[],
                &field_resolver,
                &HashMap::new(),
                &HashSet::new(),
                &ResultTypeName::Resolved("Result".into()),
                "",
                None,
                Some(raw_type),
                None,
                None,
                false,
                false,
                None,
                &[],
                &config,
                &[],
                &[],
                false,
                &FieldConfigSources {
                    result_fields: EffectiveConfigSource::Global,
                    fields: EffectiveConfigSource::Global,
                },
                TargetParams::IrAbsent,
            )
            .expect("test fixture renders");

            assert!(
                out.contains(expected_assert),
                "raw_type={raw_type}: expected `{expected_assert}` in:\n{out}"
            );
            assert!(
                !out.contains("expected call to succeed"),
                "raw_type={raw_type}: unexpected success-path assertion in:\n{out}"
            );
        }
    }

    #[test]
    fn raw_result_test_function_falls_back_to_last_error_code_for_unmodeled_raw_types() {
        // raw_c_result_type is a free-form config string (bool, uint64_t, size_t, ...),
        // not a closed char*/int32_t/uintptr_t set. A fixture using any type outside
        // that trio must still emit a failing check via the always-present
        // last_error_code FFI symbol — not silently emit nothing.
        for raw_type in ["bool", "uint64_t", "size_t"] {
            let mut fixture = Fixture {
                id: "invalid_input".into(),
                description: "Invalid input".into(),
                ..Fixture::default()
            };
            fixture.assertions.push(crate::e2e::fixture::Assertion {
                assertion_type: "error".into(),
                ..Default::default()
            });
            let config = ResolvedCrateConfig {
                name: "sample".into(),
                ..ResolvedCrateConfig::default()
            };
            let field_resolver = FieldResolver::new(
                &HashMap::new(),
                &HashSet::new(),
                &HashSet::new(),
                &HashSet::new(),
                &HashSet::new(),
            );

            let mut out = String::new();
            render_test_function_impl(
                &mut out,
                &fixture,
                "sample",
                "sample_parse_input",
                "result",
                &[],
                &field_resolver,
                &HashMap::new(),
                &HashSet::new(),
                &ResultTypeName::Resolved("Result".into()),
                "",
                None,
                Some(raw_type),
                None,
                None,
                false,
                false,
                None,
                &[],
                &config,
                &[],
                &[],
                false,
                &FieldConfigSources {
                    result_fields: EffectiveConfigSource::Global,
                    fields: EffectiveConfigSource::Global,
                },
                TargetParams::IrAbsent,
            )
            .expect("test fixture renders");

            assert!(
                out.contains("assert(sample_last_error_code() != 0 && \"expected call to fail\");"),
                "raw_type={raw_type}: expected last_error_code fallback assert in:\n{out}"
            );
        }
    }

    /// Builds an error fixture with `raw_c_result_type = "char*"` plus the extra assertions the
    /// error path has to account for.
    fn render_c_error_fixture(extra: Vec<crate::e2e::fixture::Assertion>, declared: Option<&str>) -> String {
        let mut fixture = Fixture {
            id: "rate_limited".into(),
            description: "Rejects the request".into(),
            ..Fixture::default()
        };
        fixture.assertions.push(crate::e2e::fixture::Assertion {
            assertion_type: "error".into(),
            value: declared.map(|v| serde_json::Value::String(v.to_string())),
            ..Default::default()
        });
        fixture.assertions.extend(extra);
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };
        let field_resolver = FieldResolver::new(
            &HashMap::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
            &HashSet::new(),
        );
        let mut out = String::new();
        let _ = crate::e2e::codegen::take_skip_records();
        render_test_function_impl(
            &mut out,
            &fixture,
            "sample",
            "sample_parse_input",
            "result",
            &[],
            &field_resolver,
            &HashMap::new(),
            &HashSet::new(),
            &ResultTypeName::Resolved("Result".into()),
            "",
            None,
            Some("char*"),
            None,
            None,
            false,
            false,
            None,
            &[],
            &config,
            &[],
            &[],
            false,
            &FieldConfigSources {
                result_fields: EffectiveConfigSource::Global,
                fields: EffectiveConfigSource::Global,
            },
            TargetParams::IrAbsent,
        )
        .expect("test fixture renders");
        out
    }

    /// The defect: a declared `error` value was discarded outright, so `assert(result == NULL)`
    /// was the whole test — it could not tell the expected failure from any other. The C ABI's
    /// `last_error_context()` is the only textual evidence available, and it must be compared.
    #[test]
    fn a_declared_error_value_is_compared_against_the_ffi_error_message() {
        let out = render_c_error_fixture(Vec::new(), Some("rate limit"));

        assert!(
            out.contains("assert(result == NULL && \"expected call to fail\");"),
            "the failure check must still render: {out}"
        );
        assert!(
            out.contains("const char* _err_message = sample_last_error_context();"),
            "the FFI message must be bound: {out}"
        );
        assert!(
            out.contains("assert(strstr(_err_message, \"rate limit\") != NULL && \"error message mismatch\");"),
            "the declared value must be compared: {out}"
        );
    }

    /// Negative control: with no declared value the emitter must not invent a message check.
    #[test]
    fn an_error_assertion_without_a_value_emits_no_message_check() {
        let out = render_c_error_fixture(Vec::new(), None);

        assert!(
            out.contains("assert(result == NULL && \"expected call to fail\");"),
            "the failure check must still render: {out}"
        );
        assert!(!out.contains("last_error_context"), "{out}");
    }

    #[test]
    fn an_equals_on_an_error_field_is_named_instead_of_dropped() {
        let out = render_c_error_fixture(
            vec![crate::e2e::fixture::Assertion {
                assertion_type: "equals".into(),
                field: Some("error.status_code".into()),
                ..Default::default()
            }],
            Some("rate limit"),
        );

        assert!(
            out.contains("assert(result == NULL && \"expected call to fail\");"),
            "the error block must render before we assert anything about the second assertion: {out}"
        );
        assert!(
            out.contains(
                "// skipped: assertion type 'equals' has no accessor for error field error.status_code in this backend"
            ),
            "{out}"
        );

        let records = crate::e2e::codegen::take_skip_records();
        assert_eq!(records.len(), 1, "got: {records:?}");
        assert_eq!(records[0].language, "c");
        assert_eq!(records[0].field, "equals");
    }

    #[test]
    fn void_result_snippet_calls_api_without_placeholder_result() {
        let fixture = Fixture {
            id: "clear_formats".into(),
            description: "Clear formats".into(),
            ..Fixture::default()
        };
        let mut e2e = E2eConfig::default();
        e2e.call.function = "clear_formats".into();
        e2e.call.returns_void = true;
        let config = ResolvedCrateConfig {
            name: "sample".into(),
            ..ResolvedCrateConfig::default()
        };

        let rendered = CCodegen
            .render_snippet_body(&fixture, &e2e, &config, &[], &[])
            .expect("void-result snippet renders");

        assert!(rendered.contains("sample_clear_formats();"), "{rendered}");
        assert!(!rendered.contains("result ="), "{rendered}");
        assert!(!rendered.contains("_free("), "{rendered}");
    }

    /// `enum_fields_from_ir` must recover exactly the field a config author forgot to
    /// list in `fields_enum` -- this is the reported mechanism behind the `strcmp()`-on-
    /// `uint64_t` defect: `BatchObject.status` maps to the real IR enum `BatchStatus` in
    /// `fields_c_types`, but nothing in this config declares `status` an enum field.
    #[test]
    fn enum_fields_from_ir_recovers_field_missing_from_declared_fields_enum() {
        let fields_c_types = HashMap::from([("batch_object.status".to_string(), "BatchStatus".to_string())]);
        let enums = vec![crate::core::ir::EnumDef {
            name: "BatchStatus".into(),
            ..crate::core::ir::EnumDef::default()
        }];

        let derived = enum_fields_from_ir(&fields_c_types, &enums);

        assert_eq!(derived, HashSet::from(["status".to_string()]));
    }

    /// A field whose `fields_c_types` type does NOT name a real IR enum must not be
    /// swept in by the override — otherwise a genuine opaque-struct field would be
    /// misrouted through the enum accessor and the codegen would call a
    /// `_to_string` function cbindgen never generated for it.
    #[test]
    fn enum_fields_from_ir_ignores_a_field_whose_type_is_not_a_registered_enum() {
        let fields_c_types = HashMap::from([("batch_object.usage".to_string(), "BatchUsage".to_string())]);
        let enums = vec![crate::core::ir::EnumDef {
            name: "BatchStatus".into(),
            ..crate::core::ir::EnumDef::default()
        }];

        let derived = enum_fields_from_ir(&fields_c_types, &enums);

        assert!(derived.is_empty(), "got: {derived:?}");
    }

    /// End-to-end proof that the override reaches `try_emit_enum_accessor`: with
    /// `fields_enum` empty (the reported gap) but the IR-derived override unioned in — the
    /// same composition `render_test_file` performs — the enum arm must fire and convert
    /// via `_to_string`, not leave a bare `AlefHandle` for the caller to `strcmp` against.
    #[test]
    fn try_emit_enum_accessor_fires_for_a_field_ir_proves_is_an_enum_even_when_fields_enum_omits_it() {
        let fields_c_types = HashMap::from([("batch_object.status".to_string(), "BatchStatus".to_string())]);
        let enums = vec![crate::core::ir::EnumDef {
            name: "BatchStatus".into(),
            ..crate::core::ir::EnumDef::default()
        }];
        let mut fields_enum: HashSet<String> = HashSet::new();
        fields_enum.extend(enum_fields_from_ir(&fields_c_types, &enums));

        let mut out = String::new();
        let mut handles = Vec::new();
        let fired = try_emit_enum_accessor(
            &mut out,
            "sample",
            "SAMPLE",
            "status",
            "status",
            "batch_object",
            "sample_batch_object_status",
            "result",
            "status",
            &fields_c_types,
            &fields_enum,
            &mut handles,
        );

        assert!(
            fired,
            "enum accessor must fire once the IR-derived override is unioned in"
        );
        assert!(
            out.contains("sample_batch_status_to_string("),
            "must convert via _to_string, not leave a bare handle for strcmp: {out}"
        );
        assert!(!out.contains("strcmp"), "{out}");
    }
}

#[cfg(test)]
mod result_type_resolution_tests;