llvm-native-core 0.1.13

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! C ABI Bridge — Rust-to-C Foreign Function Interface for llvm-native.
//!
//! This module provides a stable, C-compatible ABI layer that enables
//! the use of llvm-native's compilation pipeline from C programs.
//! It serves as the foundation for self-hosting: the compiled llvm-native
//! binary can invoke its own compilation pipeline through the same ABI
//! that external C clients use.
//!
//! # Architecture
//!
//! ```text
//!   ┌──────────────┐     extern "C"      ┌──────────────────┐
//!   │  C Program   │ ──────────────────>  │  ABI Bridge      │
//!   │  (or stageN  │   compile_file(),     │  (this module)   │
//!   │   compiler)  │   compile_string(),   │                  │
//!   │              │   get_error(),        │  ┌────────────┐  │
//!   │              │   version()           │  │  ClangDriver│  │
//!   └──────────────┘                       │  └────────────┘  │
//!          ▲                               └──────────────────┘
//!          │  returns:                          │
//!          │  int (0=OK, -1=error)              │ calls into
//!          │  const char* (error msg / version) │ Rust pipeline
//!                                             ┌─▼──────────────┐
//!                                             │  Lexer -> Parse │
//!                                             │  -> Sema -> CG  │
//!                                             └─────────────────┘
//! ```
//!
//! # Self-Hosting Contract
//!
//! The ABI functions are designed so that a stage-1 llvm-native binary
//! (built by the system compiler) can call back into llvm-native's
//! own compilation logic. This enables the classic bootstrap sequence:
//!
//! 1. System C compiler builds llvm-native (stage0 output = stage1)
//! 2. Stage1 links against itself; extern "C" calls use the stage1
//!    implementation, yielding stage2
//! 3. Stage2 compiles itself; stage2 and stage3 are compared for
//!    bit-identical output to verify determinism
//!
//! # Thread Safety
//!
//! All public functions are thread-safe. Error state uses thread-local
//! storage so concurrent callers do not interfere.

use std::ffi::{CStr, CString};

use super::driver::ClangDriver;
use super::{CLangStandard, ClangOptions};

// ═══════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════

/// Semantic version of the llvm-native ABI bridge. Bumped on breaking
/// changes to the C ABI (struct layout changes, function signature
/// changes, semantic contract changes). This is separate from the
/// Rust crate version.
pub const LLVM_NATIVE_ABI_VERSION_MAJOR: u32 = 1;
pub const LLVM_NATIVE_ABI_VERSION_MINOR: u32 = 0;
pub const LLVM_NATIVE_ABI_VERSION_PATCH: u32 = 0;

/// The maximum length (in bytes) for a source file path or option string
/// passed over the ABI. C callers must not exceed this bound.
pub const LLVM_NATIVE_MAX_PATH: usize = 4096;
pub const LLVM_NATIVE_MAX_OPTIONS: usize = 65536;
pub const LLVM_NATIVE_MAX_ERROR: usize = 2048;

// ═══════════════════════════════════════════════════════════════════════════
// FFI-Safe Data Structures
// ═══════════════════════════════════════════════════════════════════════════

/// C-compatible language standard identifiers.
///
/// These correspond 1:1 with the Rust `CLangStandard` enum but use
/// explicit integer discriminants for ABI stability.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CLangStandardFFI {
    /// ISO C90 (ANSI C)
    C89 = 0,
    /// ISO C99
    C99 = 1,
    /// ISO C11
    C11 = 2,
    /// ISO C17 (also known as C18)
    C17 = 3,
    /// ISO C23
    C23 = 4,
    /// GNU C90
    Gnu89 = 5,
    /// GNU C99
    Gnu99 = 6,
    /// GNU C11
    Gnu11 = 7,
    /// GNU C17
    Gnu17 = 8,
}

/// Flags bitmask for compilation options.
///
/// Each bit controls a boolean compiler flag. This avoids adding
/// multiple boolean fields to the options struct, keeping the ABI
/// surface small and stable.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompileFlags {
    /// Bitmask of flags. Use the `CompileFlagBits` constants to test/set.
    pub bits: u64,
}

impl CompileFlags {
    /// No special flags.
    pub const fn none() -> Self {
        Self { bits: 0 }
    }

    /// Create a flags struct from a single bit.
    pub const fn from_bit(bit: u64) -> Self {
        Self { bits: bit }
    }

    /// Check whether a specific flag bit is set.
    pub fn has(&self, bit: u64) -> bool {
        self.bits & bit != 0
    }

    /// Set a specific flag bit.
    pub fn set(&mut self, bit: u64, val: bool) {
        if val {
            self.bits |= bit;
        } else {
            self.bits &= !bit;
        }
    }

    /// Combine two flag sets.
    pub fn merge(&self, other: &Self) -> Self {
        Self {
            bits: self.bits | other.bits,
        }
    }
}

/// Well-known bit flags for `CompileFlags.bits`.
pub mod compile_flag_bits {
    /// Enable optimization (-O1/-O2 equivalent).
    pub const OPTIMIZE: u64 = 1 << 0;
    /// Emit debug info (-g).
    pub const DEBUG_INFO: u64 = 1 << 1;
    /// Enable all warnings (-Wall).
    pub const WALL: u64 = 1 << 2;
    /// Treat warnings as errors (-Werror).
    pub const WERROR: u64 = 1 << 3;
    /// Enable pedantic warnings (-pedantic).
    pub const PEDANTIC: u64 = 1 << 4;
    /// Enable verbose diagnostics.
    pub const VERBOSE: u64 = 1 << 5;
    /// Disable all warnings (-w).
    pub const NO_WARNINGS: u64 = 1 << 6;
    /// Produce position-independent code (-fPIC).
    pub const PIC: u64 = 1 << 7;
    /// Emit LLVM IR instead of native code (-emit-llvm).
    pub const EMIT_LLVM: u64 = 1 << 8;
    /// Compile only, do not link (-c).
    pub const COMPILE_ONLY: u64 = 1 << 9;
    /// Enable all safe optimizations (-O2).
    pub const OPTIMIZE_MORE: u64 = 1 << 10;
    /// Optimize for size (-Oz).
    pub const OPTIMIZE_SIZE: u64 = 1 << 11;
    /// Enable LTO (Link-Time Optimization).
    pub const LTO: u64 = 1 << 12;
    /// Generate position-independent executable (-pie).
    pub const PIE: u64 = 1 << 13;
    /// Static linking (-static).
    pub const STATIC: u64 = 1 << 14;
    /// Enable sanitizer (address sanitizer).
    pub const SANITIZE_ADDRESS: u64 = 1 << 15;
    /// Enable undefined behavior sanitizer.
    pub const SANITIZE_UNDEFINED: u64 = 1 << 16;
    /// Enable thread sanitizer.
    pub const SANITIZE_THREAD: u64 = 1 << 17;
    /// Enable memory sanitizer.
    pub const SANITIZE_MEMORY: u64 = 1 << 18;
    /// Enable coverage instrumentation.
    pub const COVERAGE: u64 = 1 << 19;
    /// Enable profile-guided optimization generate mode.
    pub const PGO_GEN: u64 = 1 << 20;
    /// Enable profile-guided optimization use mode.
    pub const PGO_USE: u64 = 1 << 21;
    /// Enable control-flow integrity.
    pub const CFI: u64 = 1 << 22;
    /// Enable safe stack.
    pub const SAFE_STACK: u64 = 1 << 23;
    /// Enable shadow call stack.
    pub const SHADOW_CALL_STACK: u64 = 1 << 24;
    /// Produce a shared library (-shared).
    pub const SHARED: u64 = 1 << 25;
    /// Enable all warnings plus extra (-Wextra).
    pub const WEXTRA: u64 = 1 << 26;
    /// Dump AST before codegen (-ast-dump).
    pub const AST_DUMP: u64 = 1 << 27;
    /// Print timing information (-ftime-report).
    pub const TIME_REPORT: u64 = 1 << 28;
    /// Generate crash reproducer (-fcrash-diagnostics).
    pub const CRASH_DIAG: u64 = 1 << 29;
    /// Enable modules support (-fmodules).
    pub const MODULES: u64 = 1 << 30;
    /// Enable split dwarf (-gsplit-dwarf).
    pub const SPLIT_DWARF: u64 = 1 << 31;
}

