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
//! Clang C++20 Modules Full — Complete module system implementation.
//!
//! This module provides the complete C++20 modules infrastructure:
//!
//! - Module interface unit: `export module M;` with exported declarations
//! - Module implementation unit: `module M;` with non-exported declarations
//! - Module partition: `export module M:part;` with partition imports
//! - Import resolution: `import M;` — BMI search, dependency resolution
//! - BMI (Binary Module Interface): serialization/deserialization to binary
//! - Module ownership: track which module owns each declaration (ODR)
//! - Header unit: `import <header>;` — synthesize BMI from header
//! - Global module fragment: `module;` declarations before module declaration
//! - Private module fragment: `module :private;` non-ABI-visible impl
//! - Module reachability: transitive import computation for name lookup
//! - Module map: module.modulemap file parsing, framework modules
//!
//! Clean-room behavioral reconstruction from:
//! - C++20 Standard §10 (Modules)
//! - Published Clang modules documentation
//! - No LLVM/Clang source code is consulted.

use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt;
use std::path::PathBuf;

use super::cpp_modules::{ModuleDecl, ModuleImport, ModuleMap, ModuleName};

// ═══════════════════════════════════════════════════════════════════════════════
// Module Kind
// ═══════════════════════════════════════════════════════════════════════════════

/// The kind of a module unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleUnitKind {
    /// `export module M;` — primary module interface.
    ModuleInterface,
    /// `module M;` — module implementation unit.
    ModuleImplementation,
    /// `export module M:part;` — module interface partition.
    ModulePartitionInterface,
    /// `module M:part;` — module implementation partition.
    ModulePartitionImplementation,
    /// `module;` ... `export module M;` — global module fragment.
    GlobalModuleFragment,
    /// `module :private;` — private module fragment.
    PrivateModuleFragment,
    /// `export import <header>;` — header unit.
    HeaderUnit,
}

impl ModuleUnitKind {
    pub fn is_interface(&self) -> bool {
        matches!(
            self,
            ModuleUnitKind::ModuleInterface
                | ModuleUnitKind::ModulePartitionInterface
                | ModuleUnitKind::HeaderUnit
        )
    }

    pub fn is_partition(&self) -> bool {
        matches!(
            self,
            ModuleUnitKind::ModulePartitionInterface
                | ModuleUnitKind::ModulePartitionImplementation
        )
    }

