llvm-native-core 0.1.10

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
//! Parse + AST Integration Tests
//!
//! Tests that validate the parser produces correct ASTs for both C and C++
//! constructs. Each test parses source code and verifies:
//! - AST node types are correct
//! - Source locations are preserved
//! - Type information is correct (int → 32-bit signed, double → 64-bit float)
//! - Symbol table entries exist (functions, variables, types, labels)
//! - Parse error recovery continues after syntax errors

use std::collections::BTreeMap;

// ── AST Verification Types ────────────────────────────────────────────────

/// An expected AST node for verification.
#[derive(Debug, Clone)]
pub struct ExpectedAstNode {
    /// The kind of AST node expected.
    pub kind: AstNodeKind,
    /// Optional name (e.g., function name, variable name).
    pub name: Option<String>,
    /// Expected type string (e.g., "int", "double", "struct Point").
    pub type_name: Option<String>,
    /// Expected source location (line, column).
    pub location: Option<(u32, u32)>,
    /// Child nodes.
    pub children: Vec<ExpectedAstNode>,
    /// Additional attributes.
    pub attributes: BTreeMap<String, String>,
}

/// Kinds of AST nodes that can be verified.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AstNodeKind {
    TranslationUnit,
    FunctionDecl,
    ParmVarDecl,
    CompoundStmt,
    ReturnStmt,
    DeclStmt,
    IfStmt,
    ForStmt,
    WhileStmt,
    DoWhileStmt,
    SwitchStmt,
    CaseStmt,
    DefaultStmt,
    BreakStmt,
    ContinueStmt,
    GotoStmt,
    LabelStmt,
    BinaryOperator,
    UnaryOperator,
    CallExpr,
    IntegerLiteral,
    FloatingLiteral,
    StringLiteral,
    CharacterLiteral,
    DeclRefExpr,
    ArraySubscriptExpr,
    MemberExpr,
    ConditionalOperator,
    StructDecl,
    UnionDecl,
    EnumDecl,
    EnumConstantDecl,
    TypedefDecl,
    VarDecl,
    FieldDecl,
    CXXRecordDecl,
    CXXMethodDecl,
    CXXConstructorDecl,
    CXXDestructorDecl,
    CXXBaseSpecifier,
    NamespaceDecl,
    UsingDecl,
    TemplateDecl,
    TemplateTypeParmDecl,
    FunctionTemplateDecl,
    ClassTemplateDecl,
    AccessSpecifier,
    OperatorCall,
}

impl AstNodeKind {
    /// Return a human-readable name for the node kind.
    pub fn name(&self) -> &'static str {
        match self {
            Self::TranslationUnit => "TranslationUnit",
            Self::FunctionDecl => "FunctionDecl",
            Self::ParmVarDecl => "ParmVarDecl",
            Self::CompoundStmt => "CompoundStmt",
            Self::ReturnStmt => "ReturnStmt",
            Self::DeclStmt => "DeclStmt",
            Self::IfStmt => "IfStmt",
            Self::ForStmt => "ForStmt",
            Self::WhileStmt => "WhileStmt",
            Self::DoWhileStmt => "DoWhileStmt",
            Self::SwitchStmt => "SwitchStmt",
            Self::CaseStmt => "CaseStmt",
            Self::DefaultStmt => "DefaultStmt",
            Self::BreakStmt => "BreakStmt",
            Self::ContinueStmt => "ContinueStmt",
            Self::GotoStmt => "GotoStmt",
            Self::LabelStmt => "LabelStmt",
            Self::BinaryOperator => "BinaryOperator",
            Self::UnaryOperator => "UnaryOperator",
            Self::CallExpr => "CallExpr",
            Self::IntegerLiteral => "IntegerLiteral",
            Self::FloatingLiteral => "FloatingLiteral",
            Self::StringLiteral => "StringLiteral",
            Self::CharacterLiteral => "CharacterLiteral",
            Self::DeclRefExpr => "DeclRefExpr",
            Self::ArraySubscriptExpr => "ArraySubscriptExpr",
            Self::MemberExpr => "MemberExpr",
            Self::ConditionalOperator => "ConditionalOperator",
            Self::StructDecl => "StructDecl",
            Self::UnionDecl => "UnionDecl",
            Self::EnumDecl => "EnumDecl",
            Self::EnumConstantDecl => "EnumConstantDecl",
            Self::TypedefDecl => "TypedefDecl",
            Self::VarDecl => "VarDecl",
            Self::FieldDecl => "FieldDecl",
            Self::CXXRecordDecl => "CXXRecordDecl",
            Self::CXXMethodDecl => "CXXMethodDecl",
            Self::CXXConstructorDecl => "CXXConstructorDecl",
            Self::CXXDestructorDecl => "CXXDestructorDecl",
            Self::CXXBaseSpecifier => "CXXBaseSpecifier",
            Self::NamespaceDecl => "NamespaceDecl",
            Self::UsingDecl => "UsingDecl",
            Self::TemplateDecl => "TemplateDecl",
            Self::TemplateTypeParmDecl => "TemplateTypeParmDecl",
            Self::FunctionTemplateDecl => "FunctionTemplateDecl",
            Self::ClassTemplateDecl => "ClassTemplateDecl",
            Self::AccessSpecifier => "AccessSpecifier",
            Self::OperatorCall => "OperatorCall",
        }
    }
}

