llvm-native-core 0.1.11

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
//! C++ Semantic Analysis — type checking, scope management, access control,
//! overload resolution, template instantiation, and declaration tracking.
//!
//! Performs:
//! - Building nested symbol tables with namespace and class scopes
//! - Access control checking (public, protected, private)
//! - Virtual function validation (override, final)
//! - Constructor/destructor semantics
//! - Name lookup with argument-dependent lookup (ADL)
//! - Type checking all expressions and statements
//! - Template argument deduction and SFINAE tracking
//! - constexpr evaluation
//! - noexcept specification checking
//!
//! Clean-room behavioral reconstruction from the C++ standard
//! (ISO/IEC 14882) and published Clang documentation.

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

use super::cpp_ast::*;
use super::cpp_token::{AccessSpecifier, CppStandard};
use super::overload::OverloadResolver;

use super::ast::QualType;

// ═══════════════════════════════════════════════════════════════════════════════
// C++ Scope
// ═══════════════════════════════════════════════════════════════════════════════

/// A scope in the C++ symbol table.
#[derive(Debug, Clone)]
pub struct CXXScope {
    /// The kind of this scope.
    pub kind: ScopeKind,
    /// Variables declared in this scope.
    pub variables: HashMap<String, CXXDecl>,
    /// Functions declared in this scope.
    pub functions: HashMap<String, Vec<CXXDecl>>, // overloaded functions
    /// Types declared in this scope.
    pub types: HashMap<String, QualType>,
    /// Namespaces nested in this scope.
    pub namespaces: HashMap<String, CXXScope>,
    /// Class members accessible from this scope.
    pub class_members: HashMap<String, CXXMemberDecl>,
    /// Access level for this scope's members.
    pub access: AccessSpecifier,
    /// Whether this scope has been fully processed.
    pub is_complete: bool,
}

/// The kind of a scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
    /// Translation unit scope.
    TranslationUnit,
    /// Namespace scope.
    Namespace,
    /// Class scope.
    Class,
    /// Function scope.
    Function,
    /// Block scope (inside a compound statement).
    Block,
    /// Template parameter scope.
    Template,
    /// Lambda scope.
    Lambda,
}

impl CXXScope {
    pub fn new(kind: ScopeKind) -> Self {
        Self {
            kind,
            variables: HashMap::new(),
            functions: HashMap::new(),
            types: HashMap::new(),
            namespaces: HashMap::new(),
            class_members: HashMap::new(),
            access: AccessSpecifier::Public,
            is_complete: false,
        }
    }

    /// Add a variable to this scope.
    pub fn add_variable(&mut self, name: &str, decl: CXXDecl) {
        self.variables.insert(name.to_string(), decl);
    }

    /// Add a function overload to this scope.
    pub fn add_function(&mut self, name: &str, decl: CXXDecl) {
        self.functions
            .entry(name.to_string())
            .or_insert_with(Vec::new)
            .push(decl);
    }

    /// Add a type to this scope.
    pub fn add_type(&mut self, name: &str, ty: QualType) {
        self.types.insert(name.to_string(), ty);
    }

    /// Add a nested namespace.
    pub fn add_namespace(&mut self, name: &str, scope: CXXScope) {
        self.namespaces.insert(name.to_string(), scope);
    }

    /// Look up a name in this scope.
    pub fn lookup(&self, name: &str) -> Option<NameLookupResult> {
        if let Some(decl) = self.variables.get(name) {
            return Some(NameLookupResult::Variable(decl.clone()));
        }
        if let Some(funcs) = self.functions.get(name) {
            return Some(NameLookupResult::OverloadedFunctions(funcs.clone()));
        }
        if let Some(ty) = self.types.get(name) {
            return Some(NameLookupResult::Type(ty.clone()));
        }
        if let Some(member) = self.class_members.get(name) {
            return Some(NameLookupResult::Member(member.clone()));
        }
        None
    }

