gloam 0.1.4

Loader generator for Vulkan, OpenGL, OpenGL ES, EGL, GLX, and WGL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
//! Feature-set resolution.
//!
//! Takes a `RawSpec` plus the user's API requests and produces a `FeatureSet`
//! with all arrays indexed, range tables built, and alias pairs computed.
//! This is the bridge between the parser and the code generators.

use std::collections::{HashMap, HashSet};

use anyhow::Result;
use indexmap::IndexMap;
use serde::Serialize;

use crate::cli::{ApiRequest, Cli};
use crate::fetch;
use crate::ir::{RawCommand, RawSpec};
use crate::parse;
use crate::parse::commands::infer_vulkan_scope;
use crate::parse::types::ident_words;

// ---------------------------------------------------------------------------
// FeatureSet — the resolved, indexed output
// ---------------------------------------------------------------------------

/// Everything a code generator needs, fully indexed and sorted.
#[derive(Debug, Serialize)]
pub struct FeatureSet {
    /// "gl", "egl", "glx", "wgl", "vk"
    pub spec_name: String,
    /// Display name: "GL", "EGL", "GLX", "WGL", "Vulkan"
    pub display_name: String,
    /// API names active in this feature set (may be multiple for merged builds).
    pub apis: Vec<String>,
    pub is_merged: bool,
    pub is_vulkan: bool,
    pub is_gl_family: bool,
    /// C context struct name, e.g. "GloamGLContext", "GloamGLES2Context".
    /// Precomputed so templates can use it directly without a filter.
    pub context_name: String,

    /// Version features, in ascending version order.
    /// featArray index = position in this Vec.
    pub features: Vec<Feature>,

    /// Extensions, alphabetically sorted by name.
    /// extArray index = position in this Vec.
    pub extensions: Vec<Extension>,

    /// All commands, in declaration order (core version order then ext order).
    /// pfnArray index = position in this Vec.
    pub commands: Vec<Command>,

    /// Types to emit (in dependency order).
    pub types: Vec<TypeDef>,

    /// GL-style flat #define constants.
    pub flat_enums: Vec<FlatEnum>,

    /// Vulkan typed enum groups.
    pub enum_groups: Vec<EnumGroup>,

    /// Feature PFN range table (shared across APIs in a merged build).
    pub feature_pfn_ranges: Vec<PfnRange>,

    /// Per-API extension PFN range tables.
    /// Key = api name (e.g. "gl", "gles2").
    pub ext_pfn_ranges: IndexMap<String, Vec<PfnRange>>,

    /// Per-API extension index subsets for s_extIdx[] in find_extensions_*.
    /// Key = api name.  Value = extArray indices relevant to that API.
    pub ext_subset_indices: IndexMap<String, Vec<u16>>,

    /// Bijective alias pairs.  Empty unless --alias was requested.
    pub alias_pairs: Vec<AliasPair>,