/// C-compatible compilation options.
///
/// Passed over the FFI boundary to configure compiler behavior.
/// All string fields are NUL-terminated C strings or NULL for defaults.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct CompileOptionsFFI {
    /// Language standard (see `CLangStandardFFI`).
    pub standard: CLangStandardFFI,
    /// Flags bitmask (see `compile_flag_bits` and `CompileFlags`).
    pub flags: CompileFlags,
    /// Target triple (e.g. "x86_64-unknown-linux-gnu"). NULL = host default.
    pub target_triple: *const std::ffi::c_char,
    /// Output file path. NULL = infer from input.
    pub output_file: *const std::ffi::c_char,
    /// Semicolon-separated list of include paths. NULL = none.
    pub include_paths: *const std::ffi::c_char,
    /// Semicolon-separated list of macro definitions (e.g. "FOO=1;BAR").
    /// NULL = none.
    pub defines: *const std::ffi::c_char,
    /// Optimization level override (-O0 through -O3) as a single character.
    /// '0' = -O0, '1' = -O1, '2' = -O2, '3' = -O3, 'z' = -Oz, 's' = -Os.
    /// 'd' = debug (same as '0'), 'g' = same as '2'. 0xFF = use flags.
    pub opt_level_override: u8,
    /// Reserved for future use. Must be zero-initialized.
    pub _reserved: [u64; 4],
}

/// Return status of an ABI function.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompileResult {
    /// 0 on success, -1 on error.
    pub status: i32,
    /// Number of errors (0 on success).
    pub error_count: u32,
    /// Reserved for future use. Must be zero-initialized.
    pub _reserved: [u64; 4],
}

impl CompileResult {
    /// Create a success result.
    pub const fn success() -> Self {
        Self {
            status: 0,
            error_count: 0,
            _reserved: [0; 4],
        }
    }

    /// Create an error result.
    pub const fn error(count: u32) -> Self {
        Self {
            status: -1,
            error_count: count,
            _reserved: [0; 4],
        }
    }

    /// Returns true if the result indicates success.
    pub fn is_ok(&self) -> bool {
        self.status == 0
    }

    /// Returns true if the result indicates failure.
    pub fn is_err(&self) -> bool {
        self.status != 0
    }
}

/// Version information returned by the ABI.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct VersionInfoFFI {
    /// Major version number.
    pub major: u32,
    /// Minor version number.
    pub minor: u32,
    /// Patch version number.
    pub patch: u32,
    /// ABI compatibility tag. Incremented on breaking ABI changes.
    pub abi_version: u32,
    /// Reserved for future use. Must be zero-initialized.
    pub _reserved: [u64; 4],
}

impl VersionInfoFFI {
    /// The current version of the llvm-native ABI bridge.
    pub const fn current() -> Self {
        Self {
            major: LLVM_NATIVE_ABI_VERSION_MAJOR,
            minor: LLVM_NATIVE_ABI_VERSION_MINOR,
            patch: LLVM_NATIVE_ABI_VERSION_PATCH,
            abi_version: 1,
            _reserved: [0; 4],
        }
    }
}

/// ABI layout sanity check constants.
///
/// C callers can verify struct sizes match expectations at compile time
/// using `static_assert`. We export the expected sizes here.
pub mod abi_layout {
    use super::*;

    /// Expected size of `CompileOptionsFFI` in bytes.
    pub const COMPILE_OPTIONS_FFI_SIZE: usize = core::mem::size_of::<CompileOptionsFFI>();
    /// Expected size of `CompileResult` in bytes.
    pub const COMPILE_RESULT_SIZE: usize = core::mem::size_of::<CompileResult>();
    /// Expected size of `VersionInfoFFI` in bytes.
    pub const VERSION_INFO_FFI_SIZE: usize = core::mem::size_of::<VersionInfoFFI>();
    /// Expected size of `CompileFlags` in bytes.
    pub const COMPILE_FLAGS_SIZE: usize = core::mem::size_of::<CompileFlags>();
    /// Expected alignment of `CompileOptionsFFI`.
    pub const COMPILE_OPTIONS_FFI_ALIGN: usize = core::mem::align_of::<CompileOptionsFFI>();
    /// Expected alignment of `CompileResult`.
    pub const COMPILE_RESULT_ALIGN: usize = core::mem::align_of::<CompileResult>();
    /// Expected alignment of `VersionInfoFFI`.
    pub const VERSION_INFO_FFI_ALIGN: usize = core::mem::align_of::<VersionInfoFFI>();
}

// ═══════════════════════════════════════════════════════════════════════════
// Global / Thread-Local State
// ═══════════════════════════════════════════════════════════════════════════

/// Thread-local buffer for error messages.
///
/// Using thread-local storage means concurrent C callers never corrupt
/// each other's error state.
std::thread_local! {
    static LAST_ERROR: std::cell::RefCell<Option<CString>> = const { std::cell::RefCell::new(None) };
}

/// Global mutex protecting access to the compiler driver.
///
/// Only one compilation may be in flight at a time. This is acceptable
/// for a self-hosting bootstrap compiler where compilation is inherently
/// sequential per stage.
static DRIVER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

// ═══════════════════════════════════════════════════════════════════════════
// Type Conversion Helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Convert a C-compatible `CLangStandardFFI` value to the Rust
/// `CLangStandard` enum.
///
/// Returns `CLangStandard::C17` for unrecognized values (forward-compat).
#[allow(unreachable_patterns)]
pub fn standard_ffi_to_rust(val: CLangStandardFFI) -> CLangStandard {
    match val {
        CLangStandardFFI::C89 => CLangStandard::C89,
        CLangStandardFFI::C99 => CLangStandard::C99,
        CLangStandardFFI::C11 => CLangStandard::C11,
        CLangStandardFFI::C17 => CLangStandard::C17,
        CLangStandardFFI::C23 => CLangStandard::C23,
        CLangStandardFFI::Gnu89 => CLangStandard::Gnu89,
        CLangStandardFFI::Gnu99 => CLangStandard::Gnu99,
        CLangStandardFFI::Gnu11 => CLangStandard::Gnu11,
        CLangStandardFFI::Gnu17 => CLangStandard::Gnu17,
        // Unknown values map to C17 for forward-compatibility.
        _ => CLangStandard::C17,
    }
}

/// Convert a Rust `CLangStandard` to the C-compatible `CLangStandardFFI`.
pub fn standard_rust_to_ffi(val: CLangStandard) -> CLangStandardFFI {
    match val {
        CLangStandard::C89 => CLangStandardFFI::C89,
        CLangStandard::C99 => CLangStandardFFI::C99,
        CLangStandard::C11 => CLangStandardFFI::C11,
        CLangStandard::C17 => CLangStandardFFI::C17,
        CLangStandard::C23 => CLangStandardFFI::C23,
        CLangStandard::Gnu89 => CLangStandardFFI::Gnu89,
        CLangStandard::Gnu99 => CLangStandardFFI::Gnu99,
        CLangStandard::Gnu11 => CLangStandardFFI::Gnu11,
        CLangStandard::Gnu17 => CLangStandardFFI::Gnu17,
    }
}