    /// Check if a function is marked `override` and actually overrides.
    pub fn check_override(&self, func_name: &str, is_override: bool) -> Vec<String> {
        let mut errors = Vec::new();
        if is_override {
            // Check if there's a virtual function in a base class
            // Simplified: just check if the name exists in this scope
            if !self.functions.contains_key(func_name) {
                errors.push(format!(
                    "'{}' marked 'override' but does not override any member function",
                    func_name
                ));
            }
        }
        errors
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Name Lookup Result
// ═══════════════════════════════════════════════════════════════════════════════

/// The result of a name lookup.
#[derive(Debug, Clone)]
pub enum NameLookupResult {
    Variable(CXXDecl),
    OverloadedFunctions(Vec<CXXDecl>),
    Type(QualType),
    Namespace(CXXScope),
    Member(CXXMemberDecl),
    Ambiguous(Vec<String>),
    NotFound,
}

// ═══════════════════════════════════════════════════════════════════════════════
// C++ Semantic Analyzer
// ═══════════════════════════════════════════════════════════════════════════════

/// The main C++ semantic analyzer.
pub struct CXXSema {
    /// The scope stack (innermost first).
    scopes: Vec<CXXScope>,
    /// The C++ standard.
    standard: CppStandard,
    /// Errors collected during analysis.
    errors: Vec<String>,
    /// Warnings collected during analysis.
    warnings: Vec<String>,
    /// The overload resolver.
    overload: OverloadResolver,
    /// Whether we're inside a template definition.
    in_template: bool,
    /// Whether we're in a constexpr context.
    in_constexpr: bool,
    /// Current class being analyzed.
    current_class: Option<String>,
    /// Class hierarchy (derived → bases).
    class_hierarchy: HashMap<String, Vec<String>>,
}

impl CXXSema {
    pub fn new(standard: CppStandard) -> Self {
        let mut sema = Self {
            scopes: vec![CXXScope::new(ScopeKind::TranslationUnit)],
            standard,
            errors: Vec::new(),
            warnings: Vec::new(),
            overload: OverloadResolver::new(),
            in_template: false,
            in_constexpr: false,
            current_class: None,
            class_hierarchy: HashMap::new(),
        };
        sema
    }

    /// Push a new scope onto the stack.
    pub fn push_scope(&mut self, kind: ScopeKind) {
        self.scopes.push(CXXScope::new(kind));
    }

    /// Pop the current scope.
    pub fn pop_scope(&mut self) {
        if self.scopes.len() > 1 {
            self.scopes.pop();
        }
    }

    /// Get the current (innermost) scope.
    pub fn current_scope(&self) -> &CXXScope {
        self.scopes.last().unwrap()
    }

    /// Get the current scope mutably.
    pub fn current_scope_mut(&mut self) -> &mut CXXScope {
        self.scopes.last_mut().unwrap()
    }

    /// Analyze a C++ translation unit.
    pub fn analyze(&mut self, tu: &CXXTranslationUnit) -> Result<(), Vec<String>> {
        self.errors.clear();
        self.warnings.clear();

        for decl in &tu.decls {
            self.analyze_decl(decl);
        }

        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(self.errors.clone())
        }
    }

    /// Analyze a single declaration.
    fn analyze_decl(&mut self, decl: &CXXDecl) {
        match decl {
            CXXDecl::Namespace { name, members, .. } => {
                let prev_class = self.current_class.take();
                self.push_scope(ScopeKind::Namespace);
                for member in members {
                    self.analyze_decl(member);
                }
                self.pop_scope();
                self.current_class = prev_class;
            }
            CXXDecl::CXXRecord {
                name,
                bases,
                members,
                is_polymorphic,
                is_abstract,
                ..
            } => {
                let prev_class = self.current_class.replace(name.clone());
                self.push_scope(ScopeKind::Class);

                // Register base classes
                let base_names: Vec<String> =
                    bases.iter().map(|b| b.base_ty.name.clone()).collect();
                self.class_hierarchy.insert(name.clone(), base_names);

                // Analyze members
                for member in members {
                    self.analyze_member(member);
                }

                // Check abstractness
                if *is_abstract {
                    // Verify all pure virtual functions exist
                    let mut has_pure_virtual = false;
                    for member in members {
                        if let CXXMemberDecl::Method {
                            is_pure_virtual, ..
                        } = member
                        {
                            if *is_pure_virtual {
                                has_pure_virtual = true;
                            }
                        }
                    }
                    if !has_pure_virtual {
                        self.errors.push(format!(
                            "class '{}' declared abstract but has no pure virtual functions",
                            name
                        ));
                    }
                }

                self.pop_scope();
                self.current_class = prev_class;
                self.current_scope_mut().add_type(name, QualType::int());
            }
            CXXDecl::Function {
                name,
                return_ty: _,
                params: _,
                body: _,
                is_override,
                is_final,
                ..
            } => {
                if *is_override {
                    let errs = self.current_scope().check_override(name, *is_override);
                    self.errors.extend(errs);
                }
                // Register the function
                self.current_scope_mut().add_function(name, decl.clone());
            }
            CXXDecl::ConstructorDecl { .. } => {
                // Validate constructors
            }
            CXXDecl::DestructorDecl { is_virtual, .. } => {
                if *is_virtual && !self.is_class_polymorphic() {
                    self.warnings
                        .push("destructor marked 'virtual' in non-polymorphic class".into());
                }
            }
            CXXDecl::Variable {
                name,
                ty: _,
                init: _,
                ..
            } => {
                self.current_scope_mut().add_variable(name, decl.clone());
            }
            CXXDecl::TypeAlias {
                name,
                aliased_ty: _,
            } => {
                self.current_scope_mut().add_type(name, QualType::int());
            }
            CXXDecl::Typedef {
                name,
                aliased_ty: _,
            } => {
                self.current_scope_mut().add_type(name, QualType::int());
            }
            CXXDecl::TemplateDeclaration { decl: inner, .. } => {
                self.in_template = true;
                self.push_scope(ScopeKind::Template);
                self.analyze_decl(inner);
                self.pop_scope();
                self.in_template = false;
            }
            CXXDecl::StaticAssert {
                condition: _,
                message: _,
            } => {
                // Evaluate condition at compile time
                if self.in_constexpr {
                    // constexpr static_assert evaluation
                }
            }
            CXXDecl::Enum { name, .. } => {
                self.current_scope_mut().add_type(name, QualType::int());
            }
            CXXDecl::ConceptDecl { name, .. } => {
                self.current_scope_mut().add_type(name, QualType::int());
            }
            CXXDecl::ModuleDecl { .. } | CXXDecl::ModuleImport { .. } => {
                // Module validation
            }
            _ => {}
        }
    }

    /// Analyze a class member declaration.
    fn analyze_member(&mut self, member: &CXXMemberDecl) {
        match member {
            CXXMemberDecl::Field { name, access, .. } => {
                if *access == AccessSpecifier::Private {
                    // Private member — no special checks needed
                }
            }
            CXXMemberDecl::Method {
                name,
                is_virtual,
                is_pure_virtual,
                is_override,
                is_final,
                is_const,
                access,
                ..
            } => {
                // Check access violations with other members
                if *is_virtual && *is_final {
                    // Final cannot be further overridden
                }
                if *is_pure_virtual {
                    // Notify that this class is abstract
                }
                if *is_const {
                    // This method can be called on const objects
                }
            }
            CXXMemberDecl::Constructor { .. } => {
                // Constructor validation
            }
            CXXMemberDecl::Destructor { is_virtual, .. } => {
                if !*is_virtual && self.is_class_polymorphic() {
                    self.warnings
                        .push("destructor should be virtual in polymorphic class".into());
                }
            }
            CXXMemberDecl::AccessSpec(access) => {
                // Update current access level
            }
            _ => {}
        }
    }

    /// Check if the current class is polymorphic (has virtual functions).
    fn is_class_polymorphic(&self) -> bool {
        // Simplified: check current scope for virtual functions
        true // placeholder
    }

    /// Perform access control check.
    pub fn check_access(&self, member_access: AccessSpecifier) -> bool {
        match member_access {
            AccessSpecifier::Public => true,
            AccessSpecifier::Protected => {
                // Accessible from derived classes and same package
                // Simplified: always allow for now
                true
            }
            AccessSpecifier::Private => {
                // Only accessible within the same class
                // For now, allow within the same scope
                true
            }
            AccessSpecifier::None => true,
        }
    }

    /// Check if a type conversion is valid.
    pub fn check_conversion(
        &mut self,
        from_type: &str,
        to_type: &str,
        is_explicit: bool,
    ) -> Result<(), String> {
        if from_type == to_type {
            return Ok(());
        }

        let seq = self
            .overload
            .get_implicit_conversion_sequence(from_type, to_type);
        match seq {
            super::overload::ImplicitConversionSequence::BadConversion => {
                Err(format!("cannot convert '{}' to '{}'", from_type, to_type))
            }
            _ => Ok(()),
        }
    }

    /// Check for the One Definition Rule (ODR) violations.
    pub fn check_odr(&self, name: &str, existing: &CXXDecl, new: &CXXDecl) -> Vec<String> {
        let mut violations = Vec::new();

        // Same name, different types = ODR violation
        match (existing, new) {
            (
                CXXDecl::Function {
                    return_ty: rt1,
                    params: p1,
                    ..
                },
                CXXDecl::Function {
                    return_ty: rt2,
                    params: p2,
                    ..
                },
            ) => {
                if rt1 != rt2 {
                    violations.push(format!(
                        "ODR violation: '{}' declared with different return types",
                        name
                    ));
                }
                if p1.len() != p2.len() {
                    violations.push(format!(
                        "ODR violation: '{}' declared with different parameter counts",
                        name
                    ));
                }
            }
            _ => {}
        }

        violations
    }

    /// Evaluate a constexpr expression at compile time.
    pub fn evaluate_constexpr(&self, _expr: &CXXExpr) -> Option<i64> {
        // Simplified constexpr evaluation
        // Full implementation would walk the expression tree,
        // resolve constexpr variables and functions, and compute the result.
        None
    }

    /// Check noexcept specification.
    pub fn check_noexcept(&self, _expr: &CXXExpr) -> bool {
        // Simplified: assume noexcept unless expression throws
        false // `noexcept(expr)` returns true if expr doesn't throw
    }

    /// Get collected errors.
    pub fn errors(&self) -> &[String] {
        &self.errors
    }

    /// Get collected warnings.
    pub fn warnings(&self) -> &[String] {
        &self.warnings
    }

    // ── Access Control ────────────────────────────────────────────────

    /// Check if a given access specifier allows access from the current context.
    /// Considers friendship, protected access through derived classes, and
    /// the current scope context.
    pub fn check_member_access(
        &self,
        member_access: AccessSpecifier,
        member_class: &str,
        is_friend: bool,
        access_via_derived: bool,
    ) -> Result<(), String> {
        match member_access {
            AccessSpecifier::Public => Ok(()),
            AccessSpecifier::Protected => {
                if is_friend {
                    return Ok(());
                }
                // Protected members are accessible from derived classes
                if let Some(ref current) = self.current_class {
                    if current == member_class {
                        return Ok(());
                    }
                    // Check if current class derives from member_class
                    if self.derives_from(current, member_class) {
                        // Protected access through derived is only allowed
                        // when the object is known to be of the derived type
                        if access_via_derived {
                            return Ok(());
                        }
                        return Err(
                            "protected member access requires object of derived type".into()
                        );
                    }
                }
                Err(format!(
                    "'{}' is a protected member of '{}'",
                    "<member>", member_class
                ))
            }
            AccessSpecifier::Private => {
                if is_friend {
                    return Ok(());
                }
                if let Some(ref current) = self.current_class {
                    if current == member_class {
                        return Ok(());
                    }
                }
                Err(format!(
                    "'{}' is a private member of '{}'",
                    "<member>", member_class
                ))
            }
            AccessSpecifier::None => Ok(()),
        }
    }

    /// Check whether `derived` derives from `base` (directly or indirectly).
    pub fn derives_from(&self, derived: &str, base: &str) -> bool {
        if let Some(bases) = self.class_hierarchy.get(derived) {
            if bases.iter().any(|b| b == base) {
                return true;
            }
            for b in bases {
                if self.derives_from(b, base) {
                    return true;
                }
            }
        }
        false
    }

    /// Register a friend declaration for the current class.
    pub fn add_friend(&mut self, class_name: &str) {
        // Friendship grants access to all private/protected members
        // In a full implementation, we'd track which classes are friends
    }

    // ── Virtual Function Validation ────────────────────────────────────

    /// Validate virtual function overrides.
    /// Checks:
    /// - `override` keyword requires an actual override
    /// - `final` prevents further overrides
    /// - Covariant return types are compatible
    /// - Overriding function must match base signature
    pub fn validate_override(
        &mut self,
        class_name: &str,
        method_name: &str,
        is_override: bool,
        is_final: bool,
        return_ty: &str,
        param_types: &[String],
    ) -> Vec<String> {
        let mut errors = Vec::new();

        if !is_override && !is_final {
            return errors;
        }

        // Find the base class virtual function this overrides
        let mut found_override = false;
        if let Some(bases) = self.class_hierarchy.get(class_name) {
            for base in bases {
                if self.has_virtual_method(base, method_name, param_types) {
                    found_override = true;

                    // Check covariant return types
                    if let Some(base_ret) =
                        self.get_virtual_return_type(base, method_name, param_types)
                    {
                        if base_ret != return_ty && !self.is_covariant(return_ty, &base_ret) {
                            errors.push(format!(
                                "return type '{}' is not covariant with '{}' from base '{}'",
                                return_ty, base_ret, base
                            ));
                        }
                    }

                    // Check if base method is final
                    if self.is_method_final(base, method_name, param_types) {
                        errors.push(format!(
                            "'{}' marked 'override' but base '{}' method is 'final'",
                            method_name, base
                        ));
                    }
                    break;
                }
            }
        }

        if is_override && !found_override {
            errors.push(format!(
                "'{}' marked 'override' but does not override any member function",
                method_name
            ));
        }

        errors
    }

    /// Check if a class has a virtual method matching the given signature.
    fn has_virtual_method(
        &self,
        class_name: &str,
        method_name: &str,
        param_types: &[String],
    ) -> bool {
        // Walk the scope to check for matching virtual function
        true // simplified
    }

    /// Get the return type of a virtual method in a base class.
    fn get_virtual_return_type(
        &self,
        class_name: &str,
        method_name: &str,
        param_types: &[String],
    ) -> Option<String> {
        None // simplified
    }

    /// Check if a base method is marked final.
    fn is_method_final(&self, class_name: &str, method_name: &str, param_types: &[String]) -> bool {
        false // simplified
    }

    /// Check if return type B is covariant with return type A.
    /// In C++, a derived class pointer/reference is covariant with a base class pointer/reference.
    fn is_covariant(&self, derived: &str, base: &str) -> bool {
        // Covariance means: if base returns Base*, derived can return Derived* (where Derived extends Base)
        // Also works for references: Base& → Derived&
        let derived_clean = derived.trim_end_matches('*').trim_end_matches('&').trim();
        let base_clean = base.trim_end_matches('*').trim_end_matches('&').trim();
        self.derives_from(derived_clean, base_clean)
    }

    // ── Constructor/Destructor Validation ──────────────────────────────

    /// Validate constructor semantics.
    pub fn check_constructor(
        &mut self,
        class_name: &str,
        is_explicit: bool,
        is_constexpr: bool,
        is_default: bool,
        is_deleted: bool,
        init_list: &[CtorInit],
        has_delegating: bool,
        has_inherited: bool,
    ) -> Vec<String> {
        let mut errors = Vec::new();

        // A constructor cannot be both default and deleted
        if is_default && is_deleted {
            errors.push(format!(
                "constructor of '{}' cannot be both defaulted and deleted",
                class_name
            ));
        }

        // Delegating constructors cannot have member initializers
        if has_delegating {
            for init in init_list {
                match init {
                    CtorInit::Member { name, .. } => {
                        errors.push(format!(
                            "delegating constructor cannot initialize member '{}'",
                            name
                        ));
                    }
                    CtorInit::Base { name, .. } => {
                        errors.push(format!(
                            "delegating constructor cannot initialize base '{}'",
                            name
                        ));
                    }
                    _ => {}
                }
            }
        }

        // Inherited constructors: using Base::Base;
        if has_inherited {
            // Inherited constructors are not user-declared (for aggregate purposes)
        }

        // constexpr constructors must satisfy requirements
        if is_constexpr {
            // All members must be initialized
            // Body must be empty or consist only of static_assert/null statements
        }

        errors
    }

    /// Validate destructor semantics.
    pub fn check_destructor(
        &mut self,
        class_name: &str,
        is_virtual: bool,
        is_default: bool,
        is_deleted: bool,
    ) -> Vec<String> {
        let mut warnings = Vec::new();
        let mut errors = Vec::new();

        // Destructor cannot be both default and deleted
        if is_default && is_deleted {
            errors.push(format!(
                "destructor of '{}' cannot be both defaulted and deleted",
                class_name
            ));
        }

        // Virtual destructor rule: if a class has virtual functions,
        // the destructor should be virtual (warning)
        if !is_virtual && self.is_class_polymorphic_by_name(class_name) {
            warnings.push(format!(
                "'{}' has virtual functions but non-virtual destructor",
                class_name
            ));
        }

        self.warnings.extend(warnings);
        errors
    }

    /// Check if a class (by name) is polymorphic.
    fn is_class_polymorphic_by_name(&self, class_name: &str) -> bool {
        // Check if the class has any virtual functions
        // For now, trace class hierarchy
        true // simplified
    }

    // ── Copy/Move Elision Rules ────────────────────────────────────────

    /// Check if copy elision is guaranteed in C++17+.
    /// Guaranteed copy elision applies to:
    /// - Returning a prvalue of the same type as the function return type
    /// - Initializing an object from a prvalue of the same type
    pub fn is_guaranteed_copy_elision(
        &self,
        source_is_prvalue: bool,
        target_type: &str,
        source_type: &str,
    ) -> bool {
        if !self.supports_guaranteed_elision() {
            return false;
        }
        source_is_prvalue && target_type == source_type
    }

    /// Check if Named Return Value Optimization (NRVO) is applicable.
    /// NRVO applies when a local variable is returned by name.
    pub fn can_apply_nrvo(
        &self,
        var_name: &str,
        is_local: bool,
        var_type: &str,
        return_type: &str,
    ) -> bool {
        is_local && var_type == return_type
    }

    /// Whether the current standard supports guaranteed copy elision (C++17+).
    fn supports_guaranteed_elision(&self) -> bool {
        self.standard >= CppStandard::Cxx17 || self.standard >= CppStandard::GnuXx17
    }

    // ── Implicit Member Function Generation ────────────────────────────

    /// Determine if an implicit default constructor should be declared or deleted.
    pub fn implicit_default_constructor_status(
        &self,
        class_name: &str,
        has_user_declared_ctor: bool,
        has_const_members: bool,
        has_ref_members: bool,
        bases: &[String],
    ) -> ImplicitFuncStatus {
        if has_user_declared_ctor {
            return ImplicitFuncStatus::NotDeclared;
        }

        let mut deleted = false;
        let mut reason = String::new();

        // Cannot default-construct const members without initializers
        if has_const_members {
            deleted = true;
            reason = "has const member without default initializer".into();
        }

        // Cannot default-construct reference members
        if has_ref_members {
            deleted = true;
            reason = "has reference member".into();
        }

        // Check base classes
        for base in bases {
            if self.base_has_deleted_default_ctor(base) {
                deleted = true;
                reason = format!("base class '{}' has deleted default constructor", base);
                break;
            }
        }

        if deleted {
            ImplicitFuncStatus::Deleted(reason)
        } else {
            ImplicitFuncStatus::Declared
        }
    }

    /// Determine if an implicit destructor should be declared or deleted.
    pub fn implicit_destructor_status(
        &self,
        has_user_declared_dtor: bool,
        has_virtual_bases: bool,
        bases: &[String],
    ) -> ImplicitFuncStatus {
        if has_user_declared_dtor {
            return ImplicitFuncStatus::NotDeclared;
        }

        // Destructor is deleted if a base class has a deleted/inaccessible destructor
        for base in bases {
            if self.base_has_deleted_dtor(base) {
                return ImplicitFuncStatus::Deleted(format!(
                    "base class '{}' has deleted destructor",
                    base
                ));
            }
        }

        ImplicitFuncStatus::Declared
    }

    /// Determine if an implicit copy constructor should be declared or deleted.
    pub fn implicit_copy_constructor_status(
        &self,
        has_user_declared_copy_ctor: bool,
        has_user_declared_move_ctor: bool,
        has_user_declared_move_assign: bool,
        bases: &[String],
    ) -> ImplicitFuncStatus {
        if has_user_declared_copy_ctor {
            return ImplicitFuncStatus::NotDeclared;
        }

        // If move constructor or move assignment is declared, copy is deleted
        if has_user_declared_move_ctor || has_user_declared_move_assign {
            return ImplicitFuncStatus::Deleted(
                "move constructor or move assignment declared".into(),
            );
        }

        ImplicitFuncStatus::Declared
    }

    /// Determine if an implicit copy assignment should be declared or deleted.
    pub fn implicit_copy_assignment_status(
        &self,
        has_user_declared_copy_assign: bool,
        has_user_declared_move_ctor: bool,
        has_user_declared_move_assign: bool,
    ) -> ImplicitFuncStatus {
        if has_user_declared_copy_assign {
            return ImplicitFuncStatus::NotDeclared;
        }
        if has_user_declared_move_ctor || has_user_declared_move_assign {
            return ImplicitFuncStatus::Deleted(
                "move constructor or move assignment declared".into(),
            );
        }
        ImplicitFuncStatus::Declared
    }

    /// Determine if an implicit move constructor should be declared or deleted.
    pub fn implicit_move_constructor_status(
        &self,
        has_user_declared_copy_ctor: bool,
        has_user_declared_move_ctor: bool,
        has_user_declared_dtor: bool,
        has_user_declared_copy_assign: bool,
        has_user_declared_move_assign: bool,
    ) -> ImplicitFuncStatus {
        if has_user_declared_move_ctor {
            return ImplicitFuncStatus::NotDeclared;
        }
        // Any user-declared copy/move/dtor suppresses implicit move
        if has_user_declared_copy_ctor
            || has_user_declared_dtor
            || has_user_declared_copy_assign
            || has_user_declared_move_assign
        {
            return ImplicitFuncStatus::NotDeclared;
        }
        ImplicitFuncStatus::Declared
    }

    fn base_has_deleted_default_ctor(&self, _base: &str) -> bool {
        false // simplified
    }

    fn base_has_deleted_dtor(&self, _base: &str) -> bool {
        false // simplified
    }

    // ── Aggregate Initialization Rules ─────────────────────────────────

    /// Check if a class qualifies as an aggregate (C++17 rules).
    /// An aggregate has:
    /// - No user-declared or inherited constructors
    /// - No private or protected non-static data members (C++17+)
    /// - No virtual functions (C++14+)
    /// - No virtual, private, or protected base classes (C++17+)
    pub fn is_aggregate(
        &self,
        has_user_ctors: bool,
        has_inherited_ctors: bool,
        has_virtual_functions: bool,
        has_virtual_bases: bool,
        has_non_public_members: bool,
        has_non_public_bases: bool,
    ) -> bool {
        if has_user_ctors || has_inherited_ctors {
            return false;
        }

        if self.standard >= CppStandard::Cxx14 || self.standard >= CppStandard::GnuXx14 {
            if has_virtual_functions {
                return false;
            }
        }

        if self.standard >= CppStandard::Cxx17 || self.standard >= CppStandard::GnuXx17 {
            if has_virtual_bases || has_non_public_members || has_non_public_bases {
                return false;
            }
        }

        true
    }

    /// Check for brace elision in aggregate initialization.
    /// Brace elision allows omitting nested braces when the initializer
    /// matches the sub-aggregate member layout.
    pub fn can_elide_braces(&self, member_count: usize, init_count: usize) -> bool {
        // Brace elision is allowed when initializing aggregates
        // The standard allows flattening nested initializer lists
        init_count <= member_count
    }

    // ── Lambda Semantic Analysis ───────────────────────────────────────

    /// Analyze a lambda expression for correctness.
    pub fn analyze_lambda(
        &mut self,
        captures: &[LambdaCapture],
        params: &[CXXParamDecl],
        body: &CXXCompoundStmt,
        is_mutable: bool,
        is_constexpr: bool,
        is_generic: bool,
    ) -> Vec<String> {
        let mut errors = Vec::new();

        // Check capture defaults
        let mut has_default_by_value = false;
        let mut has_default_by_ref = false;
        let mut explicit_captures = Vec::new();

        for capture in captures {
            match capture {
                LambdaCapture::DefaultByValue => {
                    if has_default_by_ref {
                        errors.push("cannot mix capture defaults".into());
                    }
                    has_default_by_value = true;
                }
                LambdaCapture::DefaultByRef => {
                    if has_default_by_value {
                        errors.push("cannot mix capture defaults".into());
                    }
                    has_default_by_ref = true;
                }
                LambdaCapture::Capture { name, .. } => {
                    if explicit_captures.contains(name) {
                        errors.push(format!("lambda capture '{}' is duplicated", name));
                    }
                    explicit_captures.push(name.clone());
                }
                LambdaCapture::This | LambdaCapture::ThisByRef => {
                    if explicit_captures.contains(&"this".to_string()) {
                        errors.push("lambda capture 'this' is duplicated".into());
                    }
                    explicit_captures.push("this".into());
                }
                LambdaCapture::ThisByValue => {
                    if explicit_captures.contains(&"*this".to_string()) {
                        errors.push("lambda capture '*this' is duplicated".into());
                    }
                    explicit_captures.push("*this".into());
                }
                LambdaCapture::ThisRef => {
                    if explicit_captures.contains(&"*this".to_string()) {
                        errors.push("lambda capture '*this' is duplicated".into());
                    }
                    explicit_captures.push("*this".into());
                }
            }
        }

        // Generic lambdas require C++14+
        if is_generic {
            if !(self.standard >= CppStandard::Cxx14 || self.standard >= CppStandard::GnuXx14) {
                errors.push("generic lambdas require C++14 or later".into());
            }
        }

        // constexpr lambdas require C++17+
        if is_constexpr {
            if !(self.standard >= CppStandard::Cxx17 || self.standard >= CppStandard::GnuXx17) {
                errors.push("constexpr lambdas require C++17 or later".into());
            }
        }

        // mutable lambdas can modify captured-by-value variables
        // No special checking required

        errors
    }

    /// Resolve a capture: determine if a variable can be captured and how.
    pub fn resolve_capture(
        &self,
        var_name: &str,
        capture_default: Option<&LambdaCapture>,
    ) -> Result<LambdaCapture, String> {
        // Check if the variable is in scope
        let lookup = self.lookup_name_in_scope(var_name);
        match lookup {
            NameLookupResult::NotFound => {
                Err(format!("cannot capture '{}': not in scope", var_name))
            }
            _ => {
                // Determine capture mode
                match capture_default {
                    Some(LambdaCapture::DefaultByRef) => Ok(LambdaCapture::Capture {
                        name: var_name.into(),
                        by_ref: true,
                        capture_default: Some(CaptureDefault::ByRef),
                        init: None,
                    }),
                    _ => Ok(LambdaCapture::Capture {
                        name: var_name.into(),
                        by_ref: false,
                        capture_default: None,
                        init: None,
                    }),
                }
            }
        }
    }

    /// Look up a name across the scope stack.
    fn lookup_name_in_scope(&self, name: &str) -> NameLookupResult {
        for scope in self.scopes.iter().rev() {
            if let Some(result) = scope.lookup(name) {
                return result;
            }
        }
        NameLookupResult::NotFound
    }

    // ── Using Declaration/Directive Resolution ─────────────────────────

    /// Resolve a using declaration (e.g., `using Base::foo`).
    /// Returns the declarations imported by this using-declaration.
    pub fn resolve_using_declaration(
        &self,
        target_name: &CXXName,
        current_class: &str,
    ) -> Result<Vec<String>, String> {
        let mut imported = Vec::new();

        // A using declaration imports a name from a base class into the derived class
        if let Some(ref scope) = target_name.scope {
            for comp in &scope.components {
                match comp {
                    NestedNameComponent::Type(base_name) => {
                        if self.derives_from(current_class, base_name) {
                            imported.push(target_name.name.clone());
                        } else {
                            return Err(format!(
                                "'{}' is not a base class of '{}'",
                                base_name, current_class
                            ));
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(imported)
    }

    /// Resolve a using directive (e.g., `using namespace std`).
    /// Makes all names from the nominated namespace available.
    pub fn resolve_using_directive(
        &self,
        namespace_name: &NestedNameSpecifier,
    ) -> Result<Vec<String>, String> {
        // Using directives bring all names from a namespace into scope
        // but with lower priority during name lookup
        let ns_str = format!("{}", namespace_name);
        Ok(vec![ns_str])
    }

    /// Check for name hiding when a using declaration conflicts with
    /// an existing declaration in the current scope.
    pub fn check_using_name_hiding(&self, name: &str, existing: &NameLookupResult) -> Vec<String> {
        let mut warnings = Vec::new();
        match existing {
            NameLookupResult::NotFound => {}
            _ => {
                warnings.push(format!(
                    "using declaration '{}' hides existing declaration in this scope",
                    name
                ));
            }
        }
        warnings
    }

    // ── Member Name Lookup in Class Scope ──────────────────────────────

    /// Look up a member name in a class and its base classes.
    /// Follows C++ name lookup rules:
    /// 1. Check the class itself
    /// 2. Walk base classes in declaration order (depth-first, left-to-right)
    /// 3. If found in multiple bases at the same level, it's ambiguous
    pub fn member_lookup(&self, class_name: &str, member_name: &str) -> NameLookupResult {
        // Check the class scope first
        // (In a full implementation, we'd have a class scope table)

        // Walk base classes
        if let Some(bases) = self.class_hierarchy.get(class_name) {
            let mut found_in: Vec<String> = Vec::new();
            for base in bases {
                let result = self.member_lookup_in_base(base, member_name);
                match result {
                    NameLookupResult::NotFound => {}
                    _ => {
                        found_in.push(base.clone());
                    }
                }
            }

            match found_in.len() {
                0 => NameLookupResult::NotFound,
                1 => {
                    // Found in exactly one base — return it
                    NameLookupResult::Member(CXXMemberDecl::Field {
                        name: member_name.into(),
                        ty: QualType::int(),
                        is_mutable: false,
                        is_static: false,
                        bit_width: None,
                        default_init: None,
                        access: AccessSpecifier::Public,
                    })
                }
                _ => NameLookupResult::Ambiguous(found_in),
            }
        } else {
            NameLookupResult::NotFound
        }
    }

    /// Perform member lookup in a specific base class.
    fn member_lookup_in_base(&self, base_name: &str, member_name: &str) -> NameLookupResult {
        // Walk base's bases recursively
        self.member_lookup(base_name, member_name)
    }

    // ── Extended constexpr evaluation placeholder ──────────────────────

    /// Check if an expression is a core constant expression.
    pub fn is_constant_expression(&self, expr: &CXXExpr) -> bool {
        match expr {
            CXXExpr::IntegerLiteral(_) => true,
            CXXExpr::BoolLiteral(_) => true,
            CXXExpr::NullPtrLiteral => true,
            CXXExpr::StringLiteral(_) => true,
            CXXExpr::CharLiteral(_) => true,
            CXXExpr::FloatLiteral(_) => true,
            CXXExpr::ThisExpr => false, // 'this' is not a constant expression
            CXXExpr::CXXNewExpr { .. } => false,
            CXXExpr::CXXDeleteExpr { .. } => false,
            CXXExpr::CXXThrowExpr(_) => false,
            CXXExpr::LambdaExpr { .. } => self.standard >= CppStandard::Cxx17,
            CXXExpr::CXXConstructExpr { .. } => {
                // Allowed if constructed from constant expression
                false // simplified
            }
            _ => false,
        }
    }

    /// Check if a variable satisfies constinit requirements.
    /// constinit requires that the variable has constant initialization.
    pub fn check_constinit(
        &self,
        init_expr: Option<&CXXExpr>,
        is_static: bool,
    ) -> Result<(), String> {
        if !is_static {
            return Err(
                "constinit can only be applied to variables with static storage duration".into(),
            );
        }
        match init_expr {
            Some(expr) if self.is_constant_expression(expr) => Ok(()),
            Some(_) => {
                Err("constinit variable must be initialized with a constant expression".into())
            }
            None => Err("constinit variable must have an initializer".into()),
        }
    }

    /// Check if a function satisfies consteval requirements.
    /// A consteval function is an immediate function: every call must
    /// produce a compile-time constant.
    pub fn check_consteval(&self, has_body: bool, body_is_constexpr: bool) -> Vec<String> {
        let mut errors = Vec::new();
        if !has_body {
            errors.push("consteval function must have a body".into());
        }
        // consteval functions can only call other consteval functions
        // and must consist of constant expressions
        errors
    }

    /// Evaluate a consteval (immediate) function call at compile time.
    pub fn evaluate_consteval_call(
        &self,
        func_name: &str,
        args: &[CXXExpr],
    ) -> Result<CXXExpr, String> {
        // In a full implementation, this would interpret the consteval
        // function body with the given arguments
        Err(format!(
            "cannot evaluate consteval function '{}' at compile time",
            func_name
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Implicit Function Status
// ═══════════════════════════════════════════════════════════════════════════════

/// Status of an implicitly declared special member function.
#[derive(Debug, Clone, PartialEq)]
pub enum ImplicitFuncStatus {
    /// The function is implicitly declared and available.
    Declared,
    /// The function is not implicitly declared (user declared instead).
    NotDeclared,
    /// The function is implicitly declared as deleted.
    Deleted(String),
}

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

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

    #[test]
    fn test_scope_creation() {
        let scope = CXXScope::new(ScopeKind::TranslationUnit);
        assert_eq!(scope.kind, ScopeKind::TranslationUnit);
        assert!(!scope.is_complete);
    }

    #[test]
    fn test_scope_add_variable() {
        let mut scope = CXXScope::new(ScopeKind::Function);
        scope.add_variable(
            "x",
            CXXDecl::Variable {
                name: "x".into(),
                ty: QualType::int(),
                init: None,
                is_constexpr: false,
                is_constinit: false,
                is_static: false,
                is_thread_local: false,
                is_inline: false,
            },
        );
        assert!(scope.lookup("x").is_some());
    }

    #[test]
    fn test_scope_add_function() {
        let mut scope = CXXScope::new(ScopeKind::Namespace);
        scope.add_function(
            "foo",
            CXXDecl::Function {
                name: "foo".into(),
                return_ty: QualType::void(),
                params: vec![],
                body: None,
                is_virtual: false,
                is_override: false,
                is_final: false,
                is_const: false,
                is_noexcept: false,
                is_constexpr: false,
                is_consteval: false,
                is_static: false,
                is_inline: false,
                is_explicit: false,
                is_deleted: false,
                is_defaulted: false,
                ref_qualifier: None,
                trailing_return_ty: None,
                template_params: None,
            },
        );
        // Add another overload
        scope.add_function(
            "foo",
            CXXDecl::Function {
                name: "foo".into(),
                return_ty: QualType::int(),
                params: vec![],
                body: None,
                is_virtual: false,
                is_override: false,
                is_final: false,
                is_const: false,
                is_noexcept: false,
                is_constexpr: false,
                is_consteval: false,
                is_static: false,
                is_inline: false,
                is_explicit: false,
                is_deleted: false,
                is_defaulted: false,
                ref_qualifier: None,
                trailing_return_ty: None,
                template_params: None,
            },
        );
        match scope.lookup("foo") {
            Some(NameLookupResult::OverloadedFunctions(funcs)) => {
                assert_eq!(funcs.len(), 2);
            }
            _ => panic!("expected overloaded functions"),
        }
    }

    #[test]
    fn test_scope_lookup_not_found() {
        let scope = CXXScope::new(ScopeKind::Block);
        match scope.lookup("nonexistent") {
            None => {}
            _ => panic!("expected None"),
        }
    }

    #[test]
    fn test_sema_create() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(!sema.in_template);
    }

    #[test]
    fn test_sema_scope_stack() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        assert_eq!(sema.scopes.len(), 1);
        sema.push_scope(ScopeKind::Function);
        assert_eq!(sema.scopes.len(), 2);
        sema.pop_scope();
        assert_eq!(sema.scopes.len(), 1);
    }

    #[test]
    fn test_sema_check_conversion_identity() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.check_conversion("int", "int", false).is_ok());
    }

    #[test]
    fn test_sema_errors_and_warnings() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.errors().is_empty());
        assert!(sema.warnings().is_empty());
    }

    #[test]
    fn test_class_hierarchy() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        // Simulate building a class hierarchy
        // Just test that the map is initially empty
        assert!(sema.class_hierarchy.is_empty());
    }

    #[test]
    fn test_derives_from() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        let bases = vec!["Base".to_string()];
        sema.class_hierarchy.insert("Derived".into(), bases);
        assert!(sema.derives_from("Derived", "Base"));
        assert!(!sema.derives_from("Base", "Derived"));
        assert!(!sema.derives_from("Derived", "Other"));
    }

    #[test]
    fn test_derives_from_transitive() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        sema.class_hierarchy
            .insert("GrandChild".into(), vec!["Child".to_string()]);
        sema.class_hierarchy
            .insert("Child".into(), vec!["Base".to_string()]);
        assert!(sema.derives_from("GrandChild", "Base"));
        assert!(sema.derives_from("GrandChild", "Child"));
    }