    /// Auxiliary headers that must be copied to the output include tree.
    /// Derived from the `requires=` attributes of selected types.
    /// Paths are relative to the include root, e.g. "KHR/khrplatform.h".
    pub required_headers: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct Feature {
    pub index: u16,
    /// Short name with no API prefix, e.g. "VERSION_3_3".
    pub short_name: String,
    /// Full feature name, e.g. "GL_VERSION_3_3".
    pub full_name: String,
    pub version: SerVersion,
    /// Packed (major << 8 | minor) — used for version comparison in find_core_*.
    pub packed: u16,
    /// Which API this feature belongs to, e.g. "gl", "gles2".
    /// Used in templates to filter features per-API in merged builds.
    pub api: String,
}

#[derive(Debug, Serialize)]
pub struct SerVersion {
    pub major: u32,
    pub minor: u32,
}

#[derive(Debug, Serialize)]
pub struct Extension {
    pub index: u16,
    /// Full extension name e.g. "GL_ANGLE_framebuffer_blit".
    pub name: String,
    /// Short name (no API prefix) e.g. "ANGLE_framebuffer_blit".
    pub short_name: String,
    /// Pre-baked XXH3_64 hash as "0x...ULL" literal.
    pub hash: String,
    /// Platform protection macros (if any).
    pub protect: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct Command {
    pub index: u16,
    /// Full name e.g. "glCullFace"
    pub name: String,
    /// Member name in the context struct e.g. "CullFace"
    pub short_name: String,
    /// PFN typedef name e.g. "PFNGLCULLFACEPROC"
    pub pfn_type: String,
    /// C return type text e.g. "void", "const GLubyte *"
    pub return_type: String,
    /// Formatted parameter list for PFN typedef (empty → "void").
    pub params_str: String,
    /// Full params for IntelliSense prototypes.
    pub params: Vec<Param>,
    /// Vulkan scope name (empty string for non-Vulkan).
    pub scope: String,
    /// Platform guard macro (if any).
    pub protect: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct Param {
    pub type_raw: String,
    pub name: String,
}

#[derive(Debug, Serialize)]
pub struct TypeDef {
    /// The canonical type name as declared in the spec.
    pub name: String,
    pub raw_c: String,
    pub category: String,
    /// Platform protection macros.  Empty = unconditional.
    pub protect: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct FlatEnum {
    pub name: String,
    pub value: String,
    pub comment: String,
}

#[derive(Debug, Serialize)]
pub struct EnumGroup {
    pub name: String,
    pub is_bitmask: bool,
    pub bitwidth: u32,
    pub values: Vec<FlatEnum>,
}

#[derive(Debug, Serialize, Clone, Copy)]
pub struct PfnRange {
    /// Index into featArray or extArray.
    pub extension: u16,
    /// First pfnArray index covered by this range.
    pub start: u16,
    /// Number of consecutive pfnArray slots.
    pub count: u16,
}

#[derive(Debug, Serialize)]
pub struct AliasPair {
    pub canonical: u16,
    pub secondary: u16,
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

pub fn build_feature_sets(cli: &Cli) -> Result<Vec<FeatureSet>> {
    let requests = cli.api_requests()?;
    let ext_filter = cli.extension_filter()?;
    let promoted = cli.promoted;
    let predecessors = cli.predecessors;

    let alias = match &cli.generator {
        crate::cli::Generator::C(c) => c.alias,
        crate::cli::Generator::Rust(r) => r.alias,
    };

    // Group requests by spec family only for merged builds.
    // For non-merged builds, resolve each API request independently
    // so the generator produces separate files per API.
    let mut feature_sets = Vec::new();

    if cli.merge {
        let mut by_spec: IndexMap<String, Vec<ApiRequest>> = IndexMap::new();
        for req in requests {
            by_spec
                .entry(req.spec_name().to_string())
                .or_default()
                .push(req);
        }
        for (spec_name, reqs) in &by_spec {
            let sources = fetch::load_spec(spec_name, cli.fetch)?;
            let raw = parse::parse(&sources, spec_name)?;
            let fs =
                resolve_feature_set(&raw, reqs, &ext_filter, true, alias, promoted, predecessors)?;
            feature_sets.push(fs);
        }
    } else {
        for req in &requests {
            let spec_name = req.spec_name();
            let sources = fetch::load_spec(spec_name, cli.fetch)?;
            let raw = parse::parse(&sources, spec_name)?;
            let fs = resolve_feature_set(
                &raw,
                std::slice::from_ref(req),
                &ext_filter,
                false,
                alias,
                promoted,
                predecessors,
            )?;
            feature_sets.push(fs);
        }
    }

    Ok(feature_sets)
}

// ---------------------------------------------------------------------------
// Core resolution
// ---------------------------------------------------------------------------

fn resolve_feature_set(
    raw: &RawSpec,
    requests: &[ApiRequest],
    ext_filter: &Option<Vec<String>>,
    is_merged: bool,
    want_aliases: bool,
    want_promoted: bool,
    want_predecessors: bool,
) -> Result<FeatureSet> {
    let spec_name = &raw.spec_name;
    let is_vulkan = spec_name == "vk";
    let is_gl_family = matches!(spec_name.as_str(), "gl" | "egl" | "glx" | "wgl");

    let display_name = match spec_name.as_str() {
        "gl" => "GL",
        "egl" => "EGL",
        "glx" => "GLX",
        "wgl" => "WGL",
        "vk" => "Vulkan",
        _ => spec_name.as_str(),
    };

    let api_names: Vec<String> = requests.iter().map(|r| r.name.clone()).collect();

    // ------------------------------------------------------------------
    // Step 1: Determine which features (versions) are selected.
    // ------------------------------------------------------------------
    let selected_features = select_features(raw, requests);

    // ------------------------------------------------------------------
    // Step 2: Collect required names from selected features.
    // ------------------------------------------------------------------
    let mut req_types: HashSet<String> = HashSet::new();
    let mut req_enums: HashSet<String> = HashSet::new();
    let mut req_commands: IndexMap<String, ()> = IndexMap::new(); // preserves order
    let mut removed_commands: HashSet<String> = HashSet::new();
    let mut removed_enums: HashSet<String> = HashSet::new();
    // Per-API core command sets used by --promoted to scope promotion checks.
    // Keyed by API name (e.g. "gl", "gles2"); values exclude profile-removed commands.
    let mut per_api_core_cmds: HashMap<String, HashSet<String>> = HashMap::new();

    for feat in &selected_features {
        let req_for_api = requests.iter().find(|r| r.name == feat.api);
        let profile = req_for_api.and_then(|r| r.profile.as_deref());
        let api_cmds = per_api_core_cmds.entry(feat.api.clone()).or_default();

        for require in &feat.raw.requires {
            if !api_profile_matches(
                require.api.as_deref(),
                require.profile.as_deref(),
                &feat.api,
                profile,
            ) {
                continue;
            }
            req_types.extend(require.types.iter().cloned());
            req_enums.extend(require.enums.iter().cloned());
            for cmd in &require.commands {
                req_commands.entry(cmd.clone()).or_insert(());
                api_cmds.insert(cmd.clone());
            }
        }
        for remove in &feat.raw.removes {
            if !profile_matches(remove.profile.as_deref(), profile) {
                continue;
            }
            removed_commands.extend(remove.commands.iter().cloned());
            removed_enums.extend(remove.enums.iter().cloned());
            // Apply removes inline — features are processed in version order so
            // each version's removes are applied immediately after its requires.
            for cmd in &remove.commands {
                api_cmds.remove(cmd.as_str());
            }
        }
    }
    for cmd in &removed_commands {
        req_commands.shift_remove(cmd.as_str());
    }

    // ------------------------------------------------------------------
    // Step 3: Determine which extensions are selected.
    // ------------------------------------------------------------------
    let selected_exts = select_extensions(
        raw,
        requests,
        ext_filter,
        spec_name,
        &per_api_core_cmds,
        want_promoted,
        want_predecessors,
    );

    // ------------------------------------------------------------------
    // Step 4: Collect additional required names from extensions.
    // ------------------------------------------------------------------
    let mut ext_commands: IndexMap<String, usize> = IndexMap::new(); // cmd -> ext_index

    for (ext_idx, ext) in selected_exts.iter().enumerate() {
        for require in &ext.raw.requires {
            for api in &api_names {
                if !api_profile_matches(require.api.as_deref(), None, api, None) {
                    continue;
                }
                req_types.extend(require.types.iter().cloned());
                req_enums.extend(require.enums.iter().cloned());
                for e in &require.enums {
                    removed_enums.remove(e.as_str());
                }
                for cmd in &require.commands {
                    // Core commands already in req_commands stay there.
                    if !req_commands.contains_key(cmd.as_str()) {
                        ext_commands.entry(cmd.clone()).or_insert(ext_idx);
                    }
                }
            }
        }
    }

    for e in &removed_enums {
        req_enums.remove(e.as_str());
    }

    // ------------------------------------------------------------------
    // Step 5: Build the indexed command list.
    // Core functions first (in req_commands order), then extension functions.
    // ------------------------------------------------------------------
    let core_cmd_names: Vec<String> = req_commands.keys().cloned().collect();
    let ext_cmd_names: Vec<String> = ext_commands.keys().cloned().collect();

    let all_cmd_names: Vec<&str> = core_cmd_names
        .iter()
        .chain(ext_cmd_names.iter())
        .map(String::as_str)
        .collect();

    let pfn_prefix = api_pfn_prefix(spec_name);
    let name_prefix = api_name_prefix(spec_name);

    let mut commands: Vec<Command> = Vec::with_capacity(all_cmd_names.len());
    for (idx, &cmd_name) in all_cmd_names.iter().enumerate() {
        let raw_cmd = match raw.commands.get(cmd_name) {
            Some(c) => c,
            None => {
                eprintln!("warning: command '{}' required but not in spec", cmd_name);
                continue;
            }
        };

        let scope = if is_vulkan {
            infer_vulkan_scope(raw_cmd).c_name().to_string()
        } else {
            String::new()
        };

        let protect = find_command_protect(raw, cmd_name, &selected_exts);

        commands.push(build_command(
            idx as u16,
            raw_cmd,
            &scope,
            protect,
            pfn_prefix,
            name_prefix,
        ));
    }

    // ------------------------------------------------------------------
    // Step 6: Build indexed feature and extension lists.
    // ------------------------------------------------------------------
    let features: Vec<Feature> = selected_features
        .iter()
        .enumerate()
        .map(|(i, sf)| {
            let ver = &sf.raw.version;
            let short = version_short_name(&sf.raw.name, &sf.api);
            Feature {
                index: i as u16,
                full_name: sf.raw.name.clone(),
                short_name: short,
                version: SerVersion {
                    major: ver.major,
                    minor: ver.minor,
                },
                packed: ver.packed(),
                api: sf.api.clone(),
            }
        })
        .collect();

    // Extensions are sorted alphabetically.
    let mut sorted_exts: Vec<_> = selected_exts.iter().collect();
    sorted_exts.sort_by_key(|e| e.raw.name.as_str());

    let extensions: Vec<Extension> = sorted_exts
        .iter()
        .enumerate()
        .map(|(i, e)| build_extension(i as u16, e))
        .collect();

    // Ext name → sorted index (for building range tables).
    let ext_index_map: HashMap<&str, u16> = extensions
        .iter()
        .map(|e| (e.name.as_str(), e.index))
        .collect();

    // ------------------------------------------------------------------
    // Step 7: Build PFN range tables.
    // ------------------------------------------------------------------
    let feature_pfn_ranges = build_feature_pfn_ranges(&selected_features, &features, &commands);

    // Per-API extension PFN ranges and subset indices.
    let mut ext_pfn_ranges: IndexMap<String, Vec<PfnRange>> = IndexMap::new();
    let mut ext_subset_indices: IndexMap<String, Vec<u16>> = IndexMap::new();

    for api in &api_names {
        let (ranges, indices) = build_ext_pfn_ranges(
            api,
            &selected_exts,
            &ext_commands,
            &ext_index_map,
            &commands,
        );
        ext_pfn_ranges.insert(api.clone(), ranges);
        ext_subset_indices.insert(api.clone(), indices);
    }

    // ------------------------------------------------------------------
    // Step 8: Types to emit.
    // ------------------------------------------------------------------
    // Iteratively expand req_types to a fixed point: any type referenced
    // in the raw_c of a selected type must itself be selected.  This catches
    // member pointer types like VkPipelineLibraryCreateInfoKHR that are used
    // inside required structs but never appear in any <require><type> block.
    // Auto-included categories (define/basetype/bitmask/funcpointer/enum/
    // handle) are also treated as seeds for the expansion.
    if is_vulkan {
        let type_names: HashSet<&str> = raw.types.iter().map(|t| t.name.as_str()).collect();

        // Seed req_types with parameter and return types from all selected commands.
        // This catches types that are only referenced as command parameters rather
        // than being explicitly listed in <require><type> blocks — e.g.
        // VkViewportSwizzleNV appears only as a parameter of vkCmdSetViewportSwizzleNV,
        // which VK_EXT_shader_object pulls in without also selecting VK_NV_viewport_swizzle.
        for &cmd_name in &all_cmd_names {
            if let Some(raw_cmd) = raw.commands.get(cmd_name) {
                for param in &raw_cmd.params {
                    if !param.type_name.is_empty() {
                        req_types.insert(param.type_name.clone());
                    }
                }
            }
        }

        loop {
            let mut added = false;
            for t in &raw.types {
                if t.raw_c.is_empty() {
                    continue;
                }
                let auto = matches!(
                    t.category.as_str(),
                    "define" | "basetype" | "bitmask" | "funcpointer" | "enum" | "handle"
                );
                if !auto && !req_types.contains(&t.name) {
                    continue;
                }
                for word in crate::parse::types::ident_words(&t.raw_c) {
                    if type_names.contains(word) && req_types.insert(word.to_string()) {
                        added = true;
                    }
                }
            }
            if !added {
                break;
            }
        }
    }

    let types = build_type_list(raw, &req_types, spec_name, is_vulkan);

    // ------------------------------------------------------------------
    // Step 9: Flat enums and enum groups.
    // ------------------------------------------------------------------
    let flat_enums = build_flat_enums(raw, &req_enums, is_vulkan);
    let enum_groups = build_enum_groups(raw);

    // ------------------------------------------------------------------
    // Step 10: Alias pairs (optional).
    // ------------------------------------------------------------------
    let alias_pairs = if want_aliases {
        build_alias_pairs(raw, &commands)
    } else {
        Vec::new()
    };

    let required_headers = collect_required_headers(raw, &req_types, spec_name);

    let context_name = build_context_name(spec_name);

    Ok(FeatureSet {
        spec_name: spec_name.clone(),
        display_name: display_name.to_string(),
        apis: api_names,
        is_merged,
        is_vulkan,
        is_gl_family,
        context_name,
        features,
        extensions,
        commands,
        types,
        flat_enums,
        enum_groups,
        feature_pfn_ranges,
        ext_pfn_ranges,
        ext_subset_indices,
        alias_pairs,
        required_headers,
    })
}

// ---------------------------------------------------------------------------
// Feature selection
// ---------------------------------------------------------------------------

struct SelectedFeature<'a> {
    api: String,
    raw: &'a crate::ir::RawFeature,
}

fn select_features<'a>(raw: &'a RawSpec, requests: &[ApiRequest]) -> Vec<SelectedFeature<'a>> {
    let mut selected = Vec::new();
    for req in requests {
        let max_ver = req.version.clone();
        for feat in &raw.features {
            if feat.api != req.name {
                continue;
            }
            if let Some(ref mv) = max_ver
                && feat.version > *mv
            {
                continue;
            }
            selected.push(SelectedFeature {
                api: req.name.clone(),
                raw: feat,
            });
        }
    }
    // Sort: GL versions first, then GLES, matching the spec's ordering rule.
    selected.sort_by(|a, b| {
        api_order(&a.api)
            .cmp(&api_order(&b.api))
            .then_with(|| a.raw.version.cmp(&b.raw.version))
    });
    selected
}

fn api_order(api: &str) -> u8 {
    match api {
        "gl" | "glcore" => 0,
        "gles1" => 1,
        "gles2" => 2,
        "egl" => 3,
        "glx" => 4,
        "wgl" => 5,
        "vk" | "vulkan" => 6,
        _ => 7,
    }
}

// ---------------------------------------------------------------------------
// Extension selection
// ---------------------------------------------------------------------------

struct SelectedExt<'a> {
    raw: &'a crate::ir::RawExtension,
}

fn select_extensions<'a>(
    raw: &'a RawSpec,
    requests: &[ApiRequest],
    filter: &Option<Vec<String>>,
    spec_name: &str,
    per_api_core_cmds: &HashMap<String, HashSet<String>>,
    want_promoted: bool,
    want_predecessors: bool,
) -> Vec<SelectedExt<'a>> {
    let api_set: HashSet<&str> = requests.iter().map(|r| r.name.as_str()).collect();
    // WGL mandatory extensions (spec gotcha #9).
    let wgl_mandatory: HashSet<&str> = if spec_name == "wgl" {
        ["WGL_ARB_extensions_string", "WGL_EXT_extensions_string"]
            .iter()
            .copied()
            .collect()
    } else {
        HashSet::new()
    };

    let mut selected: Vec<SelectedExt<'a>> = raw
        .extensions
        .iter()
        .filter(|e| {
            let supported = e.supported.iter().any(|s| api_set.contains(s.as_str()));
            if !supported {
                return false;
            }
            if wgl_mandatory.contains(e.name.as_str()) {
                return true;
            }
            match filter {
                None => true,
                Some(list) => list.contains(&e.name),
            }
        })
        .map(|e| SelectedExt { raw: e })
        .collect();

    // Build the bidirectional alias maps once — they're used by both the
    // --promoted and --predecessors passes.
    let cmd_to_alias: HashMap<&str, &str> = if want_promoted || want_predecessors {
        let mut m = HashMap::new();
        for (name, cmd) in &raw.commands {
            if let Some(ref alias) = cmd.alias {
                m.insert(name.as_str(), alias.as_str());
                m.insert(alias.as_str(), name.as_str());
            }
        }
        m
    } else {
        HashMap::new()
    };
    let enum_to_alias: HashMap<&str, &str> = if want_predecessors {
        let mut m = HashMap::new();
        for (name, e) in &raw.flat_enums {
            if let Some(ref alias) = e.alias {
                m.insert(name.as_str(), alias.as_str());
                m.insert(alias.as_str(), name.as_str());
            }
        }
        m
    } else {
        HashMap::new()
    };

    if want_promoted {
        // Snapshot names already selected so we don't duplicate them.
        let already: HashSet<&str> = selected.iter().map(|e| e.raw.name.as_str()).collect();

        for ext in &raw.extensions {
            if already.contains(ext.name.as_str()) {
                continue;
            }

            // An extension is considered promoted if, for at least one API A that:
            //   (a) the extension claims to support, and
            //   (b) we are generating,
            // any of the extension's commands for that API appear in A's core
            // command set — either directly (same-name promotion) or via the
            // alias graph (renamed promotion, e.g. glActiveTextureARB → glActiveTexture).
            //
            // Checking per-API (rather than against the unified req_commands) prevents
            // cross-contamination in merged builds: a GLES2-only extension whose
            // commands happen to match GLES2 core will not be auto-included for gl:core.
            let is_promoted = ext
                .supported
                .iter()
                .filter(|s| api_set.contains(s.as_str()))
                .any(|api| {
                    let Some(core_cmds) = per_api_core_cmds.get(api.as_str()) else {
                        return false;
                    };
                    ext.requires
                        .iter()
                        // Only consider require blocks that apply to this API.
                        .filter(|req| api_profile_matches(req.api.as_deref(), None, api, None))
                        .any(|req| {
                            req.commands.iter().any(|c| {
                                // Same-name promotion: the command landed in core
                                // with the same name (e.g. ARB_copy_buffer →
                                // glCopyBufferSubData is unchanged).
                                core_cmds.contains(c.as_str())
                                    // Renamed promotion: the command has an alias
                                    // that is in core (e.g. glActiveTextureARB →
                                    // glActiveTexture).
                                    || cmd_to_alias
                                        .get(c.as_str())
                                        .is_some_and(|a| core_cmds.contains(*a))
                            })
                        })
                });

            if is_promoted {
                selected.push(SelectedExt { raw: ext });
            }
        }
    }

    if want_predecessors {
        // Build the set of all commands contributed by the currently selected
        // extensions (after --promoted may have expanded the set).
        // An unselected extension is a "predecessor" of the selected set if any
        // of its commands are aliases of commands in this set — i.e. the
        // extension was superseded by one already selected.
        //
        // We iterate to a fixed point because adding a predecessor may itself
        // have predecessors not yet in the set.
        loop {
            // Collect commands from all currently selected extensions.
            let selected_ext_cmds: HashSet<&str> = selected
                .iter()
                .flat_map(|e| {
                    e.raw
                        .requires
                        .iter()
                        .flat_map(|req| req.commands.iter().map(String::as_str))
                })
                .collect();

            // Collect enums from all currently selected extensions.
            let selected_ext_enums: HashSet<&str> = selected
                .iter()
                .flat_map(|e| {
                    e.raw
                        .requires
                        .iter()
                        .flat_map(|req| req.enums.iter().map(String::as_str))
                })
                .collect();

            let already: HashSet<&str> = selected.iter().map(|e| e.raw.name.as_str()).collect();

            let mut added_any = false;
            for ext in &raw.extensions {
                if already.contains(ext.name.as_str()) {
                    continue;
                }
                let supported = ext.supported.iter().any(|s| api_set.contains(s.as_str()));
                if !supported {
                    continue;
                }
                let is_predecessor = ext.requires.iter().any(|req| {
                    // Check if this extension's command or enum is in the selected set directly, or
                    // its alias is — meaning a newer extension absorbed it.
                    req.commands.iter().any(|c| {
                        selected_ext_cmds.contains(c.as_str())
                            || cmd_to_alias
                                .get(c.as_str())
                                .is_some_and(|a| selected_ext_cmds.contains(*a))
                    }) || req.enums.iter().any(|e| {
                        selected_ext_enums.contains(e.as_str())
                            || enum_to_alias
                                .get(e.as_str())
                                .is_some_and(|a| selected_ext_enums.contains(*a))
                    })
                });
                if is_predecessor {
                    selected.push(SelectedExt { raw: ext });
                    added_any = true;
                }
            }

            if !added_any {
                break;
            }
        }
    }

    selected
}