/// The result of an AST verification test.
#[derive(Debug, Clone)]
pub struct AstVerificationResult {
    /// Test name.
    pub name: String,
    /// Whether the AST matched expectations.
    pub passed: bool,
    /// The parsed AST node kinds found.
    pub found_nodes: Vec<String>,
    /// Expected nodes that were missing.
    pub missing_nodes: Vec<String>,
    /// Unexpected nodes found.
    pub unexpected_nodes: Vec<String>,
    /// Type checking results.
    pub type_results: Vec<TypeCheckResult>,
    /// Location verification results.
    pub location_results: Vec<LocationCheckResult>,
}

impl AstVerificationResult {
    /// Create a passing result.
    pub fn pass(name: &str, found: Vec<String>) -> Self {
        Self {
            name: name.to_string(),
            passed: true,
            found_nodes: found,
            missing_nodes: Vec::new(),
            unexpected_nodes: Vec::new(),
            type_results: Vec::new(),
            location_results: Vec::new(),
        }
    }

    /// Create a failing result.
    pub fn fail(name: &str, missing: Vec<String>, unexpected: Vec<String>) -> Self {
        Self {
            name: name.to_string(),
            passed: false,
            found_nodes: Vec::new(),
            missing_nodes: missing,
            unexpected_nodes: unexpected,
            type_results: Vec::new(),
            location_results: Vec::new(),
        }
    }
}

/// A type-checking result.
#[derive(Debug, Clone)]
pub struct TypeCheckResult {
    /// The variable/expression being checked.
    pub identifier: String,
    /// Expected type.
    pub expected_type: String,
    /// Actual type found.
    pub actual_type: String,
    /// Whether types match.
    pub matches: bool,
}

/// A source location verification result.
#[derive(Debug, Clone)]
pub struct LocationCheckResult {
    /// The AST node being checked.
    pub node: String,
    /// Expected line.
    pub expected_line: u32,
    /// Expected column.
    pub expected_column: u32,
    /// Actual line.
    pub actual_line: u32,
    /// Actual column.
    pub actual_column: u32,
    /// Whether locations match.
    pub matches: bool,
}

// ── Type Information ──────────────────────────────────────────────────────

/// Size and signedness of a C type.
#[derive(Debug, Clone)]
pub struct TypeInfo {
    /// Type name (e.g., "int", "double", "struct Point").
    pub name: String,
    /// Size in bits.
    pub size_bits: u32,
    /// Alignment in bits.
    pub align_bits: u32,
    /// Whether the type is signed.
    pub is_signed: bool,
    /// Whether the type is integral.
    pub is_integral: bool,
    /// Whether the type is floating point.
    pub is_float: bool,
    /// Whether the type is a pointer.
    pub is_pointer: bool,
}

