cheadergen_cli 0.1.0

A tool for generating C bindings to Rust code.
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
// User-facing documentation for the `cheadergen.toml` schema lives in
// `cheadergen::config_reference` (see `cheadergen/src/config_reference.rs`).
// When you add, rename, or change the meaning of a field below, update that
// page so it stays in sync with what users see on docs.rs.

pub mod cbindgen;

use std::collections::{BTreeMap, HashMap};
use std::path::Path;

use clap::ValueEnum;
use serde::{Deserialize, Serialize};

/// The target language for the generated header file.
///
/// Used by the CLI `--lang` flag to select which language output to produce.
#[derive(Debug, Clone, PartialEq, Eq, ValueEnum)]
pub enum Language {
    /// Generate a C-compatible header.
    #[value(name = "c", alias = "C")]
    C,
    /// Generate a C++ header.
    #[value(name = "c++", alias = "C++", alias = "cpp")]
    Cxx,
    /// Reserved for future Cython support. Currently rejected at validation time
    /// by [`RawConfig::into_config`].
    #[value(name = "cython", alias = "Cython")]
    Cython,
}

impl Language {
    pub fn extension(&self) -> &'static str {
        match self {
            Language::C => "h",
            Language::Cxx => "hpp",
            Language::Cython => "pyx",
        }
    }
}

/// Controls how items of a given kind are sorted in the generated header.
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SortKey {
    /// Emit items in the order they appear in the Rust source file.
    #[default]
    SourceOrder,
    /// Sort items alphabetically by name.
    Name,
}

/// The comment style used when emitting Rust doc comments in the header.
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DocumentationStyle {
    /// Use C-style block comments (`/** ... */`) for C output,
    /// C++ line comments (`///`) for C++ output.
    #[default]
    Auto,
    /// Always use C-style block comments: `/** ... */`.
    C,
    /// Always use C99/C++ line comments: `// ...`.
    C99,
    /// Use Doxygen-style block comments: `/** ... */` (same as `C` currently).
    Doxy,
    /// Use C++ triple-slash comments: `/// ...`.
    Cxx,
}

/// Controls how much of the Rust doc comment is included.
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DocumentationLength {
    /// Include the entire doc comment.
    #[default]
    Full,
    /// Include only the first paragraph (up to the first blank line).
    Short,
}

/// Function-specific configuration inside the `[fn]` TOML section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawFnSection {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<SortKey>,
}

/// Static-specific configuration inside the `[static]` TOML section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawStaticSection {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<SortKey>,
}

/// Constant-specific configuration inside the `[constant]` TOML section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawConstantSection {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<SortKey>,
}

/// Enum-specific configuration inside the `[enum]` TOML section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawEnumSection {
    /// When true, prefix tagged-union variant names with the enum name
    /// (e.g. `Foo_A` instead of `A`). Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix_with_name: Option<bool>,
}

/// Per-header configuration inside a `[header.<name>]` TOML section.
///
/// Each header section can override any common option for a specific
/// crate's generated header. The `include_guard` field is only available
/// here (not at the top level or in language sections).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawHeaderSection {
    /// Custom `#ifndef`/`#define` include guard name for this header.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_guard: Option<String>,

    // Common option overrides.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preamble: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trailer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autogen_warning: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pragma_once: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub includes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_includes: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_includes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_style: Option<DocumentationStyle>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_length: Option<DocumentationLength>,

    /// Default sort order override for this header.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<SortKey>,

    /// Function-specific configuration.
    #[serde(rename = "fn", skip_serializing_if = "Option::is_none")]
    pub fn_: Option<RawFnSection>,
    /// Static-specific configuration.
    #[serde(rename = "static", skip_serializing_if = "Option::is_none")]
    pub static_: Option<RawStaticSection>,
    /// Constant-specific configuration.
    #[serde(rename = "constant", skip_serializing_if = "Option::is_none")]
    pub constant_: Option<RawConstantSection>,
    /// Enum-specific configuration.
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_: Option<RawEnumSection>,

    /// C-specific configuration section.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub c: Option<RawCSection>,
    /// C++-specific configuration section.
    #[serde(alias = "c++", alias = "cpp", skip_serializing_if = "Option::is_none")]
    pub cxx: Option<RawCxxSection>,
}

/// Controls how types from a specific dependency package are emitted
/// in the generated header.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PackageTypeMode {
    /// Emit only forward declarations for all types from this package.
    Opaque,
    /// Do not emit anything for types from this package.
    /// The consumer is expected to provide definitions via included headers.
    Skip,
}

/// Per-dependency-package configuration inside a `[package.<name>]` TOML section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawPackageConfig {
    /// How types from this package should be emitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub types: Option<PackageTypeMode>,
    /// Override the on-disk base name of the generated header for this package
    /// in partitioned mode. Must be a bare filename (no path separators, no
    /// extension). Rejected in bundle mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header_name: Option<String>,
    /// Override the global `usize_is_size_t` setting for items defined in
    /// this package. When `Some`, takes precedence over the top-level value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usize_is_size_t: Option<bool>,
}

/// The declaration style for C struct and enum definitions.
///
/// This only applies when the target language is [`Language::C`].
/// C++ does not use typedef-style declarations, so this option is ignored
/// (and rejected) for [`Language::Cxx`].
#[derive(Debug, Clone, ValueEnum, Deserialize, Serialize)]
pub enum Style {
    /// Emit both a tag definition and a typedef:
    /// `typedef struct MyType { ... } MyType;`
    #[value(name = "both", alias = "Both")]
    #[serde(alias = "both")]
    Both,
    /// Emit only a tag definition: `struct MyType { ... };`
    #[value(name = "tag", alias = "Tag")]
    #[serde(alias = "tag")]
    Tag,
    /// Emit only a typedef: `typedef struct { ... } MyType;`
    #[value(name = "type", alias = "Type")]
    #[serde(alias = "type")]
    Type,
}