// ---------------------------------------------------------------------------
// Building the Command entry
// ---------------------------------------------------------------------------

fn build_command(
    index: u16,
    raw: &RawCommand,
    scope: &str,
    protect: Option<String>,
    pfn_prefix: &str,
    name_prefix: &str,
) -> Command {
    let short_name = raw
        .name
        .strip_prefix(name_prefix)
        .unwrap_or(&raw.name)
        .to_string();

    let pfn_type = if pfn_prefix == "PFN_" {
        // Vulkan: PFN_vkFoo
        format!("PFN_{}", raw.name)
    } else {
        // GL family: PFNGLFOOPROC — strip the lowercase api prefix (e.g. "gl")
        // before uppercasing so we don't get PFNGLGLFOOPROC.
        let stem = raw.name.strip_prefix(name_prefix).unwrap_or(&raw.name);
        format!("{}{}PROC", pfn_prefix, stem.to_uppercase())
    };

    let params: Vec<Param> = raw
        .params
        .iter()
        .map(|p| Param {
            type_raw: p.type_raw.clone(),
            name: p.name.clone(),
        })
        .collect();

    let params_str = if params.is_empty() {
        "void".to_string()
    } else {
        params
            .iter()
            .map(|p| {
                if p.name.is_empty() {
                    p.type_raw.clone()
                } else if p.type_raw.trim_end().ends_with(']') {
                    // Array param: type_raw already contains the name and
                    // array suffix, e.g. "float blendConstants[4]".
                    // Emit verbatim — don't append the name again.
                    p.type_raw.trim().to_string()
                } else {
                    format!("{} {}", p.type_raw, p.name)
                }
            })
            .collect::<Vec<_>>()
            .join(", ")
    };

    Command {
        index,
        name: raw.name.clone(),
        short_name,
        pfn_type,
        return_type: raw.return_type.clone(),
        params_str,
        params,
        scope: scope.to_string(),
        protect,
    }
}

