boltffi_bindgen 0.24.1

Code generation library for BoltFFI - generates Swift, Kotlin, and TypeScript bindings
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
//! View model for the C# backend: the data shapes the templates
//! consume. `CSharpType` is the central vocabulary: every record
//! field, param, return, and variant field resolves to one. All wire
//! expressions (decode, size, encode) are pre-rendered strings
//! produced by the lowerer; templates only interpolate.
//!
//! `CSharpType` owns its IR-to-type constructors
//! (`impl From<PrimitiveType>`, `enum_backing_for`, `for_enum`,
//! `from_read_op`, `from_type_expr`), so one place answers "what C#
//! type does this become?".
//!
//! No dependency on `emit` or `lower`: the plan is passive data.
//! `lower` produces it, `templates` consume it.

use std::collections::HashSet;
use std::fmt;

use crate::ir::codec::EnumLayout;
use crate::ir::definitions::{EnumDef, EnumRepr};
use crate::ir::ops::ReadOp;
use crate::ir::types::{PrimitiveType, TypeExpr};
use boltffi_ffi_rules::naming::{LibraryName, Name};

use super::NamingConvention;

/// Represents a lowered C# module, containing everything the templates need
/// to render a `.cs` file.
#[derive(Debug, Clone)]
pub struct CSharpModule {
    /// C# namespace for the generated file (e.g., `"MyApp"`).
    pub namespace: String,
    /// Top-level class name (e.g., `"MyApp"`).
    pub class_name: String,
    /// Native library name used in `[DllImport("...")]` declarations.
    pub lib_name: Name<LibraryName>,
    /// FFI symbol prefix (e.g., `"boltffi"`).
    pub prefix: String,
    /// Records exposed by the module. Each record is rendered to its own
    /// `.cs` file as a `readonly record struct`.
    pub records: Vec<CSharpRecord>,
    /// Enums exposed by the module. Each enum is rendered to its own `.cs`
    /// file: C-style as a native `enum`, data-carrying as an
    /// `abstract record` with nested `sealed record` variants.
    pub enums: Vec<CSharpEnum>,
    /// Top-level primitive functions. Used by both the public wrapper class
    /// and the `[DllImport]` native declarations: C# P/Invoke passes
    /// primitives directly, so one struct serves both layers.
    pub functions: Vec<CSharpFunction>,
}

impl CSharpModule {
    pub fn has_functions(&self) -> bool {
        !self.functions.is_empty()
    }

    /// Whether the shared runtime helpers need `System.Text`.
    ///
    /// Top-level string params use `Encoding.UTF8.GetBytes` in the wrapper,
    /// and `WireWriter` uses `Encoding.UTF8.GetByteCount` / `GetBytes` when
    /// encoding string-bearing params (including `Vec<String>` / nested
    /// string vecs) or string fields of a record. Decoding no longer needs
    /// `System.Text`. `WireReader` reads strings through
    /// `Marshal.PtrToStringUTF8`.
    pub fn needs_system_text(&self) -> bool {
        self.functions
            .iter()
            .any(|f| f.params.iter().any(|p| p.csharp_type.contains_string()))
            || self.records.iter().any(CSharpRecord::has_string_fields)
    }

    /// Whether any function takes a wire-encoded record param. Blittable
    /// record params pass through the CLR as direct struct values and do
    /// not contribute here.
    pub fn has_wire_params(&self) -> bool {
        self.functions.iter().any(|f| !f.wire_writers.is_empty())
    }

    /// Whether any function returns through an `FfiBuf`, a wire-decoded
    /// string or non-blittable record. Blittable records come back as
    /// direct struct values and do not count here.
    pub fn has_ffi_buf_returns(&self) -> bool {
        self.functions
            .iter()
            .any(|f| f.return_kind.native_returns_ffi_buf())
    }

    /// Whether the `FfiBuf` struct and `FreeBuf` DllImport are emitted.
    /// Needed for wire-encoded returns, and pulled in whenever a record or
    /// enum exists so the `WireReader` (which takes `FfiBuf`) compiles.
    pub fn needs_ffi_buf(&self) -> bool {
        self.has_ffi_buf_returns() || !self.records.is_empty() || !self.enums.is_empty()
    }

    /// Whether the stateful `WireReader` helper is emitted. Needed for
    /// wire-decoded returns, for any record's `Decode` method, and for the
    /// enum wire helpers (`StatusWire.Decode`, `Shape.Decode`).
    pub fn needs_wire_reader(&self) -> bool {
        self.has_ffi_buf_returns() || !self.records.is_empty() || !self.enums.is_empty()
    }

    /// Whether the `WireWriter` helper is emitted. Needed for wire-encoded
    /// params, for any record's `WireEncodeTo` method, and for the enum
    /// encode helpers.
    pub fn needs_wire_writer(&self) -> bool {
        self.has_wire_params() || !self.records.is_empty() || !self.enums.is_empty()
    }
}

/// A C# type keyword. Includes `Void` so return types and value types share
/// one enum; params never carry `Void` because the lowerer rejects it before
/// constructing a [`CSharpParam`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CSharpType {
    Void,
    Bool,
    SByte,
    Byte,
    Short,
    UShort,
    Int,
    UInt,
    Long,
    ULong,
    NInt,
    NUInt,
    Float,
    Double,
    String,
    /// A user-defined record, identified by its rendered PascalCase class
    /// name (e.g., `"Point"`).
    Record(String),
    /// A user-defined C-style enum (all variants are unit). Renders as a
    /// C# `enum` with an `int` backing type. Blittable: passes directly
    /// across P/Invoke as its underlying integer, and stays blittable when
    /// embedded in a `[StructLayout(Sequential)]` record.
    CStyleEnum(String),
    /// A user-defined data enum (at least one variant carries a payload).
    /// Renders as an `abstract record` with nested `sealed record` variants.
    /// Always wire-encoded (never blittable) because variant payloads
    /// are variable-width.
    DataEnum(String),
    /// A `Vec<T>` projected into the C# surface as a `T[]` jagged array.
    /// Uniform representation across every element kind: primitives ride
    /// the blittable bulk-copy path, composites walk element-by-element.
    /// Nested vecs fall out naturally via recursive `Array(Array(...))`.
    Array(Box<CSharpType>),
    /// An `Option<T>` projected into the C# surface as `T?`. Uniform
    /// across value-type and reference-type inners: for value types it
    /// desugars to `Nullable<T>`, for reference types it reads as a
    /// nullable-annotated reference (both require `#nullable enable`,
    /// which the generated files opt in to). Always travels
    /// wire-encoded across the ABI. The 1-byte tag + payload form does
    /// not line up with any CLR primitive layout.
    Nullable(Box<CSharpType>),
}

impl CSharpType {
    pub fn is_void(&self) -> bool {
        matches!(self, Self::Void)
    }

    pub fn is_bool(&self) -> bool {
        matches!(self, Self::Bool)
    }

    pub fn is_string(&self) -> bool {
        matches!(self, Self::String)
    }

    /// Whether this type contains `string` at any nesting depth. Used for
    /// import decisions where `string[]` / `string[][]` still require
    /// `System.Text` because their encode path calls `Encoding.UTF8`.
    pub fn contains_string(&self) -> bool {
        match self {
            Self::String => true,
            Self::Array(inner) | Self::Nullable(inner) => inner.contains_string(),
            _ => false,
        }
    }

    pub fn is_record(&self) -> bool {
        matches!(self, Self::Record(_))
    }

    pub fn is_c_style_enum(&self) -> bool {
        matches!(self, Self::CStyleEnum(_))
    }

    pub fn is_data_enum(&self) -> bool {
        matches!(self, Self::DataEnum(_))
    }

    pub fn is_array(&self) -> bool {
        matches!(self, Self::Array(_))
    }

    /// If this is `Array(inner)`, returns `Some(inner)`; otherwise `None`.
    pub fn array_element(&self) -> Option<&CSharpType> {
        match self {
            Self::Array(inner) => Some(inner),
            _ => None,
        }
    }

    /// If `self` is a user-defined named type (record or enum) whose
    /// class name is shadowed by an enclosing scope, return a variant
    /// wrapping the fully-qualified `global::{namespace}.{ClassName}`.
    /// Primitives and unnamed types pass through unchanged. The
    /// `global::` prefix dodges both nested-type shadowing *and* any
    /// same-named class in the current namespace (the generated
    /// top-level wrapper class, typically).
    pub fn qualify_if_shadowed(
        self,
        shadowed: &std::collections::HashSet<String>,
        namespace: &str,
    ) -> Self {
        match self {
            Self::Record(n) if shadowed.contains(&n) => {
                Self::Record(format!("global::{}.{}", namespace, n))
            }
            Self::CStyleEnum(n) if shadowed.contains(&n) => {
                Self::CStyleEnum(format!("global::{}.{}", namespace, n))
            }
            Self::DataEnum(n) if shadowed.contains(&n) => {
                Self::DataEnum(format!("global::{}.{}", namespace, n))
            }
            Self::Array(inner) => {
                Self::Array(Box::new((*inner).qualify_if_shadowed(shadowed, namespace)))
            }
            Self::Nullable(inner) => {
                Self::Nullable(Box::new((*inner).qualify_if_shadowed(shadowed, namespace)))
            }
            other => other,
        }
    }

    /// Applies [`Self::qualify_if_shadowed`] when `scope` is `Some`.
    pub fn qualify_if_shadowed_opt(self, scope: Option<&ShadowScope<'_>>) -> Self {
        match scope {
            Some(s) => self.qualify_if_shadowed(s.shadowed, s.namespace),
            None => self,
        }
    }