/// The raw configuration as deserialized from a TOML file.
///
/// Common options live at the top level and are inherited by all language
/// outputs. Language-specific sections (`[c]`, `[cxx]`) can override any
/// common option and add language-specific settings.
///
/// Defaults are resolved and language-specific constraints are validated
/// when converting into a [`Config`] via [`RawConfig::into_config`].
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawConfig {
    /// Verbatim text prepended to the generated file (e.g. a license block).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preamble: Option<String>,
    /// Verbatim text appended to the end of the generated file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trailer: Option<String>,
    /// Warning text emitted between major sections to discourage manual edits.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autogen_warning: Option<String>,
    /// Emit `#pragma once` instead of (or in addition to) an include guard.
    /// Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pragma_once: Option<bool>,
    /// Extra headers to include in the generated output.
    ///
    /// An entry wrapped in angle brackets (e.g. `"<stdint.h>"`) is emitted
    /// verbatim as a system include (`#include <stdint.h>`). Any other entry
    /// is rendered with double quotes (`#include "my_types.h"`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub includes: Vec<String>,
    /// Suppress the default language-specific includes (e.g. `<stdint.h>` for C).
    /// Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_includes: Option<bool>,
    /// Verbatim text inserted immediately after the include block.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_includes: Option<String>,

    /// Whether to emit Rust doc comments in the generated header.
    /// Defaults to `true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<bool>,
    /// Comment style for doc comments. Defaults to [`DocumentationStyle::Auto`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_style: Option<DocumentationStyle>,
    /// How much of the doc comment to include. Defaults to [`DocumentationLength::Full`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_length: Option<DocumentationLength>,

    /// Default sort order for all item kinds.
    /// Can be overridden per-kind via `[fn]` or `[static]` sections.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<SortKey>,

    /// Function-specific configuration.
    #[serde(rename = "fn", skip_serializing_if = "Option::is_none")]
    pub fn_: Option<RawFnSection>,
    /// Static-specific configuration.
    #[serde(rename = "static", skip_serializing_if = "Option::is_none")]
    pub static_: Option<RawStaticSection>,
    /// Constant-specific configuration.
    #[serde(rename = "constant", skip_serializing_if = "Option::is_none")]
    pub constant_: Option<RawConstantSection>,
    /// Enum-specific configuration.
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    pub enum_: Option<RawEnumSection>,

    /// Produce a single combined header per target, inlining all dependency
    /// types instead of emitting per-crate headers with `#include` directives.
    /// Defaults to `false` (partitioned mode).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bundle: Option<bool>,

    /// Translate Rust's `usize`/`isize` to C's `size_t`/`ptrdiff_t` instead of
    /// the default `uintptr_t`/`intptr_t`. Defaults to `false`. Can be
    /// overridden per dependency via [`RawPackageConfig::usize_is_size_t`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usize_is_size_t: Option<bool>,

    /// Per-dependency-package configuration.
    ///
    /// Keys are crate names (e.g. `my-dep`) or Cargo-style `name@version`
    /// specifiers for disambiguation (e.g. `"foo@1.0"`). Stored as a
    /// `BTreeMap` so iteration order is deterministic (alphabetical).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub package: BTreeMap<String, RawPackageConfig>,

    /// Per-header configuration sections.
    ///
    /// Keys are crate names. Each section can override common options
    /// for that crate's generated header.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub header: HashMap<String, RawHeaderSection>,

    /// C-specific configuration section.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub c: Option<RawCSection>,
    /// C++-specific configuration section.
    #[serde(alias = "c++", alias = "cpp", skip_serializing_if = "Option::is_none")]
    pub cxx: Option<RawCxxSection>,
}

/// C-specific options inside the `[c]` TOML section.
///
/// Any common option specified here overrides the top-level default
/// for C output only.
///
/// Common fields are duplicated from [`RawConfig`] (rather than extracted
/// into a shared struct with `#[serde(flatten)]`) so that we can keep
/// `#[serde(deny_unknown_fields)]` on every struct — giving clear error
/// messages when a config file contains a typo.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawCSection {
    /// C declaration style for structs and enums. Defaults to [`Style::Both`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<Style>,
    /// Wrap C output in an `extern "C"` block for C++ compatibility.
    /// Defaults to `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpp_compat: Option<bool>,
    // Common option overrides (see struct-level doc for why these are duplicated).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preamble: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trailer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autogen_warning: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pragma_once: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub includes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_includes: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_includes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_style: Option<DocumentationStyle>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_length: Option<DocumentationLength>,
}

/// C++-specific options inside the `[cxx]` TOML section.
///
/// Any common option specified here overrides the top-level default
/// for C++ output only.
///
/// See [`RawCSection`] for why common fields are duplicated here.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawCxxSection {
    // Common option overrides (see RawCSection doc for why these are duplicated).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preamble: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trailer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autogen_warning: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pragma_once: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub includes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_includes: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after_includes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_style: Option<DocumentationStyle>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_length: Option<DocumentationLength>,
}

/// Validated, language-specific configuration.
///
/// Produced by [`RawConfig::into_config`] after resolving defaults and
/// enforcing language-specific constraints.
#[derive(Debug, Clone)]
pub enum Config {
    /// Configuration for [`Language::C`] output.
    C(CConfig),
    /// Configuration for [`Language::Cxx`] output.
    #[allow(dead_code)]
    Cxx(CxxConfig),
}

/// A set of validated configs: one default plus optional per-header overrides.
///
/// Produced by [`RawConfig::into_config`]. Use [`ConfigSet::for_header`] to
/// look up the config for a specific generated header (falls back to the default).
#[derive(Debug, Clone)]
pub struct ConfigSet {
    /// Config for headers without a `[header.<name>]` section.
    pub default: Config,
    /// Per-header configs, keyed by the final on-disk base name of the header
    /// (i.e. the name produced by `HeaderFilenames::base_name`).
    pub per_header: HashMap<String, Config>,
    /// Whether to produce a single combined header per target (bundle mode).
    pub bundle: bool,
    /// Header rename overrides, keyed by the `[package.<name>]` section key
    /// (crate name, or `name@version` for disambiguation). Values are the
    /// final on-disk base name (no extension, no path separators).
    pub header_renames: HashMap<String, String>,
}

impl ConfigSet {
    /// Look up the config for a header by its final base name.
    ///
    /// Returns the per-header config if one exists, otherwise the default.
    pub fn for_header(&self, base_name: &str) -> &Config {
        self.per_header.get(base_name).unwrap_or(&self.default)
    }