// ---------------------------------------------------------------------------
// Building the Extension entry
// ---------------------------------------------------------------------------

fn build_extension(index: u16, e: &SelectedExt<'_>) -> Extension {
    use xxhash_rust::xxh3::xxh3_64;

    let hash_val = xxh3_64(e.raw.name.as_bytes());
    // No ULL suffix — templates append it at the point of use.
    let hash = format!("0x{:016x}", hash_val);
    let short = ext_short_name(&e.raw.name);

    Extension {
        index,
        name: e.raw.name.clone(),
        short_name: short,
        hash,
        protect: e.raw.protect.clone(),
    }
}

// ---------------------------------------------------------------------------
// Context struct name
// ---------------------------------------------------------------------------

fn build_context_name(spec: &str) -> String {
    let display = match spec {
        "gl" => "GL",
        "egl" => "EGL",
        "glx" => "GLX",
        "wgl" => "WGL",
        "vk" => "Vulkan",
        other => other,
    };
    format!("Gloam{}Context", display)
}

/// Strip API prefix from extension name: "GL_ARB_sync" → "ARB_sync".
fn ext_short_name(name: &str) -> String {
    for prefix in &["GL_", "EGL_", "GLX_", "WGL_", "VK_"] {
        if let Some(s) = name.strip_prefix(prefix) {
            return s.to_string();
        }
    }
    name.to_string()
}

/// Strip version prefix: "GL_VERSION_3_3" → "VERSION_3_3".
fn version_short_name(name: &str, api: &str) -> String {
    let prefix = match api {
        "gl" | "glcore" => "GL_",
        "gles1" | "gles2" => "GL_",
        "egl" => "EGL_",
        "glx" => "GLX_",
        "wgl" => "WGL_",
        "vk" | "vulkan" => "VK_",
        _ => "",
    };
    name.strip_prefix(prefix).unwrap_or(name).to_string()
}

// ---------------------------------------------------------------------------
// PFN range table construction
// ---------------------------------------------------------------------------