    /// The C# type a Rust C-style enum's tag primitive becomes when used
    /// as the enum's backing type. Returns `None` for primitives that C#
    /// does not accept as an enum base (`nint`, `nuint`, `bool`, `f32`,
    /// `f64`), so the caller can drop the enum from the supported set
    /// instead of emitting an illegal `enum : nuint`.
    pub fn enum_backing_for(tag_type: PrimitiveType) -> Option<CSharpType> {
        match tag_type {
            PrimitiveType::I8 => Some(CSharpType::SByte),
            PrimitiveType::U8 => Some(CSharpType::Byte),
            PrimitiveType::I16 => Some(CSharpType::Short),
            PrimitiveType::U16 => Some(CSharpType::UShort),
            PrimitiveType::I32 => Some(CSharpType::Int),
            PrimitiveType::U32 => Some(CSharpType::UInt),
            PrimitiveType::I64 => Some(CSharpType::Long),
            PrimitiveType::U64 => Some(CSharpType::ULong),
            PrimitiveType::Bool
            | PrimitiveType::ISize
            | PrimitiveType::USize
            | PrimitiveType::F32
            | PrimitiveType::F64 => None,
        }
    }

    /// The C# type a Rust enum definition lifts to. The `EnumRepr` drives
    /// the split: a C-style enum (all unit variants) becomes
    /// [`CSharpType::CStyleEnum`] and rides P/Invoke as its declared
    /// backing integral type; a data enum (at least one payload-carrying
    /// variant) becomes [`CSharpType::DataEnum`] and wire-encodes.
    /// Everything downstream (the return-kind dispatch, param marshaling,
    /// record blittability) keys off this one decision.
    pub fn for_enum(enum_def: &EnumDef) -> CSharpType {
        let class_name = NamingConvention::class_name(enum_def.id.as_str());
        match &enum_def.repr {
            EnumRepr::CStyle { .. } => CSharpType::CStyleEnum(class_name),
            EnumRepr::Data { .. } => CSharpType::DataEnum(class_name),
        }
    }

    /// Converts from a [`ReadOp`].
    pub fn from_read_op(op: &ReadOp) -> Self {
        match op {
            ReadOp::Primitive { primitive, .. } => Self::from(*primitive),
            ReadOp::String { .. } => Self::String,
            ReadOp::Bytes { .. } => Self::Array(Box::new(Self::Byte)),
            ReadOp::Option { some, .. } => {
                let inner = Self::from_read_op(some.ops.first().expect("option inner read op"));
                Self::Nullable(Box::new(inner))
            }
            ReadOp::Vec { element_type, .. } => {
                Self::Array(Box::new(Self::from_type_expr(element_type)))
            }
            ReadOp::Record { id, .. } => Self::Record(NamingConvention::class_name(id.as_str())),
            ReadOp::Enum { id, layout, .. } => {
                let class_name = NamingConvention::class_name(id.as_str());
                match layout {
                    EnumLayout::CStyle { .. } => Self::CStyleEnum(class_name),
                    EnumLayout::Data { .. } | EnumLayout::Recursive => Self::DataEnum(class_name),
                }
            }
            ReadOp::Custom { underlying, .. } => {
                Self::from_read_op(underlying.ops.first().expect("custom underlying read op"))
            }
            ReadOp::Result { .. } | ReadOp::Builtin { .. } => {
                todo!("CSharpType::from_read_op: {:?}", op)
            }
        }
    }

    /// Converts from a [`TypeExpr`]. `TypeExpr::Enum` picks [`Self::DataEnum`]
    /// arbitrarily; all three named-type variants render the same through
    /// [`fmt::Display`] and [`Self::qualify_if_shadowed`].
    pub fn from_type_expr(expr: &TypeExpr) -> Self {
        match expr {
            TypeExpr::Void => Self::Void,
            TypeExpr::Primitive(p) => Self::from(*p),
            TypeExpr::String => Self::String,
            TypeExpr::Bytes => Self::Array(Box::new(Self::Byte)),
            TypeExpr::Vec(inner) => Self::Array(Box::new(Self::from_type_expr(inner))),
            TypeExpr::Option(inner) => Self::Nullable(Box::new(Self::from_type_expr(inner))),
            TypeExpr::Record(id) => Self::Record(NamingConvention::class_name(id.as_str())),
            TypeExpr::Enum(id) => Self::DataEnum(NamingConvention::class_name(id.as_str())),
            TypeExpr::Result { .. }
            | TypeExpr::Callback(_)
            | TypeExpr::Custom(_)
            | TypeExpr::Builtin(_)
            | TypeExpr::Handle(_) => todo!("CSharpType::from_type_expr: {:?}", expr),
        }
    }

    /// Whether this type is blittable in the CLR's sense: it can
    /// live inside a `[StructLayout(Sequential)]` record field and pass
    /// across P/Invoke without wire encoding. Primitives all qualify;
    /// `bool` does not (P/Invoke defaults to a 4-byte Win32 BOOL, so
    /// records with bool fields go through the wire path today). Strings
    /// and data enums are always wire-encoded. C-style enums are `int`
    /// underneath and ride the zero-copy path. Records are blittable or
    /// not based on their own field contents, decided elsewhere. This
    /// predicate only answers "is this *leaf* type blittable?".
    pub fn is_blittable_leaf(&self) -> bool {
        match self {
            Self::SByte
            | Self::Byte
            | Self::Short
            | Self::UShort
            | Self::Int
            | Self::UInt
            | Self::Long
            | Self::ULong
            | Self::NInt
            | Self::NUInt
            | Self::Float
            | Self::Double
            | Self::CStyleEnum(_) => true,
            Self::Void
            | Self::Bool
            | Self::String
            | Self::Record(_)
            | Self::DataEnum(_)
            | Self::Array(_)
            | Self::Nullable(_) => false,
        }
    }
}

impl From<PrimitiveType> for CSharpType {
    /// Each boltffi primitive maps to a distinct C# type. C# has native
    /// unsigned types (`byte`, `ushort`, `uint`, `ulong`) and platform-
    /// sized integers (`nint`, `nuint`), so the conversion is lossless.
    fn from(primitive: PrimitiveType) -> Self {
        match primitive {
            PrimitiveType::Bool => CSharpType::Bool,
            PrimitiveType::I8 => CSharpType::SByte,
            PrimitiveType::U8 => CSharpType::Byte,
            PrimitiveType::I16 => CSharpType::Short,
            PrimitiveType::U16 => CSharpType::UShort,
            PrimitiveType::I32 => CSharpType::Int,
            PrimitiveType::U32 => CSharpType::UInt,
            PrimitiveType::I64 => CSharpType::Long,
            PrimitiveType::U64 => CSharpType::ULong,
            PrimitiveType::ISize => CSharpType::NInt,
            PrimitiveType::USize => CSharpType::NUInt,
            PrimitiveType::F32 => CSharpType::Float,
            PrimitiveType::F64 => CSharpType::Double,
        }
    }
}

impl fmt::Display for CSharpType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Void => f.write_str("void"),
            Self::Bool => f.write_str("bool"),
            Self::SByte => f.write_str("sbyte"),
            Self::Byte => f.write_str("byte"),
            Self::Short => f.write_str("short"),
            Self::UShort => f.write_str("ushort"),
            Self::Int => f.write_str("int"),
            Self::UInt => f.write_str("uint"),
            Self::Long => f.write_str("long"),
            Self::ULong => f.write_str("ulong"),
            Self::NInt => f.write_str("nint"),
            Self::NUInt => f.write_str("nuint"),
            Self::Float => f.write_str("float"),
            Self::Double => f.write_str("double"),
            Self::String => f.write_str("string"),
            Self::Record(name) | Self::CStyleEnum(name) | Self::DataEnum(name) => f.write_str(name),
            Self::Array(inner) => write!(f, "{inner}[]"),
            Self::Nullable(inner) => write!(f, "{inner}?"),
        }
    }
}

/// Type names shadowed by a nested scope at the render site. Used when
/// emitting inside a data enum's body, where nested `sealed record`
/// variants shadow module-level types of the same name: any class
/// reference whose name is in `shadowed` gets qualified as
/// `global::{namespace}.{ClassName}` so it resolves past the shadowing
/// variant. Constructed by the lowerer and passed down through emit.
pub struct ShadowScope<'a> {
    pub shadowed: &'a HashSet<String>,
    pub namespace: &'a str,
}

/// A record (Rust struct) exposed as a C# `readonly record struct`.
///
/// Each record is emitted to its own `.cs` file. Blittable records (all
/// fields are primitives, layout matches Rust's `#[repr(C)]`) get a
/// `[StructLayout(LayoutKind.Sequential)]` attribute so the CLR passes
/// them directly across the P/Invoke boundary by value, no wire encoding
/// needed. Non-blittable records carry `Decode` / `WireEncodedSize` /
/// `WireEncodeTo` members and travel as wire-encoded buffers.
#[derive(Debug, Clone)]
pub struct CSharpRecord {
    /// PascalCase class name (e.g., `"Point"`).
    pub class_name: String,
    /// The record's fields, in declaration order.
    pub fields: Vec<CSharpRecordField>,
    /// Whether the record can cross the P/Invoke boundary as a direct
    /// `[StructLayout(Sequential)]` value. True when the Rust type is
    /// `#[repr(C)]` with blittable fields only.
    pub is_blittable: bool,
}

impl CSharpRecord {
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// Wire helpers are only needed for non-blittable records. Blittable
    /// records skip wire encoding entirely.
    pub fn needs_wire_helpers(&self) -> bool {
        !self.is_blittable
    }