    /// Returns the names of all `[header.<name>]` sections.
    pub fn header_names(&self) -> impl Iterator<Item = &str> {
        self.per_header.keys().map(|s| s.as_str())
    }
}

/// Validated options shared across all target languages.
///
/// Fields mirror [`RawConfig`] but with defaults resolved
/// (e.g. `Option<bool>` becomes `bool`).
#[derive(Debug, Clone)]
pub struct CommonConfig {
    /// See [`RawConfig::preamble`].
    pub preamble: Option<String>,
    /// See [`RawConfig::trailer`].
    pub trailer: Option<String>,
    /// See [`RawConfig::autogen_warning`].
    pub autogen_warning: Option<String>,
    /// Custom `#ifndef`/`#define` include guard name.
    /// Only available in per-header `[header.<name>]` sections.
    pub include_guard: Option<String>,
    /// See [`RawConfig::pragma_once`]. Defaults to `false`.
    pub pragma_once: bool,
    /// See [`RawConfig::includes`].
    pub includes: Vec<String>,
    /// See [`RawConfig::no_includes`]. Defaults to `false`.
    pub no_includes: bool,
    /// See [`RawConfig::after_includes`].
    pub after_includes: Option<String>,
    /// Resolved sort order for functions: `[fn].sort_by` → top-level `sort_by` → `SourceOrder`.
    pub fn_sort_by: SortKey,
    /// Resolved sort order for statics: `[static].sort_by` → top-level `sort_by` → `SourceOrder`.
    pub static_sort_by: SortKey,
    /// Resolved sort order for constants: `[constant].sort_by` → top-level `sort_by` → `SourceOrder`.
    pub constant_sort_by: SortKey,
    /// Whether to emit Rust doc comments. Defaults to `true`.
    pub documentation: bool,
    /// Comment style for doc comments.
    pub documentation_style: DocumentationStyle,
    /// How much of the doc comment to include.
    pub documentation_length: DocumentationLength,
    /// Per-dependency-package configuration, keyed by the raw config key
    /// (crate name or `name@version`).
    pub package_configs: HashMap<String, PackageConfig>,
    /// See [`RawConfig::usize_is_size_t`]. Defaults to `false`. Per-package
    /// overrides on [`PackageConfig::usize_is_size_t`] take priority for items
    /// defined in that package.
    pub usize_is_size_t: bool,
}

/// Validated per-dependency-package configuration.
#[derive(Debug, Clone)]
pub struct PackageConfig {
    /// How types from this package should be emitted, if specified.
    pub types: Option<PackageTypeMode>,
    /// Override of [`CommonConfig::usize_is_size_t`] for items defined in
    /// this package, if specified.
    pub usize_is_size_t: Option<bool>,
}

/// C-specific configuration, including options that are only meaningful for
/// [`Language::C`] output (e.g. [`Style`] and `cpp_compat`).
#[derive(Debug, Clone)]
pub struct CConfig {
    /// Options shared with all languages.
    pub common: CommonConfig,
    /// See [`RawCSection::style`]. Defaults to [`Style::Both`].
    pub style: Style,
    /// See [`RawCSection::cpp_compat`]. Defaults to `false`.
    pub cpp_compat: bool,
    /// Whether to prefix tagged-union variant names with the enum name.
    /// Defaults to `false`.
    pub enum_prefix_with_name: bool,
}

/// C++-specific configuration for [`Language::Cxx`] output.
///
/// Currently only holds the [`CommonConfig`] shared options, since C++ does not
/// use typedef-style declarations or `cpp_compat`.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct CxxConfig {
    /// Options shared with all languages.
    pub common: CommonConfig,
}