    pub fn label(&self) -> &'static str {
        match self {
            ModuleUnitKind::ModuleInterface => "module interface",
            ModuleUnitKind::ModuleImplementation => "module implementation",
            ModuleUnitKind::ModulePartitionInterface => "module partition interface",
            ModuleUnitKind::ModulePartitionImplementation => "module partition implementation",
            ModuleUnitKind::GlobalModuleFragment => "global module fragment",
            ModuleUnitKind::PrivateModuleFragment => "private module fragment",
            ModuleUnitKind::HeaderUnit => "header unit",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Unit
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a single module unit (interface or implementation).
#[derive(Debug, Clone)]
pub struct ModuleUnit {
    /// The module name.
    pub name: ModuleName,
    /// The kind of this module unit.
    pub kind: ModuleUnitKind,
    /// Partition name, if this is a partition.
    pub partition: Option<String>,
    /// Source file path for this unit.
    pub source_path: PathBuf,
    /// Path to the BMI (Binary Module Interface) file.
    pub bmi_path: Option<PathBuf>,
    /// Whether this unit has been compiled.
    pub is_compiled: bool,
    /// Whether this unit is the primary interface for the module.
    pub is_primary: bool,
    /// List of imported module names (direct imports).
    pub imports: Vec<ModuleName>,
    /// Imported partition names.
    pub partition_imports: Vec<(ModuleName, String)>,
    /// Header unit imports.
    pub header_imports: Vec<String>,
    /// All exported declarations in this unit.
    pub exported_decls: Vec<String>,
    /// All owned (non-exported) declarations in this unit.
    pub owned_decls: Vec<String>,
    /// Literal source content of the module unit.
    pub source_content: String,
}

impl ModuleUnit {
    pub fn new(name: ModuleName, kind: ModuleUnitKind, source: &str) -> Self {
        Self {
            name,
            kind,
            partition: None,
            source_path: PathBuf::from(source),
            bmi_path: None,
            is_compiled: false,
            is_primary: kind == ModuleUnitKind::ModuleInterface,
            imports: Vec::new(),
            partition_imports: Vec::new(),
            header_imports: Vec::new(),
            exported_decls: Vec::new(),
            owned_decls: Vec::new(),
            source_content: String::new(),
        }
    }

    /// Set this unit as a partition.
    pub fn with_partition(mut self, partition: &str) -> Self {
        self.partition = Some(partition.to_string());
        self
    }

    /// Add a direct module import.
    pub fn add_import(&mut self, module: ModuleName) {
        if !self.imports.contains(&module) {
            self.imports.push(module);
        }
    }

    /// Add a partition import.
    pub fn add_partition_import(&mut self, module: ModuleName, partition: &str) {
        self.partition_imports.push((module, partition.to_string()));
    }

    /// Add a header unit import.
    pub fn add_header_import(&mut self, header: &str) {
        self.header_imports.push(header.to_string());
    }

    /// Add an exported declaration.
    pub fn add_exported_decl(&mut self, decl: &str) {
        self.exported_decls.push(decl.to_string());
    }

    /// Add an owned (internal) declaration.
    pub fn add_owned_decl(&mut self, decl: &str) {
        self.owned_decls.push(decl.to_string());
    }

    /// Set the BMI path.
    pub fn set_bmi_path(&mut self, path: &str) {
        self.bmi_path = Some(PathBuf::from(path));
    }

    /// Mark this unit as compiled.
    pub fn mark_compiled(&mut self) {
        self.is_compiled = true;
    }

    /// Get all declarations (exported + owned).
    pub fn all_decls(&self) -> Vec<&str> {
        self.exported_decls
            .iter()
            .map(|s| s.as_str())
            .chain(self.owned_decls.iter().map(|s| s.as_str()))
            .collect()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Database — tracks all modules and their units
// ═══════════════════════════════════════════════════════════════════════════════

/// The central registry of all module units in a translation.
#[derive(Debug, Clone)]
pub struct ModuleDatabase {
    /// All module units, indexed by module name.
    pub units: HashMap<String, Vec<ModuleUnit>>,
    /// Primary interface unit for each module.
    pub primary_interfaces: HashMap<String, usize>,
    /// Path to the BMI cache directory.
    pub bmi_cache_dir: Option<PathBuf>,
    /// Paths to search for module sources.
    pub search_paths: Vec<PathBuf>,
    /// The dependency graph (module name -> set of imported module names).
    pub dependency_graph: HashMap<String, HashSet<String>>,
    /// Transitive closure of imports for each module.
    pub reachability: HashMap<String, HashSet<String>>,
}

impl ModuleDatabase {
    pub fn new() -> Self {
        Self {
            units: HashMap::new(),
            primary_interfaces: HashMap::new(),
            bmi_cache_dir: None,
            search_paths: Vec::new(),
            dependency_graph: HashMap::new(),
            reachability: HashMap::new(),
        }
    }

    /// Register a module unit.
    pub fn register_unit(&mut self, unit: ModuleUnit) {
        let name = unit.name.to_string();
        let is_primary = unit.is_primary;

        let entry = self.units.entry(name.clone()).or_default();
        let idx = entry.len();
        entry.push(unit);

        if is_primary {
            self.primary_interfaces.insert(name.clone(), idx);
        }
    }

    /// Find the primary interface unit for a module.
    pub fn primary_interface(&self, module_name: &str) -> Option<&ModuleUnit> {
        self.primary_interfaces
            .get(module_name)
            .and_then(|&idx| self.units.get(module_name).and_then(|units| units.get(idx)))
    }

    /// Find a module partition.
    pub fn find_partition(&self, module_name: &str, partition: &str) -> Option<&ModuleUnit> {
        self.units.get(module_name).and_then(|units| {
            units
                .iter()
                .find(|u| u.partition.as_deref() == Some(partition))
        })
    }

    /// Resolve an import: find the BMI or source for a module.
    pub fn resolve_import(&self, module_name: &str) -> Option<ModuleResolution> {
        // First, check if we have the module registered.
        if let Some(primary) = self.primary_interface(module_name) {
            if let Some(ref bmi) = primary.bmi_path {
                return Some(ModuleResolution::Bmi(bmi.clone()));
            }
            return Some(ModuleResolution::Source(primary.source_path.clone()));
        }

        // Search for a BMI file in the cache directory.
        if let Some(ref cache_dir) = self.bmi_cache_dir {
            let bmi_path = cache_dir.join(format!("{}.bmi", module_name));
            if bmi_path.exists() {
                return Some(ModuleResolution::Bmi(bmi_path));
            }
        }

        // Search for source in search paths.
        for path in &self.search_paths {
            let source_path = path.join(format!("{}.cppm", module_name));
            if source_path.exists() {
                return Some(ModuleResolution::Source(source_path));
            }
            let alt_path = path.join(format!("{}.ixx", module_name));
            if alt_path.exists() {
                return Some(ModuleResolution::Source(alt_path));
            }
        }

        None
    }

    /// Build the dependency graph from import relationships.
    pub fn build_dependency_graph(&mut self) {
        self.dependency_graph.clear();
        for (module_name, units) in &self.units {
            let mut deps = HashSet::new();
            for unit in units {
                for imp in &unit.imports {
                    deps.insert(imp.to_string());
                }
                for (imp, _part) in &unit.partition_imports {
                    deps.insert(imp.to_string());
                }
            }
            self.dependency_graph.insert(module_name.clone(), deps);
        }
    }

    /// Compute the transitive closure of imports (module reachability).
    pub fn compute_reachability(&mut self) {
        self.reachability.clear();
        for module_name in self.units.keys() {
            let mut visited = HashSet::new();
            let mut queue = VecDeque::new();
            queue.push_back(module_name.clone());

            while let Some(current) = queue.pop_front() {
                if !visited.insert(current.clone()) {
                    continue;
                }
                if let Some(deps) = self.dependency_graph.get(&current) {
                    for dep in deps {
                        if !visited.contains(dep) {
                            queue.push_back(dep.clone());
                        }
                    }
                }
            }

            visited.remove(module_name); // Remove self
            self.reachability.insert(module_name.clone(), visited);
        }
    }

    /// Check if module `from` can see declarations from module `to`.
    pub fn is_reachable(&self, from: &str, to: &str) -> bool {
        if from == to {
            return true;
        }
        self.reachability
            .get(from)
            .map_or(false, |r| r.contains(to))
    }

    /// Topological sort of modules respecting import dependencies.
    pub fn topological_order(&self) -> Vec<String> {
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        for name in self.units.keys() {
            in_degree.entry(name.clone()).or_insert(0);
        }
        for (name, deps) in &self.dependency_graph {
            for dep in deps {
                if self.units.contains_key(dep) {
                    *in_degree.entry(dep.clone()).or_insert(0) += 1;
                }
            }
        }

        let mut queue: VecDeque<String> = in_degree
            .iter()
            .filter(|(_, &deg)| deg == 0)
            .map(|(n, _)| n.clone())
            .collect();

        let mut order = Vec::new();
        while let Some(current) = queue.pop_front() {
            order.push(current.clone());
            if let Some(deps) = self.dependency_graph.get(&current) {
                for dep in deps {
                    if let Some(deg) = in_degree.get_mut(dep) {
                        *deg = deg.saturating_sub(1);
                        if *deg == 0 {
                            queue.push_back(dep.clone());
                        }
                    }
                }
            }
        }

        order
    }

    /// Check for cyclic module dependencies.
    pub fn has_cycles(&self) -> bool {
        let order = self.topological_order();
        order.len() != self.units.len()
    }

    /// Get all module names.
    pub fn module_names(&self) -> Vec<&String> {
        self.units.keys().collect()
    }

    pub fn len(&self) -> usize {
        self.units.len()
    }

    pub fn is_empty(&self) -> bool {
        self.units.is_empty()
    }
}

impl Default for ModuleDatabase {
    fn default() -> Self {
        Self::new()
    }
}

/// The result of resolving a module import.
#[derive(Debug, Clone)]
pub enum ModuleResolution {
    /// A Binary Module Interface file was found.
    Bmi(PathBuf),
    /// A source file for the module was found.
    Source(PathBuf),
    /// The module is a header unit (the header name).
    HeaderUnit(String),
}

// ═══════════════════════════════════════════════════════════════════════════════
// BMI — Binary Module Interface serialization
// ═══════════════════════════════════════════════════════════════════════════════

/// The header for a Binary Module Interface (BMI) file.
#[derive(Debug, Clone)]
pub struct BmiHeader {
    /// Magic bytes identifying this as a BMI file.
    pub magic: [u8; 4],
    /// BMI format version.
    pub version: u32,
    /// The module name.
    pub module_name: ModuleName,
    /// Whether this is an interface BMI.
    pub is_interface: bool,
    /// Compiler version that produced this BMI.
    pub compiler_version: String,
    /// Target triple.
    pub target_triple: String,
    /// Number of imported modules.
    pub import_count: u32,
    /// Number of exported declarations.
    pub exported_count: u32,
    /// Number of owned declarations.
    pub owned_count: u32,
    /// Checksum of the source that produced this BMI.
    pub source_checksum: u64,
    /// Total size of the BMI data section.
    pub data_size: u64,
}

impl Default for BmiHeader {
    fn default() -> Self {
        Self {
            magic: *b"BMI\0",
            version: 1,
            module_name: ModuleName::new(Vec::new()),
            is_interface: false,
            compiler_version: "llvm-native 1.0".to_string(),
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            import_count: 0,
            exported_count: 0,
            owned_count: 0,
            source_checksum: 0,
            data_size: 0,
        }
    }
}

/// A BMI (Binary Module Interface) file representation.
#[derive(Debug, Clone)]
pub struct BinaryModuleInterface {
    /// BMI file header.
    pub header: BmiHeader,
    /// Imported module names.
    pub imports: Vec<ModuleImport>,
    /// Serialized AST for exported declarations.
    pub exported_ast: Vec<u8>,
    /// Serialized AST for owned declarations.
    pub owned_ast: Vec<u8>,
    /// The raw binary content of the file.
    pub raw_data: Vec<u8>,
}

impl BinaryModuleInterface {
    pub fn new(module_name: ModuleName) -> Self {
        let mut header = BmiHeader::default();
        header.module_name = module_name;
        Self {
            header,
            imports: Vec::new(),
            exported_ast: Vec::new(),
            owned_ast: Vec::new(),
            raw_data: Vec::new(),
        }
    }

    /// Serialize the BMI to bytes for writing to disk.
    pub fn serialize(&self) -> Vec<u8> {
        let mut data = Vec::new();

        // Magic
        data.extend_from_slice(&self.header.magic);
        // Version
        data.extend_from_slice(&self.header.version.to_le_bytes());
        // Module name length + name
        let name_str = self.header.module_name.to_string();
        let name_bytes = name_str.as_bytes();
        data.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
        data.extend_from_slice(name_bytes);
        // Is interface
        data.push(if self.header.is_interface { 1 } else { 0 });
        // Compiler version
        let cv = self.header.compiler_version.as_bytes();
        data.extend_from_slice(&(cv.len() as u32).to_le_bytes());
        data.extend_from_slice(cv);
        // Target triple
        let tt = self.header.target_triple.as_bytes();
        data.extend_from_slice(&(tt.len() as u32).to_le_bytes());
        data.extend_from_slice(tt);
        // Import count + imports
        data.extend_from_slice(&(self.imports.len() as u32).to_le_bytes());
        for imp in &self.imports {
            let imp_str = imp.module.to_string();
            let ib = imp_str.as_bytes();
            data.extend_from_slice(&(ib.len() as u32).to_le_bytes());
            data.extend_from_slice(ib);
        }
        // Exported AST
        data.extend_from_slice(&(self.exported_ast.len() as u64).to_le_bytes());
        data.extend_from_slice(&self.exported_ast);
        // Owned AST
        data.extend_from_slice(&(self.owned_ast.len() as u64).to_le_bytes());
        data.extend_from_slice(&self.owned_ast);
        // Source checksum
        data.extend_from_slice(&self.header.source_checksum.to_le_bytes());

        data
    }

    /// Deserialize a BMI from bytes.
    pub fn deserialize(data: &[u8]) -> Option<Self> {
        if data.len() < 20 {
            return None;
        }

        let mut pos = 0;

        // Magic
        let magic: [u8; 4] = data[pos..pos + 4].try_into().ok()?;
        if &magic != b"BMI\0" {
            return None;
        }
        pos += 4;

        // Version
        let version = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?);
        pos += 4;

        // Module name
        let name_len = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?) as usize;
        pos += 4;
        let name_str = std::str::from_utf8(&data[pos..pos + name_len]).ok()?;
        pos += name_len;
        let module_name = ModuleName::from_str(name_str);

        // Is interface
        let is_interface = data[pos] != 0;
        pos += 1;

        // Compiler version
        let cv_len = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?) as usize;
        pos += 4;
        let compiler_version = std::str::from_utf8(&data[pos..pos + cv_len])
            .ok()?
            .to_string();
        pos += cv_len;

        // Target triple
        let tt_len = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?) as usize;
        pos += 4;
        let target_triple = std::str::from_utf8(&data[pos..pos + tt_len])
            .ok()?
            .to_string();
        pos += tt_len;

        // Imports
        let import_count = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?) as usize;
        pos += 4;
        let mut imports = Vec::new();
        for _ in 0..import_count {
            let ilen = u32::from_le_bytes(data[pos..pos + 4].try_into().ok()?) as usize;
            pos += 4;
            let imp_str = std::str::from_utf8(&data[pos..pos + ilen]).ok()?;
            pos += ilen;
            imports.push(ModuleImport::new(ModuleName::from_str(imp_str)));
        }