    /// Whether the record has at least one field whose type contains a
    /// string at any nesting depth (bare `string`, `string?`, `string[]`,
    /// nested vecs of strings). Used by the record template to decide
    /// whether to import `System.Text` (for `Encoding.UTF8.GetByteCount`).
    /// Required because `TreatWarningsAsErrors` flags unused usings.
    pub fn has_string_fields(&self) -> bool {
        self.fields.iter().any(|f| f.csharp_type.contains_string())
    }
}

/// A field on a [`CSharpRecord`]. All wire expressions are pre-rendered by
/// the lowerer so the template can paste them verbatim.
#[derive(Debug, Clone)]
pub struct CSharpRecordField {
    /// PascalCase property name (e.g., `"X"`). Records use PascalCase
    /// property names, not camelCase, matching idiomatic C# record syntax.
    pub name: String,
    /// C# type of the field.
    pub csharp_type: CSharpType,
    /// Expression that decodes this field from a `WireReader`
    /// (e.g., `"reader.ReadF64()"` or `"Point.Decode(reader)"`).
    pub wire_decode_expr: String,
    /// Expression that produces the wire-encoded byte size of this field
    /// (e.g., `"8"`, `"WireWriter.StringWireSize(this.Name)"`).
    pub wire_size_expr: String,
    /// Statement that writes this field to a `WireWriter` named `wire`
    /// (e.g., `"wire.WriteF64(this.X)"`).
    pub wire_encode_expr: String,
}

/// A Rust enum lifted into the C# type surface. C-style enums (all unit
/// variants) render as native `enum` declarations and ride the CLR's
/// transparent int-marshaling; data enums render as `abstract record`
/// hierarchies and travel wire-encoded.
#[derive(Debug, Clone)]
pub struct CSharpEnum {
    /// PascalCase class name (e.g., `"Shape"`, `"Status"`).
    pub class_name: String,
    /// Whether this is a C-style or data enum. Drives the rendering shape.
    pub kind: CSharpEnumKind,
    /// For C-style enums, the declared integral repr primitive. `None` for
    /// data enums, whose public surface is always a reference type and whose
    /// wire tag stays an implementation detail of the codec.
    pub c_style_tag_type: Option<PrimitiveType>,
    /// Variants, in declaration order. The wire tag is the variant's index
    /// in this list (per `EnumTagStrategy::OrdinalIndex`), so order is
    /// load-bearing.
    pub variants: Vec<CSharpEnumVariant>,
    /// Methods and factory constructors declared via `#[data(impl)]`. For
    /// C-style enums these render as a companion `{Name}Methods` static
    /// class; for data enums they go directly on the abstract record.
    /// The Rust IR separates constructors from methods, but at the C#
    /// call site they're both just static or instance methods, merged
    /// into one list here.
    pub methods: Vec<CSharpMethod>,
}

/// The two flavors the enum renderer knows how to produce. The `#[repr]`
/// type could inform the C# backing type of a C-style enum, but for now
/// we always use `int`, which matches the i32 wire tag and keeps the DllImport
/// signatures uniform with the free-function enum param/return shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CSharpEnumKind {
    /// Every variant is a unit variant. Renders as `public enum Name : int`
    /// plus a `NameWire` static helper class with `Decode` and a
    /// `WireEncodeTo` extension method for when the enum embeds inside a
    /// wire-encoded record.
    CStyle,
    /// At least one variant carries fields. Renders as
    /// `public abstract record Name` with nested `sealed record` variants
    /// and switch-expression wire codec.
    Data,
}

/// One variant of a [`CSharpEnum`]. For C-style enums, `fields` is always
/// empty; for data enums, a unit variant also has empty `fields` (and
/// renders as `sealed record Name() : Enum`).
#[derive(Debug, Clone)]
pub struct CSharpEnumVariant {
    /// PascalCase variant name (e.g., `"Circle"`, `"Active"`).
    pub name: String,
    /// Numeric value rendered in the *public* surface. For C-style enums
    /// this is the Rust discriminant (`HttpCode.NotFound = 404`), so
    /// client code reading or comparing the enum sees real values, not
    /// ordinals. For data-enum variants this equals `wire_tag`; their
    /// public surface is a `sealed record`, not a numbered enum member,
    /// and only the codec uses the value.
    pub tag: i32,
    /// Ordinal index on the wire (0, 1, 2…), matching
    /// `EnumTagStrategy::OrdinalIndex`. Every boltffi backend wire-encodes
    /// C-style and data enums alike as a 4-byte little-endian `i32` of
    /// this tag, so C# must too, even for enums whose public `tag`
    /// diverges from their declaration order (gapped or negative
    /// discriminants). Keeping `wire_tag` separate from `tag` makes the
    /// two concepts explicit instead of hoping they'll always match.
    pub wire_tag: i32,
    /// Variant fields. Empty for unit variants and for every C-style
    /// variant. Reuses [`CSharpRecordField`] because variant payloads are
    /// structurally identical to record fields: same name, type, and
    /// pre-rendered wire expressions.
    pub fields: Vec<CSharpRecordField>,
}

impl CSharpEnum {
    pub fn is_c_style(&self) -> bool {
        self.kind == CSharpEnumKind::CStyle
    }

    pub fn is_data(&self) -> bool {
        self.kind == CSharpEnumKind::Data
    }

    pub fn has_methods(&self) -> bool {
        !self.methods.is_empty()
    }

    fn c_style_tag_type(&self) -> PrimitiveType {
        self.c_style_tag_type
            .expect("c-style enum helpers only apply to C-style enums")
    }

    /// The C# enum backing type keyword (`byte`, `short`, `int`, `long`,
    /// etc.). C# does not permit `nint` / `nuint` enum base types, so those
    /// reprs are filtered out before a plan is ever constructed.
    pub fn c_style_backing_type(&self) -> &'static str {
        match self.c_style_tag_type() {
            PrimitiveType::I8 => "sbyte",
            PrimitiveType::U8 => "byte",
            PrimitiveType::I16 => "short",
            PrimitiveType::U16 => "ushort",
            PrimitiveType::I32 => "int",
            PrimitiveType::U32 => "uint",
            PrimitiveType::I64 => "long",
            PrimitiveType::U64 => "ulong",
            PrimitiveType::Bool
            | PrimitiveType::ISize
            | PrimitiveType::USize
            | PrimitiveType::F32
            | PrimitiveType::F64 => panic!("unsupported C# enum backing type"),
        }
    }

    /// Whether any variant payload field's type contains a string at any
    /// nesting depth. Drives the `using System.Text;` import in the data
    /// enum template, needed because string-valued wire-size expressions
    /// call `Encoding.UTF8.GetByteCount(...)`, which lives in
    /// `System.Text`.
    pub fn has_string_fields(&self) -> bool {
        self.variants
            .iter()
            .flat_map(|v| v.fields.iter())
            .any(|f| f.csharp_type.contains_string())
    }
}

impl CSharpEnumVariant {
    /// Whether this variant carries no payload. True for every C-style
    /// variant, and for data enum "unit" variants like `Shape::Point`.
    pub fn is_unit(&self) -> bool {
        self.fields.is_empty()
    }
}

/// A method or factory constructor on a value type, today always an
/// enum, eventually also records. Renders as a static method, a C#
/// extension method (for C-style enum instance methods, since C# enums
/// can't have members), or a native instance method on the owning type.
/// The dispatch is driven by [`CSharpReceiver`].
#[derive(Debug, Clone)]
pub struct CSharpMethod {
    /// PascalCase method name as it appears on the owning type's public
    /// API (e.g., `"Opposite"`, `"UnitCircle"`).
    pub name: String,
    /// Name used for this method's DllImport entry inside the shared
    /// `NativeMethods` class. Prefixed with the owning class name (e.g.,
    /// `"DirectionOpposite"`, `"ShapeArea"`) because two types may
    /// declare methods of the same name, and the DllImport class is
    /// flat.
    pub native_method_name: String,
    /// The C FFI symbol implementing this method (e.g.,
    /// `"boltffi_direction_opposite"`).
    pub ffi_name: String,
    /// How `self` (if any) participates in the call.
    pub receiver: CSharpReceiver,
    /// Explicit params. Does not include `self` for instance methods.
    pub params: Vec<CSharpParam>,
    /// C# return type of the public-facing method.
    pub return_type: CSharpType,
    /// How the return value crosses the ABI.
    pub return_kind: CSharpReturnKind,
    /// For each non-blittable record/data-enum param, the setup block
    /// that wire-encodes it into a `byte[]` before the native call.
    pub wire_writers: Vec<CSharpWireWriter>,
}

/// How a method's receiver (`self`) participates in the rendered C#.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CSharpReceiver {
    /// Static method, no `self`. Lives on whichever container the
    /// owning type uses: a companion `{Name}Methods` class for C-style
    /// enums, the abstract record for data enums, the record struct for
    /// records. Renders as `public static {ReturnType} {Name}({params})`.
    Static,
    /// Instance method on a C-style enum. Renders as a C# *extension*
    /// method `public static {ReturnType} {Name}(this {EnumType} self,
    /// {params})` in the companion class, giving `d.Name(args)` call
    /// syntax without requiring members on the enum itself. `self`
    /// passes directly to the DllImport since the CLR marshals the enum
    /// as its declared backing integral type.
    InstanceExtension,
    /// Instance method on a type that can hold its own members: data
    /// enums (on the abstract record) and records. Renders as a native
    /// method: `public {ReturnType} {Name}({params})`. When the owning
    /// type is wire-encoded (data enums, non-blittable records), the
    /// body wire-encodes `this` into a `byte[]` before the native call;
    /// blittable records pass `this` by value through P/Invoke.
    InstanceNative,
}