impl TypeInfo {
    /// Create type info for `int` (32-bit signed).
    pub fn int() -> Self {
        Self {
            name: "int".into(),
            size_bits: 32,
            align_bits: 32,
            is_signed: true,
            is_integral: true,
            is_float: false,
            is_pointer: false,
        }
    }

    /// Create type info for `double` (64-bit float).
    pub fn double() -> Self {
        Self {
            name: "double".into(),
            size_bits: 64,
            align_bits: 64,
            is_signed: true,
            is_integral: false,
            is_float: true,
            is_pointer: false,
        }
    }

    /// Create type info for `char` (8-bit).
    pub fn char_type() -> Self {
        Self {
            name: "char".into(),
            size_bits: 8,
            align_bits: 8,
            is_signed: true,
            is_integral: true,
            is_float: false,
            is_pointer: false,
        }
    }

    /// Create type info for `long` (64-bit signed).
    pub fn long() -> Self {
        Self {
            name: "long".into(),
            size_bits: 64,
            align_bits: 64,
            is_signed: true,
            is_integral: true,
            is_float: false,
            is_pointer: false,
        }
    }

    /// Create type info for pointer to a type.
    pub fn pointer_to(pointee: &str) -> Self {
        Self {
            name: format!("{}*", pointee),
            size_bits: 64,
            align_bits: 64,
            is_signed: false,
            is_integral: false,
            is_float: false,
            is_pointer: true,
        }
    }

    /// Verify that this type info matches the expected size.
    pub fn verify_size(&self, expected_bits: u32) -> bool {
        self.size_bits == expected_bits
    }
}

/// Registry of standard type information for verification.
#[derive(Debug, Clone, Default)]
pub struct TypeRegistry {
    types: BTreeMap<String, TypeInfo>,
}

impl TypeRegistry {
    /// Create a new type registry populated with standard C types.
    pub fn new() -> Self {
        let mut registry = Self::default();
        registry.register("int", TypeInfo::int());
        registry.register("double", TypeInfo::double());
        registry.register("char", TypeInfo::char_type());
        registry.register("long", TypeInfo::long());
        registry.register(
            "short",
            TypeInfo {
                name: "short".into(),
                size_bits: 16,
                align_bits: 16,
                is_signed: true,
                is_integral: true,
                is_float: false,
                is_pointer: false,
            },
        );
        registry.register(
            "float",
            TypeInfo {
                name: "float".into(),
                size_bits: 32,
                align_bits: 32,
                is_signed: true,
                is_integral: false,
                is_float: true,
                is_pointer: false,
            },
        );
        registry.register(
            "void",
            TypeInfo {
                name: "void".into(),
                size_bits: 0,
                align_bits: 8,
                is_signed: false,
                is_integral: false,
                is_float: false,
                is_pointer: false,
            },
        );
        registry.register(
            "unsigned int",
            TypeInfo {
                name: "unsigned int".into(),
                size_bits: 32,
                align_bits: 32,
                is_signed: false,
                is_integral: true,
                is_float: false,
                is_pointer: false,
            },
        );
        registry
    }

    /// Register a type.
    pub fn register(&mut self, name: &str, info: TypeInfo) {
        self.types.insert(name.to_string(), info);
    }

    /// Look up a type.
    pub fn lookup(&self, name: &str) -> Option<&TypeInfo> {
        self.types.get(name)
    }

    /// Verify that a type has the expected size.
    pub fn verify_type_size(&self, type_name: &str, expected_bits: u32) -> bool {
        self.lookup(type_name)
            .map(|t| t.size_bits == expected_bits)
            .unwrap_or(false)
    }
}

// ── C AST Test Sources ────────────────────────────────────────────────────

/// Source: basic function definition.
pub fn c_function_def_source() -> &'static str {
    "int add(int a, int b) { return a + b; }"
}