/// Convert FFI compile flags and options into a Rust `ClangOptions` struct.
///
/// SAFETY: `opts` must be a valid, non-null pointer to a properly
/// initialized `CompileOptionsFFI`. String fields must point to valid
/// NUL-terminated C strings or be null.
pub unsafe fn compile_options_ffi_to_rust(opts: *const CompileOptionsFFI) -> ClangOptions { unsafe {
    if opts.is_null() {
        return ClangOptions::default();
    }

    let opts = &*opts;
    let flags = opts.flags;
    let mut rust_opts = ClangOptions::default();

    // Language standard
    rust_opts.standard = standard_ffi_to_rust(opts.standard);

    // Boolean flags from bitmask
    rust_opts.optimize =
        flags.has(compile_flag_bits::OPTIMIZE) || flags.has(compile_flag_bits::OPTIMIZE_MORE);
    rust_opts.debug_info = flags.has(compile_flag_bits::DEBUG_INFO);
    rust_opts.warnings = !flags.has(compile_flag_bits::NO_WARNINGS);
    rust_opts.pedantic = flags.has(compile_flag_bits::PEDANTIC);
    rust_opts.wall = flags.has(compile_flag_bits::WALL);
    rust_opts.werror = flags.has(compile_flag_bits::WERROR);
    rust_opts.verbose = flags.has(compile_flag_bits::VERBOSE);

    // Optimization level override
    if opts.opt_level_override != 0xFF {
        // Override the flag-based optimize setting
        rust_opts.optimize = match opts.opt_level_override {
            b'0' | b'd' => false,
            b'1' | b'2' | b'3' | b'g' | b's' | b'z' => true,
            _ => rust_opts.optimize,
        };
    }

    // Target triple
    if !opts.target_triple.is_null() {
        let cstr = CStr::from_ptr(opts.target_triple);
        if let Ok(s) = cstr.to_str() {
            rust_opts.target_triple = s.to_string();
        }
    }

    // Output file
    if !opts.output_file.is_null() {
        let cstr = CStr::from_ptr(opts.output_file);
        if let Ok(s) = cstr.to_str() {
            rust_opts.output_file = Some(s.to_string());
        }
    }

    // Include paths (semicolon-separated)
    if !opts.include_paths.is_null() {
        let cstr = CStr::from_ptr(opts.include_paths);
        if let Ok(s) = cstr.to_str() {
            for path in s.split(';') {
                let trimmed = path.trim();
                if !trimmed.is_empty() {
                    rust_opts.includes.push(trimmed.to_string());
                }
            }
        }
    }

    // Macro defines (semicolon-separated, each "NAME=VALUE" or "NAME")
    if !opts.defines.is_null() {
        let cstr = CStr::from_ptr(opts.defines);
        if let Ok(s) = cstr.to_str() {
            for def in s.split(';') {
                let trimmed = def.trim();
                if trimmed.is_empty() {
                    continue;
                }
                if let Some(eq_pos) = trimmed.find('=') {
                    let name = trimmed[..eq_pos].to_string();
                    let value = trimmed[eq_pos + 1..].to_string();
                    rust_opts.defines.push((name, Some(value)));
                } else {
                    rust_opts.defines.push((trimmed.to_string(), None));
                }
            }
        }
    }

    rust_opts
}}

/// Extract the version string for the llvm-native crate.
///
/// Format: "llvm-native x.y.z (ABI vN.M.P)"
pub fn crate_version_string() -> String {
    format!(
        "llvm-native {}.{}.{} (ABI v{}.{}.{})",
        LLVM_NATIVE_ABI_VERSION_MAJOR,
        LLVM_NATIVE_ABI_VERSION_MINOR,
        LLVM_NATIVE_ABI_VERSION_PATCH,
        env!("CARGO_PKG_VERSION_MAJOR"),
        env!("CARGO_PKG_VERSION_MINOR"),
        env!("CARGO_PKG_VERSION_PATCH"),
    )
}

/// Build an FFI version info struct.
pub fn ffi_version_info() -> VersionInfoFFI {
    VersionInfoFFI::current()
}

/// Check that an FFI options struct has valid fields.
///
/// Returns `Ok(())` if all fields appear valid, or an error string
/// describing the first problem found.
pub fn validate_ffi_options(opts: *const CompileOptionsFFI) -> Result<(), String> {
    if opts.is_null() {
        // NULL options are valid (means defaults).
        return Ok(());
    }

    let opts = unsafe { &*opts };

    // Check that reserved fields are zeroed.
    for (i, &word) in opts._reserved.iter().enumerate() {
        if word != 0 {
            return Err(format!(
                "CompileOptionsFFI._reserved[{}] is non-zero (0x{:016x}); must be zero for ABI compat",
                i, word
            ));
        }
    }

    // Validate string fields if non-null.
    if !opts.target_triple.is_null() {
        let cstr = unsafe { CStr::from_ptr(opts.target_triple) };
        if cstr.to_str().is_err() {
            return Err("target_triple is not valid UTF-8".into());
        }
    }

    if !opts.output_file.is_null() {
        let cstr = unsafe { CStr::from_ptr(opts.output_file) };
        if cstr.to_str().is_err() {
            return Err("output_file is not valid UTF-8".into());
        }
    }

    if !opts.include_paths.is_null() {
        let cstr = unsafe { CStr::from_ptr(opts.include_paths) };
        if cstr.to_str().is_err() {
            return Err("include_paths is not valid UTF-8".into());
        }
    }

    if !opts.defines.is_null() {
        let cstr = unsafe { CStr::from_ptr(opts.defines) };
        if cstr.to_str().is_err() {
            return Err("defines is not valid UTF-8".into());
        }
    }

    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════
// C-Compatible Extern "C" Functions
// ═══════════════════════════════════════════════════════════════════════════

/// Compile a C source file on disk.
///
/// `path` must be a NUL-terminated C string pointing to a readable file.
/// `options` must be a valid `CompileOptionsFFI*` or NULL (for defaults).
///
/// Returns 0 on success, -1 on error. On error, call `llvm_native_get_error()`
/// to retrieve the error message.
///
/// # Safety
///
/// - `path` must be a valid pointer to a NUL-terminated C string.
/// - `options` must be a valid pointer to a `CompileOptionsFFI`, or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn llvm_native_compile_file(
    path: *const std::ffi::c_char,
    options: *const CompileOptionsFFI,
) -> i32 { unsafe {
    // Validate path
    if path.is_null() {
        set_last_error("llvm_native_compile_file: path is null".into());
        return -1;
    }

    let path_str = match CStr::from_ptr(path).to_str() {
        Ok(s) => s.to_string(),
        Err(_) => {
            set_last_error("llvm_native_compile_file: path is not valid UTF-8".into());
            return -1;
        }
    };

    // Validate options
    if let Err(e) = validate_ffi_options(options) {
        set_last_error(format!("llvm_native_compile_file: invalid options: {}", e));
        return -1;
    }

    // Build Rust options from FFI options
    let rust_opts = unsafe { compile_options_ffi_to_rust(options) };
    let mut driver = ClangDriver::new(rust_opts);

    // Lock the driver (serialize compilation)
    let _lock = match DRIVER_LOCK.lock() {
        Ok(guard) => guard,
        Err(_poisoned) => {
            // Recover from a poisoned mutex — this should never happen
            // in normal operation, but we handle it gracefully.
            set_last_error("llvm_native_compile_file: internal lock poisoned".into());
            return -1;
        }
    };

    // Compile
    match driver.compile_file(&path_str) {
        Ok(_module) => {
            clear_last_error();
            0
        }
        Err(errors) => {
            let msg = errors.join("; ");
            set_last_error(msg);
            -1
        }
    }
}}