impl CSharpReceiver {
    pub fn is_static(&self) -> bool {
        matches!(self, Self::Static)
    }

    pub fn is_instance_extension(&self) -> bool {
        matches!(self, Self::InstanceExtension)
    }

    pub fn is_instance_native(&self) -> bool {
        matches!(self, Self::InstanceNative)
    }
}

impl CSharpMethod {
    pub fn is_void(&self) -> bool {
        matches!(self.return_kind, CSharpReturnKind::Void)
    }

    /// Comma-joined param declarations for the method signature.
    /// Excludes `self`, which the template handles separately based on
    /// the receiver kind.
    pub fn wrapper_param_list(&self) -> String {
        self.params
            .iter()
            .map(CSharpParam::wrapper_declaration)
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Comma-joined call arguments for the native DllImport invocation,
    /// excluding `self`. Matches [`CSharpFunction::native_call_args`].
    pub fn native_call_args(&self) -> String {
        self.params
            .iter()
            .map(CSharpParam::native_call_arg)
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// The return type used in the DllImport signature. Wire-decoded
    /// returns (strings, non-blittable records, data enums) come back
    /// as an `FfiBuf`; everything else uses the C# type directly.
    pub fn native_return_type(&self) -> String {
        if self.return_kind.native_returns_ffi_buf() {
            "FfiBuf".to_string()
        } else {
            self.return_type.to_string()
        }
    }

    /// Declarations for nested `fixed` statements pinning every
    /// [`CSharpParamKind::PinnedArray`] param in the signature.
    pub fn pinned_fixed_args(&self) -> Vec<String> {
        pinned_fixed_args(&self.params)
    }

    pub fn has_pinned_params(&self) -> bool {
        !self.pinned_fixed_args().is_empty()
    }

    /// Param list used in the DllImport signature, including the
    /// receiver-dependent self declaration prepended when the method is
    /// an instance method:
    /// - `InstanceExtension`: prepends `{OwnerClass} self`, relying on
    ///   the CLR to marshal the enum as its declared backing integral type.
    /// - `InstanceNative`: prepends `byte[] self, UIntPtr selfLen` for
    ///   wire-encoded `this`; passes `{OwnerClass} self` for blittable
    ///   types.
    /// - `Static`: no self declaration.
    ///
    /// `owner_is_blittable` distinguishes the two `InstanceNative` sub-
    /// cases. For wire-encoded owners it's `false`; for blittable
    /// records it will be `true` once record instance methods land.
    pub fn native_param_list(&self, owner_class_name: &str, owner_is_blittable: bool) -> String {
        let explicit: Vec<String> = self
            .params
            .iter()
            .map(CSharpParam::native_declaration)
            .collect();
        let self_decl: Option<String> = match self.receiver {
            CSharpReceiver::Static => None,
            CSharpReceiver::InstanceExtension => Some(format!("{} self", owner_class_name)),
            CSharpReceiver::InstanceNative if owner_is_blittable => {
                Some(format!("{} self", owner_class_name))
            }
            CSharpReceiver::InstanceNative => Some("byte[] self, UIntPtr selfLen".to_string()),
        };
        match self_decl {
            Some(d) => std::iter::once(d)
                .chain(explicit)
                .collect::<Vec<_>>()
                .join(", "),
            None => explicit.join(", "),
        }
    }

    /// Comma-joined call arguments *including* the receiver's
    /// self-argument where the receiver needs one. Extension methods
    /// prepend the bound `self` local; data-enum instance methods
    /// prepend the pre-encoded `_selfBytes, (UIntPtr)_selfBytes.Length`
    /// pair that the surrounding method body set up.
    pub fn full_native_call_args(&self) -> String {
        let explicit = self.native_call_args();
        let self_prefix: &str = match self.receiver {
            CSharpReceiver::Static => "",
            CSharpReceiver::InstanceExtension => "self",
            CSharpReceiver::InstanceNative => "_selfBytes, (UIntPtr)_selfBytes.Length",
        };
        match (self_prefix.is_empty(), explicit.is_empty()) {
            (true, _) => explicit,
            (false, true) => self_prefix.to_string(),
            (false, false) => format!("{self_prefix}, {explicit}"),
        }
    }
}

/// A primitive function binding. Serves double duty: the template uses `name`
/// and C# types for the public static method, and `ffi_name` for the
/// `[DllImport]` entry point.
#[derive(Debug, Clone)]
pub struct CSharpFunction {
    /// PascalCase method name (e.g., `"EchoI32"`).
    pub name: String,
    /// Parameters with C# types.
    pub params: Vec<CSharpParam>,
    /// C# return type as it appears in the public wrapper signature.
    pub return_type: CSharpType,
    /// How the return value crosses the ABI. Drives how the wrapper body
    /// decodes the native return and what the `[DllImport]` signature looks
    /// like.
    pub return_kind: CSharpReturnKind,
    /// The C symbol name (e.g., `"boltffi_echo_i32"`).
    pub ffi_name: String,
    /// For each non-blittable record param, the setup code that wire-encodes
    /// it into a `byte[]` before the native call. Empty if the function has
    /// no wire-encoded params (blittable record params count as direct and
    /// do not appear here).
    pub wire_writers: Vec<CSharpWireWriter>,
}

impl CSharpFunction {
    pub fn is_void(&self) -> bool {
        matches!(self.return_kind, CSharpReturnKind::Void)
    }

    /// Comma-joined param declarations as they appear in the public
    /// wrapper signature.
    pub fn wrapper_param_list(&self) -> String {
        self.params
            .iter()
            .map(CSharpParam::wrapper_declaration)
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Comma-joined param declarations as they appear in the
    /// `[DllImport]` native signature.
    pub fn native_param_list(&self) -> String {
        self.params
            .iter()
            .map(CSharpParam::native_declaration)
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Comma-joined call arguments handed to the native invocation.
    pub fn native_call_args(&self) -> String {
        self.params
            .iter()
            .map(CSharpParam::native_call_arg)
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// The return type used in the `[DllImport]` signature. Wire-encoded
    /// returns come back as an `FfiBuf`; everything else (primitives,
    /// bools, blittable records) uses the C# type directly.
    pub fn native_return_type(&self) -> String {
        if self.return_kind.native_returns_ffi_buf() {
            "FfiBuf".to_string()
        } else {
            self.return_type.to_string()
        }
    }

    /// Declarations for nested `fixed` statements pinning every
    /// [`CSharpParamKind::PinnedArray`] param in the signature.
    ///
    /// Rendered shape for a function with two pinned params:
    ///
    /// ```ignore
    /// [
    ///   "Location* _locationsPtr = locations",
    ///   "Trade* _tradesPtr = trades",
    /// ]
    /// ```
    ///
    /// The template wraps the call in `unsafe { fixed (...) { fixed (...)
    /// { ... } } }` so Rust reads directly from the C# heap without the
    /// GC relocating either managed array during the call.
    pub fn pinned_fixed_args(&self) -> Vec<String> {
        pinned_fixed_args(&self.params)
    }

    pub fn has_pinned_params(&self) -> bool {
        !self.pinned_fixed_args().is_empty()
    }
}

/// How a function's return value is delivered across the ABI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CSharpReturnKind {
    /// No return value.
    Void,
    /// Returned directly. Primitives, bools, and blittable records all
    /// share this path. The CLR already knows how to marshal them.
    Direct,
    /// The native function returns an `FfiBuf`. The wrapper copies the
    /// bytes into a managed `string` via `WireReader.ReadString` and
    /// frees the buffer.
    WireDecodeString,
    /// The native function returns an `FfiBuf` carrying a wire-encoded
    /// value with a static `Decode(WireReader)` method. The wrapper wraps
    /// it in a `WireReader` and calls `{class_name}.Decode(reader)` to
    /// reconstruct the value. Used for non-blittable records and data
    /// enums, whose rendered C# types both expose the same `Decode` API
    /// at the call site.
    WireDecodeObject { class_name: String },
    /// The native function returns an `FfiBuf` carrying a wire-encoded
    /// `Vec<T>`. The wrapper wraps it in a `WireReader` and invokes
    /// `reader_call` on the reader to reconstruct the managed `T[]`.
    /// `reader_call` is the full method invocation without the receiver,
    /// e.g. `ReadBlittableArray<int>()` for `Vec<i32>` or
    /// `ReadBoolArray()` for `Vec<bool>`.
    WireDecodeArray { reader_call: String },
    /// The native function returns an `FfiBuf` carrying a wire-encoded
    /// `Option<T>` (1-byte tag + optional payload). The wrapper wraps
    /// it in a `WireReader` named `reader` and evaluates `decode_expr`,
    /// which emit has already rendered against that reader so it
    /// handles every inner shape (primitive, string, record, enum, vec)
    /// without per-shape branching here.
    WireDecodeOption { decode_expr: String },
}

impl CSharpReturnKind {
    pub fn is_void(&self) -> bool {
        matches!(self, Self::Void)
    }

    pub fn is_direct(&self) -> bool {
        matches!(self, Self::Direct)
    }

    pub fn is_wire_decode_string(&self) -> bool {
        matches!(self, Self::WireDecodeString)
    }

    pub fn is_wire_decode_object(&self) -> bool {
        matches!(self, Self::WireDecodeObject { .. })
    }

    pub fn is_wire_decode_array(&self) -> bool {
        matches!(self, Self::WireDecodeArray { .. })
    }

    pub fn is_wire_decode_option(&self) -> bool {
        matches!(self, Self::WireDecodeOption { .. })
    }

    /// Whether the native (DllImport) signature returns an `FfiBuf`.
    pub fn native_returns_ffi_buf(&self) -> bool {
        matches!(
            self,
            Self::WireDecodeString
                | Self::WireDecodeObject { .. }
                | Self::WireDecodeArray { .. }
                | Self::WireDecodeOption { .. }
        )
    }

    /// For `WireDecodeObject`, the decoded C# class name (e.g., `"Point"`
    /// for a record, `"Shape"` for a data enum); `None` for every other
    /// kind. Templates use this to emit `{class_name}.Decode`.
    pub fn decode_class_name(&self) -> Option<&str> {
        match self {
            Self::WireDecodeObject { class_name } => Some(class_name),
            _ => None,
        }
    }

    /// The `return` statement that goes inside the `try` block of a
    /// wire-decoded call body. `buf_var` is the local name holding the
    /// `FfiBuf` from the native call. Returns `None` for non-wire-decoded
    /// kinds so callers cannot misuse an empty-string fallback as valid
    /// generated code.
    pub fn wire_decode_return(&self, buf_var: &str) -> Option<String> {
        match self {
            Self::WireDecodeString => {
                Some(format!("return new WireReader({}).ReadString();", buf_var))
            }
            Self::WireDecodeObject { class_name } => Some(format!(
                "return {}.Decode(new WireReader({}));",
                class_name, buf_var
            )),
            Self::WireDecodeArray { reader_call } => Some(format!(
                "return new WireReader({}).{};",
                buf_var, reader_call
            )),
            Self::WireDecodeOption { decode_expr } => Some(format!(
                "var reader = new WireReader({}); return {};",
                buf_var, decode_expr
            )),
            _ => None,
        }
    }
}

/// A parameter in a C# function.
#[derive(Debug, Clone)]
pub struct CSharpParam {
    /// camelCase parameter name, keyword-escaped with `@` if needed.
    pub name: String,
    /// C# type as it appears in the public wrapper signature.
    pub csharp_type: CSharpType,
    /// How the parameter crosses the ABI.
    pub kind: CSharpParamKind,
}

impl CSharpParam {
    /// Declaration as it appears in the public wrapper signature,
    /// e.g. `"int value"`, `"string v"`, `"Point point"`.
    pub fn wrapper_declaration(&self) -> String {
        format!("{} {}", self.csharp_type, self.name)
    }

    /// Declaration as it appears in the `[DllImport]` signature. This
    /// is where the different marshalling paths diverge:
    /// - Primitives and blittable records pass through directly.
    /// - Bool needs the `[MarshalAs(UnmanagedType.I1)]` attribute
    ///   because P/Invoke defaults to the 4-byte Win32 BOOL.
    /// - Strings and wire-encoded records are split into
    ///   `(byte[] x, UIntPtr xLen)`.
    pub fn native_declaration(&self) -> String {
        match &self.kind {
            CSharpParamKind::Utf8Bytes | CSharpParamKind::WireEncoded { .. } => {
                format!("byte[] {name}, UIntPtr {name}Len", name = self.name)
            }
            CSharpParamKind::Direct if self.csharp_type.is_bool() => {
                format!("[MarshalAs(UnmanagedType.I1)] bool {}", self.name)
            }
            CSharpParamKind::Direct => {
                format!("{} {}", self.csharp_type, self.name)
            }
            CSharpParamKind::DirectArray => {
                let element = self
                    .csharp_type
                    .array_element()
                    .expect("DirectArray param must carry an Array type");
                let decl = format!("{element}[] {name}, UIntPtr {name}Len", name = self.name);
                if matches!(element, CSharpType::Bool) {
                    format!(
                        "[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1)] {decl}"
                    )
                } else {
                    decl
                }
            }
            // The wrapper's `fixed` block takes the managed array and
            // hands the native side a raw pointer, so the DllImport sees
            // only `IntPtr` and a length. No element type, no P/Invoke
            // marshaling.
            CSharpParamKind::PinnedArray { .. } => {
                format!("IntPtr {name}, UIntPtr {name}Len", name = self.name)
            }
        }
    }

    /// The argument expression to hand to the native call: either the
    /// raw param, or the pre-encoded byte array plus its length.
    pub fn native_call_arg(&self) -> String {
        match &self.kind {
            CSharpParamKind::Direct => self.name.clone(),
            CSharpParamKind::Utf8Bytes => {
                let buf = format!("_{}Bytes", self.name);
                format!("{buf}, (UIntPtr){buf}.Length")
            }
            CSharpParamKind::WireEncoded { binding_name } => {
                format!("{binding_name}, (UIntPtr){binding_name}.Length")
            }
            CSharpParamKind::DirectArray => {
                format!("{name}, (UIntPtr){name}.Length", name = self.name)
            }
            // `_{name}Ptr` is the pointer local introduced by the
            // enclosing `fixed` statement; see `pinned_fixed_args`. The
            // cast to `IntPtr` matches the DllImport signature.
            //
            // The Rust FFI shim for `Vec<Passable>` takes a raw byte
            // length and divides by `size_of::<T>()` to recover the
            // element count, the opposite of `Vec<Primitive>`, which
            // takes element count directly. The primitive path and this
            // path therefore send different numbers across the same
            // `UIntPtr` slot. `Unsafe.SizeOf<T>()` is a JIT-time constant
            // for `unmanaged` struct types, so the multiply folds away.
            CSharpParamKind::PinnedArray { element_type } => {
                let ptr_name = self
                    .pinned_ptr_name()
                    .expect("PinnedArray params must have a pointer local");
                format!(
                    "(IntPtr){ptr_name}, (UIntPtr)({name}.Length * Unsafe.SizeOf<{element_type}>())",
                    ptr_name = ptr_name,
                    name = self.name,
                )
            }
        }
    }

    /// The one-line setup statement that prepares this param before the
    /// native call, or `None` when the param passes through directly.
    /// UTF-8 encoding is the only inline setup; record wire encoding
    /// needs a `using` block and is handled separately via
    /// [`CSharpFunction::wire_writers`].
    pub fn setup_statement(&self) -> Option<String> {
        match &self.kind {
            CSharpParamKind::Utf8Bytes => Some(format!(
                "byte[] _{name}Bytes = Encoding.UTF8.GetBytes({name});",
                name = self.name
            )),
            _ => None,
        }
    }

    pub fn pinned_fixed_arg(&self) -> Option<String> {
        match &self.kind {
            CSharpParamKind::PinnedArray { element_type } => Some(format!(
                "{element_type}* {ptr_name} = {name}",
                ptr_name = self
                    .pinned_ptr_name()
                    .expect("PinnedArray params must have a pointer local"),
                name = self.name,
            )),
            _ => None,
        }
    }

    fn pinned_ptr_name(&self) -> Option<String> {
        match self.kind {
            CSharpParamKind::PinnedArray { .. } => {
                let base_name = self.name.strip_prefix('@').unwrap_or(&self.name);
                Some(format!("_{base_name}Ptr"))
            }
            _ => None,
        }
    }
}

fn pinned_fixed_args(params: &[CSharpParam]) -> Vec<String> {
    params
        .iter()
        .filter_map(CSharpParam::pinned_fixed_arg)
        .collect()
}

/// How a parameter is marshalled across the C# / C ABI boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CSharpParamKind {
    /// Passed directly as a primitive (bool, int, double, etc.).
    Direct,
    /// A managed `string` that must be UTF-8 encoded into a `byte[]`
    /// and passed as `(byte[], UIntPtr)` to the native call.
    Utf8Bytes,
    /// A record that must be wire-encoded into a `byte[]` by a
    /// `WireWriter` and passed as `(byte[], UIntPtr)`. `binding_name`
    /// is the local variable holding the encoded byte array.
    WireEncoded { binding_name: String },
    /// A managed array of a blittable primitive element type, passed
    /// directly as `(T[], UIntPtr)` without any wire encoding. The CLR's
    /// default P/Invoke marshaller pins the array and hands the native
    /// side a pointer to the element buffer. `bool[]` gets an explicit
    /// `[MarshalAs(LPArray, ArraySubType = U1)]` override so CLR emits
    /// one byte per element instead of the 4-byte Win32 BOOL default.
    DirectArray,
    /// A managed array of a blittable record element type, pinned with
    /// a `fixed` statement so Rust can read directly from the C# heap.
    ///
    /// The struct layout of a blittable record matches Rust's `#[repr(C)]`
    /// exactly, so a pointer to the first element plus an element count
    /// is everything Rust needs. Primitive arrays can use the CLR's
    /// built-in direct-array path, but record arrays are trickier once
    /// the element type stops being blittable to the marshaller (for
    /// example because it contains `bool` or `char`): P/Invoke may
    /// marshal through a temporary native buffer instead of exposing the
    /// managed array in place. With the right field-level marshalling
    /// that copy can still be layout-compatible, but it is no longer the
    /// zero-copy contract this fast path wants. The wrapper sidesteps the
    /// marshaller entirely by taking a raw pointer with `fixed (T* _xPtr
    /// = x)`, which pins the array in place for the duration of the
    /// native call and passes the pointer as `IntPtr`. C# and Rust then
    /// read the same block of managed heap memory.
    ///
    /// `element_type` is the C# type literal for `T` (e.g., `"Location"`),
    /// threaded here so `pinned_fixed_args` can render
    /// `Location* _xPtr = x` without re-deriving from `csharp_type`.
    PinnedArray { element_type: String },
}

/// Bookkeeping for a single record param that must be wire-encoded into a
/// `byte[]` before the native call. The template wraps these setup lines
/// in a `using` block so each `WireWriter` is disposed (and its rented
/// buffer recycled) even if the native call throws.
#[derive(Debug, Clone)]
pub struct CSharpWireWriter {
    /// The `_wire_foo` local name for the `WireWriter` instance.
    pub binding_name: String,
    /// The `_fooBytes` local name for the resulting `byte[]`.
    pub bytes_binding_name: String,
    /// The original (camelCase) param name, used to find the corresponding
    /// `CSharpParam` at render time.
    pub param_name: String,
    /// Expression rendered against the param that returns its wire-encoded
    /// byte size (e.g., `"point.WireEncodedSize()"`).
    pub size_expr: String,
    /// Statement that writes the param's contents into the `WireWriter`
    /// named by `binding_name` (e.g., `"point.WireEncodeTo(_wire_point)"`).
    pub encode_expr: String,
}

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

    fn function_with_return(
        return_type: CSharpType,
        return_kind: CSharpReturnKind,
    ) -> CSharpFunction {
        CSharpFunction {
            name: "Test".to_string(),
            params: vec![],
            return_type,
            return_kind,
            ffi_name: "boltffi_test".to_string(),
            wire_writers: vec![],
        }
    }

    fn param(name: &str, csharp_type: CSharpType, kind: CSharpParamKind) -> CSharpParam {
        CSharpParam {
            name: name.to_string(),
            csharp_type,
            kind,
        }
    }

    #[rstest]
    #[case::void(CSharpType::Void, CSharpReturnKind::Void, true)]
    #[case::int(CSharpType::Int, CSharpReturnKind::Direct, false)]
    #[case::bool(CSharpType::Bool, CSharpReturnKind::Direct, false)]
    #[case::double(CSharpType::Double, CSharpReturnKind::Direct, false)]
    fn is_void(
        #[case] return_type: CSharpType,
        #[case] return_kind: CSharpReturnKind,
        #[case] expected: bool,
    ) {
        assert_eq!(
            function_with_return(return_type, return_kind).is_void(),
            expected
        );
    }

    #[test]
    fn record_type_display_uses_class_name() {
        let ty = CSharpType::Record("Point".to_string());
        assert_eq!(ty.to_string(), "Point");
        assert!(ty.is_record());
    }

    #[test]
    fn c_style_enum_type_display_uses_class_name() {
        let ty = CSharpType::CStyleEnum("Status".to_string());
        assert_eq!(ty.to_string(), "Status");
        assert!(ty.is_c_style_enum());
        assert!(!ty.is_data_enum());
    }

    #[test]
    fn data_enum_type_display_uses_class_name() {
        let ty = CSharpType::DataEnum("Shape".to_string());
        assert_eq!(ty.to_string(), "Shape");
        assert!(ty.is_data_enum());
        assert!(!ty.is_c_style_enum());
    }

    /// A variant with no payload fields is a unit: true for every C-style
    /// variant and for data-enum unit variants like `Shape::Point`.
    #[test]
    fn variant_with_empty_fields_is_unit() {
        let variant = CSharpEnumVariant {
            name: "Active".to_string(),
            tag: 0,
            wire_tag: 0,
            fields: vec![],
        };
        assert!(variant.is_unit());
    }

    /// A variant with at least one payload field is not a unit. The
    /// renderer emits a positional `sealed record Foo(double Radius)`
    /// rather than the empty-paren `sealed record Foo()` shape.
    #[test]
    fn variant_with_payload_is_not_unit() {
        let variant = CSharpEnumVariant {
            name: "Circle".to_string(),
            tag: 0,
            wire_tag: 0,
            fields: vec![CSharpRecordField {
                name: "Radius".to_string(),
                csharp_type: CSharpType::Double,
                wire_decode_expr: "reader.ReadF64()".to_string(),
                wire_size_expr: "8".to_string(),
                wire_encode_expr: "wire.WriteF64(this.Radius)".to_string(),
            }],
        };
        assert!(!variant.is_unit());
    }

    #[test]
    fn c_style_kind_is_c_style_and_not_data() {
        let enumeration = CSharpEnum {
            class_name: "Status".to_string(),
            kind: CSharpEnumKind::CStyle,
            c_style_tag_type: Some(PrimitiveType::I32),
            variants: vec![],
            methods: vec![],
        };
        assert!(enumeration.is_c_style());
        assert!(!enumeration.is_data());
    }

    #[test]
    fn data_kind_is_data_and_not_c_style() {
        let enumeration = CSharpEnum {
            class_name: "Shape".to_string(),
            kind: CSharpEnumKind::Data,
            c_style_tag_type: None,
            variants: vec![],
            methods: vec![],
        };
        assert!(enumeration.is_data());
        assert!(!enumeration.is_c_style());
    }

    /// `c_style_backing_type` drives only the public enum declaration
    /// (`public enum LogLevel : byte`). The wire codec is width-fixed at
    /// 4 bytes across every boltffi backend, so there is no per-backing-
    /// type read/write method to resolve: the template hardcodes
    /// `ReadI32`/`WriteI32` around an ordinal-tag switch.
    #[test]
    fn c_style_backing_type_maps_primitive_to_csharp_keyword() {
        let enumeration = CSharpEnum {
            class_name: "LogLevel".to_string(),
            kind: CSharpEnumKind::CStyle,
            c_style_tag_type: Some(PrimitiveType::U8),
            variants: vec![],
            methods: vec![],
        };

        assert_eq!(enumeration.c_style_backing_type(), "byte");
    }

    /// C-style enums ride P/Invoke as their declared backing integral type,
    /// so they count as blittable leaves alongside the numeric primitives.
    /// Data enums never do: their payloads are variable-width and must
    /// wire-encode.
    #[rstest]
    #[case::int(CSharpType::Int, true)]
    #[case::double(CSharpType::Double, true)]
    #[case::cstyle_enum(CSharpType::CStyleEnum("Status".to_string()), true)]
    #[case::bool(CSharpType::Bool, false)]
    #[case::string(CSharpType::String, false)]
    #[case::record(CSharpType::Record("Point".to_string()), false)]
    #[case::data_enum(CSharpType::DataEnum("Shape".to_string()), false)]
    #[case::nullable_int(CSharpType::Nullable(Box::new(CSharpType::Int)), false)]
    #[case::nullable_string(CSharpType::Nullable(Box::new(CSharpType::String)), false)]
    fn is_blittable_leaf_matches_marshaling_story(#[case] ty: CSharpType, #[case] expected: bool) {
        assert_eq!(ty.is_blittable_leaf(), expected);
    }

    /// `Nullable` renders as `{inner}?`, uniform for value-type inners
    /// (which desugar to `Nullable<T>`) and reference-type inners (which
    /// read as nullable-annotated references under `#nullable enable`).
    #[test]
    fn nullable_type_display_appends_question_mark() {
        assert_eq!(
            CSharpType::Nullable(Box::new(CSharpType::Int)).to_string(),
            "int?"
        );
        assert_eq!(
            CSharpType::Nullable(Box::new(CSharpType::String)).to_string(),
            "string?"
        );
        assert_eq!(
            CSharpType::Nullable(Box::new(CSharpType::Record("Point".to_string()))).to_string(),
            "Point?"
        );
    }

    /// `contains_string` must see through `Nullable` so a `string?` field
    /// still triggers the `System.Text` import: the wire-size expression
    /// for a nullable string still calls `Encoding.UTF8.GetByteCount`.
    #[test]
    fn contains_string_sees_through_nullable() {
        assert!(CSharpType::Nullable(Box::new(CSharpType::String)).contains_string());
        assert!(
            CSharpType::Array(Box::new(CSharpType::Nullable(Box::new(CSharpType::String))))
                .contains_string()
        );
        assert!(!CSharpType::Nullable(Box::new(CSharpType::Int)).contains_string());
    }

    // ----- CSharpParam render helpers -----

    #[test]
    fn wrapper_declaration_puts_type_before_name() {
        let p = param("value", CSharpType::Int, CSharpParamKind::Direct);
        assert_eq!(p.wrapper_declaration(), "int value");
    }

    #[test]
    fn wrapper_declaration_uses_record_class_name() {
        let p = param(
            "point",
            CSharpType::Record("Point".to_string()),
            CSharpParamKind::Direct,
        );
        assert_eq!(p.wrapper_declaration(), "Point point");
    }

    /// Direct primitives pass through the native declaration unchanged.
    #[test]
    fn native_declaration_direct_primitive_matches_wrapper() {
        let p = param("value", CSharpType::Int, CSharpParamKind::Direct);
        assert_eq!(p.native_declaration(), "int value");
    }

    /// P/Invoke marshals `bool` as a 4-byte Win32 BOOL by default, but the
    /// C ABI uses a 1-byte native bool, so the `DllImport` signature must
    /// force `UnmanagedType.I1`. The public wrapper side stays plain.
    #[test]
    fn native_declaration_bool_gets_marshal_attribute() {
        let p = param("flag", CSharpType::Bool, CSharpParamKind::Direct);
        assert_eq!(
            p.native_declaration(),
            "[MarshalAs(UnmanagedType.I1)] bool flag"
        );
    }

    /// Blittable record params use `Direct` kind and pass by value, so the
    /// native declaration is just the struct name, no byte[] split.
    #[test]
    fn native_declaration_blittable_record_passes_by_value() {
        let p = param(
            "point",
            CSharpType::Record("Point".to_string()),
            CSharpParamKind::Direct,
        );
        assert_eq!(p.native_declaration(), "Point point");
    }

    /// String params split into two arguments to match the C ABI
    /// `(const uint8_t* ptr, uintptr_t len)`.
    #[test]
    fn native_declaration_string_splits_into_bytes_and_length() {
        let p = param("v", CSharpType::String, CSharpParamKind::Utf8Bytes);
        assert_eq!(p.native_declaration(), "byte[] v, UIntPtr vLen");
    }

    /// Wire-encoded record params use the same `byte[] + UIntPtr` split
    /// as strings because the C ABI signature is identical.
    #[test]
    fn native_declaration_wire_encoded_record_splits_into_bytes_and_length() {
        let p = param(
            "person",
            CSharpType::Record("Person".to_string()),
            CSharpParamKind::WireEncoded {
                binding_name: "_personBytes".to_string(),
            },
        );
        assert_eq!(p.native_declaration(), "byte[] person, UIntPtr personLen");
    }

    #[test]
    fn native_call_arg_direct_passes_name() {
        let p = param("value", CSharpType::Int, CSharpParamKind::Direct);
        assert_eq!(p.native_call_arg(), "value");
    }

    #[test]
    fn native_call_arg_utf8_bytes_passes_buffer_and_length() {
        let p = param("v", CSharpType::String, CSharpParamKind::Utf8Bytes);
        assert_eq!(p.native_call_arg(), "_vBytes, (UIntPtr)_vBytes.Length");
    }

    #[test]
    fn native_call_arg_wire_encoded_uses_binding_name() {
        let p = param(
            "person",
            CSharpType::Record("Person".to_string()),
            CSharpParamKind::WireEncoded {
                binding_name: "_personBytes".to_string(),
            },
        );
        assert_eq!(
            p.native_call_arg(),
            "_personBytes, (UIntPtr)_personBytes.Length"
        );
    }

    /// Only UTF-8 string params have an inline setup statement. Direct
    /// params need no prep; wire-encoded records use a `using` block
    /// that is emitted around the call, not as a flat setup line.
    #[rstest]
    #[case::direct(CSharpParamKind::Direct, None)]
    #[case::wire_encoded(
        CSharpParamKind::WireEncoded { binding_name: "_personBytes".to_string() },
        None,
    )]
    fn setup_statement_non_string_has_none(
        #[case] kind: CSharpParamKind,
        #[case] expected: Option<&str>,
    ) {
        let p = param("x", CSharpType::Int, kind);
        assert_eq!(p.setup_statement().as_deref(), expected);
    }