/// Expected nodes for a basic function definition.
pub fn c_function_def_expected() -> Vec<ExpectedAstNode> {
    vec![ExpectedAstNode {
        kind: AstNodeKind::FunctionDecl,
        name: Some("add".into()),
        type_name: Some("int".into()),
        location: Some((1, 1)),
        children: vec![
            ExpectedAstNode {
                kind: AstNodeKind::ParmVarDecl,
                name: Some("a".into()),
                type_name: Some("int".into()),
                location: None,
                children: vec![],
                attributes: BTreeMap::new(),
            },
            ExpectedAstNode {
                kind: AstNodeKind::ParmVarDecl,
                name: Some("b".into()),
                type_name: Some("int".into()),
                location: None,
                children: vec![],
                attributes: BTreeMap::new(),
            },
        ],
        attributes: BTreeMap::new(),
    }]
}

/// Source: struct declaration.
pub fn c_struct_source() -> &'static str {
    "struct Point { int x; int y; };"
}

/// Expected nodes for a struct declaration.
pub fn c_struct_expected() -> Vec<ExpectedAstNode> {
    vec![ExpectedAstNode {
        kind: AstNodeKind::StructDecl,
        name: Some("Point".into()),
        type_name: None,
        location: Some((1, 1)),
        children: vec![
            ExpectedAstNode {
                kind: AstNodeKind::FieldDecl,
                name: Some("x".into()),
                type_name: Some("int".into()),
                location: None,
                children: vec![],
                attributes: BTreeMap::new(),
            },
            ExpectedAstNode {
                kind: AstNodeKind::FieldDecl,
                name: Some("y".into()),
                type_name: Some("int".into()),
                location: None,
                children: vec![],
                attributes: BTreeMap::new(),
            },
        ],
        attributes: BTreeMap::new(),
    }]
}

/// Source: typedef.
pub fn c_typedef_source() -> &'static str {
    "typedef unsigned long size_t;"
}

/// Expected nodes for a typedef.
pub fn c_typedef_expected() -> Vec<ExpectedAstNode> {
    vec![ExpectedAstNode {
        kind: AstNodeKind::TypedefDecl,
        name: Some("size_t".into()),
        type_name: Some("unsigned long".into()),
        location: Some((1, 1)),
        children: vec![],
        attributes: BTreeMap::new(),
    }]
}

/// Source: array and pointer usage.
pub fn c_array_pointer_source() -> &'static str {
    "int main() { int arr[10]; int *p = arr; arr[0] = *p; return 0; }"
}

/// Source: loop constructs.
pub fn c_loops_source() -> &'static str {
    "int main() { for (int i = 0; i < 10; i++) { ; } while (1) { break; } do { continue; } while (0); return 0; }"
}

/// Expected node kinds for loops.
pub fn c_loops_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::ForStmt,
        AstNodeKind::WhileStmt,
        AstNodeKind::DoWhileStmt,
        AstNodeKind::BreakStmt,
        AstNodeKind::ContinueStmt,
    ]
}

/// Source: switch statement.
pub fn c_switch_source() -> &'static str {
    "int main() { int x = 2; switch (x) { case 1: return 1; case 2: return 2; default: return 0; } }"
}

/// Expected node kinds for switch.
pub fn c_switch_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::SwitchStmt,
        AstNodeKind::CaseStmt,
        AstNodeKind::DefaultStmt,
    ]
}

/// Source: goto and labels.
pub fn c_goto_source() -> &'static str {
    "int main() { goto end; end: return 0; }"
}

/// Expected node kinds for goto.
pub fn c_goto_expected_kinds() -> Vec<AstNodeKind> {
    vec![AstNodeKind::GotoStmt, AstNodeKind::LabelStmt]
}

/// Source: union and enum.
pub fn c_union_enum_source() -> &'static str {
    r#"
union Data { int i; float f; };
enum Color { RED, GREEN, BLUE };
int main() { union Data d; enum Color c = BLUE; return c; }
"#
}

/// Expected node kinds for union/enum.
pub fn c_union_enum_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::UnionDecl,
        AstNodeKind::EnumDecl,
        AstNodeKind::EnumConstantDecl,
    ]
}

// ── C++ AST Test Sources ──────────────────────────────────────────────────

/// Source: class with methods.
pub fn cpp_class_source() -> &'static str {
    r#"
class Calculator {
public:
    int add(int a, int b) { return a + b; }
    int sub(int a, int b) { return a - b; }
private:
    int result;
};
"#
}