/// Error returned when config parsing or validation fails.
///
/// This covers both TOML deserialization errors (from [`RawConfig::from_toml_file`])
/// and semantic validation errors (from [`RawConfig::into_config`]).
#[derive(Debug)]
pub struct ConfigError {
    pub message: String,
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for ConfigError {}

/// Top-level common fields extracted from [`RawConfig`] for merging with
/// language-section overrides.
#[derive(Clone)]
struct RawCommonFields {
    preamble: Option<String>,
    trailer: Option<String>,
    autogen_warning: Option<String>,
    pragma_once: Option<bool>,
    includes: Vec<String>,
    no_includes: Option<bool>,
    after_includes: Option<String>,
    sort_by: Option<SortKey>,
    fn_sort_by: Option<SortKey>,
    static_sort_by: Option<SortKey>,
    constant_sort_by: Option<SortKey>,
    documentation: Option<bool>,
    documentation_style: Option<DocumentationStyle>,
    documentation_length: Option<DocumentationLength>,
    package_configs: HashMap<String, PackageConfig>,
    usize_is_size_t: Option<bool>,
}

/// Optional overrides from a language section that can replace top-level
/// common field values.
struct RawCommonOverrides {
    preamble: Option<String>,
    trailer: Option<String>,
    autogen_warning: Option<String>,
    pragma_once: Option<bool>,
    includes: Option<Vec<String>>,
    no_includes: Option<bool>,
    after_includes: Option<String>,
    documentation: Option<bool>,
    documentation_style: Option<DocumentationStyle>,
    documentation_length: Option<DocumentationLength>,
}

impl RawCommonOverrides {
    /// Merge `other` on top of `self`. Values in `other` win when present.
    fn merge(self, other: RawCommonOverrides) -> RawCommonOverrides {
        RawCommonOverrides {
            preamble: other.preamble.or(self.preamble),
            trailer: other.trailer.or(self.trailer),
            autogen_warning: other.autogen_warning.or(self.autogen_warning),
            pragma_once: other.pragma_once.or(self.pragma_once),
            includes: other.includes.or(self.includes),
            no_includes: other.no_includes.or(self.no_includes),
            after_includes: other.after_includes.or(self.after_includes),
            documentation: other.documentation.or(self.documentation),
            documentation_style: other.documentation_style.or(self.documentation_style),
            documentation_length: other.documentation_length.or(self.documentation_length),
        }
    }
}

impl RawCommonFields {
    /// Merge section overrides onto these base fields, producing a validated
    /// [`CommonConfig`]. Section values win when present; otherwise the
    /// top-level value is used.
    ///
    /// `include_guard` is passed separately because it is only available
    /// in per-header sections, not at the global or language-section level.
    fn resolve(self, overrides: RawCommonOverrides, include_guard: Option<String>) -> CommonConfig {
        CommonConfig {
            preamble: overrides.preamble.or(self.preamble),
            trailer: overrides.trailer.or(self.trailer),
            autogen_warning: overrides.autogen_warning.or(self.autogen_warning),
            include_guard,
            pragma_once: overrides.pragma_once.or(self.pragma_once).unwrap_or(false),
            includes: overrides.includes.unwrap_or(self.includes),
            no_includes: overrides.no_includes.or(self.no_includes).unwrap_or(false),
            after_includes: overrides.after_includes.or(self.after_includes),
            fn_sort_by: self.fn_sort_by.or(self.sort_by).unwrap_or_default(),
            static_sort_by: self.static_sort_by.or(self.sort_by).unwrap_or_default(),
            constant_sort_by: self.constant_sort_by.or(self.sort_by).unwrap_or_default(),
            documentation: overrides
                .documentation
                .or(self.documentation)
                .unwrap_or(true),
            documentation_style: overrides
                .documentation_style
                .or(self.documentation_style)
                .unwrap_or_default(),
            documentation_length: overrides
                .documentation_length
                .or(self.documentation_length)
                .unwrap_or_default(),
            package_configs: self.package_configs,
            usize_is_size_t: self.usize_is_size_t.unwrap_or(false),
        }
    }
}

/// Trait for language-specific sections that can provide common option overrides.
trait IntoCommonOverrides {
    fn into_common_overrides(self) -> RawCommonOverrides;
}

impl IntoCommonOverrides for RawCSection {
    fn into_common_overrides(self) -> RawCommonOverrides {
        RawCommonOverrides {
            preamble: self.preamble,
            trailer: self.trailer,
            autogen_warning: self.autogen_warning,
            pragma_once: self.pragma_once,
            includes: self.includes,
            no_includes: self.no_includes,
            after_includes: self.after_includes,
            documentation: self.documentation,
            documentation_style: self.documentation_style,
            documentation_length: self.documentation_length,
        }
    }
}

impl IntoCommonOverrides for RawCxxSection {
    fn into_common_overrides(self) -> RawCommonOverrides {
        RawCommonOverrides {
            preamble: self.preamble,
            trailer: self.trailer,
            autogen_warning: self.autogen_warning,
            pragma_once: self.pragma_once,
            includes: self.includes,
            no_includes: self.no_includes,
            after_includes: self.after_includes,
            documentation: self.documentation,
            documentation_style: self.documentation_style,
            documentation_length: self.documentation_length,
        }
    }
}

impl IntoCommonOverrides for RawHeaderSection {
    fn into_common_overrides(self) -> RawCommonOverrides {
        RawCommonOverrides {
            preamble: self.preamble,
            trailer: self.trailer,
            autogen_warning: self.autogen_warning,
            pragma_once: self.pragma_once,
            includes: self.includes,
            no_includes: self.no_includes,
            after_includes: self.after_includes,
            documentation: self.documentation,
            documentation_style: self.documentation_style,
            documentation_length: self.documentation_length,
        }
    }
}

/// CLI overrides that can be applied to the config before validation.
#[derive(Debug, Default)]
pub struct CliOverrides {
    /// Override the C declaration style.
    pub style: Option<Style>,
    /// Force `cpp_compat` on.
    pub cpp_compat: bool,
}

impl RawConfig {
    /// Read and deserialize a [`RawConfig`] from a TOML file at `path`.
    pub fn from_toml_file(path: &Path) -> Result<Self, ConfigError> {
        let contents = fs_err::read_to_string(path).map_err(|e| ConfigError {
            message: format!("failed to read config file: {e}"),
        })?;
        toml::from_str(&contents).map_err(|e| ConfigError {
            message: format!("failed to parse config file: {e}"),
        })
    }