    #[test]
    fn setup_statement_utf8_bytes_encodes_string() {
        let p = param("v", CSharpType::String, CSharpParamKind::Utf8Bytes);
        assert_eq!(
            p.setup_statement().as_deref(),
            Some("byte[] _vBytes = Encoding.UTF8.GetBytes(v);"),
        );
    }

    // ----- CSharpFunction render helpers -----

    fn function_with_params(
        params: Vec<CSharpParam>,
        return_type: CSharpType,
        return_kind: CSharpReturnKind,
    ) -> CSharpFunction {
        CSharpFunction {
            name: "Test".to_string(),
            params,
            return_type,
            return_kind,
            ffi_name: "boltffi_test".to_string(),
            wire_writers: vec![],
        }
    }

    #[test]
    fn wrapper_param_list_joins_with_comma_space() {
        let f = function_with_params(
            vec![
                param("a", CSharpType::Int, CSharpParamKind::Direct),
                param("b", CSharpType::String, CSharpParamKind::Utf8Bytes),
            ],
            CSharpType::Void,
            CSharpReturnKind::Void,
        );
        assert_eq!(f.wrapper_param_list(), "int a, string b");
    }

    #[test]
    fn wrapper_param_list_empty_for_no_params() {
        let f = function_with_params(vec![], CSharpType::Void, CSharpReturnKind::Void);
        assert_eq!(f.wrapper_param_list(), "");
    }