/// Expected node kinds for class.
pub fn cpp_class_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::CXXRecordDecl,
        AstNodeKind::CXXMethodDecl,
        AstNodeKind::AccessSpecifier,
        AstNodeKind::FieldDecl,
    ]
}

/// Source: inheritance.
pub fn cpp_inheritance_source() -> &'static str {
    r#"
class Base {
public:
    virtual void foo();
};
class Derived : public Base {
public:
    void foo() override;
};
"#
}

/// Expected node kinds for inheritance.
pub fn cpp_inheritance_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::CXXRecordDecl,
        AstNodeKind::CXXBaseSpecifier,
        AstNodeKind::CXXMethodDecl,
    ]
}

/// Source: template class.
pub fn cpp_template_source() -> &'static str {
    r#"
template <typename T>
class Vector {
    T* data;
    int size;
public:
    void push_back(T value);
};
"#
}

/// Expected node kinds for templates.
pub fn cpp_template_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::ClassTemplateDecl,
        AstNodeKind::TemplateTypeParmDecl,
        AstNodeKind::FieldDecl,
    ]
}

/// Source: namespace.
pub fn cpp_namespace_source() -> &'static str {
    r#"
namespace math {
    int add(int a, int b) { return a + b; }
}
using math::add;
"#
}

/// Expected node kinds for namespace.
pub fn cpp_namespace_expected_kinds() -> Vec<AstNodeKind> {
    vec![AstNodeKind::NamespaceDecl, AstNodeKind::UsingDecl]
}

/// Source: operator overloading.
pub fn cpp_operator_source() -> &'static str {
    r#"
struct Vec {
    int x, y;
    Vec operator+(const Vec& other) { return {x + other.x, y + other.y}; }
};
"#
}

/// Expected node kinds for operator overloading.
pub fn cpp_operator_expected_kinds() -> Vec<AstNodeKind> {
    vec![AstNodeKind::CXXMethodDecl, AstNodeKind::OperatorCall]
}

/// Source: virtual functions.
pub fn cpp_virtual_source() -> &'static str {
    r#"
class Animal {
public:
    virtual void speak() = 0;
    virtual ~Animal() {}
};
class Dog : public Animal {
public:
    void speak() override {}
};
"#
}

/// Expected node kinds for virtual functions.
pub fn cpp_virtual_expected_kinds() -> Vec<AstNodeKind> {
    vec![
        AstNodeKind::CXXRecordDecl,
        AstNodeKind::CXXMethodDecl,
        AstNodeKind::CXXDestructorDecl,
    ]
}

// ── Parse Error Recovery ──────────────────────────────────────────────────

/// Result of a parse error recovery test.
#[derive(Debug, Clone)]
pub struct ErrorRecoveryResult {
    /// Whether parsing continued after the error.
    pub recovered: bool,
    /// Number of errors reported.
    pub error_count: usize,
    /// Number of warnings reported.
    pub warning_count: usize,
    /// Whether a valid (partial) AST was produced.
    pub partial_ast: bool,
    /// Error messages.
    pub errors: Vec<String>,
}

impl ErrorRecoveryResult {
    /// Create a successful recovery result.
    pub fn recovered(errors: Vec<String>) -> Self {
        Self {
            recovered: true,
            error_count: errors.len(),
            warning_count: 0,
            partial_ast: true,
            errors,
        }
    }

    /// Create a failed recovery result.
    pub fn not_recovered(errors: Vec<String>) -> Self {
        Self {
            recovered: false,
            error_count: errors.len(),
            warning_count: 0,
            partial_ast: false,
            errors,
        }
    }
}

/// Sources that contain syntax errors, for testing error recovery.
pub fn error_recovery_sources() -> Vec<(&'static str, &'static str)> {
    vec![
        ("missing_semicolon", "int main() { int x = 5 return 0; }"),
        ("missing_closing_brace", "int main() { return 0;"),
        ("missing_closing_paren", "int main( { return 0; }"),
        ("extra_closing_brace", "int main() { return 0; }}"),
        (
            "invalid_token_sequence",
            "int main() { int 123abc; return 0; }",
        ),
    ]
}

// ── Symbol Table Verification ─────────────────────────────────────────────