        // Exported AST
        let exported_len = u64::from_le_bytes(data[pos..pos + 8].try_into().ok()?) as usize;
        pos += 8;
        let exported_ast = data[pos..pos + exported_len].to_vec();
        pos += exported_len;

        // Owned AST
        let owned_len = u64::from_le_bytes(data[pos..pos + 8].try_into().ok()?) as usize;
        pos += 8;
        let owned_ast = data[pos..pos + owned_len].to_vec();
        pos += owned_len;

        // Source checksum
        let source_checksum = u64::from_le_bytes(data[pos..pos + 8].try_into().ok()?);

        Some(Self {
            header: BmiHeader {
                magic,
                version,
                module_name,
                is_interface,
                compiler_version,
                target_triple,
                import_count: import_count as u32,
                exported_count: exported_ast.len() as u32,
                owned_count: owned_ast.len() as u32,
                source_checksum,
                data_size: data.len() as u64,
            },
            imports,
            exported_ast,
            owned_ast,
            raw_data: data.to_vec(),
        })
    }

    /// Check if this BMI is compatible with the current compiler version.
    pub fn is_compatible(&self, expected_version: &str) -> bool {
        self.header.compiler_version == expected_version
    }

    /// Compute a simple checksum of the source content.
    pub fn compute_source_checksum(source: &str) -> u64 {
        let mut hash: u64 = 0xcbf29ce484222325;
        for byte in source.as_bytes() {
            hash ^= *byte as u64;
            hash = hash.wrapping_mul(0x100000001b3);
        }
        hash
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Ownership — ODR checking across modules
// ═══════════════════════════════════════════════════════════════════════════════

/// Tracks which module owns each declaration for ODR checking.
#[derive(Debug, Clone)]
pub struct ModuleOwnershipTracker {
    /// Maps declaration names to the module that owns them.
    pub ownership: HashMap<String, ModuleName>,
    /// Maps declaration names to the module unit that defines them.
    pub definitions: HashMap<String, ModuleName>,
    /// Potential ODR violations detected.
    pub odr_violations: Vec<OdrViolation>,
}

impl ModuleOwnershipTracker {
    pub fn new() -> Self {
        Self {
            ownership: HashMap::new(),
            definitions: HashMap::new(),
            odr_violations: Vec::new(),
        }
    }

    /// Register a declaration as owned by a module.
    pub fn register_declaration(&mut self, decl_name: &str, module: ModuleName) {
        self.ownership.insert(decl_name.to_string(), module);
    }

    /// Register a definition and check for ODR violations.
    pub fn register_definition(&mut self, decl_name: &str, module: ModuleName) {
        if let Some(existing) = self.definitions.get(decl_name) {
            if existing != &module {
                self.odr_violations.push(OdrViolation {
                    declaration: decl_name.to_string(),
                    module_a: existing.clone(),
                    module_b: module,
                    violation_kind: OdrViolationKind::MultipleDefinitions,
                });
            }
        } else {
            self.definitions.insert(decl_name.to_string(), module);
        }
    }

    /// Check if a declaration is exported by a module.
    pub fn is_exported_by(&self, decl_name: &str, module: &ModuleName) -> bool {
        self.ownership
            .get(decl_name)
            .map_or(false, |owner| owner == module)
    }

    /// Get the owning module for a declaration.
    pub fn owner_of(&self, decl_name: &str) -> Option<&ModuleName> {
        self.ownership.get(decl_name)
    }

    /// Clear all tracking data.
    pub fn clear(&mut self) {
        self.ownership.clear();
        self.definitions.clear();
        self.odr_violations.clear();
    }
}

impl Default for ModuleOwnershipTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// A One-Definition Rule violation detected across modules.
#[derive(Debug, Clone)]
pub struct OdrViolation {
    /// The name of the declaration that violates ODR.
    pub declaration: String,
    /// The first module that defines it.
    pub module_a: ModuleName,
    /// The second module that defines it.
    pub module_b: ModuleName,
    /// The kind of ODR violation.
    pub violation_kind: OdrViolationKind,
}

/// Kinds of ODR violations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OdrViolationKind {
    /// Multiple definitions of the same entity.
    MultipleDefinitions,
    /// Inconsistent definitions across modules.
    InconsistentDefinitions,
    /// Missing definition for a declaration.
    MissingDefinition,
    /// Definition not reachable from use point.
    UnreachableDefinition,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Header Unit Support
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a header unit (`import <header>;`).
#[derive(Debug, Clone)]
pub struct HeaderUnit {
    /// The header name (e.g., `<iostream>`, `"myheader.h"`).
    pub header_name: String,
    /// Whether the header is a system header (angle brackets).
    pub is_system_header: bool,
    /// Whether a BMI has been synthesized for this header.
    pub bmi_synthesized: bool,
    /// Path to the synthesized BMI.
    pub bmi_path: Option<PathBuf>,
    /// Path to the header file.
    pub header_path: PathBuf,
    /// The synthesized module name for the header unit.
    pub synthetic_module_name: ModuleName,
    /// All declarations from the header.
    pub declarations: Vec<String>,
}

impl HeaderUnit {
    pub fn new(header_name: &str, header_path: &str, is_system: bool) -> Self {
        // Synthesize a module name from the header name.
        let clean_name = header_name
            .trim_matches(|c: char| c == '<' || c == '>' || c == '"' || c == '.')
            .replace('.', "_")
            .replace('/', "_");
        let synthetic_name = format!("__header_{}", clean_name);

        Self {
            header_name: header_name.to_string(),
            is_system_header: is_system,
            bmi_synthesized: false,
            bmi_path: None,
            header_path: PathBuf::from(header_path),
            synthetic_module_name: ModuleName::from_str(&synthetic_name),
            declarations: Vec::new(),
        }
    }

    /// Mark the BMI as synthesized.
    pub fn synthesize_bmi(&mut self, bmi_path: &str) {
        self.bmi_synthesized = true;
        self.bmi_path = Some(PathBuf::from(bmi_path));
    }

    /// Add a declaration from the header.
    pub fn add_declaration(&mut self, decl: &str) {
        self.declarations.push(decl.to_string());
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Map File Parsing
// ═══════════════════════════════════════════════════════════════════════════════

/// A parsed module map (module.modulemap) entry.
#[derive(Debug, Clone)]
pub struct ModuleMapEntry {
    /// The module name.
    pub name: ModuleName,
    /// Whether this is a framework module.
    pub is_framework: bool,
    /// Whether this module is explicit (must be imported explicitly).
    pub is_explicit: bool,
    /// Header files that comprise this module.
    pub headers: Vec<ModuleMapHeader>,
    /// Sub-modules of this module.
    pub submodules: Vec<ModuleMapEntry>,
    /// Modules this module exports.
    pub exports: Vec<ModuleName>,
    /// Modules this module uses (implicitly imports).
    pub uses: Vec<ModuleName>,
    /// Link libraries for this module.
    pub link_libraries: Vec<String>,
}

impl ModuleMapEntry {
    pub fn new(name: ModuleName) -> Self {
        Self {
            name,
            is_framework: false,
            is_explicit: false,
            headers: Vec::new(),
            submodules: Vec::new(),
            exports: Vec::new(),
            uses: Vec::new(),
            link_libraries: Vec::new(),
        }
    }
}

/// A header file declaration in a module map.
#[derive(Debug, Clone)]
pub struct ModuleMapHeader {
    /// Path to the header file.
    pub path: PathBuf,
    /// Whether this is a textual header (not part of the module's AST).
    pub is_textual: bool,
    /// Whether this is a private header.
    pub is_private: bool,
    /// Whether this is an umbrella header.
    pub is_umbrella: bool,
    /// Size of the header file.
    pub size: u64,
}

impl ModuleMapHeader {
    pub fn new(path: &str) -> Self {
        Self {
            path: PathBuf::from(path),
            is_textual: false,
            is_private: false,
            is_umbrella: false,
            size: 0,
        }
    }
}

/// Parsed module.modulemap file.
#[derive(Debug, Clone)]
pub struct ModuleMapFile {
    /// The path to the module map file.
    pub path: PathBuf,
    /// Top-level module entries.
    pub modules: Vec<ModuleMapEntry>,
    /// Whether the module map has been parsed.
    pub is_parsed: bool,
}

impl ModuleMapFile {
    pub fn new(path: &str) -> Self {
        Self {
            path: PathBuf::from(path),
            modules: Vec::new(),
            is_parsed: false,
        }
    }

    /// Parse a module.map file from its text content.
    pub fn parse(&mut self, content: &str) {
        self.modules.clear();
        // Simplified parser for module.map files
        // In a real implementation, this would handle the full grammar.
        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with("//") {
                continue;
            }
            let tokens: Vec<&str> = trimmed.split_whitespace().collect();
            if tokens.is_empty() {
                continue;
            }

            match tokens[0] {
                "module" if tokens.len() >= 2 => {
                    let name = tokens[1].trim_end_matches('{');
                    let mut entry = ModuleMapEntry::new(ModuleName::from_str(name));
                    if trimmed.contains("framework") {
                        entry.is_framework = true;
                    }
                    if trimmed.contains("explicit") {
                        entry.is_explicit = true;
                    }
                    self.modules.push(entry);
                }
                "header" if tokens.len() >= 2 => {
                    let path = tokens[1].trim_matches('"');
                    if let Some(last) = self.modules.last_mut() {
                        last.headers.push(ModuleMapHeader::new(path));
                    }
                }
                "export" if tokens.len() >= 2 => {
                    if let Some(last) = self.modules.last_mut() {
                        last.exports
                            .push(ModuleName::from_str(tokens[1].trim_end_matches(',')));
                    }
                }
                "link" if tokens.len() >= 2 => {
                    if let Some(last) = self.modules.last_mut() {
                        last.link_libraries
                            .push(tokens[1].trim_matches('"').to_string());
                    }
                }
                "umbrella" if tokens.len() >= 2 => {
                    let path = tokens[1].trim_matches('"');
                    if let Some(last) = self.modules.last_mut() {
                        let mut h = ModuleMapHeader::new(path);
                        h.is_umbrella = true;
                        last.headers.push(h);
                    }
                }
                _ => {}
            }
        }
        self.is_parsed = true;
    }

    /// Get all module names declared in this map.
    pub fn module_names(&self) -> Vec<String> {
        self.modules.iter().map(|m| m.name.to_string()).collect()
    }

    /// Find a module by name.
    pub fn find_module(&self, name: &str) -> Option<&ModuleMapEntry> {
        self.modules.iter().find(|m| m.name.to_string() == name)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Compilation Orchestrator
// ═══════════════════════════════════════════════════════════════════════════════

/// Orchestrates the compilation of a set of module units,
/// respecting dependencies and producing BMIs.
pub struct ModuleCompilationOrchestrator {
    /// The module database.
    pub database: ModuleDatabase,
    /// The ownership tracker for ODR checking.
    pub ownership: ModuleOwnershipTracker,
    /// Registered header units.
    pub header_units: HashMap<String, HeaderUnit>,
    /// Module map files.
    pub module_maps: Vec<ModuleMapFile>,
    /// Whether to rebuild out-of-date BMIs.
    pub rebuild_stale: bool,
    /// Whether to verify BMI compatibility.
    pub verify_compatibility: bool,
}

impl ModuleCompilationOrchestrator {
    pub fn new() -> Self {
        Self {
            database: ModuleDatabase::new(),
            ownership: ModuleOwnershipTracker::new(),
            header_units: HashMap::new(),
            module_maps: Vec::new(),
            rebuild_stale: true,
            verify_compatibility: true,
        }
    }

    /// Register a module unit for compilation.
    pub fn add_unit(&mut self, unit: ModuleUnit) {
        self.database.register_unit(unit);
    }

    /// Register a header unit.
    pub fn add_header_unit(&mut self, header: HeaderUnit) {
        self.header_units.insert(header.header_name.clone(), header);
    }

    /// Load a module map file.
    pub fn load_module_map(&mut self, path: &str, content: &str) {
        let mut map = ModuleMapFile::new(path);
        map.parse(content);
        self.module_maps.push(map);
    }

    /// Compute the optimal compilation order for all modules.
    pub fn compilation_order(&self) -> Vec<String> {
        self.database.topological_order()
    }

    /// Check for any ODR violations in the current module set.
    pub fn check_odr(&mut self) -> Vec<OdrViolation> {
        self.ownership.odr_violations.clone()
    }

    /// Generate a report of all modules and their dependencies.
    pub fn generate_dependency_report(&self) -> String {
        let mut report = String::new();
        report.push_str("# Module Dependency Report\n\n");

        for (name, units) in &self.database.units {
            report.push_str(&format!("## Module: {}\n\n", name));
            for unit in units {
                report.push_str(&format!(
                    "- Unit: {} ({})\n",
                    unit.source_path.display(),
                    unit.kind.label()
                ));
                if let Some(ref part) = unit.partition {
                    report.push_str(&format!("  Partition: {}\n", part));
                }
                if !unit.imports.is_empty() {
                    report.push_str("  Imports:\n");
                    for imp in &unit.imports {
                        report.push_str(&format!("    - {}\n", imp));
                    }
                }
                if !unit.header_imports.is_empty() {
                    report.push_str("  Header imports:\n");
                    for h in &unit.header_imports {
                        report.push_str(&format!("    - {}\n", h));
                    }
                }
            }
            report.push('\n');
        }

        if let Some(reach) = self.database.reachability.get("") {
            report.push_str("Reachability computed.\n");
        }

        report
    }

    /// Summary of the module compilation state.
    pub fn summary(&self) -> String {
        format!(
            "Modules: {} total, {} headers, {} module maps loaded, topological order: {:?}",
            self.database.len(),
            self.header_units.len(),
            self.module_maps.len(),
            self.compilation_order(),
        )
    }
}

impl Default for ModuleCompilationOrchestrator {
    fn default() -> Self {
        Self::new()
    }
}

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

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

    // ── ModuleUnitKind ──────────────────────────────────────────────────────

    #[test]
    fn test_module_unit_kind_labels() {
        assert_eq!(ModuleUnitKind::ModuleInterface.label(), "module interface");
        assert_eq!(
            ModuleUnitKind::ModuleImplementation.label(),
            "module implementation"
        );
        assert!(ModuleUnitKind::ModuleInterface.is_interface());
        assert!(!ModuleUnitKind::ModuleImplementation.is_interface());
    }

    #[test]
    fn test_module_unit_kind_is_partition() {
        assert!(ModuleUnitKind::ModulePartitionInterface.is_partition());
        assert!(!ModuleUnitKind::ModuleInterface.is_partition());
    }

    // ── ModuleUnit ────────────────────────────────────────────────────────

    #[test]
    fn test_module_unit_new() {
        let unit = ModuleUnit::new(
            ModuleName::from_str("std.core"),
            ModuleUnitKind::ModuleInterface,
            "src/std.core.cppm",
        );
        assert_eq!(unit.name.to_string(), "std.core");
        assert!(unit.is_interface());
        assert!(unit.is_primary);
    }

    #[test]
    fn test_module_unit_with_partition() {
        let unit = ModuleUnit::new(
            ModuleName::from_str("std"),
            ModuleUnitKind::ModulePartitionInterface,
            "src/std-io.cppm",
        )
        .with_partition("io");
        assert_eq!(unit.partition, Some("io".to_string()));
    }

    #[test]
    fn test_module_unit_add_import() {
        let mut unit = ModuleUnit::new(
            ModuleName::from_str("mymod"),
            ModuleUnitKind::ModuleInterface,
            "src/mod.cppm",
        );
        unit.add_import(ModuleName::from_str("std.core"));
        assert_eq!(unit.imports.len(), 1);
    }

    #[test]
    fn test_module_unit_add_exported_decl() {
        let mut unit = ModuleUnit::new(
            ModuleName::from_str("mymod"),
            ModuleUnitKind::ModuleInterface,
            "src/mod.cppm",
        );
        unit.add_exported_decl("int f();");
        unit.add_owned_decl("static int x;");
        assert_eq!(unit.exported_decls.len(), 1);
        assert_eq!(unit.owned_decls.len(), 1);
        assert_eq!(unit.all_decls().len(), 2);
    }

    // ── ModuleDatabase ───────────────────────────────────────────────────────

    #[test]
    fn test_database_register_unit() {
        let mut db = ModuleDatabase::new();
        let unit = ModuleUnit::new(
            ModuleName::from_str("mymod"),
            ModuleUnitKind::ModuleInterface,
            "src/mymod.cppm",
        );
        db.register_unit(unit);
        assert_eq!(db.len(), 1);
        assert!(db.primary_interface("mymod").is_some());
    }

    #[test]
    fn test_database_resolve_import() {
        let mut db = ModuleDatabase::new();
        let mut unit = ModuleUnit::new(
            ModuleName::from_str("mymod"),
            ModuleUnitKind::ModuleInterface,
            "src/mymod.cppm",
        );
        unit.set_bmi_path("/cache/mymod.bmi");
        db.register_unit(unit);

        let resolution = db.resolve_import("mymod");
        assert!(resolution.is_some());
    }

    #[test]
    fn test_database_dependency_graph() {
        let mut db = ModuleDatabase::new();

        let mut mod_a = ModuleUnit::new(
            ModuleName::from_str("A"),
            ModuleUnitKind::ModuleInterface,
            "A.cppm",
        );
        mod_a.add_import(ModuleName::from_str("B"));

        let mod_b = ModuleUnit::new(
            ModuleName::from_str("B"),
            ModuleUnitKind::ModuleInterface,
            "B.cppm",
        );

        db.register_unit(mod_a);
        db.register_unit(mod_b);
        db.build_dependency_graph();

        assert!(db.dependency_graph.contains_key("A"));
        assert!(db.dependency_graph["A"].contains("B"));
    }

    #[test]
    fn test_database_topological_order() {
        let mut db = ModuleDatabase::new();

        let mut mod_a = ModuleUnit::new(
            ModuleName::from_str("A"),
            ModuleUnitKind::ModuleInterface,
            "A.cppm",
        );
        mod_a.add_import(ModuleName::from_str("B"));

        let mod_b = ModuleUnit::new(
            ModuleName::from_str("B"),
            ModuleUnitKind::ModuleInterface,
            "B.cppm",
        );

        db.register_unit(mod_a);
        db.register_unit(mod_b);
        db.build_dependency_graph();

        let order = db.topological_order();
        assert_eq!(order.len(), 2);
        assert!(order[0] == "B"); // B has no deps, should come first
        assert!(order[1] == "A");
    }

    #[test]
    fn test_database_no_cycles() {
        let mut db = ModuleDatabase::new();
        let mod_a = ModuleUnit::new(
            ModuleName::from_str("A"),
            ModuleUnitKind::ModuleInterface,
            "A.cppm",
        );
        let mod_b = ModuleUnit::new(
            ModuleName::from_str("B"),
            ModuleUnitKind::ModuleInterface,
            "B.cppm",
        );
        db.register_unit(mod_a);
        db.register_unit(mod_b);
        db.build_dependency_graph();
        assert!(!db.has_cycles());
    }

    #[test]
    fn test_database_compute_reachability() {
        let mut db = ModuleDatabase::new();

        let mut mod_a = ModuleUnit::new(
            ModuleName::from_str("A"),
            ModuleUnitKind::ModuleInterface,
            "A.cppm",
        );
        mod_a.add_import(ModuleName::from_str("B"));

        let mut mod_b = ModuleUnit::new(
            ModuleName::from_str("B"),
            ModuleUnitKind::ModuleInterface,
            "B.cppm",
        );
        mod_b.add_import(ModuleName::from_str("C"));

        let mod_c = ModuleUnit::new(
            ModuleName::from_str("C"),
            ModuleUnitKind::ModuleInterface,
            "C.cppm",
        );

        db.register_unit(mod_a);
        db.register_unit(mod_b);
        db.register_unit(mod_c);
        db.build_dependency_graph();
        db.compute_reachability();

        assert!(db.is_reachable("A", "C"));
    }

    // ── BMI ─────────────────────────────────────────────────────────────────

    #[test]
    fn test_bmi_serialize_deserialize() {
        let name = ModuleName::from_str("test.mod");
        let mut bmi = BinaryModuleInterface::new(name);
        bmi.imports
            .push(ModuleImport::new(ModuleName::from_str("std.core")));
        bmi.exported_ast = b"int f(); int g();".to_vec();
        bmi.header.source_checksum = BinaryModuleInterface::compute_source_checksum("test");

        let serialized = bmi.serialize();
        let deserialized = BinaryModuleInterface::deserialize(&serialized);
        assert!(deserialized.is_some());

        let deser = deserialized.unwrap();
        assert_eq!(deser.header.module_name.to_string(), "test.mod");
        assert_eq!(deser.imports.len(), 1);
        assert_eq!(deser.exported_ast, b"int f(); int g();".to_vec());
    }

    #[test]
    fn test_bmi_compatibility_check() {
        let bmi = BinaryModuleInterface::new(ModuleName::from_str("test"));
        assert!(bmi.is_compatible("llvm-native 1.0"));
        assert!(!bmi.is_compatible("other-compiler 2.0"));
    }

    #[test]
    fn test_bmi_source_checksum() {
        let cs1 = BinaryModuleInterface::compute_source_checksum("hello");
        let cs2 = BinaryModuleInterface::compute_source_checksum("hello");
        assert_eq!(cs1, cs2);

        let cs3 = BinaryModuleInterface::compute_source_checksum("world");
        assert_ne!(cs1, cs3);
    }

    // ── ModuleOwnershipTracker ──────────────────────────────────────────────

    #[test]
    fn test_ownership_tracker_register() {
        let mut tracker = ModuleOwnershipTracker::new();
        tracker.register_declaration("f", ModuleName::from_str("A"));
        assert_eq!(tracker.owner_of("f").unwrap().to_string(), "A");
    }

    #[test]
    fn test_ownership_tracker_is_exported_by() {
        let mut tracker = ModuleOwnershipTracker::new();
        tracker.register_declaration("f", ModuleName::from_str("A"));
        assert!(tracker.is_exported_by("f", &ModuleName::from_str("A")));
        assert!(!tracker.is_exported_by("f", &ModuleName::from_str("B")));
    }

    #[test]
    fn test_ownership_tracker_odr_violation() {
        let mut tracker = ModuleOwnershipTracker::new();
        tracker.register_definition("f", ModuleName::from_str("A"));
        tracker.register_definition("f", ModuleName::from_str("B"));
        assert_eq!(tracker.odr_violations.len(), 1);
    }

    // ── HeaderUnit ─────────────────────────────────────────────────────────

    #[test]
    fn test_header_unit_new() {
        let header = HeaderUnit::new("<vector>", "/usr/include/c++/vector", true);
        assert!(header.is_system_header);
        assert_eq!(header.synthetic_module_name.to_string(), "__header_vector");
    }

    #[test]
    fn test_header_unit_synthesize_bmi() {
        let mut header = HeaderUnit::new("<iostream>", "/usr/include/c++/iostream", true);
        header.synthesize_bmi("/cache/iostream.bmi");
        assert!(header.bmi_synthesized);
        assert!(header.bmi_path.is_some());
    }

    // ── ModuleMapFile ─────────────────────────────────────────────────────

    #[test]
    fn test_module_map_parse() {
        let content = r#"
module std {
  header "string"
  header "vector"
  export *
}
"#;
        let mut map = ModuleMapFile::new("module.modulemap");
        map.parse(content);
        assert!(map.is_parsed);
        assert_eq!(map.modules.len(), 1);
        assert_eq!(map.modules[0].headers.len(), 2);
    }

    #[test]
    fn test_module_map_find() {
        let content = "module Foo { header \"foo.h\" }";
        let mut map = ModuleMapFile::new("module.modulemap");
        map.parse(content);
        assert!(map.find_module("Foo").is_some());
        assert!(map.find_module("Bar").is_none());
    }

    #[test]
    fn test_module_map_with_link() {
        let content = "module Bar { header \"bar.h\" link \"z\" }";
        let mut map = ModuleMapFile::new("module.modulemap");
        map.parse(content);
        assert_eq!(map.modules[0].link_libraries.len(), 1);
        assert_eq!(map.modules[0].link_libraries[0], "z");
    }

    // ── ModuleCompilationOrchestrator ──────────────────────────────────────

    #[test]
    fn test_orchestrator_add_unit() {
        let mut orch = ModuleCompilationOrchestrator::new();
        let unit = ModuleUnit::new(
            ModuleName::from_str("test"),
            ModuleUnitKind::ModuleInterface,
            "test.cppm",
        );
        orch.add_unit(unit);
        assert_eq!(orch.database.len(), 1);
    }

    #[test]
    fn test_orchestrator_add_header_unit() {
        let mut orch = ModuleCompilationOrchestrator::new();
        let header = HeaderUnit::new("<vector>", "/usr/include/c++/vector", true);
        orch.add_header_unit(header);
        assert_eq!(orch.header_units.len(), 1);
    }

    #[test]
    fn test_orchestrator_compilation_order() {
        let mut orch = ModuleCompilationOrchestrator::new();

        let mut mod_a = ModuleUnit::new(
            ModuleName::from_str("A"),
            ModuleUnitKind::ModuleInterface,
            "A.cppm",
        );
        mod_a.add_import(ModuleName::from_str("B"));
        let mod_b = ModuleUnit::new(
            ModuleName::from_str("B"),
            ModuleUnitKind::ModuleInterface,
            "B.cppm",
        );

        orch.add_unit(mod_a);
        orch.add_unit(mod_b);

        let order = orch.compilation_order();
        assert_eq!(order, vec!["B", "A"]);
    }
}