    /// The native param list exposes each slot's marshalling shape: a
    /// string expands to a pair, bool gets a MarshalAs, and primitives
    /// stay bare. This is the one place the different shapes must line
    /// up, so we pin it with a mixed-shape case.
    #[test]
    fn native_param_list_expands_each_slot_by_kind() {
        let f = function_with_params(
            vec![
                param("flag", CSharpType::Bool, CSharpParamKind::Direct),
                param("v", CSharpType::String, CSharpParamKind::Utf8Bytes),
                param("count", CSharpType::UInt, CSharpParamKind::Direct),
                param(
                    "person",
                    CSharpType::Record("Person".to_string()),
                    CSharpParamKind::WireEncoded {
                        binding_name: "_personBytes".to_string(),
                    },
                ),
            ],
            CSharpType::Void,
            CSharpReturnKind::Void,
        );
        assert_eq!(
            f.native_param_list(),
            "[MarshalAs(UnmanagedType.I1)] bool flag, byte[] v, UIntPtr vLen, uint count, byte[] person, UIntPtr personLen",
        );
    }

    #[test]
    fn native_call_args_mirror_param_shapes() {
        let f = function_with_params(
            vec![
                param("v", CSharpType::String, CSharpParamKind::Utf8Bytes),
                param("count", CSharpType::UInt, CSharpParamKind::Direct),
            ],
            CSharpType::Void,
            CSharpReturnKind::Void,
        );
        assert_eq!(
            f.native_call_args(),
            "_vBytes, (UIntPtr)_vBytes.Length, count",
        );
    }