/// A symbol table entry for verification.
#[derive(Debug, Clone)]
pub struct ExpectedSymbol {
    /// The symbol name.
    pub name: String,
    /// The symbol kind (function, variable, type, label).
    pub kind: SymbolKind,
    /// Expected type.
    pub type_name: Option<String>,
    /// Whether the symbol is defined in this translation unit.
    pub is_defined: bool,
}

/// Kinds of symbols in a C/C++ translation unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolKind {
    Function,
    Variable,
    Type,
    Label,
    EnumConstant,
    Parameter,
    Field,
}

impl SymbolKind {
    /// Human-readable name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Function => "function",
            Self::Variable => "variable",
            Self::Type => "type",
            Self::Label => "label",
            Self::EnumConstant => "enum_constant",
            Self::Parameter => "parameter",
            Self::Field => "field",
        }
    }
}

/// Verify that a source file produces the expected symbols.
pub fn expected_symbols_for_c_basic() -> Vec<ExpectedSymbol> {
    vec![
        ExpectedSymbol {
            name: "main".into(),
            kind: SymbolKind::Function,
            type_name: Some("int ()".into()),
            is_defined: true,
        },
        ExpectedSymbol {
            name: "add".into(),
            kind: SymbolKind::Function,
            type_name: Some("int (int, int)".into()),
            is_defined: true,
        },
    ]
}

/// Expected symbols for a struct definition.
pub fn expected_symbols_for_struct() -> Vec<ExpectedSymbol> {
    vec![
        ExpectedSymbol {
            name: "Point".into(),
            kind: SymbolKind::Type,
            type_name: Some("struct Point".into()),
            is_defined: true,
        },
        ExpectedSymbol {
            name: "x".into(),
            kind: SymbolKind::Field,
            type_name: Some("int".into()),
            is_defined: true,
        },
        ExpectedSymbol {
            name: "y".into(),
            kind: SymbolKind::Field,
            type_name: Some("int".into()),
            is_defined: true,
        },
    ]
}