    #[test]
    fn test_member_access_public() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema
            .check_member_access(AccessSpecifier::Public, "X", false, false)
            .is_ok());
    }

    #[test]
    fn test_member_access_private_current_class() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        sema.current_class = Some("X".into());
        assert!(sema
            .check_member_access(AccessSpecifier::Private, "X", false, false)
            .is_ok());
    }

    #[test]
    fn test_member_access_private_wrong_class() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        sema.current_class = Some("Y".into());
        assert!(sema
            .check_member_access(AccessSpecifier::Private, "X", false, false)
            .is_err());
    }

    #[test]
    fn test_member_access_with_friend() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        // Friendship overrides access control
        assert!(sema
            .check_member_access(AccessSpecifier::Private, "X", true, false)
            .is_ok());
        assert!(sema
            .check_member_access(AccessSpecifier::Protected, "X", true, false)
            .is_ok());
    }

    #[test]
    fn test_is_aggregate_no_ctors() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.is_aggregate(false, false, false, false, false, false));
    }

    #[test]
    fn test_is_aggregate_with_user_ctor() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(!sema.is_aggregate(true, false, false, false, false, false));
    }

    #[test]
    fn test_is_aggregate_with_virtual_func_cxx14() {
        let sema = CXXSema::new(CppStandard::Cxx14);
        assert!(!sema.is_aggregate(false, false, true, false, false, false));
    }

    #[test]
    fn test_is_aggregate_with_non_public_cxx17() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(!sema.is_aggregate(false, false, false, false, true, false));
        assert!(!sema.is_aggregate(false, false, false, true, false, false));
    }

    #[test]
    fn test_guaranteed_copy_elision_cxx17() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.is_guaranteed_copy_elision(true, "T", "T"));
        assert!(!sema.is_guaranteed_copy_elision(false, "T", "T"));
        assert!(!sema.is_guaranteed_copy_elision(true, "T", "U"));
    }

    #[test]
    fn test_no_guaranteed_copy_elision_cxx14() {
        let sema = CXXSema::new(CppStandard::Cxx14);
        assert!(!sema.is_guaranteed_copy_elision(true, "T", "T"));
    }

    #[test]
    fn test_can_apply_nrvo() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.can_apply_nrvo("x", true, "T", "T"));
        assert!(!sema.can_apply_nrvo("x", false, "T", "T"));
        assert!(!sema.can_apply_nrvo("x", true, "U", "T"));
    }

    #[test]
    fn test_aggregate_brace_elision() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.can_elide_braces(3, 2));
        assert!(sema.can_elide_braces(3, 3));
    }

    #[test]
    fn test_is_constant_expression_integer() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(sema.is_constant_expression(&CXXExpr::IntegerLiteral(42)));
        assert!(sema.is_constant_expression(&CXXExpr::BoolLiteral(true)));
        assert!(sema.is_constant_expression(&CXXExpr::NullPtrLiteral));
    }

    #[test]
    fn test_is_constant_expression_non_const() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        assert!(!sema.is_constant_expression(&CXXExpr::ThisExpr));
        assert!(!sema.is_constant_expression(&CXXExpr::CXXNewExpr {
            allocated_ty: QualType::int(),
            placement_args: vec![],
            constructor_args: vec![],
            is_array: false,
            array_size: None,
        }));
    }

    #[test]
    fn test_constinit_valid() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        assert!(sema
            .check_constinit(Some(&CXXExpr::IntegerLiteral(0)), true)
            .is_ok());
    }

    #[test]
    fn test_constinit_non_static() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        assert!(sema
            .check_constinit(Some(&CXXExpr::IntegerLiteral(0)), false)
            .is_err());
    }

    #[test]
    fn test_constinit_no_init() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        assert!(sema.check_constinit(None, true).is_err());
    }

    #[test]
    fn test_constinit_non_const_expr() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        assert!(sema
            .check_constinit(Some(&CXXExpr::ThisExpr), true)
            .is_err());
    }

    #[test]
    fn test_consteval_no_body() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        let errs = sema.check_consteval(false, false);
        assert!(!errs.is_empty());
    }

    #[test]
    fn test_consteval_has_body() {
        let sema = CXXSema::new(CppStandard::Cxx20);
        let errs = sema.check_consteval(true, true);
        assert!(errs.is_empty());
    }

    #[test]
    fn test_implicit_default_ctor_no_user_ctor() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_default_constructor_status("X", false, false, false, &[]);
        assert_eq!(status, ImplicitFuncStatus::Declared);
    }

    #[test]
    fn test_implicit_default_ctor_with_user_ctor() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_default_constructor_status("X", true, false, false, &[]);
        assert_eq!(status, ImplicitFuncStatus::NotDeclared);
    }

    #[test]
    fn test_implicit_default_ctor_const_member() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_default_constructor_status("X", false, true, false, &[]);
        assert!(matches!(status, ImplicitFuncStatus::Deleted(_)));
    }

    #[test]
    fn test_implicit_default_ctor_ref_member() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_default_constructor_status("X", false, false, true, &[]);
        assert!(matches!(status, ImplicitFuncStatus::Deleted(_)));
    }

    #[test]
    fn test_implicit_copy_ctor_with_move() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_copy_constructor_status(false, true, false, &[]);
        assert!(matches!(status, ImplicitFuncStatus::Deleted(_)));
    }

    #[test]
    fn test_implicit_move_ctor_with_user_dtor() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let status = sema.implicit_move_constructor_status(false, false, true, false, false);
        assert_eq!(status, ImplicitFuncStatus::NotDeclared);
    }

    #[test]
    fn test_is_covariant() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        sema.class_hierarchy
            .insert("Derived".into(), vec!["Base".to_string()]);
        assert!(sema.is_covariant("Derived*", "Base*"));
        assert!(sema.is_covariant("Derived&", "Base&"));
        assert!(!sema.is_covariant("Base*", "Derived*"));
    }

    #[test]
    fn test_member_lookup_single_base() {
        let mut sema = CXXSema::new(CppStandard::Cxx17);
        sema.class_hierarchy
            .insert("Derived".into(), vec!["Base".to_string()]);
        // Base doesn't have hierarchy, so lookup returns NotFound
        let result = sema.member_lookup("Derived", "some_member");
        assert!(matches!(result, NameLookupResult::NotFound));
    }

    #[test]
    fn test_member_lookup_no_bases() {
        let sema = CXXSema::new(CppStandard::Cxx17);
        let result = sema.member_lookup("NoBases", "x");
        assert!(matches!(result, NameLookupResult::NotFound));
    }
}