    /// Wire-encoded returns (string, non-blittable record) come back as
    /// an `FfiBuf` in the native signature regardless of the wrapper's
    /// public return type.
    #[rstest]
    #[case::void(CSharpType::Void, CSharpReturnKind::Void, "void")]
    #[case::primitive(CSharpType::Int, CSharpReturnKind::Direct, "int")]
    #[case::blittable_record(
        CSharpType::Record("Point".to_string()),
        CSharpReturnKind::Direct,
        "Point",
    )]
    #[case::string(CSharpType::String, CSharpReturnKind::WireDecodeString, "FfiBuf")]
    #[case::wire_record(
        CSharpType::Record("Person".to_string()),
        CSharpReturnKind::WireDecodeObject { class_name: "Person".to_string() },
        "FfiBuf",
    )]
    #[case::option_primitive(
        CSharpType::Nullable(Box::new(CSharpType::Int)),
        CSharpReturnKind::WireDecodeOption {
            decode_expr: "reader.ReadU8() == 0 ? (int?)null : reader.ReadI32()".to_string(),
        },
        "FfiBuf",
    )]
    fn native_return_type_reflects_ffi_buf_paths(
        #[case] return_type: CSharpType,
        #[case] return_kind: CSharpReturnKind,
        #[case] expected: &str,
    ) {
        assert_eq!(
            function_with_return(return_type, return_kind).native_return_type(),
            expected
        );
    }

    #[test]
    fn wire_decode_return_for_string_uses_read_string() {
        let kind = CSharpReturnKind::WireDecodeString;
        assert_eq!(
            kind.wire_decode_return("_buf").as_deref(),
            Some("return new WireReader(_buf).ReadString();"),
        );
    }

    #[test]
    fn wire_decode_return_for_object_calls_decode() {
        let kind = CSharpReturnKind::WireDecodeObject {
            class_name: "Person".to_string(),
        };
        assert_eq!(
            kind.wire_decode_return("_buf").as_deref(),
            Some("return Person.Decode(new WireReader(_buf));"),
        );
    }

    /// `WireDecodeOption` wraps the pre-rendered `decode_expr` in a local
    /// `reader` binding so the emit-time decoder can reference `reader`
    /// multiple times (once for the 1-byte tag, again for the payload)
    /// without duplicating buffer construction.
    #[test]
    fn wire_decode_return_for_option_binds_reader_local() {
        let kind = CSharpReturnKind::WireDecodeOption {
            decode_expr: "reader.ReadU8() == 0 ? (int?)null : reader.ReadI32()".to_string(),
        };
        assert_eq!(
            kind.wire_decode_return("_buf").as_deref(),
            Some(
                "var reader = new WireReader(_buf); return reader.ReadU8() == 0 ? (int?)null : reader.ReadI32();"
            ),
        );
    }

    #[rstest]
    #[case::void(CSharpReturnKind::Void)]
    #[case::direct(CSharpReturnKind::Direct)]
    fn wire_decode_return_none_for_non_wire_kinds(#[case] kind: CSharpReturnKind) {
        assert_eq!(kind.wire_decode_return("_buf"), None);
    }

    #[test]
    fn decode_class_name_some_only_for_wire_decode_object() {
        assert_eq!(
            CSharpReturnKind::WireDecodeObject {
                class_name: "Point".to_string()
            }
            .decode_class_name(),
            Some("Point"),
        );
        assert_eq!(CSharpReturnKind::WireDecodeString.decode_class_name(), None);
        assert_eq!(CSharpReturnKind::Void.decode_class_name(), None);
        assert_eq!(CSharpReturnKind::Direct.decode_class_name(), None);
    }

    mod from_read_op {
        use super::*;
        use crate::ir::codec::{EnumLayout, VecLayout};
        use crate::ir::ids::{EnumId, RecordId};
        use crate::ir::ops::{OffsetExpr, ReadOp, ReadSeq, SizeExpr, WireShape};
        use boltffi_ffi_rules::transport::EnumTagStrategy;

        fn seq(op: ReadOp) -> ReadSeq {
            ReadSeq {
                size: SizeExpr::Fixed(0),
                ops: vec![op],
                shape: WireShape::Value,
            }
        }

        fn prim(p: PrimitiveType) -> ReadOp {
            ReadOp::Primitive {
                primitive: p,
                offset: OffsetExpr::Base,
            }
        }

        fn cstyle_layout() -> EnumLayout {
            EnumLayout::CStyle {
                tag_type: PrimitiveType::I32,
                tag_strategy: EnumTagStrategy::Discriminant,
                is_error: false,
            }
        }

        fn data_layout() -> EnumLayout {
            EnumLayout::Data {
                tag_type: PrimitiveType::I32,
                tag_strategy: EnumTagStrategy::Discriminant,
                variants: vec![],
            }
        }

        #[test]
        fn primitive_maps_to_backing_type() {
            assert_eq!(
                CSharpType::from_read_op(&prim(PrimitiveType::I32)),
                CSharpType::Int
            );
            assert_eq!(
                CSharpType::from_read_op(&prim(PrimitiveType::F64)),
                CSharpType::Double
            );
        }

        #[test]
        fn string_maps_to_string() {
            let op = ReadOp::String {
                offset: OffsetExpr::Base,
            };
            assert_eq!(CSharpType::from_read_op(&op), CSharpType::String);
        }

        #[test]
        fn record_maps_to_record_with_class_name() {
            let op = ReadOp::Record {
                id: RecordId::new("point"),
                offset: OffsetExpr::Base,
                fields: vec![],
            };
            assert_eq!(
                CSharpType::from_read_op(&op),
                CSharpType::Record("Point".to_string())
            );
        }

        #[test]
        fn enum_cstyle_layout_maps_to_cstyle_enum() {
            let op = ReadOp::Enum {
                id: EnumId::new("status"),
                offset: OffsetExpr::Base,
                layout: cstyle_layout(),
            };
            assert_eq!(
                CSharpType::from_read_op(&op),
                CSharpType::CStyleEnum("Status".to_string())
            );
        }

        #[test]
        fn enum_data_layout_maps_to_data_enum() {
            let op = ReadOp::Enum {
                id: EnumId::new("shape"),
                offset: OffsetExpr::Base,
                layout: data_layout(),
            };
            assert_eq!(
                CSharpType::from_read_op(&op),
                CSharpType::DataEnum("Shape".to_string())
            );
        }

        #[test]
        fn option_wraps_inner_in_nullable() {
            let op = ReadOp::Option {
                tag_offset: OffsetExpr::Base,
                some: Box::new(seq(prim(PrimitiveType::I32))),
            };
            assert_eq!(
                CSharpType::from_read_op(&op),
                CSharpType::Nullable(Box::new(CSharpType::Int))
            );
        }

        #[test]
        fn vec_wraps_element_type_in_array() {
            let op = ReadOp::Vec {
                len_offset: OffsetExpr::Base,
                element_type: TypeExpr::Record(RecordId::new("point")),
                element: Box::new(seq(ReadOp::Record {
                    id: RecordId::new("point"),
                    offset: OffsetExpr::Base,
                    fields: vec![],
                })),
                layout: VecLayout::Encoded,
            };
            assert_eq!(
                CSharpType::from_read_op(&op),
                CSharpType::Array(Box::new(CSharpType::Record("Point".to_string())))
            );
        }

        #[test]
        fn option_of_vec_of_record_nests_correctly() {
            let inner_vec = ReadOp::Vec {
                len_offset: OffsetExpr::Base,
                element_type: TypeExpr::Record(RecordId::new("point")),
                element: Box::new(seq(ReadOp::Record {
                    id: RecordId::new("point"),
                    offset: OffsetExpr::Base,
                    fields: vec![],
                })),
                layout: VecLayout::Encoded,
            };
            let option_op = ReadOp::Option {
                tag_offset: OffsetExpr::Base,
                some: Box::new(seq(inner_vec)),
            };
            assert_eq!(
                CSharpType::from_read_op(&option_op),
                CSharpType::Nullable(Box::new(CSharpType::Array(Box::new(CSharpType::Record(
                    "Point".to_string()
                )))))
            );
        }

        /// Plan step 2 note: `qualify_if_shadowed` recurses through the
        /// typed intermediate, so a shadowed `Point` inside `Option<Vec<Point>>`
        /// still qualifies correctly.
        #[test]
        fn qualify_if_shadowed_reaches_through_nested_builder_output() {
            let option_op = ReadOp::Option {
                tag_offset: OffsetExpr::Base,
                some: Box::new(seq(ReadOp::Vec {
                    len_offset: OffsetExpr::Base,
                    element_type: TypeExpr::Record(RecordId::new("point")),
                    element: Box::new(seq(ReadOp::Record {
                        id: RecordId::new("point"),
                        offset: OffsetExpr::Base,
                        fields: vec![],
                    })),
                    layout: VecLayout::Encoded,
                })),
            };
            let ty = CSharpType::from_read_op(&option_op);
            let shadowed: std::collections::HashSet<String> =
                std::iter::once("Point".to_string()).collect();
            let qualified = ty.qualify_if_shadowed(&shadowed, "Demo");
            assert_eq!(qualified.to_string(), "global::Demo.Point[]?");
        }
    }

    mod from_type_expr {
        use super::*;
        use crate::ir::ids::{EnumId, RecordId};

        #[test]
        fn primitive_maps_to_backing_type() {
            assert_eq!(
                CSharpType::from_type_expr(&TypeExpr::Primitive(PrimitiveType::I32)),
                CSharpType::Int
            );
        }

        #[test]
        fn string_maps_to_string() {
            assert_eq!(
                CSharpType::from_type_expr(&TypeExpr::String),
                CSharpType::String
            );
        }

        #[test]
        fn record_maps_to_record_with_class_name() {
            assert_eq!(
                CSharpType::from_type_expr(&TypeExpr::Record(RecordId::new("point"))),
                CSharpType::Record("Point".to_string())
            );
        }

        /// `TypeExpr::Enum` has no layout metadata available here, so we
        /// commit to [`CSharpType::DataEnum`] by convention. Display and
        /// qualification render identically for all named-type variants,
        /// so downstream rendering is unaffected.
        #[test]
        fn enum_maps_to_data_enum_by_convention() {
            assert_eq!(
                CSharpType::from_type_expr(&TypeExpr::Enum(EnumId::new("status"))),
                CSharpType::DataEnum("Status".to_string())
            );
        }

        #[test]
        fn vec_wraps_element_in_array() {
            let expr = TypeExpr::Vec(Box::new(TypeExpr::Primitive(PrimitiveType::F64)));
            assert_eq!(
                CSharpType::from_type_expr(&expr),
                CSharpType::Array(Box::new(CSharpType::Double))
            );
        }

        #[test]
        fn option_wraps_inner_in_nullable() {
            let expr = TypeExpr::Option(Box::new(TypeExpr::String));
            assert_eq!(
                CSharpType::from_type_expr(&expr),
                CSharpType::Nullable(Box::new(CSharpType::String))
            );
        }

        #[test]
        fn option_of_vec_of_record_nests_correctly() {
            let expr = TypeExpr::Option(Box::new(TypeExpr::Vec(Box::new(TypeExpr::Record(
                RecordId::new("point"),
            )))));
            assert_eq!(
                CSharpType::from_type_expr(&expr),
                CSharpType::Nullable(Box::new(CSharpType::Array(Box::new(CSharpType::Record(
                    "Point".to_string()
                )))))
            );
        }
    }

    mod for_enum {
        use super::*;
        use crate::ir::definitions::{CStyleVariant, DataVariant, VariantPayload};
        use crate::ir::ids::EnumId;

        fn enum_def(id: &str, repr: EnumRepr) -> EnumDef {
            EnumDef {
                id: EnumId::new(id),
                repr,
                is_error: false,
                constructors: vec![],
                methods: vec![],
                doc: None,
                deprecated: None,
            }
        }

        #[test]
        fn c_style_repr_maps_to_c_style_enum_type() {
            let def = enum_def(
                "Status",
                EnumRepr::CStyle {
                    tag_type: PrimitiveType::I32,
                    variants: vec![CStyleVariant {
                        name: "Active".into(),
                        discriminant: 0,
                        doc: None,
                    }],
                },
            );
            assert_eq!(
                CSharpType::for_enum(&def),
                CSharpType::CStyleEnum("Status".to_string())
            );
        }

        #[test]
        fn data_repr_maps_to_data_enum_type() {
            let def = enum_def(
                "Shape",
                EnumRepr::Data {
                    tag_type: PrimitiveType::I32,
                    variants: vec![DataVariant {
                        name: "Point".into(),
                        discriminant: 0,
                        payload: VariantPayload::Unit,
                        doc: None,
                    }],
                },
            );
            assert_eq!(
                CSharpType::for_enum(&def),
                CSharpType::DataEnum("Shape".to_string())
            );
        }

        /// `class_name` runs the source `snake_case` enum name through
        /// [`NamingConvention::class_name`], so the C# type keeps the name
        /// in PascalCase even if upstream ever shifts the ID casing.
        #[test]
        fn class_name_round_trips_through_naming_convention() {
            let def = enum_def(
                "log_level",
                EnumRepr::CStyle {
                    tag_type: PrimitiveType::I32,
                    variants: vec![],
                },
            );
            assert_eq!(
                CSharpType::for_enum(&def),
                CSharpType::CStyleEnum("LogLevel".to_string())
            );
        }
    }

    mod enum_backing_for {
        use super::*;

        #[test]
        fn maps_u8_to_byte() {
            assert_eq!(
                CSharpType::enum_backing_for(PrimitiveType::U8),
                Some(CSharpType::Byte)
            );
        }

        #[test]
        fn rejects_usize() {
            assert_eq!(CSharpType::enum_backing_for(PrimitiveType::USize), None);
        }
    }
}