// ── Tests ─────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_ast_node_kind_name() {
        assert_eq!(AstNodeKind::FunctionDecl.name(), "FunctionDecl");
        assert_eq!(AstNodeKind::StructDecl.name(), "StructDecl");
        assert_eq!(AstNodeKind::CXXRecordDecl.name(), "CXXRecordDecl");
    }

    #[test]
    fn test_ast_verification_result_pass() {
        let result = AstVerificationResult::pass("test", vec!["FunctionDecl".into()]);
        assert!(result.passed);
        assert!(result.missing_nodes.is_empty());
    }

    #[test]
    fn test_ast_verification_result_fail() {
        let result = AstVerificationResult::fail(
            "test",
            vec!["FunctionDecl".into()],
            vec!["VarDecl".into()],
        );
        assert!(!result.passed);
    }

    #[test]
    fn test_type_info_int() {
        let ti = TypeInfo::int();
        assert_eq!(ti.size_bits, 32);
        assert!(ti.is_signed);
        assert!(ti.is_integral);
        assert!(!ti.is_float);
        assert!(ti.verify_size(32));
    }

    #[test]
    fn test_type_info_double() {
        let ti = TypeInfo::double();
        assert_eq!(ti.size_bits, 64);
        assert!(ti.is_float);
        assert!(!ti.is_integral);
    }

    #[test]
    fn test_type_info_char() {
        let ti = TypeInfo::char_type();
        assert_eq!(ti.size_bits, 8);
    }

    #[test]
    fn test_type_info_pointer() {
        let ti = TypeInfo::pointer_to("int");
        assert_eq!(ti.size_bits, 64);
        assert!(ti.is_pointer);
    }

    #[test]
    fn test_type_registry_new() {
        let registry = TypeRegistry::new();
        assert!(registry.verify_type_size("int", 32));
        assert!(registry.verify_type_size("double", 64));
        assert!(registry.verify_type_size("char", 8));
        assert!(registry.verify_type_size("float", 32));
        assert!(!registry.verify_type_size("int", 64));
    }

    #[test]
    fn test_type_registry_lookup() {
        let registry = TypeRegistry::new();
        assert!(registry.lookup("int").is_some());
        assert!(registry.lookup("nonexistent").is_none());
    }

    // ── C AST test source checks ───────────────────────────────────────

    #[test]
    fn test_c_function_def_source() {
        let src = c_function_def_source();
        assert!(src.contains("int add"));
        assert!(src.contains("a + b"));
    }

    #[test]
    fn test_c_function_def_expected() {
        let expected = c_function_def_expected();
        assert_eq!(expected.len(), 1);
        assert_eq!(expected[0].kind, AstNodeKind::FunctionDecl);
        assert_eq!(expected[0].children.len(), 2);
    }

    #[test]
    fn test_c_struct_source() {
        let src = c_struct_source();
        assert!(src.contains("struct Point"));
        assert!(src.contains("int x"));
    }

    #[test]
    fn test_c_struct_expected() {
        let expected = c_struct_expected();
        assert_eq!(expected[0].kind, AstNodeKind::StructDecl);
        assert_eq!(expected[0].children.len(), 2);
    }

    #[test]
    fn test_c_typedef_source() {
        let src = c_typedef_source();
        assert!(src.contains("typedef"));
        assert!(src.contains("size_t"));
    }

    #[test]
    fn test_c_array_pointer_source() {
        let src = c_array_pointer_source();
        assert!(src.contains("arr[10]"));
        assert!(src.contains("*p"));
    }

    #[test]
    fn test_c_loops_source() {
        let src = c_loops_source();
        assert!(src.contains("for"));
        assert!(src.contains("while"));
        assert!(src.contains("do"));
    }

    #[test]
    fn test_c_loops_expected_kinds() {
        let kinds = c_loops_expected_kinds();
        assert!(kinds.contains(&AstNodeKind::ForStmt));
        assert!(kinds.contains(&AstNodeKind::WhileStmt));
        assert!(kinds.contains(&AstNodeKind::DoWhileStmt));
    }

    #[test]
    fn test_c_switch_source() {
        let src = c_switch_source();
        assert!(src.contains("switch"));
        assert!(src.contains("case"));
        assert!(src.contains("default"));
    }

    #[test]
    fn test_c_switch_expected_kinds() {
        let kinds = c_switch_expected_kinds();
        assert!(kinds.contains(&AstNodeKind::SwitchStmt));
        assert!(kinds.contains(&AstNodeKind::CaseStmt));
        assert!(kinds.contains(&AstNodeKind::DefaultStmt));
    }

    #[test]
    fn test_c_goto_source() {
        let src = c_goto_source();
        assert!(src.contains("goto"));
        assert!(src.contains("end:"));
    }

    #[test]
    fn test_c_union_enum_source() {
        let src = c_union_enum_source();
        assert!(src.contains("union Data"));
        assert!(src.contains("enum Color"));
    }

    // ── C++ AST test source checks ─────────────────────────────────────

    #[test]
    fn test_cpp_class_source() {
        let src = cpp_class_source();
        assert!(src.contains("class Calculator"));
        assert!(src.contains("public:"));
        assert!(src.contains("private:"));
    }

    #[test]
    fn test_cpp_class_expected_kinds() {
        let kinds = cpp_class_expected_kinds();
        assert!(kinds.contains(&AstNodeKind::CXXRecordDecl));
        assert!(kinds.contains(&AstNodeKind::CXXMethodDecl));
    }

    #[test]
    fn test_cpp_inheritance_source() {
        let src = cpp_inheritance_source();
        assert!(src.contains("class Base"));
        assert!(src.contains("class Derived"));
        assert!(src.contains("public Base"));
    }

    #[test]
    fn test_cpp_template_source() {
        let src = cpp_template_source();
        assert!(src.contains("template"));
        assert!(src.contains("typename T"));
    }

    #[test]
    fn test_cpp_template_expected_kinds() {
        let kinds = cpp_template_expected_kinds();
        assert!(kinds.contains(&AstNodeKind::ClassTemplateDecl));
        assert!(kinds.contains(&AstNodeKind::TemplateTypeParmDecl));
    }

    #[test]
    fn test_cpp_namespace_source() {
        let src = cpp_namespace_source();
        assert!(src.contains("namespace math"));
        assert!(src.contains("using"));
    }

    #[test]
    fn test_cpp_namespace_expected_kinds() {
        let kinds = cpp_namespace_expected_kinds();
        assert!(kinds.contains(&AstNodeKind::NamespaceDecl));
        assert!(kinds.contains(&AstNodeKind::UsingDecl));
    }

    #[test]
    fn test_cpp_operator_source() {
        let src = cpp_operator_source();
        assert!(src.contains("operator+"));
    }

    #[test]
    fn test_cpp_virtual_source() {
        let src = cpp_virtual_source();
        assert!(src.contains("virtual"));
        assert!(src.contains("override"));
        assert!(src.contains("~Animal"));
    }

    // ── Error recovery tests ───────────────────────────────────────────

    #[test]
    fn test_error_recovery_sources_not_empty() {
        let sources = error_recovery_sources();
        assert!(!sources.is_empty());
    }

    #[test]
    fn test_error_recovery_result_recovered() {
        let result = ErrorRecoveryResult::recovered(vec!["expected ';'".into()]);
        assert!(result.recovered);
        assert_eq!(result.error_count, 1);
        assert!(result.partial_ast);
    }

    #[test]
    fn test_error_recovery_result_not_recovered() {
        let result = ErrorRecoveryResult::not_recovered(vec!["fatal error".into()]);
        assert!(!result.recovered);
        assert!(!result.partial_ast);
    }

    // ── Symbol table tests ─────────────────────────────────────────────

    #[test]
    fn test_expected_symbols_for_c_basic() {
        let syms = expected_symbols_for_c_basic();
        assert!(syms.iter().any(|s| s.name == "main"));
        assert!(syms.iter().any(|s| s.name == "add"));
        assert_eq!(syms[0].kind, SymbolKind::Function);
    }

    #[test]
    fn test_expected_symbols_for_struct() {
        let syms = expected_symbols_for_struct();
        assert!(syms
            .iter()
            .any(|s| s.name == "Point" && s.kind == SymbolKind::Type));
        assert!(syms
            .iter()
            .any(|s| s.name == "x" && s.kind == SymbolKind::Field));
    }

    #[test]
    fn test_symbol_kind_name() {
        assert_eq!(SymbolKind::Function.name(), "function");
        assert_eq!(SymbolKind::Type.name(), "type");
        assert_eq!(SymbolKind::Label.name(), "label");
    }

    // ── ExpectedAstNode tests ──────────────────────────────────────────

    #[test]
    fn test_expected_ast_node_builder() {
        let node = ExpectedAstNode {
            kind: AstNodeKind::TranslationUnit,
            name: None,
            type_name: None,
            location: Some((1, 1)),
            children: vec![],
            attributes: BTreeMap::new(),
        };
        assert_eq!(node.kind, AstNodeKind::TranslationUnit);
        assert_eq!(node.location, Some((1, 1)));
    }

    #[test]
    fn test_expected_ast_node_with_children() {
        let child = ExpectedAstNode {
            kind: AstNodeKind::ReturnStmt,
            name: None,
            type_name: None,
            location: None,
            children: vec![],
            attributes: BTreeMap::new(),
        };
        let parent = ExpectedAstNode {
            kind: AstNodeKind::FunctionDecl,
            name: Some("f".into()),
            type_name: Some("int".into()),
            location: Some((1, 1)),
            children: vec![child],
            attributes: BTreeMap::new(),
        };
        assert_eq!(parent.children.len(), 1);
    }

    #[test]
    fn test_ast_node_kind_variants() {
        // Ensure all expected variants have names
        let kinds = [
            AstNodeKind::TranslationUnit,
            AstNodeKind::FunctionDecl,
            AstNodeKind::StructDecl,
            AstNodeKind::TypedefDecl,
            AstNodeKind::IfStmt,
            AstNodeKind::BinaryOperator,
            AstNodeKind::CallExpr,
            AstNodeKind::ArraySubscriptExpr,
        ];
        for k in &kinds {
            assert!(!k.name().is_empty());
        }
    }
}