/// Compile a C source string directly.
///
/// `source` must be a NUL-terminated C string containing C source code.
/// `options` must be a valid `CompileOptionsFFI*` or NULL (for defaults).
///
/// Returns 0 on success, -1 on error. On error, call `llvm_native_get_error()`
/// to retrieve the error message.
///
/// # Safety
///
/// - `source` must be a valid pointer to a NUL-terminated C string.
/// - `options` must be a valid pointer to a `CompileOptionsFFI`, or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn llvm_native_compile_string(
    source: *const std::ffi::c_char,
    options: *const CompileOptionsFFI,
) -> i32 { unsafe {
    // Validate source
    if source.is_null() {
        set_last_error("llvm_native_compile_string: source is null".into());
        return -1;
    }

    let source_str = match CStr::from_ptr(source).to_str() {
        Ok(s) => s.to_string(),
        Err(_) => {
            set_last_error("llvm_native_compile_string: source is not valid UTF-8".into());
            return -1;
        }
    };

    // Validate options
    if let Err(e) = validate_ffi_options(options) {
        set_last_error(format!("llvm_native_compile_string: invalid options: {}", e));
        return -1;
    }

    // Build Rust options from FFI options
    let rust_opts = unsafe { compile_options_ffi_to_rust(options) };
    let mut driver = ClangDriver::new(rust_opts);

    // Lock the driver (serialize compilation)
    let _lock = match DRIVER_LOCK.lock() {
        Ok(guard) => guard,
        Err(_poisoned) => {
            set_last_error("llvm_native_compile_string: internal lock poisoned".into());
            return -1;
        }
    };

    // Compile
    match driver.compile_string(&source_str) {
        Ok(_module) => {
            clear_last_error();
            0
        }
        Err(errors) => {
            let msg = errors.join("; ");
            set_last_error(msg);
            -1
        }
    }
}}

/// Retrieve the last error message.
///
/// Returns a pointer to a NUL-terminated C string. The string is valid
/// until the next call to any llvm_native_* function on the same thread.
/// Returns NULL if there is no error.
///
/// The caller must NOT free the returned pointer.
#[unsafe(no_mangle)]
pub extern "C" fn llvm_native_get_error() -> *const std::ffi::c_char {
    LAST_ERROR.with(|cell| {
        let borrow = cell.borrow();
        match &*borrow {
            Some(cstr) => cstr.as_ptr(),
            None => std::ptr::null(),
        }
    })
}

/// Return the llvm-native version string.
///
/// Returns a pointer to a static NUL-terminated C string containing
/// version information. The string is valid for the lifetime of the
/// process. The caller must NOT free the returned pointer.
#[unsafe(no_mangle)]
pub extern "C" fn llvm_native_version() -> *const std::ffi::c_char {
    // Use a static CString that lives for the entire program.
    // Leaked once on first access — acceptable since it's process-lifetime.
    static VERSION_STRING: std::sync::OnceLock<std::ffi::CString> = std::sync::OnceLock::new();
    VERSION_STRING.get_or_init(|| {
        let ver = crate_version_string();
        std::ffi::CString::new(ver).expect("version string contains NUL")
    }).as_ptr()
}

/// Return the version information as a structured struct.
///
/// Writes version info into `out`, which must point to a valid
/// `VersionInfoFFI` struct. Returns 0 on success, -1 if `out` is NULL.
#[unsafe(no_mangle)]
pub extern "C" fn llvm_native_version_info(
    out: *mut VersionInfoFFI,
) -> i32 {
    if out.is_null() {
        return -1;
    }
    unsafe {
        *out = ffi_version_info();
    }
    0
}

/// Reset the thread-local error state.
///
/// After calling this, `llvm_native_get_error()` returns NULL until
/// the next error.
#[unsafe(no_mangle)]
pub extern "C" fn llvm_native_clear_error() {
    clear_last_error();
}