    /// Validate and convert into a language-specific [`Config`].
    ///
    /// `language` selects which language section to use.
    /// If the matching section is absent, top-level common options are used with
    /// language-specific defaults.
    ///
    /// `overrides` allows CLI flags to override config values.
    pub fn into_config(
        self,
        language: &Language,
        overrides: &CliOverrides,
    ) -> Result<ConfigSet, ConfigError> {
        match language {
            Language::Cython => {
                return Err(ConfigError {
                    message: "Cython output is not yet supported".to_string(),
                });
            }
            Language::Cxx => {
                return Err(ConfigError {
                    message: "C++ output is not yet supported".to_string(),
                });
            }
            Language::C => {}
        }

        let bundle = self.bundle.unwrap_or(false);

        // Extract header renames and per-package type configs from [package.<name>]
        // sections. Iteration is over a BTreeMap, so error messages naming
        // multiple packages stay deterministic.
        let mut package_configs: HashMap<String, PackageConfig> = HashMap::new();
        let mut header_renames: HashMap<String, String> = HashMap::new();
        let mut rename_targets: HashMap<String, String> = HashMap::new();
        for (key, raw) in self.package {
            if raw.types.is_some() || raw.usize_is_size_t.is_some() {
                package_configs.insert(
                    key.clone(),
                    PackageConfig {
                        types: raw.types,
                        usize_is_size_t: raw.usize_is_size_t,
                    },
                );
            }
            if let Some(header_name) = raw.header_name {
                if bundle {
                    return Err(ConfigError {
                        message: format!(
                            "`header_name` is not supported in bundle mode \
                             (set on `[package.\"{key}\"]`)"
                        ),
                    });
                }
                if header_name.is_empty() {
                    return Err(ConfigError {
                        message: format!(
                            "`header_name` on `[package.\"{key}\"]` must not be empty"
                        ),
                    });
                }
                if header_name.contains(['/', '\\']) {
                    return Err(ConfigError {
                        message: format!(
                            "`header_name` on `[package.\"{key}\"]` must not contain \
                             path separators: `{header_name}`"
                        ),
                    });
                }
                if header_name.contains('.') {
                    return Err(ConfigError {
                        message: format!(
                            "`header_name` on `[package.\"{key}\"]` must not include \
                             a file extension (got `{header_name}`); the language extension \
                             is appended automatically"
                        ),
                    });
                }
                if let Some(prev_key) = rename_targets.insert(header_name.clone(), key.clone()) {
                    return Err(ConfigError {
                        message: format!(
                            "`header_name = \"{header_name}\"` is set on both \
                             `[package.\"{prev_key}\"]` and `[package.\"{key}\"]`"
                        ),
                    });
                }
                header_renames.insert(key, header_name);
            }
        }

        // Build the base CommonConfig from top-level fields.
        let base = RawCommonFields {
            preamble: self.preamble,
            trailer: self.trailer,
            autogen_warning: self.autogen_warning,
            pragma_once: self.pragma_once,
            includes: self.includes,
            no_includes: self.no_includes,
            after_includes: self.after_includes,
            sort_by: self.sort_by,
            fn_sort_by: self.fn_.and_then(|s| s.sort_by),
            static_sort_by: self.static_.and_then(|s| s.sort_by),
            constant_sort_by: self.constant_.and_then(|s| s.sort_by),
            documentation: self.documentation,
            documentation_style: self.documentation_style,
            documentation_length: self.documentation_length,
            package_configs,
            usize_is_size_t: self.usize_is_size_t,
        };

        // Build the default config (no include_guard, no per-header overrides).
        let default = Self::build_config(
            language,
            overrides,
            &base,
            &self.c,
            &self.cxx,
            self.enum_.as_ref(),
            None, // no per-header overrides
            None, // no per-header C section
            None, // no per-header C++ section
            None, // no include_guard
        )?;

        // Build per-header configs.
        let mut per_header = HashMap::new();
        for (name, mut header_section) in self.header {
            let include_guard = header_section.include_guard.take();

            // Merge header-level item-kind overrides with global defaults.
            let header_sort_by = header_section.sort_by;
            let header_fn_sort_by = header_section.fn_.as_ref().and_then(|s| s.sort_by);
            let header_static_sort_by = header_section.static_.as_ref().and_then(|s| s.sort_by);
            let header_constant_sort_by = header_section.constant_.as_ref().and_then(|s| s.sort_by);

            // Build a modified base with per-header sort overrides.
            let mut header_base = base.clone();
            if let Some(sort_by) = header_sort_by {
                header_base.sort_by = Some(sort_by);
            }
            if let Some(fn_sort_by) = header_fn_sort_by {
                header_base.fn_sort_by = Some(fn_sort_by);
            }
            if let Some(static_sort_by) = header_static_sort_by {
                header_base.static_sort_by = Some(static_sort_by);
            }
            if let Some(constant_sort_by) = header_constant_sort_by {
                header_base.constant_sort_by = Some(constant_sort_by);
            }

            // Extract per-header language and enum sections before consuming header_section.
            let header_c = header_section.c.take();
            let header_cxx = header_section.cxx.take();
            let header_enum = header_section.enum_.take();
            let effective_enum = header_enum.as_ref().or(self.enum_.as_ref());

            let header_config = Self::build_config(
                language,
                overrides,
                &header_base,
                &self.c,
                &self.cxx,
                effective_enum,
                Some(header_section),
                header_c,
                header_cxx,
                include_guard,
            )?;

            per_header.insert(name, header_config);
        }

        Ok(ConfigSet {
            default,
            per_header,
            bundle,
            header_renames,
        })
    }

    /// Build a single [`Config`] for a given language, merging overrides.
    ///
    /// When `header_section` is `Some`, its common overrides are merged
    /// on top of the language-section overrides.
    /// Build a single [`Config`] for a given language, merging overrides.
    ///
    /// Override priority (first wins):
    /// 1. CLI flags
    /// 2. `header_c_section` / `header_cxx_section` (per-header language)
    /// 3. `header_section` (per-header common)
    /// 4. `c_section` / `cxx_section` (global language)
    /// 5. `base` (top-level defaults)
    #[allow(clippy::too_many_arguments)]
    fn build_config(
        language: &Language,
        cli_overrides: &CliOverrides,
        base: &RawCommonFields,
        c_section: &Option<RawCSection>,
        cxx_section: &Option<RawCxxSection>,
        enum_section: Option<&RawEnumSection>,
        header_section: Option<RawHeaderSection>,
        header_c_section: Option<RawCSection>,
        header_cxx_section: Option<RawCxxSection>,
        include_guard: Option<String>,
    ) -> Result<Config, ConfigError> {
        match language {
            Language::C => {
                let global_section = c_section.clone().unwrap_or_default();
                // For style/cpp_compat: header-level [c] wins over global [c],
                // CLI wins over both.
                let style = cli_overrides
                    .style
                    .clone()
                    .or_else(|| header_c_section.as_ref().and_then(|s| s.style.clone()))
                    .or(global_section.style.clone())
                    .unwrap_or(Style::Both);
                let cpp_compat = if cli_overrides.cpp_compat {
                    true
                } else {
                    header_c_section
                        .as_ref()
                        .and_then(|s| s.cpp_compat)
                        .or(global_section.cpp_compat)
                        .unwrap_or(false)
                };
                let enum_prefix_with_name = enum_section
                    .and_then(|s| s.prefix_with_name)
                    .unwrap_or(false);

                // Merge: global [c] → header common → header [c]
                let mut merged = global_section.into_common_overrides();
                if let Some(hs) = header_section {
                    merged = merged.merge(hs.into_common_overrides());
                }
                if let Some(hc) = header_c_section {
                    merged = merged.merge(hc.into_common_overrides());
                }
                let common = base.clone().resolve(merged, include_guard);

                Ok(Config::C(CConfig {
                    common,
                    style,
                    cpp_compat,
                    enum_prefix_with_name,
                }))
            }
            Language::Cxx => {
                let global_section = cxx_section.clone().unwrap_or_default();

                let mut merged = global_section.into_common_overrides();
                if let Some(hs) = header_section {
                    merged = merged.merge(hs.into_common_overrides());
                }
                if let Some(hcxx) = header_cxx_section {
                    merged = merged.merge(hcxx.into_common_overrides());
                }
                let common = base.clone().resolve(merged, include_guard);
                Ok(Config::Cxx(CxxConfig { common }))
            }
            Language::Cython => unreachable!(),
        }
    }
}

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