fn build_feature_pfn_ranges(
    features: &[SelectedFeature<'_>],
    feat_entries: &[Feature],
    commands: &[Command],
) -> Vec<PfnRange> {
    // Build a map: command name → pfnArray index.
    let cmd_index: HashMap<&str, u16> = commands
        .iter()
        .map(|c| (c.name.as_str(), c.index))
        .collect();

    let mut ranges: Vec<PfnRange> = Vec::new();

    for feat in feat_entries {
        // Find the commands belonging to this feature.
        let sf = match features.iter().find(|f| f.raw.name == feat.full_name) {
            Some(f) => f,
            None => continue,
        };

        let mut cmd_indices: Vec<u16> = Vec::new();
        for require in &sf.raw.requires {
            for cmd_name in &require.commands {
                if let Some(&idx) = cmd_index.get(cmd_name.as_str()) {
                    cmd_indices.push(idx);
                }
            }
        }
        cmd_indices.sort_unstable();
        cmd_indices.dedup();

        ranges.extend(indices_to_ranges(feat.index, &cmd_indices));
    }

    ranges
}

fn build_ext_pfn_ranges(
    api: &str,
    exts: &[SelectedExt<'_>],
    _ext_commands: &IndexMap<String, usize>, // cmd -> ext index in `exts` (reserved)
    ext_index_map: &HashMap<&str, u16>,      // ext name -> sorted ext index
    commands: &[Command],
) -> (Vec<PfnRange>, Vec<u16>) {
    let cmd_index: HashMap<&str, u16> = commands
        .iter()
        .map(|c| (c.name.as_str(), c.index))
        .collect();

    let mut ranges: Vec<PfnRange> = Vec::new();
    let mut subset_indices: Vec<u16> = Vec::new();

    // Collect extensions relevant to this API.
    let relevant_exts: Vec<(usize, &SelectedExt)> = exts
        .iter()
        .enumerate()
        .filter(|(_, e)| e.raw.supported.iter().any(|s| s == api))
        .collect();

    for (_orig_idx, ext) in &relevant_exts {
        let sorted_ext_idx = match ext_index_map.get(ext.raw.name.as_str()) {
            Some(&i) => i,
            None => continue,
        };

        subset_indices.push(sorted_ext_idx);

        // Commands belonging to this extension for this API.
        let mut cmd_indices: Vec<u16> = Vec::new();
        for require in &ext.raw.requires {
            if !api_profile_matches(require.api.as_deref(), None, api, None) {
                continue;
            }
            for cmd_name in &require.commands {
                if let Some(&pfn_idx) = cmd_index.get(cmd_name.as_str()) {
                    cmd_indices.push(pfn_idx);
                }
            }
        }
        cmd_indices.sort_unstable();
        cmd_indices.dedup();

        ranges.extend(indices_to_ranges(sorted_ext_idx, &cmd_indices));
    }

    subset_indices.sort_unstable();
    (ranges, subset_indices)
}

/// Convert a sorted list of pfnArray indices belonging to the same feature/ext
/// into one or more PfnRange entries (one per contiguous run).
fn indices_to_ranges(ext_idx: u16, sorted: &[u16]) -> Vec<PfnRange> {
    if sorted.is_empty() {
        return Vec::new();
    }
    let mut ranges = Vec::new();
    let mut start = sorted[0];
    let mut count = 1u16;

    for &idx in &sorted[1..] {
        if idx == start + count {
            count += 1;
        } else {
            ranges.push(PfnRange {
                extension: ext_idx,
                start,
                count,
            });
            start = idx;
            count = 1;
        }
    }
    ranges.push(PfnRange {
        extension: ext_idx,
        start,
        count,
    });
    ranges
}

// ---------------------------------------------------------------------------
// Types list
// ---------------------------------------------------------------------------

fn build_type_list(
    raw: &RawSpec,
    req_types: &HashSet<String>,
    spec_name: &str,
    is_vulkan: bool,
) -> Vec<TypeDef> {
    let gl_auto_exclude: HashSet<&str> = ["stddef", "khrplatform", "inttypes"]
        .iter()
        .copied()
        .collect();

    // Always infer include protections — Vulkan needs it for WSI headers,
    // and GL needs it to correctly guard khrplatform and eglplatform includes.
    let include_protections = infer_include_protections(raw);
    let ext_type_protect = build_ext_type_protections(raw);

    let type_list: Vec<TypeDef> = raw
        .types
        .iter()
        .filter(|t| {
            // Empty raw_c → nothing to emit.
            if t.raw_c.is_empty() {
                return false;
            }
            // Enum-category types: plain enums have no direct C emission
            // (their values are emitted via enum groups).  Alias-only enum
            // types (e.g. VkComponentTypeNV = VkComponentTypeKHR) DO need a
            // typedef emission and must pass through the filter.
            if t.category == "enum" && t.raw_c.is_empty() {
                return false;
            }
            // Include-category types: emit only if infer_include_protections
            // decided they're needed (i.e. at least one selected extension
            // depends on a type that requires this include file).
            if t.category == "include" {
                return include_protections.contains_key(&t.name);
            }
            // `define` and `basetype` types (VK_DEFINE_HANDLE, VkFlags,
            // VkBool32, etc.) are not listed in any <require> block but must
            // always be emitted for the matching API, like GL auto-includes.
            // `bitmask` typedefs are also thin wrappers never explicitly
            // required.  Struct/union/handle/funcpointer/enum are only emitted
            // when a feature or extension explicitly requires them.
            if is_vulkan {
                let auto = matches!(
                    t.category.as_str(),
                    "define" | "basetype" | "bitmask" | "funcpointer" | "enum" | "handle"
                );
                if auto {
                    return t
                        .api
                        .as_deref()
                        .is_none_or(|a| a.split(',').any(|s| s.trim() == "vulkan"));
                }
                return req_types.contains(&t.name);
            }
            // GL family: auto-include all API-compatible types except the
            // excluded ones (spec gotcha #5 exclusions).
            if gl_auto_exclude.contains(t.name.as_str()) {
                return false;
            }
            req_types.contains(&t.name) || t.api.as_deref().is_none_or(|a| a == spec_name)
        })
        .map(|t| {
            // For include-category types, use the inferred protection list.
            // For all others, use the type's own protect attribute.
            let protect = if t.category == "include" {
                include_protections
                    .get(&t.name)
                    .cloned()
                    .unwrap_or_default()
            } else {
                // Prefer extension-derived protection over the type's own
                // protect= attribute.  Many Vulkan structs are protected only
                // via the extension that introduces them (e.g. platform="win32"
                // on the extension) and have no protect= on the <type> element.
                if let Some(p) = ext_type_protect.get(t.name.as_str()) {
                    p.clone()
                } else {
                    t.protect.iter().cloned().collect()
                }
            };
            TypeDef {
                name: t.name.clone(),
                raw_c: normalize_raw_c(&t.raw_c),
                category: t.category.clone(),
                protect,
            }
        })
        .collect::<Vec<TypeDef>>();
    topo_sort_typedefs(type_list)
}

/// Topological sort on a `Vec<TypeDef>`.
///
/// A type A depends on B if B's name appears as a word in A's raw_c.
/// We only create dep edges when scanning struct/union/funcpointer raw_c —
/// other categories (define, basetype, etc.) don't have bodies that reference
/// other types in ordering-relevant ways, and scanning them can create false
/// cycle edges.
///
/// Cycle fallback: stranded types are sorted among themselves (types used by
/// others in the same cycle come first) before being appended.
fn topo_sort_typedefs(types: Vec<TypeDef>) -> Vec<TypeDef> {
    let n = types.len();
    if n < 2 {
        return types;
    }

    // name → index map using TypeDef.name (reliable, no raw_c parsing needed).
    let mut name_to_idx: HashMap<&str, usize> = HashMap::new();
    for (i, t) in types.iter().enumerate() {
        name_to_idx.insert(t.name.as_str(), i);
    }

    // Only scan struct/union/funcpointer bodies for deps.  Other categories
    // either have no meaningful body (define is a macro, basetype/bitmask are
    // simple typedefs) or would introduce false cycles.
    let scan_cats: &[&str] = &["struct", "union", "funcpointer"];

    let deps: Vec<Vec<usize>> = types
        .iter()
        .enumerate()
        .map(|(i, t)| {
            let mut d: Vec<usize> = Vec::new();
            if scan_cats.contains(&t.category.as_str()) {
                for word in crate::parse::types::ident_words(&t.raw_c) {
                    if word == t.name.as_str() {
                        continue;
                    }
                    if let Some(&dep_idx) = name_to_idx.get(word)
                        && dep_idx != i
                    {
                        d.push(dep_idx);
                    }
                }
                d.sort_unstable();
                d.dedup();
            }
            d
        })
        .collect();

    let mut in_degree: Vec<usize> = deps.iter().map(|d| d.len()).collect();
    let mut rev: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (i, dep_list) in deps.iter().enumerate() {
        for &dep in dep_list {
            rev[dep].push(i);
        }
    }

    let mut queue: std::collections::VecDeque<usize> =
        (0..n).filter(|&i| in_degree[i] == 0).collect();
    let mut order: Vec<usize> = Vec::with_capacity(n);
    while let Some(node) = queue.pop_front() {
        order.push(node);
        for &dependent in &rev[node] {
            in_degree[dependent] -= 1;
            if in_degree[dependent] == 0 {
                queue.push_back(dependent);
            }
        }
    }

    // Cycle fallback: sort stranded nodes so that if A's raw_c references
    // B's name, B comes before A.
    if order.len() < n {
        let mut stranded: Vec<usize> = (0..n).filter(|&i| in_degree[i] != 0).collect();
        // Build a simple ordering: if stranded[j] appears in stranded[k]'s raw_c,
        // stranded[j] should come before stranded[k].
        let stranded_names: std::collections::HashSet<usize> = stranded.iter().copied().collect();
        // Topological sort among just the stranded nodes.
        let mut s_in: HashMap<usize, usize> = HashMap::new();
        let mut s_rev: HashMap<usize, Vec<usize>> = HashMap::new();
        for &i in &stranded {
            s_in.insert(i, 0);
            s_rev.insert(i, Vec::new());
        }
        for &i in &stranded {
            for word in crate::parse::types::ident_words(&types[i].raw_c) {
                if let Some(&j) = name_to_idx.get(word)
                    && j != i
                    && stranded_names.contains(&j)
                {
                    *s_in.get_mut(&i).unwrap() += 1;
                    s_rev.get_mut(&j).unwrap().push(i);
                }
            }
        }
        // Deduplicate s_in counts (since ident_words may yield same word twice).
        // Simpler: just rebuild cleanly with dedup per node.
        let mut s_deps: HashMap<usize, std::collections::HashSet<usize>> = HashMap::new();
        for &i in &stranded {
            let mut deps_i = std::collections::HashSet::new();
            for word in crate::parse::types::ident_words(&types[i].raw_c) {
                if let Some(&j) = name_to_idx.get(word)
                    && j != i
                    && stranded_names.contains(&j)
                {
                    deps_i.insert(j);
                }
            }
            s_deps.insert(i, deps_i);
        }
        let mut s_in2: HashMap<usize, usize> =
            stranded.iter().map(|&i| (i, s_deps[&i].len())).collect();
        let mut s_rev2: HashMap<usize, Vec<usize>> =
            stranded.iter().map(|&i| (i, Vec::new())).collect();
        for &i in &stranded {
            for &j in &s_deps[&i] {
                s_rev2.get_mut(&j).unwrap().push(i);
            }
        }
        let mut s_queue: std::collections::VecDeque<usize> = stranded
            .iter()
            .filter(|&&i| s_in2[&i] == 0)
            .copied()
            .collect();
        let mut s_order: Vec<usize> = Vec::new();
        while let Some(node) = s_queue.pop_front() {
            s_order.push(node);
            for &dep in &s_rev2[&node] {
                let e = s_in2.get_mut(&dep).unwrap();
                *e -= 1;
                if *e == 0 {
                    s_queue.push_back(dep);
                }
            }
        }
        // Any still-stranded types append in original index order.
        let processed: std::collections::HashSet<usize> = s_order.iter().copied().collect();
        stranded.retain(|i| !processed.contains(i));
        s_order.extend(stranded);
        order.extend(s_order);
    }

    let mut out: Vec<Option<TypeDef>> = types.into_iter().map(Some).collect();
    order.into_iter().map(|i| out[i].take().unwrap()).collect()
}

// ---------------------------------------------------------------------------
// Include protection inference
// ---------------------------------------------------------------------------

/// For each `category="include"` type in the spec, determine what `#if`
/// protection it needs based on which extensions require types that depend
/// on that include file.
///
/// Algorithm (mirrors GLAD's `protections()` method):
///
///   - Collect all types that have `requires=<include_name>`.
///   - For each such type, find every selected extension that requires it.
///   - The include's protection = union of those extensions' protections.
///   - If any requiring extension is unprotected, the include is unconditional
///     (empty protection list).
///   - If no extension requires the type at all, the include is omitted.
///
/// Build a map from type name → protection macros derived purely from the
/// extensions that require that type.
///
/// This covers the common Vulkan pattern where a struct has no `protect=`
/// attribute on its `<type>` element but is required only inside an extension
/// with `platform="win32"` (or similar), making its protection implicit.
///
/// - `None` in the intermediate map = unconditional (required by an
///   unprotected extension).
/// - Missing from the map = not required by any extension (use the type's
///   own `protect=` attribute instead, or no guard).
fn build_ext_type_protections(raw: &RawSpec) -> HashMap<String, Vec<String>> {
    // type_name → Option<Vec<guards>>  (None = unconditional)
    let mut tmp: HashMap<&str, Option<Vec<String>>> = HashMap::new();

    for ext in &raw.extensions {
        for require in &ext.requires {
            for type_name in &require.types {
                let entry = tmp
                    .entry(type_name.as_str())
                    .or_insert_with(|| Some(Vec::new()));
                match entry {
                    None => {} // already unconditional
                    Some(guards) => {
                        if ext.protect.is_empty() {
                            *entry = None;
                        } else {
                            for p in &ext.protect {
                                if !guards.contains(p) {
                                    guards.push(p.clone());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Convert: None → empty Vec (unconditional), Some(guards) → guards.
    // Only include entries that were actually found in extension require blocks.
    tmp.into_iter()
        .map(|(name, state)| (name.to_string(), state.unwrap_or_default()))
        .collect()
}

/// Record protection guards for a single type name, used during include
/// protection inference.  Standalone function to avoid lifetime issues with
/// closures over HashMap<&str, ...>.
fn record_protect<'a>(
    name: &'a str,
    ext_protect: &[String],
    all_dep_names: &std::collections::HashSet<&str>,
    map: &mut HashMap<&'a str, Option<Vec<String>>>,
) {
    if !all_dep_names.contains(name) {
        return;
    }
    let entry = map.entry(name).or_insert_with(|| Some(Vec::new()));
    if let Some(guards) = entry {
        if ext_protect.is_empty() {
            *entry = None;
        } else {
            for p in ext_protect {
                if !guards.contains(p) {
                    guards.push(p.clone());
                }
            }
        }
    }
}

fn infer_include_protections(raw: &RawSpec) -> HashMap<String, Vec<String>> {
    // Step 1: include_name → set of type names that `requires=` it.
    // e.g. "X11/Xlib.h" → {"Display", "VisualID", "Window"}
    let include_names: std::collections::HashSet<&str> = raw
        .types
        .iter()
        .filter(|t| t.category == "include")
        .map(|t| t.name.as_str())
        .collect();

    let mut include_to_deps: HashMap<&str, std::collections::HashSet<&str>> = HashMap::new();
    for t in &raw.types {
        if t.category == "include" {
            continue;
        }
        if let Some(ref req) = t.requires
            && include_names.contains(req.as_str())
        {
            include_to_deps
                .entry(req.as_str())
                .or_default()
                .insert(t.name.as_str());
        }
    }

    // Step 2: dep_type_name → protection.
    //
    // Two sources:
    //   (a) Extensions that directly list the dep type in their <require> block
    //       (e.g. VK_KHR_xlib_surface requires "Display" explicitly).
    //   (b) Protected struct/union types whose raw_c TEXT contains the dep type
    //       name (e.g. VkXlibSurfaceCreateInfoKHR has a Display* member and
    //       lives under VK_USE_PLATFORM_XLIB_KHR).  This catches the case
    //       where the dep type is never listed in any <require> block.
    //
    // None  = unconditional (required by an unprotected context)
    // Some  = guarded by these macros
    let mut type_protect: HashMap<&str, Option<Vec<String>>> = HashMap::new();

    // Collect all dep names for fast membership tests in (b).
    let all_dep_names: std::collections::HashSet<&str> = include_to_deps
        .values()
        .flat_map(|s| s.iter().copied())
        .collect();

    // Source (a): extension require blocks — type names and command parameter
    // types.  Platform types like `Display` and `RROutput` often only appear
    // as command parameters, never as explicit <type> entries in <require>.
    for ext in &raw.extensions {
        for require in &ext.requires {
            // (a1) Explicitly listed type names.
            for type_name in &require.types {
                record_protect(
                    type_name.as_str(),
                    &ext.protect,
                    &all_dep_names,
                    &mut type_protect,
                );
            }
            // (a2) Parameter types of required commands.
            for cmd_name in &require.commands {
                if let Some(cmd) = raw.commands.get(cmd_name.as_str()) {
                    for param in &cmd.params {
                        record_protect(
                            param.type_name.as_str(),
                            &ext.protect,
                            &all_dep_names,
                            &mut type_protect,
                        );
                    }
                }
            }
        }
    }

    // Source (b): scan raw_c of every type that has a known protection.
    // Collect (type_name, protection) pairs first to avoid borrow conflicts.
    // Protection comes from the type's own protect= attr, OR from extensions
    // that require that type.
    let mut type_own_protect: HashMap<&str, Option<Vec<String>>> = HashMap::new();
    for t in &raw.types {
        if t.category == "include" || t.raw_c.is_empty() {
            continue;
        }
        if let Some(ref p) = t.protect {
            type_own_protect.insert(t.name.as_str(), Some(vec![p.clone()]));
        }
    }
    // Also derive struct protection from extension context (same as above).
    for ext in &raw.extensions {
        for require in &ext.requires {
            for type_name in &require.types {
                type_own_protect
                    .entry(type_name.as_str())
                    .or_insert_with(|| {
                        if ext.protect.is_empty() {
                            None
                        } else {
                            Some(ext.protect.clone())
                        }
                    });
            }
        }
    }

    for t in &raw.types {
        if t.raw_c.is_empty() || t.category == "include" {
            continue;
        }
        let struct_protect = match type_own_protect.get(t.name.as_str()) {
            None => continue,   // unprotected type, skip
            Some(None) => None, // unconditional context
            Some(Some(v)) => Some(v.as_slice()),
        };
        for word in ident_words(&t.raw_c) {
            if !all_dep_names.contains(word) {
                continue;
            }
            let entry = type_protect.entry(word).or_insert_with(|| Some(Vec::new()));
            match (entry.as_mut(), struct_protect) {
                (None, _) => {} // already unconditional
                (Some(_), None) => {
                    *entry = None;
                } // unconditional struct
                (Some(guards), Some(ps)) => {
                    for p in ps {
                        if !guards.contains(p) {
                            guards.push(p.to_string());
                        }
                    }
                }
            }
        }
    }

    // Step 3: for each include, union its dep types' protections.
    let mut result: HashMap<String, Vec<String>> = HashMap::new();

    for (include_name, dep_names) in &include_to_deps {
        let mut all_guards: std::collections::HashSet<String> = std::collections::HashSet::new();
        let mut unconditional = false;
        let mut any_found = false;

        for &dep_name in dep_names {
            if let Some(state) = type_protect.get(dep_name) {
                any_found = true;
                match state {
                    None => {
                        unconditional = true;
                        break;
                    }
                    Some(guards) => {
                        all_guards.extend(guards.iter().cloned());
                    }
                }
            }
        }

        if !any_found {
            continue;
        }

        if unconditional || all_guards.is_empty() {
            result.insert(include_name.to_string(), Vec::new());
        } else {
            let mut v: Vec<String> = all_guards.into_iter().collect();
            v.sort();
            result.insert(include_name.to_string(), v);
        }
    }

    result
}

// ---------------------------------------------------------------------------
// Required auxiliary headers
// ---------------------------------------------------------------------------

/// Scan the selected types for `requires=` attributes that map to auxiliary
/// header files that must be copied to the output include tree.
///
/// Returns paths relative to the include root, e.g. `"KHR/khrplatform.h"`.
/// Deduplication and insertion order are preserved via IndexMap.
fn collect_required_headers(
    raw: &RawSpec,
    req_types: &HashSet<String>,
    spec_name: &str,
) -> Vec<String> {
    let gl_auto_exclude: HashSet<&str> = ["stddef", "khrplatform", "inttypes"]
        .iter()
        .copied()
        .collect();

    let mut headers: IndexMap<String, ()> = IndexMap::new();

    for t in &raw.types {
        // Only consider types that were selected (same logic as build_type_list).
        let selected = if spec_name == "vk" {
            req_types.contains(&t.name)
        } else {
            !gl_auto_exclude.contains(t.name.as_str())
                && (req_types.contains(&t.name) || t.api.as_deref().is_none_or(|a| a == spec_name))
        };
        if !selected {
            continue;
        }

        if let Some(ref req) = t.requires
            && let Some(hdr) = requires_to_bundled_header(req)
        {
            headers.insert(hdr.to_string(), ());
        }
    }

    // Vulkan: vk_platform.h is always needed; vk_video headers are bundled
    // and must be copied when any *selected* type requires them.
    // Include-category types are never in req_types directly — check whether
    // any selected non-include type has `requires=` pointing to the header.
    if spec_name == "vk" {
        headers.insert("vk_platform.h".to_string(), ());

        // Build set of vk_video include names for fast lookup.
        let vk_video_includes: std::collections::HashSet<&str> = raw
            .types
            .iter()
            .filter(|t| t.category == "include" && t.name.starts_with("vk_video/"))
            .map(|t| t.name.as_str())
            .collect();

        for t in &raw.types {
            if t.category == "include" {
                continue;
            }
            if let Some(ref req) = t.requires
                && vk_video_includes.contains(req.as_str())
            {
                // This type is selected if it's in req_types OR is auto-included.
                let auto = matches!(
                    t.category.as_str(),
                    "define" | "basetype" | "bitmask" | "funcpointer" | "enum" | "handle"
                );
                if auto || req_types.contains(&t.name) {
                    headers.insert(req.clone(), ());
                }
            }
        }
    }

    headers.into_keys().collect()
}

/// Map a `requires=` value to a *bundled* header path we own and copy to the
/// output tree.  Returns None for system/WSI headers (X11/Xlib.h, windows.h,
/// etc.) which the user must provide themselves.
fn requires_to_bundled_header(requires: &str) -> Option<&'static str> {
    match requires {
        "khrplatform" => Some("KHR/khrplatform.h"),
        "eglplatform" => Some("EGL/eglplatform.h"),
        "vk_platform" => Some("vk_platform.h"),
        _ => None,
    }
}

fn normalize_raw_c(raw: &str) -> String {
    // Semicolons are added at construction time in types.rs; XML-sourced
    // content already includes them where required.  We only trim whitespace.
    raw.trim().to_string()
}

fn build_flat_enums(raw: &RawSpec, req_enums: &HashSet<String>, is_vulkan: bool) -> Vec<FlatEnum> {
    raw.flat_enums
        .iter()
        // For Vulkan, all flat enums are API constants (VK_MAX_DESCRIPTION_SIZE
        // etc.) that are never explicitly listed in <require> blocks but are
        // always needed.  For GL, only emit constants selected by the feature set.
        .filter(|(name, _)| is_vulkan || req_enums.contains(*name))
        .filter_map(|(_, e)| {
            let value = e.value.as_deref().or(e.alias.as_deref())?;
            Some(FlatEnum {
                name: e.name.clone(),
                value: value.to_string(),
                comment: e.comment.clone(),
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Enum groups (Vulkan)
// ---------------------------------------------------------------------------

fn build_enum_groups(raw: &RawSpec) -> Vec<EnumGroup> {
    raw.enum_groups
        .iter()
        .map(|g| {
            let raw_values: Vec<FlatEnum> = g
                .values
                .iter()
                .filter_map(|v| {
                    let val = v.value.as_deref().or(v.alias.as_deref())?;
                    Some(FlatEnum {
                        name: v.name.clone(),
                        value: val.to_string(),
                        comment: v.comment.clone(),
                    })
                })
                .collect();

            EnumGroup {
                name: g.name.clone(),
                is_bitmask: false,
                bitwidth: g.bitwidth.unwrap_or(32),
                values: sort_enum_values(raw_values),
            }
        })
        .collect()
}

/// Sort enum values so that any member whose value is a reference to another
/// member name is emitted after the member it references.
///
/// A value is a "reference" if it is not a numeric literal (decimal, hex,
/// or negative).  We do a single-pass Kahn topological sort; the input order
/// is preserved for values with no inter-dependencies.
fn sort_enum_values(values: Vec<FlatEnum>) -> Vec<FlatEnum> {
    let n = values.len();
    if n == 0 {
        return values;
    }

    // Build a name → index map.
    let name_to_idx: HashMap<&str, usize> = values
        .iter()
        .enumerate()
        .map(|(i, v)| (v.name.as_str(), i))
        .collect();

    // For each value, find the index of the value it depends on (if any).
    // A dependency exists when `value` is itself a member name — i.e. it
    // starts with VK_ (or any non-numeric, non-minus character) and is
    // present in name_to_idx.
    let deps: Vec<Option<usize>> = values
        .iter()
        .map(|v| {
            let val = v.value.trim();
            // Numeric literals: decimal, negative decimal, hex.
            let is_numeric = val.starts_with(|c: char| c.is_ascii_digit())
                || val.starts_with("0x")
                || val.starts_with("0X")
                || (val.starts_with('-') && val.len() > 1);
            if is_numeric {
                return None;
            }
            name_to_idx.get(val).copied()
        })
        .collect();

    // Kahn's algorithm: in-degree = 1 if the value has a dep, else 0.
    let mut in_degree: Vec<usize> = deps.iter().map(|d| d.is_some() as usize).collect();

    // rev[i] = list of values that depend on i.
    let mut rev: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (i, dep) in deps.iter().enumerate() {
        if let Some(d) = dep {
            rev[*d].push(i);
        }
    }

    let mut queue: std::collections::VecDeque<usize> =
        (0..n).filter(|&i| in_degree[i] == 0).collect();
    let mut order: Vec<usize> = Vec::with_capacity(n);

    while let Some(node) = queue.pop_front() {
        order.push(node);
        for &dep in &rev[node] {
            in_degree[dep] -= 1;
            if in_degree[dep] == 0 {
                queue.push_back(dep);
            }
        }
    }

    // Append any remaining nodes (cycles — shouldn't happen in practice).
    for (i, item) in in_degree.iter().enumerate().take(n) {
        if *item != 0 {
            order.push(i);
        }
    }

    let mut out: Vec<Option<FlatEnum>> = values.into_iter().map(Some).collect();
    order.into_iter().map(|i| out[i].take().unwrap()).collect()
}

// ---------------------------------------------------------------------------
// Alias pairs
// ---------------------------------------------------------------------------

fn build_alias_pairs(raw: &RawSpec, commands: &[Command]) -> Vec<AliasPair> {
    // Build name -> index map for quick lookup.
    let idx: HashMap<&str, u16> = commands
        .iter()
        .map(|c| (c.name.as_str(), c.index))
        .collect();

    // Group by canonical (shortest name).
    let mut groups: HashMap<String, Vec<String>> = HashMap::new();
    for (name, cmd) in &raw.commands {
        if let Some(ref alias) = cmd.alias {
            // Both must be in the selected command set.
            if !idx.contains_key(name.as_str()) || !idx.contains_key(alias.as_str()) {
                continue;
            }
            // Canonical = shortest name; if equal, alphabetical.
            let (canonical, secondary) = if alias.len() < name.len()
                || (alias.len() == name.len() && alias.as_str() < name.as_str())
            {
                (alias.clone(), name.clone())
            } else {
                (name.clone(), alias.clone())
            };
            groups.entry(canonical).or_default().push(secondary);
        }
    }

    let mut pairs: Vec<AliasPair> = Vec::new();
    for (canonical, secondaries) in groups {
        let Some(&ci) = idx.get(canonical.as_str()) else {
            continue;
        };
        for secondary in secondaries {
            let Some(&si) = idx.get(secondary.as_str()) else {
                continue;
            };
            pairs.push(AliasPair {
                canonical: ci,
                secondary: si,
            });
        }
    }

    // Sort by canonical index (the load loop depends on consecutive ordering).
    pairs.sort_by_key(|p| (p.canonical, p.secondary));
    pairs
}

// ---------------------------------------------------------------------------
// Utility: find platform protect for a command (from its extension).
// ---------------------------------------------------------------------------

fn find_command_protect(
    _raw: &RawSpec,
    cmd_name: &str,
    exts: &[SelectedExt<'_>],
) -> Option<String> {
    for ext in exts {
        for require in &ext.raw.requires {
            if require.commands.iter().any(|c| c == cmd_name)
                && let Some(p) = ext.raw.protect.first()
            {
                return Some(p.clone());
            }
        }
    }
    None
}

// ---------------------------------------------------------------------------
// API naming helpers
// ---------------------------------------------------------------------------

/// Prefix for PFN type names.
fn api_pfn_prefix(spec: &str) -> &'static str {
    match spec {
        "vk" => "PFN_",
        "gl" | "gles1" | "gles2" | "glcore" => "PFNGL",
        "egl" => "PFNEGL",
        "glx" => "PFNGLX",
        "wgl" => "PFNWGL",
        _ => "PFN",
    }
}

/// Prefix stripped from command names to get the short (struct member) name.
fn api_name_prefix(spec: &str) -> &'static str {
    match spec {
        "gl" | "gles1" | "gles2" | "glcore" => "gl",
        "egl" => "egl",
        "glx" => "glX",
        "wgl" => "wgl",
        "vk" | "vulkan" => "vk",
        _ => "",
    }
}

// ---------------------------------------------------------------------------
// Profile / API matching helpers
// ---------------------------------------------------------------------------

fn api_profile_matches(
    elem_api: Option<&str>,
    elem_profile: Option<&str>,
    target_api: &str,
    target_prof: Option<&str>,
) -> bool {
    if let Some(a) = elem_api
        && !a.split(',').any(|x| x.trim() == target_api)
    {
        return false;
    }
    profile_matches(elem_profile, target_prof)
}

fn profile_matches(elem_profile: Option<&str>, target_profile: Option<&str>) -> bool {
    match (elem_profile, target_profile) {
        (None, _) => true,
        (Some(_), None) => true,
        (Some(ep), Some(tp)) => ep == tp,
    }
}

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

    // ---- sort_enum_values ----

    fn make_enum(name: &str, value: &str) -> FlatEnum {
        FlatEnum {
            name: name.to_string(),
            value: value.to_string(),
            comment: String::new(),
        }
    }

    #[test]
    fn sort_enum_values_numeric_only_preserves_order() {
        let input = vec![
            make_enum("VK_FOO", "0"),
            make_enum("VK_BAR", "1"),
            make_enum("VK_BAZ", "2"),
        ];
        let out = sort_enum_values(input);
        assert_eq!(out[0].name, "VK_FOO");
        assert_eq!(out[1].name, "VK_BAR");
        assert_eq!(out[2].name, "VK_BAZ");
    }

    #[test]
    fn sort_enum_values_alias_placed_after_target() {
        // VK_ALIAS references VK_ORIGINAL; ALIAS must appear after ORIGINAL.
        let input = vec![
            make_enum("VK_ALIAS", "VK_ORIGINAL"),
            make_enum("VK_ORIGINAL", "42"),
        ];
        let out = sort_enum_values(input);
        let original_pos = out.iter().position(|e| e.name == "VK_ORIGINAL").unwrap();
        let alias_pos = out.iter().position(|e| e.name == "VK_ALIAS").unwrap();
        assert!(original_pos < alias_pos, "alias must come after its target");
    }

    #[test]
    fn sort_enum_values_empty_input() {
        assert!(sort_enum_values(vec![]).is_empty());
    }

    #[test]
    fn sort_enum_values_negative_numeric_not_treated_as_alias() {
        // A negative literal like "-1" must not be treated as a name reference.
        let input = vec![make_enum("VK_MAX", "-1"), make_enum("VK_ZERO", "0")];
        let out = sort_enum_values(input);
        // Both are numeric; original order preserved.
        assert_eq!(out[0].name, "VK_MAX");
        assert_eq!(out[1].name, "VK_ZERO");
    }

    #[test]
    fn sort_enum_values_hex_literal_not_treated_as_alias() {
        let input = vec![make_enum("VK_HEX", "0xFF"), make_enum("VK_OTHER", "0x00")];
        let out = sort_enum_values(input);
        assert_eq!(out[0].name, "VK_HEX");
        assert_eq!(out[1].name, "VK_OTHER");
    }

    // ---- profile_matches ----

    #[test]
    fn profile_matches_both_none() {
        assert!(profile_matches(None, None));
    }

    #[test]
    fn profile_matches_element_none_always_matches() {
        assert!(profile_matches(None, Some("core")));
        assert!(profile_matches(None, Some("compat")));
    }

    #[test]
    fn profile_matches_target_none_always_matches() {
        assert!(profile_matches(Some("core"), None));
    }

    #[test]
    fn profile_matches_same() {
        assert!(profile_matches(Some("core"), Some("core")));
    }

    #[test]
    fn profile_matches_different() {
        assert!(!profile_matches(Some("core"), Some("compat")));
    }

    // ---- api_pfn_prefix / api_name_prefix ----

    #[test]
    fn pfn_prefix_gl_family() {
        for api in &["gl", "gles1", "gles2", "glcore"] {
            assert_eq!(api_pfn_prefix(api), "PFNGL", "failed for '{api}'");
        }
    }

    #[test]
    fn pfn_prefix_vulkan() {
        assert_eq!(api_pfn_prefix("vk"), "PFN_");
    }

    #[test]
    fn name_prefix_gl_family() {
        assert_eq!(api_name_prefix("gl"), "gl");
        assert_eq!(api_name_prefix("gles1"), "gl");
        assert_eq!(api_name_prefix("gles2"), "gl");
    }

    #[test]
    fn name_prefix_glx_is_case_sensitive() {
        // glX — capital X matters for generated member names.
        assert_eq!(api_name_prefix("glx"), "glX");
    }
}