/// Validate compilation options without compiling.
///
/// Returns 0 if options are valid, -1 if invalid. On error,
/// `llvm_native_get_error()` provides details.
///
/// # Safety
///
/// `options` must be a valid pointer to a `CompileOptionsFFI`, or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn llvm_native_validate_options(
    options: *const CompileOptionsFFI,
) -> i32 {
    match validate_ffi_options(options) {
        Ok(()) => {
            clear_last_error();
            0
        }
        Err(e) => {
            set_last_error(format!("llvm_native_validate_options: {}", e));
            -1
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Internal Helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Store an error message in thread-local storage.
fn set_last_error(msg: String) {
    LAST_ERROR.with(|cell| {
        *cell.borrow_mut() = Some(
            CString::new(msg).unwrap_or_else(|_| CString::new("internal error: NUL in error").unwrap())
        );
    });
}

/// Clear the thread-local error state.
fn clear_last_error() {
    LAST_ERROR.with(|cell| {
        *cell.borrow_mut() = None;
    });
}

// ═══════════════════════════════════════════════════════════════════════════
// C Header File Content
// ═══════════════════════════════════════════════════════════════════════════

/// A complete C header file declaring the llvm-native ABI.
///
/// Users can write this string to a file (e.g., `llvm_native.h`) and
/// `#include` it in their C programs that link against llvm-native.
///
/// # Example usage writing the header:
///
/// ```rust,ignore
/// use std::fs;
/// fs::write("llvm_native.h", llvm_native_abi_header::HEADER_C)
///     .expect("write header file");
/// ```
pub mod llvm_native_abi_header {
    /// The C header file content.
    ///
    /// This is a complete, stand-alone header that declares all types,
    /// constants, and functions in the llvm-native C ABI.
    pub const HEADER_C: &str = r#"/*
 * llvm_native.h — C ABI for the llvm-native compiler pipeline.
 *
 * Auto-generated. Do not edit by hand.
 * ABI version: 1.0.0
 *
 * This header declares the C-compatible interface to llvm-native's
 * compilation pipeline. Link against libllvm_native_core.a or
 * the shared library build of llvm-native.
 *
 * Thread safety: All functions are thread-safe. Error state is
 * thread-local; concurrent callers do not interfere.
 */

#ifndef LLVM_NATIVE_ABI_H
#define LLVM_NATIVE_ABI_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stddef.h>
#include <stdint.h>

/* ═══════════════════════════════════════════════════════════════════════
 * Constants
 * ═══════════════════════════════════════════════════════════════════════ */

#define LLVM_NATIVE_ABI_VERSION_MAJOR 1
#define LLVM_NATIVE_ABI_VERSION_MINOR 0
#define LLVM_NATIVE_ABI_VERSION_PATCH 0

#define LLVM_NATIVE_MAX_PATH    4096
#define LLVM_NATIVE_MAX_OPTIONS 65536
#define LLVM_NATIVE_MAX_ERROR   2048

/* ═══════════════════════════════════════════════════════════════════════
 * Language Standards
 * ═══════════════════════════════════════════════════════════════════════ */

typedef enum llvm_native_standard {
    LLVM_NATIVE_C89   = 0,
    LLVM_NATIVE_C99   = 1,
    LLVM_NATIVE_C11   = 2,
    LLVM_NATIVE_C17   = 3,
    LLVM_NATIVE_C23   = 4,
    LLVM_NATIVE_GNU89 = 5,
    LLVM_NATIVE_GNU99 = 6,
    LLVM_NATIVE_GNU11 = 7,
    LLVM_NATIVE_GNU17 = 8,
} llvm_native_standard_t;

/* ═══════════════════════════════════════════════════════════════════════
 * Flag Bits (for use with compile_flags_t)
 * ═══════════════════════════════════════════════════════════════════════ */

#define LLVM_NATIVE_OPTIMIZE            (1ULL << 0)
#define LLVM_NATIVE_DEBUG_INFO          (1ULL << 1)
#define LLVM_NATIVE_WALL                (1ULL << 2)
#define LLVM_NATIVE_WERROR              (1ULL << 3)
#define LLVM_NATIVE_PEDANTIC            (1ULL << 4)
#define LLVM_NATIVE_VERBOSE             (1ULL << 5)
#define LLVM_NATIVE_NO_WARNINGS         (1ULL << 6)
#define LLVM_NATIVE_PIC                 (1ULL << 7)
#define LLVM_NATIVE_EMIT_LLVM           (1ULL << 8)
#define LLVM_NATIVE_COMPILE_ONLY        (1ULL << 9)
#define LLVM_NATIVE_OPTIMIZE_MORE       (1ULL << 10)
#define LLVM_NATIVE_OPTIMIZE_SIZE       (1ULL << 11)
#define LLVM_NATIVE_LTO                 (1ULL << 12)
#define LLVM_NATIVE_PIE                 (1ULL << 13)
#define LLVM_NATIVE_STATIC              (1ULL << 14)
#define LLVM_NATIVE_SANITIZE_ADDRESS    (1ULL << 15)
#define LLVM_NATIVE_SANITIZE_UNDEFINED  (1ULL << 16)
#define LLVM_NATIVE_SANITIZE_THREAD     (1ULL << 17)
#define LLVM_NATIVE_SANITIZE_MEMORY     (1ULL << 18)
#define LLVM_NATIVE_COVERAGE            (1ULL << 19)
#define LLVM_NATIVE_PGO_GEN             (1ULL << 20)
#define LLVM_NATIVE_PGO_USE             (1ULL << 21)
#define LLVM_NATIVE_CFI                 (1ULL << 22)
#define LLVM_NATIVE_SAFE_STACK          (1ULL << 23)
#define LLVM_NATIVE_SHADOW_CALL_STACK   (1ULL << 24)
#define LLVM_NATIVE_SHARED              (1ULL << 25)
#define LLVM_NATIVE_WEXTRA              (1ULL << 26)
#define LLVM_NATIVE_AST_DUMP            (1ULL << 27)
#define LLVM_NATIVE_TIME_REPORT         (1ULL << 28)
#define LLVM_NATIVE_CRASH_DIAG          (1ULL << 29)
#define LLVM_NATIVE_MODULES             (1ULL << 30)
#define LLVM_NATIVE_SPLIT_DWARF         (1ULL << 31)

/* ═══════════════════════════════════════════════════════════════════════
 * Data Structures
 * ═══════════════════════════════════════════════════════════════════════ */

/* Flags bitmask */
typedef struct llvm_native_compile_flags {
    uint64_t bits;
} llvm_native_compile_flags_t;

/* Compilation options passed to compile functions */
typedef struct llvm_native_compile_options {
    llvm_native_standard_t   standard;
    llvm_native_compile_flags_t flags;
    const char*              target_triple;     /* NULL = host default */
    const char*              output_file;       /* NULL = infer */
    const char*              include_paths;     /* semicolon-separated, NULL = none */
    const char*              defines;           /* semicolon-separated, NULL = none */
    uint8_t                  opt_level_override;/* '0'-'3','z','s','d','g', 0xFF=use flags */
    uint64_t                 _reserved[4];      /* must be zero */
} llvm_native_compile_options_t;

/* Compilation result */
typedef struct llvm_native_compile_result {
    int32_t  status;        /* 0 = success, -1 = error */
    uint32_t error_count;   /* number of errors on failure */
    uint64_t _reserved[4];  /* must be zero */
} llvm_native_compile_result_t;

/* Version information */
typedef struct llvm_native_version_info {
    uint32_t major;
    uint32_t minor;
    uint32_t patch;
    uint32_t abi_version;
    uint64_t _reserved[4];  /* must be zero */
} llvm_native_version_info_t;

/* ═══════════════════════════════════════════════════════════════════════
 * Compilation Functions
 * ═══════════════════════════════════════════════════════════════════════ */

/*
 * Compile a C source file.
 *
 * @param path     Path to the C source file.
 * @param options  Compilation options, or NULL for defaults.
 * @return 0 on success, -1 on error (call llvm_native_get_error()).
 */
int llvm_native_compile_file(const char* path,
                             const llvm_native_compile_options_t* options);

/*
 * Compile a C source string.
 *
 * @param source   C source code as a NUL-terminated string.
 * @param options  Compilation options, or NULL for defaults.
 * @return 0 on success, -1 on error (call llvm_native_get_error()).
 */
int llvm_native_compile_string(const char* source,
                               const llvm_native_compile_options_t* options);

/*
 * Get the last error message (thread-local).
 *
 * @return Pointer to a NUL-terminated error string, or NULL if no error.
 *         The pointer is valid until the next llvm_native_* call on the
 *         same thread. Do NOT free.
 */
const char* llvm_native_get_error(void);

/*
 * Clear the thread-local error state.
 */
void llvm_native_clear_error(void);

/*
 * Get the version string.
 *
 * @return Pointer to a static NUL-terminated version string.
 *         Valid for the lifetime of the process. Do NOT free.
 */
const char* llvm_native_version(void);

/*
 * Get structured version information.
 *
 * @param out  Pointer to a version_info_t to fill.
 * @return 0 on success, -1 if out is NULL.
 */
int llvm_native_version_info(llvm_native_version_info_t* out);

/*
 * Validate compilation options without compiling.
 *
 * @param options  Options to validate, or NULL (always valid).
 * @return 0 if valid, -1 if invalid (call llvm_native_get_error()).
 */
int llvm_native_validate_options(const llvm_native_compile_options_t* options);

#ifdef __cplusplus
}
#endif

#endif /* LLVM_NATIVE_ABI_H */
"#;

    /// Return the raw bytes of the C header file.
    pub fn header_bytes() -> &'static [u8] {
        HEADER_C.as_bytes()
    }

    /// Return the number of bytes in the C header.
    pub fn header_len() -> usize {
        HEADER_C.len()
    }

    /// Write the C header to a file path.
    ///
    /// Returns `Ok(())` on success, or an IO error.
    pub fn write_header(path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        std::fs::write(path.as_ref(), HEADER_C.as_bytes())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    // ── Constants Tests ─────────────────────────────────────────────

    #[test]
    fn test_abi_version_constants() {
        assert_eq!(LLVM_NATIVE_ABI_VERSION_MAJOR, 1);
        assert_eq!(LLVM_NATIVE_ABI_VERSION_MINOR, 0);
        assert_eq!(LLVM_NATIVE_ABI_VERSION_PATCH, 0);
        assert!(LLVM_NATIVE_MAX_PATH > 0);
        assert!(LLVM_NATIVE_MAX_OPTIONS > 0);
        assert!(LLVM_NATIVE_MAX_ERROR > 0);
    }

    #[test]
    fn test_version_string_format() {
        let ver = crate_version_string();
        assert!(ver.starts_with("llvm-native "));
        assert!(ver.contains("ABI v"));
    }

    // ── FFI Struct Layout Tests ─────────────────────────────────────

    #[test]
    fn test_compile_flags_size() {
        // CompileFlags must be exactly 8 bytes (u64).
        assert_eq!(std::mem::size_of::<CompileFlags>(), 8);
    }

    #[test]
    fn test_compile_options_ffi_layout() {
        // Verify field offsets are as expected for C compatibility.
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };

        // Use pointer arithmetic to verify offsets.
        let base = &opts as *const _ as *const u8;
        let offset_standard = &opts.standard as *const _ as usize - base as usize;
        let offset_flags = &opts.flags as *const _ as usize - base as usize;
        let offset_target = &opts.target_triple as *const _ as usize - base as usize;
        let offset_output = &opts.output_file as *const _ as usize - base as usize;

        // standard should be at offset 0 (first field).
        assert_eq!(offset_standard, 0);
        // flags follows after standard (which is 4 bytes i32 + 4 padding on most platforms).
        assert!(offset_flags >= 4);
        // pointer fields start somewhere after flags.
        assert!(offset_target >= offset_flags + 8);
        // pointer fields should be aligned to pointer size.
        assert_eq!(offset_target % std::mem::size_of::<*const u8>(), 0);
        assert_eq!(offset_output % std::mem::size_of::<*const u8>(), 0);
    }

    #[test]
    fn test_compile_result_layout() {
        assert_eq!(std::mem::size_of::<CompileResult>(), 40);
        let r = CompileResult::success();
        assert_eq!(r.status, 0);
        assert_eq!(r.error_count, 0);
    }

    #[test]
    fn test_version_info_ffi_layout() {
        let vi = VersionInfoFFI::current();
        assert_eq!(vi.major, 1);
        assert_eq!(vi.minor, 0);
        assert_eq!(vi.patch, 0);
        assert_eq!(vi.abi_version, 1);
        assert_eq!(std::mem::size_of::<VersionInfoFFI>(), 48);
    }

    // ── CompileFlags Tests ──────────────────────────────────────────

    #[test]
    fn test_compile_flags_none() {
        let f = CompileFlags::none();
        assert_eq!(f.bits, 0);
        assert!(!f.has(compile_flag_bits::OPTIMIZE));
        assert!(!f.has(compile_flag_bits::DEBUG_INFO));
        assert!(!f.has(compile_flag_bits::WALL));
    }

    #[test]
    fn test_compile_flags_set_and_has() {
        let mut f = CompileFlags::none();
        assert!(!f.has(compile_flag_bits::OPTIMIZE));

        f.set(compile_flag_bits::OPTIMIZE, true);
        assert!(f.has(compile_flag_bits::OPTIMIZE));

        f.set(compile_flag_bits::OPTIMIZE, false);
        assert!(!f.has(compile_flag_bits::OPTIMIZE));
    }

    #[test]
    fn test_compile_flags_merge() {
        let f1 = CompileFlags::from_bit(compile_flag_bits::OPTIMIZE);
        let f2 = CompileFlags::from_bit(compile_flag_bits::DEBUG_INFO);
        let merged = f1.merge(&f2);

        assert!(merged.has(compile_flag_bits::OPTIMIZE));
        assert!(merged.has(compile_flag_bits::DEBUG_INFO));
    }

    #[test]
    fn test_compile_flags_multiple_bits() {
        let mut f = CompileFlags::none();
        f.set(compile_flag_bits::WALL, true);
        f.set(compile_flag_bits::WERROR, true);
        f.set(compile_flag_bits::PEDANTIC, true);

        assert!(f.has(compile_flag_bits::WALL));
        assert!(f.has(compile_flag_bits::WERROR));
        assert!(f.has(compile_flag_bits::PEDANTIC));
        assert!(!f.has(compile_flag_bits::OPTIMIZE));

        // Ensure only those three bits are set.
        let expected = compile_flag_bits::WALL
            | compile_flag_bits::WERROR
            | compile_flag_bits::PEDANTIC;
        assert_eq!(f.bits, expected);
    }

    #[test]
    fn test_compile_flags_from_bit_const() {
        let f = CompileFlags::from_bit(compile_flag_bits::LTO);
        assert!(f.has(compile_flag_bits::LTO));
        assert!(!f.has(compile_flag_bits::OPTIMIZE));
    }

    // ── CompileResult Tests ─────────────────────────────────────────

    #[test]
    fn test_compile_result_success() {
        let r = CompileResult::success();
        assert!(r.is_ok());
        assert!(!r.is_err());
        assert_eq!(r.status, 0);
        assert_eq!(r.error_count, 0);
    }

    #[test]
    fn test_compile_result_error() {
        let r = CompileResult::error(3);
        assert!(!r.is_ok());
        assert!(r.is_err());
        assert_eq!(r.status, -1);
        assert_eq!(r.error_count, 3);
    }

    // ── Type Conversion Tests ───────────────────────────────────────

    #[test]
    fn test_standard_ffi_to_rust_full_roundtrip() {
        let standards = [
            (CLangStandardFFI::C89, CLangStandard::C89),
            (CLangStandardFFI::C99, CLangStandard::C99),
            (CLangStandardFFI::C11, CLangStandard::C11),
            (CLangStandardFFI::C17, CLangStandard::C17),
            (CLangStandardFFI::C23, CLangStandard::C23),
            (CLangStandardFFI::Gnu89, CLangStandard::Gnu89),
            (CLangStandardFFI::Gnu99, CLangStandard::Gnu99),
            (CLangStandardFFI::Gnu11, CLangStandard::Gnu11),
            (CLangStandardFFI::Gnu17, CLangStandard::Gnu17),
        ];

        for (ffi, rust) in &standards {
            assert_eq!(standard_ffi_to_rust(*ffi), *rust);
            assert_eq!(standard_rust_to_ffi(*rust), *ffi);
        }
    }

    #[test]
    fn test_standard_ffi_to_rust_unknown_defaults_to_c17() {
        // ABI forward-compat: unknown discriminants → C17.
        let unknown = unsafe { std::mem::transmute::<i32, CLangStandardFFI>(42) };
        assert_eq!(standard_ffi_to_rust(unknown), CLangStandard::C17);
    }

    #[test]
    fn test_compile_options_ffi_to_rust_null() {
        // NULL options should produce defaults.
        let opts = unsafe { compile_options_ffi_to_rust(std::ptr::null()) };
        assert_eq!(opts.standard, CLangStandard::C17);
        assert!(opts.optimize);
        assert_eq!(opts.target_triple, "x86_64-unknown-linux-gnu");
    }

    #[test]
    fn test_compile_options_ffi_to_rust_full() {
        let target = CString::new("aarch64-unknown-linux-gnu").unwrap();
        let output = CString::new("out.o").unwrap();
        let includes = CString::new("/usr/include;/usr/local/include").unwrap();
        let defines = CString::new("FOO=1;BAR").unwrap();

        let mut flags = CompileFlags::none();
        flags.set(compile_flag_bits::OPTIMIZE, true);
        flags.set(compile_flag_bits::DEBUG_INFO, true);
        flags.set(compile_flag_bits::WALL, true);

        let ffi_opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C23,
            flags,
            target_triple: target.as_ptr(),
            output_file: output.as_ptr(),
            include_paths: includes.as_ptr(),
            defines: defines.as_ptr(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };

        let rust_opts = unsafe { compile_options_ffi_to_rust(&ffi_opts as *const _) };

        assert_eq!(rust_opts.standard, CLangStandard::C23);
        assert!(rust_opts.optimize);
        assert!(rust_opts.debug_info);
        assert!(rust_opts.wall);
        assert_eq!(rust_opts.target_triple, "aarch64-unknown-linux-gnu");
        assert_eq!(rust_opts.output_file, Some("out.o".into()));
        assert_eq!(rust_opts.includes.len(), 2);
        assert_eq!(rust_opts.includes[0], "/usr/include");
        assert_eq!(rust_opts.includes[1], "/usr/local/include");
        assert_eq!(rust_opts.defines.len(), 2);
        assert_eq!(rust_opts.defines[0], ("FOO".into(), Some("1".into())));
        assert_eq!(rust_opts.defines[1], ("BAR".into(), None));
    }

    #[test]
    fn test_compile_options_ffi_to_rust_optimization_override() {
        let mut flags = CompileFlags::none();
        flags.set(compile_flag_bits::OPTIMIZE, false);

        let ffi_opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags,
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: b'2',
            _reserved: [0; 4],
        };

        let rust_opts = unsafe { compile_options_ffi_to_rust(&ffi_opts as *const _) };
        assert!(rust_opts.optimize);

        // -O0 override should produce false.
        let ffi_opts_zero = CompileOptionsFFI {
            opt_level_override: b'0',
            ..ffi_opts
        };
        let rust_opts_zero = unsafe { compile_options_ffi_to_rust(&ffi_opts_zero as *const _) };
        assert!(!rust_opts_zero.optimize);
    }

    // ── Validation Tests ────────────────────────────────────────────

    #[test]
    fn test_validate_ffi_options_null_is_ok() {
        assert!(validate_ffi_options(std::ptr::null()).is_ok());
    }

    #[test]
    fn test_validate_ffi_options_valid() {
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };
        assert!(validate_ffi_options(&opts as *const _).is_ok());
    }

    #[test]
    fn test_validate_ffi_options_rejects_nonzero_reserved() {
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [1, 0, 0, 0], // Non-zero reserved field!
        };
        assert!(validate_ffi_options(&opts as *const _).is_err());
    }

    #[test]
    fn test_validate_ffi_options_valid_strings() {
        let target = CString::new("x86_64-unknown-linux-gnu").unwrap();
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: target.as_ptr(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };
        assert!(validate_ffi_options(&opts as *const _).is_ok());
    }

    // ── Extern "C" Function Tests ───────────────────────────────────

    #[test]
    fn test_llvm_native_version_not_null() {
        let ptr = llvm_native_version();
        assert!(!ptr.is_null());

        let cstr = unsafe { CStr::from_ptr(ptr) };
        let s = cstr.to_str().unwrap();
        assert!(s.contains("llvm-native"));
        assert!(s.contains("ABI"));
    }

    #[test]
    fn test_llvm_native_get_error_initial_null() {
        // Before any error, get_error should return NULL.
        llvm_native_clear_error();
        let ptr = llvm_native_get_error();
        assert!(ptr.is_null());
    }

    #[test]
    fn test_llvm_native_compile_file_null_path() {
        llvm_native_clear_error();
        let result = unsafe { llvm_native_compile_file(std::ptr::null(), std::ptr::null()) };
        assert_eq!(result, -1);

        let err_ptr = llvm_native_get_error();
        assert!(!err_ptr.is_null());
        let err_str = unsafe { CStr::from_ptr(err_ptr) }.to_str().unwrap();
        assert!(err_str.contains("path is null"));
    }

    #[test]
    fn test_llvm_native_compile_string_null_source() {
        llvm_native_clear_error();
        let result = unsafe { llvm_native_compile_string(std::ptr::null(), std::ptr::null()) };
        assert_eq!(result, -1);

        let err_ptr = llvm_native_get_error();
        assert!(!err_ptr.is_null());
        let err_str = unsafe { CStr::from_ptr(err_ptr) }.to_str().unwrap();
        assert!(err_str.contains("source is null"));
    }

    #[test]
    fn test_llvm_native_compile_string_basic() {
        // Compile a minimal valid C program.
        llvm_native_clear_error();
        let source = CString::new("int main() { return 0; }").unwrap();
        let result = unsafe { llvm_native_compile_string(source.as_ptr(), std::ptr::null()) };
        // Should succeed (return 0) or fail with a specific compile error.
        // Both are acceptable; what matters is that we don't crash.
        if result != 0 {
            let err_ptr = llvm_native_get_error();
            assert!(!err_ptr.is_null());
            let err_str = unsafe { CStr::from_ptr(err_ptr) }.to_str().unwrap();
            // Should not be an ABI-level error (those use specific phrases).
            assert!(
                !err_str.contains("null"),
                "Expected compile error, not ABI error: {}",
                err_str
            );
        }
    }

    #[test]
    fn test_llvm_native_compile_string_with_options() {
        // Test compilation with explicit FFI options.
        let source = CString::new("int main() { return 42; }").unwrap();

        let mut flags = CompileFlags::none();
        flags.set(compile_flag_bits::OPTIMIZE, true);

        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags,
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };

        let result = unsafe { llvm_native_compile_string(source.as_ptr(), &opts as *const _) };
        // Should not crash. May succeed or fail with a compile error.
        if result != 0 {
            let err_ptr = llvm_native_get_error();
            assert!(!err_ptr.is_null());
            let err_str = unsafe { CStr::from_ptr(err_ptr) }.to_str().unwrap();
            assert!(!err_str.contains("validate"),
                "Expected compile error, not validation error: {}", err_str);
        }
    }

    #[test]
    fn test_llvm_native_validate_options_null() {
        let result = unsafe { llvm_native_validate_options(std::ptr::null()) };
        assert_eq!(result, 0);
    }

    #[test]
    fn test_llvm_native_validate_options_valid() {
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0; 4],
        };
        let result = unsafe { llvm_native_validate_options(&opts as *const _) };
        assert_eq!(result, 0);
    }

    #[test]
    fn test_llvm_native_validate_options_invalid_reserved() {
        let opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C17,
            flags: CompileFlags::none(),
            target_triple: std::ptr::null(),
            output_file: std::ptr::null(),
            include_paths: std::ptr::null(),
            defines: std::ptr::null(),
            opt_level_override: 0xFF,
            _reserved: [0xDEAD, 0, 0, 0],
        };
        let result = unsafe { llvm_native_validate_options(&opts as *const _) };
        assert_eq!(result, -1);

        let err_ptr = llvm_native_get_error();
        assert!(!err_ptr.is_null());
        let err_str = unsafe { CStr::from_ptr(err_ptr) }.to_str().unwrap();
        assert!(err_str.contains("_reserved[0]"));
    }

    #[test]
    fn test_llvm_native_clear_error() {
        // Set an error first.
        llvm_native_clear_error();
        let result = unsafe { llvm_native_compile_string(std::ptr::null(), std::ptr::null()) };
        assert_eq!(result, -1);
        assert!(!llvm_native_get_error().is_null());

        // Clear it.
        llvm_native_clear_error();
        assert!(llvm_native_get_error().is_null());
    }

    #[test]
    fn test_llvm_native_version_info() {
        let mut vi = VersionInfoFFI {
            major: 0,
            minor: 0,
            patch: 0,
            abi_version: 0,
            _reserved: [0; 4],
        };
        let result = llvm_native_version_info(&mut vi as *mut _);
        assert_eq!(result, 0);
        assert_eq!(vi.major, LLVM_NATIVE_ABI_VERSION_MAJOR);
        assert_eq!(vi.minor, LLVM_NATIVE_ABI_VERSION_MINOR);
        assert_eq!(vi.patch, LLVM_NATIVE_ABI_VERSION_PATCH);
        assert_eq!(vi.abi_version, 1);
    }

    #[test]
    fn test_llvm_native_version_info_null() {
        let result = llvm_native_version_info(std::ptr::null_mut());
        assert_eq!(result, -1);
    }

    // ── Error State Thread-Local Tests ──────────────────────────────

    #[test]
    fn test_error_state_cleared_on_success() {
        // After a successful call, error should be cleared.
        llvm_native_clear_error();

        // Set an error first.
        set_last_error("test error".into());
        assert!(!llvm_native_get_error().is_null());

        // Now clear and verify.
        clear_last_error();
        assert!(llvm_native_get_error().is_null());
    }

    #[test]
    fn test_error_state_overwritable() {
        llvm_native_clear_error();

        set_last_error("first error".into());
        let err1 = unsafe { CStr::from_ptr(llvm_native_get_error()) }
            .to_str()
            .unwrap()
            .to_string();
        assert_eq!(err1, "first error");

        set_last_error("second error".into());
        let err2 = unsafe { CStr::from_ptr(llvm_native_get_error()) }
            .to_str()
            .unwrap()
            .to_string();
        assert_eq!(err2, "second error");
    }

    // ── Header File Tests ───────────────────────────────────────────

    #[test]
    fn test_header_content_not_empty() {
        assert!(!llvm_native_abi_header::HEADER_C.is_empty());
    }

    #[test]
    fn test_header_has_include_guard() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("LLVM_NATIVE_ABI_H"),
            "Header should contain include guard");
    }

    #[test]
    fn test_header_declares_all_functions() {
        let header = llvm_native_abi_header::HEADER_C;
        // Verify all four required functions are declared.
        assert!(header.contains("llvm_native_compile_file"));
        assert!(header.contains("llvm_native_compile_string"));
        assert!(header.contains("llvm_native_get_error"));
        assert!(header.contains("llvm_native_version"));
        // Additional ABI functions.
        assert!(header.contains("llvm_native_clear_error"));
        assert!(header.contains("llvm_native_version_info"));
        assert!(header.contains("llvm_native_validate_options"));
    }

    #[test]
    fn test_header_declares_data_structures() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("llvm_native_compile_options_t"));
        assert!(header.contains("llvm_native_compile_result_t"));
        assert!(header.contains("llvm_native_version_info_t"));
        assert!(header.contains("llvm_native_compile_flags_t"));
        assert!(header.contains("llvm_native_standard_t"));
    }

    #[test]
    fn test_header_has_cplusplus_guard() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("extern \"C\""));
        assert!(header.contains("__cplusplus"));
    }

    #[test]
    fn test_header_has_stdint_include() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("#include <stdint.h>"));
        assert!(header.contains("#include <stddef.h>"));
    }

    #[test]
    fn test_header_has_abi_version_constants() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("LLVM_NATIVE_ABI_VERSION_MAJOR"));
        assert!(header.contains("LLVM_NATIVE_ABI_VERSION_MINOR"));
        assert!(header.contains("LLVM_NATIVE_ABI_VERSION_PATCH"));
    }

    #[test]
    fn test_header_bytes_match_string() {
        assert_eq!(
            llvm_native_abi_header::header_bytes(),
            llvm_native_abi_header::HEADER_C.as_bytes()
        );
    }

    #[test]
    fn test_header_len_positive() {
        assert!(llvm_native_abi_header::header_len() > 0);
    }

    #[test]
    fn test_write_header_tempfile() {
        let dir = std::env::temp_dir();
        let path = dir.join("llvm_native_test_header.h");
        let result = llvm_native_abi_header::write_header(&path);
        assert!(result.is_ok());
        assert!(path.exists());

        // Clean up.
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_header_contains_all_flag_defines() {
        let header = llvm_native_abi_header::HEADER_C;
        assert!(header.contains("LLVM_NATIVE_OPTIMIZE"));
        assert!(header.contains("LLVM_NATIVE_DEBUG_INFO"));
        assert!(header.contains("LLVM_NATIVE_WALL"));
        assert!(header.contains("LLVM_NATIVE_WERROR"));
        assert!(header.contains("LLVM_NATIVE_PEDANTIC"));
        assert!(header.contains("LLVM_NATIVE_LTO"));
        assert!(header.contains("LLVM_NATIVE_PIC"));
        assert!(header.contains("LLVM_NATIVE_PIE"));
    }

    // ── ABI Layout Tests ────────────────────────────────────────────

    #[test]
    fn test_abi_layout_constants_match() {
        assert_eq!(
            abi_layout::COMPILE_OPTIONS_FFI_SIZE,
            std::mem::size_of::<CompileOptionsFFI>()
        );
        assert_eq!(
            abi_layout::COMPILE_RESULT_SIZE,
            std::mem::size_of::<CompileResult>()
        );
        assert_eq!(
            abi_layout::VERSION_INFO_FFI_SIZE,
            std::mem::size_of::<VersionInfoFFI>()
        );
        assert_eq!(
            abi_layout::COMPILE_FLAGS_SIZE,
            std::mem::size_of::<CompileFlags>()
        );
    }

    #[test]
    fn test_abi_alignments_reasonable() {
        // Alignments should be <= 16 on all reasonable platforms.
        assert!(abi_layout::COMPILE_OPTIONS_FFI_ALIGN <= 16);
        assert!(abi_layout::COMPILE_RESULT_ALIGN <= 16);
        assert!(abi_layout::VERSION_INFO_FFI_ALIGN <= 16);
    }

    // ── CompileOptions FFI Roundtrip Tests ──────────────────────────

    #[test]
    fn test_options_roundtrip_all_fields() {
        // Build FFI options → convert to Rust → verify fidelity.
        let target = CString::new("wasm32-unknown-unknown").unwrap();
        let output = CString::new("test.wasm").unwrap();
        let includes = CString::new("/sysroot/include").unwrap();
        let defines = CString::new("__wasm__;WASI").unwrap();

        let mut flags = CompileFlags::none();
        flags.set(compile_flag_bits::OPTIMIZE_SIZE, true);
        flags.set(compile_flag_bits::NO_WARNINGS, true);
        flags.set(compile_flag_bits::PIC, true);

        let ffi_opts = CompileOptionsFFI {
            standard: CLangStandardFFI::C11,
            flags,
            target_triple: target.as_ptr(),
            output_file: output.as_ptr(),
            include_paths: includes.as_ptr(),
            defines: defines.as_ptr(),
            opt_level_override: b'z', // optimize for size
            _reserved: [0; 4],
        };

        let rust = unsafe { compile_options_ffi_to_rust(&ffi_opts as *const _) };

        assert_eq!(rust.standard, CLangStandard::C11);
        assert!(rust.optimize); // opt_level_override 'z' sets optimize=true
        assert!(!rust.warnings); // NO_WARNINGS set
        assert_eq!(rust.target_triple, "wasm32-unknown-unknown");
        assert_eq!(rust.output_file, Some("test.wasm".into()));
        assert_eq!(rust.includes.len(), 1);
        assert_eq!(rust.includes[0], "/sysroot/include");
        assert_eq!(rust.defines.len(), 2);
    }

    // ── Edge Cases ──────────────────────────────────────────────────

    #[test]
    fn test_empty_source_string() {
        llvm_native_clear_error();
        let source = CString::new("").unwrap();
        let result = unsafe { llvm_native_compile_string(source.as_ptr(), std::ptr::null()) };
        // Empty source may or may not compile; should not crash.
        if result == -1 {
            let err_ptr = llvm_native_get_error();
            assert!(!err_ptr.is_null());
        }
    }

    #[test]
    fn test_opt_level_override_values() {
        // Test that all recognized opt_level_override values work.
        for &level in &[b'0', b'1', b'2', b'3', b'z', b's', b'd', b'g', 0xFFu8] {
            let ffi_opts = CompileOptionsFFI {
                standard: CLangStandardFFI::C17,
                flags: CompileFlags::none(),
                target_triple: std::ptr::null(),
                output_file: std::ptr::null(),
                include_paths: std::ptr::null(),
                defines: std::ptr::null(),
                opt_level_override: level,
                _reserved: [0; 4],
            };
            // Should not panic.
            let rust = unsafe { compile_options_ffi_to_rust(&ffi_opts as *const _) };
            // Verify it produces reasonable output.
            match level {
                b'0' | b'd' => assert!(!rust.optimize),
                b'1' | b'2' | b'3' | b'g' | b's' | b'z' => assert!(rust.optimize),
                0xFF => {}, // uses flags (which is false = no optimize)
                _ => {},
            }
        }
    }
}