    #[test]
    fn empty_config() {
        let raw: RawConfig = toml::from_str("").unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        assert!(matches!(config_set.default, Config::C(_)));
    }

    #[test]
    fn full_c_config() {
        let toml_str = r#"
preamble = "/* License */"
trailer = "/* End */"
autogen_warning = "// Auto-generated"
pragma_once = false
includes = ["<stdint.h>", "<stdbool.h>", "my_types.h"]
no_includes = false
after_includes = "/* after includes */"

[c]
style = "Tag"
cpp_compat = true
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Tag));
                assert!(c.cpp_compat);
                assert_eq!(c.common.preamble.as_deref(), Some("/* License */"));
                assert_eq!(c.common.trailer.as_deref(), Some("/* End */"));
                assert_eq!(
                    c.common.autogen_warning.as_deref(),
                    Some("// Auto-generated")
                );
                assert!(c.common.include_guard.is_none());
                assert!(!c.common.pragma_once);
                assert_eq!(
                    c.common.includes,
                    vec!["<stdint.h>", "<stdbool.h>", "my_types.h"]
                );
                assert!(!c.common.no_includes);
                assert_eq!(
                    c.common.after_includes.as_deref(),
                    Some("/* after includes */")
                );
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn full_cxx_config_rejected() {
        let toml_str = r#"
preamble = "/* C++ License */"
pragma_once = true

[cxx]
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let err = raw
            .into_config(&Language::Cxx, &CliOverrides::default())
            .unwrap_err();
        assert!(err.message.contains("C++ output is not yet supported"));
    }

    #[test]
    fn section_overrides_common() {
        let toml_str = r#"
preamble = "/* Shared */"
pragma_once = true

[c]
pragma_once = false
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert_eq!(c.common.preamble.as_deref(), Some("/* Shared */"));
                assert!(!c.common.pragma_once);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn multi_language_config() {
        let toml_str = r#"
preamble = "/* Shared License */"

[c]
style = "Tag"
cpp_compat = true

[cxx]
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();

        // Select C
        let c_config_set = raw
            .clone()
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match &c_config_set.default {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Tag));
                assert!(c.cpp_compat);
                assert_eq!(c.common.preamble.as_deref(), Some("/* Shared License */"));
                assert!(c.common.include_guard.is_none());
            }
            _ => panic!("expected Config::C"),
        }

        // Select C++ — rejected
        let err = raw
            .into_config(&Language::Cxx, &CliOverrides::default())
            .unwrap_err();
        assert!(err.message.contains("C++ output is not yet supported"));
    }

    #[test]
    fn cxx_rejected() {
        let raw: RawConfig = toml::from_str("").unwrap();
        let err = raw
            .into_config(&Language::Cxx, &CliOverrides::default())
            .unwrap_err();
        assert!(err.message.contains("C++ output is not yet supported"));
    }

    #[test]
    fn cli_overrides_style() {
        let toml_str = r#"
[c]
style = "Tag"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let overrides = CliOverrides {
            style: Some(Style::Type),
            cpp_compat: false,
        };
        let config_set = raw.into_config(&Language::C, &overrides).unwrap();
        match config_set.default {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Type));
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn cli_overrides_cpp_compat() {
        let raw: RawConfig = toml::from_str("").unwrap();
        let overrides = CliOverrides {
            style: None,
            cpp_compat: true,
        };
        let config_set = raw.into_config(&Language::C, &overrides).unwrap();
        match config_set.default {
            Config::C(c) => {
                assert!(c.cpp_compat);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn cxx_alias_parses() {
        let toml_str = r#"
[cxx]
preamble = "/* C++ */"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert!(raw.cxx.is_some());
    }

    #[test]
    fn package_opaque_mode() {
        let toml_str = r#"
[package.my-dep]
types = "opaque"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            raw.package["my-dep"].types,
            Some(PackageTypeMode::Opaque)
        );
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert_eq!(
                    c.common.package_configs["my-dep"].types,
                    Some(PackageTypeMode::Opaque)
                );
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn package_skip_mode() {
        let toml_str = r#"
[package.other-dep]
types = "skip"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            raw.package["other-dep"].types,
            Some(PackageTypeMode::Skip)
        );
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert_eq!(
                    c.common.package_configs["other-dep"].types,
                    Some(PackageTypeMode::Skip)
                );
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn package_versioned_key() {
        let toml_str = r#"
[package."foo@1.0"]
types = "opaque"

[package."foo@2.0"]
types = "skip"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(raw.package.len(), 2);
        assert_eq!(
            raw.package["foo@1.0"].types,
            Some(PackageTypeMode::Opaque)
        );
        assert_eq!(
            raw.package["foo@2.0"].types,
            Some(PackageTypeMode::Skip)
        );
    }

    #[test]
    fn package_empty_section_accepted() {
        let toml_str = r#"
[package.my-dep]
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert!(raw.package.contains_key("my-dep"));
        assert_eq!(raw.package["my-dep"].types, None);
        // Empty section produces no PackageConfig entry (types is None → filtered out)
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert!(c.common.package_configs.is_empty());
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn package_unknown_field_rejected() {
        let toml_str = r#"
[package.my-dep]
typos = "opaque"
"#;
        let result: Result<RawConfig, _> = toml::from_str(toml_str);
        assert!(result.is_err());
    }

    #[test]
    fn package_with_other_config() {
        let toml_str = r#"
preamble = "/* License */"

[package.my-dep]
types = "opaque"

[c]
style = "Tag"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                assert_eq!(c.common.preamble.as_deref(), Some("/* License */"));
                assert!(matches!(c.style, Style::Tag));
                assert_eq!(
                    c.common.package_configs["my-dep"].types,
                    Some(PackageTypeMode::Opaque)
                );
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn usize_is_size_t_global_default() {
        let raw: RawConfig = toml::from_str("").unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => assert!(!c.common.usize_is_size_t),
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn usize_is_size_t_global_set() {
        let raw: RawConfig = toml::from_str("usize_is_size_t = true").unwrap();
        assert_eq!(raw.usize_is_size_t, Some(true));
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => assert!(c.common.usize_is_size_t),
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn usize_is_size_t_per_package() {
        let toml_str = r#"
[package.my-dep]
usize_is_size_t = true
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(raw.package["my-dep"].usize_is_size_t, Some(true));
        // Per-package section materializes even without `types` set.
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                let pkg = c
                    .common
                    .package_configs
                    .get("my-dep")
                    .expect("package_configs entry should exist");
                assert_eq!(pkg.types, None);
                assert_eq!(pkg.usize_is_size_t, Some(true));
                assert!(!c.common.usize_is_size_t);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn usize_is_size_t_per_package_with_types() {
        let toml_str = r#"
[package.my-dep]
types = "opaque"
usize_is_size_t = false
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        match config_set.default {
            Config::C(c) => {
                let pkg = &c.common.package_configs["my-dep"];
                assert_eq!(pkg.types, Some(PackageTypeMode::Opaque));
                assert_eq!(pkg.usize_is_size_t, Some(false));
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn include_guard_rejected_at_global_level() {
        let toml_str = r#"
include_guard = "FOO_H"
"#;
        let result: Result<RawConfig, _> = toml::from_str(toml_str);
        assert!(result.is_err());
    }

    #[test]
    fn header_section_basic() {
        let toml_str = r#"
preamble = "/* Global */"

[header.my-lib]
include_guard = "MY_LIB_H"
preamble = "/* My Lib */"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        // Default config has no include_guard and global preamble.
        match &config_set.default {
            Config::C(c) => {
                assert!(c.common.include_guard.is_none());
                assert_eq!(c.common.preamble.as_deref(), Some("/* Global */"));
            }
            _ => panic!("expected Config::C"),
        }

        // Per-header config has include_guard and overridden preamble.
        match config_set.for_header("my-lib") {
            Config::C(c) => {
                assert_eq!(c.common.include_guard.as_deref(), Some("MY_LIB_H"));
                assert_eq!(c.common.preamble.as_deref(), Some("/* My Lib */"));
            }
            _ => panic!("expected Config::C"),
        }

        // Unknown crate falls back to default.
        match config_set.for_header("unknown") {
            Config::C(c) => {
                assert!(c.common.include_guard.is_none());
                assert_eq!(c.common.preamble.as_deref(), Some("/* Global */"));
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn header_section_inherits_global_language() {
        let toml_str = r#"
[c]
style = "Tag"
cpp_compat = true

[header.my-lib]
include_guard = "MY_LIB_H"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        // Per-header config inherits global [c] settings.
        match config_set.for_header("my-lib") {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Tag));
                assert!(c.cpp_compat);
                assert_eq!(c.common.include_guard.as_deref(), Some("MY_LIB_H"));
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn header_section_language_overrides_global() {
        let toml_str = r#"
[c]
style = "Tag"
cpp_compat = false

[header.my-lib]
include_guard = "MY_LIB_H"

[header.my-lib.c]
cpp_compat = true
style = "Type"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        // Default config uses global [c] settings.
        match &config_set.default {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Tag));
                assert!(!c.cpp_compat);
            }
            _ => panic!("expected Config::C"),
        }

        // Per-header config overrides global [c] settings.
        match config_set.for_header("my-lib") {
            Config::C(c) => {
                assert!(matches!(c.style, Style::Type));
                assert!(c.cpp_compat);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn header_section_common_overrides_global() {
        let toml_str = r#"
pragma_once = true
documentation = false

[header.my-lib]
pragma_once = false
documentation = true
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        match &config_set.default {
            Config::C(c) => {
                assert!(c.common.pragma_once);
                assert!(!c.common.documentation);
            }
            _ => panic!("expected Config::C"),
        }

        match config_set.for_header("my-lib") {
            Config::C(c) => {
                assert!(!c.common.pragma_once);
                assert!(c.common.documentation);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn header_section_override_priority() {
        // Tests the full priority chain:
        // [header.my-lib.c] > [header.my-lib] > [c] > top-level
        let toml_str = r#"
preamble = "/* top-level */"
documentation = false

[c]
preamble = "/* global-c */"

[header.my-lib]
preamble = "/* header-common */"
documentation = true

[header.my-lib.c]
preamble = "/* header-c */"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        // Default: [c] overrides top-level
        match &config_set.default {
            Config::C(c) => {
                assert_eq!(c.common.preamble.as_deref(), Some("/* global-c */"));
                assert!(!c.common.documentation);
            }
            _ => panic!("expected Config::C"),
        }

        // Per-header: [header.my-lib.c] > [header.my-lib] > [c] > top-level
        match config_set.for_header("my-lib") {
            Config::C(c) => {
                assert_eq!(c.common.preamble.as_deref(), Some("/* header-c */"));
                // documentation comes from [header.my-lib] common (not overridden in [header.my-lib.c])
                assert!(c.common.documentation);
            }
            _ => panic!("expected Config::C"),
        }
    }

    #[test]
    fn header_section_unknown_field_rejected() {
        let toml_str = r#"
[header.my-lib]
typo_field = "value"
"#;
        let result: Result<RawConfig, _> = toml::from_str(toml_str);
        assert!(result.is_err());
    }

    #[test]
    fn header_section_empty_is_valid() {
        let toml_str = r#"
[header.my-lib]
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();
        // Empty header section produces a per-header config identical to default.
        assert!(config_set.per_header.contains_key("my-lib"));
    }

    #[test]
    fn multiple_header_sections() {
        let toml_str = r#"
preamble = "/* Global */"

[header.lib-a]
include_guard = "LIB_A_H"
preamble = "/* Lib A */"

[header.lib-b]
include_guard = "LIB_B_H"
"#;
        let raw: RawConfig = toml::from_str(toml_str).unwrap();
        let config_set = raw
            .into_config(&Language::C, &CliOverrides::default())
            .unwrap();

        match config_set.for_header("lib-a") {
            Config::C(c) => {
                assert_eq!(c.common.include_guard.as_deref(), Some("LIB_A_H"));
                assert_eq!(c.common.preamble.as_deref(), Some("/* Lib A */"));
            }
            _ => panic!("expected Config::C"),
        }

        match config_set.for_header("lib-b") {
            Config::C(c) => {
                assert_eq!(c.common.include_guard.as_deref(), Some("LIB_B_H"));
                // Inherits global preamble since not overridden.
                assert_eq!(c.common.preamble.as_deref(), Some("/* Global */"));
            }
            _ => panic!("expected Config::C"),
        }
    }

    /// Drift guard: every TOML key produced by serializing a fully-populated
    /// `RawConfig` must appear in `cheadergen/src/config_reference.rs`.
    ///
    /// The instances below use struct expressions without `..Default::default()`,
    /// so the compiler refuses to build them after a new field is added until
    /// the test is updated — at which point this assertion catches missing
    /// documentation in the user-facing reference page.
    #[test]
    fn config_reference_documents_every_field() {
        const PACKAGE_DUMMY: &str = "cheadergen-test-package-dummy";
        const HEADER_DUMMY: &str = "cheadergen-test-header-dummy";

        let raw_c = RawCSection {
            style: Some(Style::Both),
            cpp_compat: Some(true),
            preamble: Some("p".into()),
            trailer: Some("t".into()),
            autogen_warning: Some("w".into()),
            pragma_once: Some(true),
            includes: Some(vec!["x".into()]),
            no_includes: Some(true),
            after_includes: Some("a".into()),
            documentation: Some(true),
            documentation_style: Some(DocumentationStyle::Auto),
            documentation_length: Some(DocumentationLength::Full),
        };
        let raw_cxx = RawCxxSection {
            preamble: Some("p".into()),
            trailer: Some("t".into()),
            autogen_warning: Some("w".into()),
            pragma_once: Some(true),
            includes: Some(vec!["x".into()]),
            no_includes: Some(true),
            after_includes: Some("a".into()),
            documentation: Some(true),
            documentation_style: Some(DocumentationStyle::Auto),
            documentation_length: Some(DocumentationLength::Full),
        };
        let raw_header = RawHeaderSection {
            include_guard: Some("G".into()),
            preamble: Some("p".into()),
            trailer: Some("t".into()),
            autogen_warning: Some("w".into()),
            pragma_once: Some(true),
            includes: Some(vec!["x".into()]),
            no_includes: Some(true),
            after_includes: Some("a".into()),
            documentation: Some(true),
            documentation_style: Some(DocumentationStyle::Auto),
            documentation_length: Some(DocumentationLength::Full),
            sort_by: Some(SortKey::Name),
            fn_: Some(RawFnSection {
                sort_by: Some(SortKey::Name),
            }),
            static_: Some(RawStaticSection {
                sort_by: Some(SortKey::Name),
            }),
            constant_: Some(RawConstantSection {
                sort_by: Some(SortKey::Name),
            }),
            enum_: Some(RawEnumSection {
                prefix_with_name: Some(true),
            }),
            c: Some(raw_c.clone()),
            cxx: Some(raw_cxx.clone()),
        };
        let raw_package = RawPackageConfig {
            types: Some(PackageTypeMode::Opaque),
            header_name: Some("name".into()),
            usize_is_size_t: Some(true),
        };
        let max = RawConfig {
            preamble: Some("p".into()),
            trailer: Some("t".into()),
            autogen_warning: Some("w".into()),
            pragma_once: Some(true),
            includes: vec!["x".into()],
            no_includes: Some(true),
            after_includes: Some("a".into()),
            documentation: Some(true),
            documentation_style: Some(DocumentationStyle::Auto),
            documentation_length: Some(DocumentationLength::Full),
            sort_by: Some(SortKey::Name),
            fn_: Some(RawFnSection {
                sort_by: Some(SortKey::Name),
            }),
            static_: Some(RawStaticSection {
                sort_by: Some(SortKey::Name),
            }),
            constant_: Some(RawConstantSection {
                sort_by: Some(SortKey::Name),
            }),
            enum_: Some(RawEnumSection {
                prefix_with_name: Some(true),
            }),
            bundle: Some(true),
            usize_is_size_t: Some(true),
            package: BTreeMap::from([(PACKAGE_DUMMY.to_string(), raw_package)]),
            header: HashMap::from([(HEADER_DUMMY.to_string(), raw_header)]),
            c: Some(raw_c),
            cxx: Some(raw_cxx),
        };

        let serialized = toml::to_string(&max).expect("serialize max RawConfig");
        let value: toml::Value = toml::from_str(&serialized).expect("re-parse serialized RawConfig");

        let mut keys: std::collections::HashSet<String> = std::collections::HashSet::new();
        let dynamic = [PACKAGE_DUMMY, HEADER_DUMMY];
        collect_table_keys(&value, &mut keys, &dynamic);

        let reference_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("cheadergen")
            .join("src")
            .join("config_reference.rs");
        let reference = std::fs::read_to_string(&reference_path)
            .unwrap_or_else(|e| panic!("failed to read {}: {e}", reference_path.display()));

        let mut missing: Vec<&String> = keys
            .iter()
            .filter(|k| !contains_word(&reference, k))
            .collect();
        missing.sort();

        assert!(
            missing.is_empty(),
            "{} does not mention these TOML keys: {:?}.\n\
             Did you add a field to a Raw* config struct without updating the user-facing reference?",
            reference_path.display(),
            missing,
        );
    }

    fn collect_table_keys(
        value: &toml::Value,
        out: &mut std::collections::HashSet<String>,
        skip: &[&str],
    ) {
        match value {
            toml::Value::Table(table) => {
                for (key, child) in table {
                    if !skip.contains(&key.as_str()) {
                        out.insert(key.clone());
                    }
                    collect_table_keys(child, out, skip);
                }
            }
            toml::Value::Array(items) => {
                for item in items {
                    collect_table_keys(item, out, skip);
                }
            }
            _ => {}
        }
    }

    fn contains_word(haystack: &str, word: &str) -> bool {
        let bytes = haystack.as_bytes();
        let len = word.len();
        let mut start = 0;
        while let Some(rel) = haystack[start..].find(word) {
            let i = start + rel;
            let before_is_word = i > 0 && is_ident_byte(bytes[i - 1]);
            let after = i + len;
            let after_is_word = after < bytes.len() && is_ident_byte(bytes[after]);
            if !before_is_word && !after_is_word {
                return true;
            }
            start = i + 1;
        }
        false
    }

    fn is_ident_byte(b: u8) -> bool {
        b.is_ascii_alphanumeric() || b == b'_'
    }
}