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
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
//! clang_analyzer_checkers2 — Extended static analyzer checkers (Phase 2).
//!
//! Additional Clang Static Analyzer checkers for C++ Core Guidelines,
//! thread safety, performance, modernization, portability, security,
//! style, and documentation.
//!
//! Clean-room design from C++ Core Guidelines, CERT coding standards,
//! and Clang Static Analyzer documentation.

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

// ═══════════════════════════════════════════════════════════════════════════════
// Checker result types
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct CheckerDiagnostic {
    pub checker: String,
    pub rule_id: String,
    pub severity: DiagLevel,
    pub message: String,
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub fixit: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagLevel {
    Note,
    Warning,
    Error,
    Fatal,
}

impl DiagLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Note => "note",
            Self::Warning => "warning",
            Self::Error => "error",
            Self::Fatal => "fatal",
        }
    }
}

#[derive(Debug, Clone)]
pub struct CheckerResult {
    pub checker_name: String,
    pub diagnostics: Vec<CheckerDiagnostic>,
    pub files_checked: usize,
}

impl CheckerResult {
    pub fn new(name: &str) -> Self {
        Self {
            checker_name: name.to_string(),
            diagnostics: Vec::new(),
            files_checked: 0,
        }
    }
}

/// Common trait for all checkers.
pub trait StaticChecker {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn check(&self, source: &str) -> CheckerResult;
}

// ═══════════════════════════════════════════════════════════════════════════════
// CppCoreGuidelinesChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct CppCoreGuidelinesChecker {
    pub enabled_rules: HashSet<String>,
}

impl CppCoreGuidelinesChecker {
    pub fn new() -> Self {
        let mut rules = HashSet::new();
        for r in &[
            "C.128", "ES.23", "I.3", "F.6", "C.35", "C.36", "C.45", "C.46", "F.15", "F.16",
            "ES.20", "ES.21", "ES.56", "Con.1", "Con.2", "Con.3", "Con.4",
        ] {
            rules.insert(r.to_string());
        }
        Self {
            enabled_rules: rules,
        }
    }

    pub fn enable_rule(&mut self, rule: &str) {
        self.enabled_rules.insert(rule.to_string());
    }
    pub fn disable_rule(&mut self, rule: &str) {
        self.enabled_rules.remove(rule);
    }

    /// C.128: Virtual functions should specify exactly one of virtual, override, or final.
    pub fn check_c128(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            let trimmed = line.trim();
            if trimmed.contains("virtual") && trimmed.contains("override") {
                diags.push(CheckerDiagnostic {
                    checker: "cppcoreguidelines".into(), rule_id: "C.128".into(),
                    severity: DiagLevel::Warning, file: "input.cpp".into(), line: i + 1, column: 1,
                    message: "Virtual function should specify exactly one of virtual, override, or final (C.128)".into(),
                    fixit: Some("consider removing 'virtual' when 'override' is used".into()),
                });
            }
        }
        diags
    }

    /// ES.23: Prefer the {}-initializer syntax.
    pub fn check_es23(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains(" = 0")
                && !line.contains(" = 0;")
                && line.contains("int")
                && !line.contains("{")
            {
                diags.push(CheckerDiagnostic {
                    checker: "cppcoreguidelines".into(),
                    rule_id: "ES.23".into(),
                    severity: DiagLevel::Warning,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Prefer {} initializer syntax over = (ES.23)".into(),
                    fixit: Some("use {0} instead of = 0".into()),
                });
            }
        }
        diags
    }

    /// I.3: Avoid singletons.
    pub fn check_i3(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("static") && source.contains("getInstance") {
            diags.push(CheckerDiagnostic {
                checker: "cppcoreguidelines".into(),
                rule_id: "I.3".into(),
                severity: DiagLevel::Warning,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Avoid singletons; consider dependency injection instead (I.3)".into(),
                fixit: None,
            });
        }
        diags
    }

    /// F.6: Prefer asserts over comments to state preconditions.
    pub fn check_f6(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.trim().starts_with("// precondition:")
                || line.trim().starts_with("// requires:")
            {
                diags.push(CheckerDiagnostic {
                    checker: "cppcoreguidelines".into(),
                    rule_id: "F.6".into(),
                    severity: DiagLevel::Note,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Prefer using assert() for preconditions instead of comments (F.6)"
                        .into(),
                    fixit: Some("replace comment with assert(condition)".into()),
                });
            }
        }
        diags
    }

    /// C.35: A base class destructor should be either public and virtual, or protected and non-virtual.
    pub fn check_c35(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("~") && source.contains("virtual") {
            // Check for protected non-virtual vs public virtual
            if !source.contains("public") && !source.contains("protected") {
                diags.push(CheckerDiagnostic {
                    checker: "cppcoreguidelines".into(), rule_id: "C.35".into(),
                    severity: DiagLevel::Warning, file: "input.cpp".into(), line: 1, column: 1,
                    message: "Base class destructor should be public and virtual, or protected and non-virtual (C.35)".into(),
                    fixit: Some("add 'public virtual' or 'protected' to destructor".into()),
                });
            }
        }
        diags
    }
}

impl StaticChecker for CppCoreGuidelinesChecker {
    fn name(&self) -> &str {
        "cppcoreguidelines"
    }
    fn description(&self) -> &str {
        "Checks C++ Core Guidelines violations"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result.diagnostics.extend(self.check_c128(source));
        result.diagnostics.extend(self.check_es23(source));
        result.diagnostics.extend(self.check_i3(source));
        result.diagnostics.extend(self.check_f6(source));
        result.diagnostics.extend(self.check_c35(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// ThreadSafetyChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LockAnnotation {
    GuardedBy(String),
    PtGuardedBy(String),
    AcquiredBefore(String),
    AcquiredAfter(String),
    ExclusiveLockFunction,
    SharedLockFunction,
    UnlockFunction,
    ExcludeLockFunction,
    NoThreadSafetyAnalysis,
}

impl LockAnnotation {
    pub fn from_attribute(s: &str) -> Option<Self> {
        if s.starts_with("guarded_by(") {
            let inner = s.trim_start_matches("guarded_by(").trim_end_matches(')');
            Some(Self::GuardedBy(inner.to_string()))
        } else if s.starts_with("pt_guarded_by(") {
            let inner = s.trim_start_matches("pt_guarded_by(").trim_end_matches(')');
            Some(Self::PtGuardedBy(inner.to_string()))
        } else if s.starts_with("acquired_before(") {
            let inner = s
                .trim_start_matches("acquired_before(")
                .trim_end_matches(')');
            Some(Self::AcquiredBefore(inner.to_string()))
        } else if s.starts_with("acquired_after(") {
            let inner = s
                .trim_start_matches("acquired_after(")
                .trim_end_matches(')');
            Some(Self::AcquiredAfter(inner.to_string()))
        } else {
            match s {
                "exclusive_lock_function" => Some(Self::ExclusiveLockFunction),
                "shared_lock_function" => Some(Self::SharedLockFunction),
                "unlock_function" => Some(Self::UnlockFunction),
                "exclude_lock_function" => Some(Self::ExcludeLockFunction),
                "no_thread_safety_analysis" => Some(Self::NoThreadSafetyAnalysis),
                _ => None,
            }
        }
    }

    pub fn is_lock_acquire(&self) -> bool {
        matches!(self, Self::ExclusiveLockFunction | Self::SharedLockFunction)
    }
}

#[derive(Debug, Clone)]
pub struct ThreadSafetyChecker {
    pub mutexes: HashMap<String, MutexDescriptor>,
    pub check_double_lock: bool,
    pub check_unlock_without_lock: bool,
}

#[derive(Debug, Clone)]
pub struct MutexDescriptor {
    pub name: String,
    pub locked: bool,
    pub locked_shared: bool,
}

impl ThreadSafetyChecker {
    pub fn new() -> Self {
        Self {
            mutexes: HashMap::new(),
            check_double_lock: true,
            check_unlock_without_lock: true,
        }
    }

    pub fn register_mutex(&mut self, name: &str) {
        self.mutexes.insert(
            name.to_string(),
            MutexDescriptor {
                name: name.to_string(),
                locked: false,
                locked_shared: false,
            },
        );
    }

    pub fn check_lock_order(&self, _acquired: &str, _held: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        // In real implementation: check acquired_before/acquired_after annotations
        diags
    }

    pub fn check_double_lock(&self, mutex_name: &str, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let mut lock_count = 0;
        for line in source.lines() {
            if line.contains(&format!("{}.lock()", mutex_name))
                || line.contains(&format!("lock_guard<{}>", mutex_name))
            {
                lock_count += 1;
            }
        }
        if lock_count > 1 {
            diags.push(CheckerDiagnostic {
                checker: "threadsafety".into(),
                rule_id: "double_lock".into(),
                severity: DiagLevel::Error,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: format!(
                    "Mutex '{}' locked twice without intervening unlock",
                    mutex_name
                ),
                fixit: None,
            });
        }
        diags
    }

    pub fn check_guarded_access(&self, var: &str, _source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        // Check that accesses to guarded variables happen under lock
        diags.push(CheckerDiagnostic {
            checker: "threadsafety".into(),
            rule_id: "guarded_access".into(),
            severity: DiagLevel::Warning,
            file: "input.cpp".into(),
            line: 1,
            column: 1,
            message: format!("Access to guarded variable '{}' outside lock", var),
            fixit: Some("acquire the mutex before accessing".into()),
        });
        diags
    }
}

impl StaticChecker for ThreadSafetyChecker {
    fn name(&self) -> &str {
        "threadsafety"
    }
    fn description(&self) -> &str {
        "Checks mutex locking discipline with annotations"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        // Run registered checks
        for (name, _) in &self.mutexes {
            result
                .diagnostics
                .extend(self.check_double_lock(name, source));
        }
        if source.contains("mutex") && !source.contains("lock") {
            result.diagnostics.push(CheckerDiagnostic {
                checker: "threadsafety".into(),
                rule_id: "missing_lock".into(),
                severity: DiagLevel::Warning,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Mutex variable not locked before use".into(),
                fixit: Some("add std::lock_guard".into()),
            });
        }
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// PerformanceAnalyzer
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct PerformanceAnalyzer {
    pub detect_unnecessary_copies: bool,
    pub detect_pass_by_value: bool,
    pub prefer_emplace: bool,
}

impl PerformanceAnalyzer {
    pub fn new() -> Self {
        Self {
            detect_unnecessary_copies: true,
            detect_pass_by_value: true,
            prefer_emplace: true,
        }
    }

    pub fn check_unnecessary_copies(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            // Detect: auto x = some_container[i]; (copy instead of const ref)
            if line.contains("auto ")
                && line.contains(" = ")
                && !line.contains("&")
                && !line.contains("&&")
                && !line.contains("std::move")
            {
                diags.push(CheckerDiagnostic {
                    checker: "performance".into(),
                    rule_id: "unnecessary_copy".into(),
                    severity: DiagLevel::Warning,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Unnecessary copy detected; consider using const auto&".into(),
                    fixit: Some("use 'const auto&' instead of 'auto'".into()),
                });
            }
        }
        diags
    }

    pub fn check_pass_by_value_sink(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            // Detect const& in parameter that could be pass-by-value (sink parameter)
            if line.contains("const std::string&") && line.contains(")") {
                diags.push(CheckerDiagnostic {
                    checker: "performance".into(),
                    rule_id: "pass_by_value_sink".into(),
                    severity: DiagLevel::Note,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Consider pass-by-value + std::move for sink parameters".into(),
                    fixit: Some("use 'std::string' instead of 'const std::string&'".into()),
                });
            }
        }
        diags
    }

    pub fn check_emplace_vs_push(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("push_back(std::make_pair")
            || source.contains("push_back(std::make_tuple")
        {
            diags.push(CheckerDiagnostic {
                checker: "performance".into(),
                rule_id: "emplace_back".into(),
                severity: DiagLevel::Warning,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Use emplace_back instead of push_back with make_pair/make_tuple".into(),
                fixit: Some("replace push_back(make_pair(a,b)) with emplace_back(a,b)".into()),
            });
        }
        if source.contains("push_back(") && source.contains("}") && !source.contains("emplace_back")
        {
            diags.push(CheckerDiagnostic {
                checker: "performance".into(),
                rule_id: "emplace_suggestion".into(),
                severity: DiagLevel::Note,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Consider emplace_back() for constructing elements in-place".into(),
                fixit: Some("replace push_back(...) with emplace_back(...)".into()),
            });
        }
        diags
    }
}

impl StaticChecker for PerformanceAnalyzer {
    fn name(&self) -> &str {
        "performance"
    }
    fn description(&self) -> &str {
        "Detects unnecessary copies, pass-by-value opportunities, and emplace suggestions"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result
            .diagnostics
            .extend(self.check_unnecessary_copies(source));
        result
            .diagnostics
            .extend(self.check_pass_by_value_sink(source));
        result
            .diagnostics
            .extend(self.check_emplace_vs_push(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// ModernizeChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct ModernizeChecker {
    pub suggest_nullptr: bool,
    pub suggest_override: bool,
    pub suggest_auto: bool,
    pub suggest_range_for: bool,
}

impl ModernizeChecker {
    pub fn new() -> Self {
        Self {
            suggest_nullptr: true,
            suggest_override: true,
            suggest_auto: true,
            suggest_range_for: true,
        }
    }

    pub fn check_nullptr(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("NULL") || line.contains(" = 0") && line.contains("*") {
                diags.push(CheckerDiagnostic {
                    checker: "modernize".into(),
                    rule_id: "nullptr".into(),
                    severity: DiagLevel::Warning,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Use nullptr instead of NULL or 0 for null pointers".into(),
                    fixit: Some("replace with nullptr".into()),
                });
            }
        }
        diags
    }

    pub fn check_override(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("virtual") && line.contains("override") {
                diags.push(CheckerDiagnostic {
                    checker: "modernize".into(),
                    rule_id: "redundant_virtual".into(),
                    severity: DiagLevel::Warning,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "'virtual' is redundant when 'override' is used".into(),
                    fixit: Some("remove 'virtual'".into()),
                });
            }
        }
        diags
    }

    pub fn check_auto(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("std::vector<")
                && line.contains("::iterator")
                && !line.contains("auto")
            {
                diags.push(CheckerDiagnostic {
                    checker: "modernize".into(),
                    rule_id: "use_auto".into(),
                    severity: DiagLevel::Note,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Use auto for iterator type deduction".into(),
                    fixit: Some("replace 'std::vector<T>::iterator' with 'auto'".into()),
                });
            }
        }
        diags
    }

    pub fn check_range_for(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("for (")
            && source.contains("::begin()")
            && source.contains("::end()")
            && !source.contains(":")
        {
            diags.push(CheckerDiagnostic {
                checker: "modernize".into(),
                rule_id: "range_for".into(),
                severity: DiagLevel::Note,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Use range-based for loop instead of iterator pair".into(),
                fixit: Some("replace with 'for (auto& x : container)'".into()),
            });
        }
        diags
    }
}

impl StaticChecker for ModernizeChecker {
    fn name(&self) -> &str {
        "modernize"
    }
    fn description(&self) -> &str {
        "Suggests modern C++ replacements (nullptr, auto, override, range-for)"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result.diagnostics.extend(self.check_nullptr(source));
        result.diagnostics.extend(self.check_override(source));
        result.diagnostics.extend(self.check_auto(source));
        result.diagnostics.extend(self.check_range_for(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// PortabilityChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct PortabilityChecker {
    pub check_type_sizes: bool,
    pub check_alignment: bool,
    pub check_endianness: bool,
    pub check_undefined_behavior: bool,
}

impl PortabilityChecker {
    pub fn new() -> Self {
        Self {
            check_type_sizes: true,
            check_alignment: true,
            check_endianness: true,
            check_undefined_behavior: true,
        }
    }

    pub fn check_type_sizes(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("sizeof(int)") {
            diags.push(CheckerDiagnostic {
                checker: "portability".into(),
                rule_id: "type_size".into(),
                severity: DiagLevel::Note,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "sizeof(int) may vary across platforms; use fixed-width types".into(),
                fixit: Some("use int32_t from <cstdint>".into()),
            });
        }
        diags
    }

    pub fn check_alignment(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("reinterpret_cast") && source.contains("char*") {
            diags.push(CheckerDiagnostic {
                checker: "portability".into(),
                rule_id: "alignment".into(),
                severity: DiagLevel::Warning,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "reinterpret_cast to char* may violate alignment requirements".into(),
                fixit: Some("use std::bit_cast or memcpy for type punning".into()),
            });
        }
        diags
    }

    pub fn check_endianness(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("htonl") || source.contains("ntohl") {
            diags.push(CheckerDiagnostic {
                checker: "portability".into(),
                rule_id: "endianness".into(),
                severity: DiagLevel::Note,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Endianness conversion detected; ensure portability".into(),
                fixit: None,
            });
        }
        diags
    }

    pub fn check_undefined_behavior(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let ub_patterns = [
            ("<< 32", "shift amount >= width of type"),
            (">> -1", "right shift by negative amount"),
            ("[", "potential buffer overflow, check bounds"),
        ];
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            for (pattern, msg) in &ub_patterns {
                if line.contains(pattern) {
                    diags.push(CheckerDiagnostic {
                        checker: "portability".into(),
                        rule_id: "undefined_behavior".into(),
                        severity: DiagLevel::Error,
                        file: "input.cpp".into(),
                        line: i + 1,
                        column: 1,
                        message: format!("Potential undefined behavior: {}", msg),
                        fixit: Some("add bounds check before operation".into()),
                    });
                }
            }
        }
        diags
    }
}

impl StaticChecker for PortabilityChecker {
    fn name(&self) -> &str {
        "portability"
    }
    fn description(&self) -> &str {
        "Detects non-portable constructs and undefined behavior"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result.diagnostics.extend(self.check_type_sizes(source));
        result.diagnostics.extend(self.check_alignment(source));
        result.diagnostics.extend(self.check_endianness(source));
        result
            .diagnostics
            .extend(self.check_undefined_behavior(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// SecurityChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct SecurityChecker {
    pub check_buffer_overflow: bool,
    pub check_format_string: bool,
    pub check_integer_overflow: bool,
    pub check_use_after_free: bool,
}

impl SecurityChecker {
    pub fn new() -> Self {
        Self {
            check_buffer_overflow: true,
            check_format_string: true,
            check_integer_overflow: true,
            check_use_after_free: true,
        }
    }

    pub fn check_buffer_overflow(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let dangerous = ["strcpy", "strcat", "sprintf", "gets", "scanf(\"%s\""];
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            for func in &dangerous {
                if line.contains(func) {
                    diags.push(CheckerDiagnostic {
                        checker: "security".into(),
                        rule_id: "buffer_overflow".into(),
                        severity: DiagLevel::Error,
                        file: "input.cpp".into(),
                        line: i + 1,
                        column: 1,
                        message: format!(
                            "Use of unsafe function '{}' may cause buffer overflow",
                            func
                        ),
                        fixit: Some(format!(
                            "replace {} with safer alternative (strncpy, snprintf, etc.)",
                            func
                        )),
                    });
                }
            }
        }
        diags
    }

    pub fn check_format_string(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("printf(") && !line.contains("\"") {
                diags.push(CheckerDiagnostic {
                    checker: "security".into(),
                    rule_id: "format_string".into(),
                    severity: DiagLevel::Error,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Format string vulnerability: user-controlled format string".into(),
                    fixit: Some("use printf(\"%s\", user_str) instead of printf(user_str)".into()),
                });
            }
        }
        diags
    }

    pub fn check_integer_overflow(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        if source.contains("malloc") && source.contains("*") && !source.contains("checked") {
            diags.push(CheckerDiagnostic {
                checker: "security".into(),
                rule_id: "integer_overflow".into(),
                severity: DiagLevel::Warning,
                file: "input.cpp".into(),
                line: 1,
                column: 1,
                message: "Integer overflow possible in malloc size calculation".into(),
                fixit: Some("use calloc or check for overflow before multiplication".into()),
            });
        }
        diags
    }

    pub fn check_use_after_free(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        let mut freed_vars: HashSet<String> = HashSet::new();
        for (i, line) in lines.iter().enumerate() {
            if line.contains("free(") {
                if let Some(start) = line.find("free(") {
                    if let Some(end) = line[start + 5..].find(')') {
                        freed_vars.insert(line[start + 5..start + 5 + end].trim().to_string());
                    }
                }
            }
            if line.contains("delete ") {
                freed_vars.insert("heap_ptr".to_string());
            }
        }
        for var in &freed_vars {
            for (i, line) in lines.iter().enumerate() {
                if line.contains(var) && !line.contains("free(") && !line.contains("delete ") {
                    diags.push(CheckerDiagnostic {
                        checker: "security".into(),
                        rule_id: "use_after_free".into(),
                        severity: DiagLevel::Error,
                        file: "input.cpp".into(),
                        line: i + 1,
                        column: 1,
                        message: format!("Use-after-free detected for '{}'", var),
                        fixit: Some("set pointer to nullptr after free".into()),
                    });
                }
            }
        }
        diags
    }
}

impl StaticChecker for SecurityChecker {
    fn name(&self) -> &str {
        "security"
    }
    fn description(&self) -> &str {
        "Detects buffer overflows, format string bugs, integer overflow, use-after-free"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result
            .diagnostics
            .extend(self.check_buffer_overflow(source));
        result.diagnostics.extend(self.check_format_string(source));
        result
            .diagnostics
            .extend(self.check_integer_overflow(source));
        result.diagnostics.extend(self.check_use_after_free(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// StyleChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct StyleChecker {
    pub check_naming: bool,
    pub check_braces: bool,
    pub check_indentation: bool,
    pub check_comments: bool,
}

impl StyleChecker {
    pub fn new() -> Self {
        Self {
            check_naming: true,
            check_braces: true,
            check_indentation: true,
            check_comments: true,
        }
    }

    pub fn check_naming(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            // Detect ALL_CAPS function names (should be snake_case or camelCase)
            if line.contains("void ") || line.contains("int ") || line.contains("auto ") {
                if let Some(start) = line.find("void ") {
                    let rest = &line[start + 5..];
                    if let Some(name) = rest.split('(').next() {
                        let name = name.trim();
                        if name.chars().all(|c| c.is_uppercase() || c == '_') && name.len() > 2 {
                            diags.push(CheckerDiagnostic {
                                checker: "style".into(),
                                rule_id: "naming".into(),
                                severity: DiagLevel::Warning,
                                file: "input.cpp".into(),
                                line: i + 1,
                                column: 1,
                                message: format!(
                                    "Function '{}' uses ALL_CAPS; prefer snake_case",
                                    name
                                ),
                                fixit: Some("rename function to snake_case".into()),
                            });
                        }
                    }
                }
            }
        }
        diags
    }

    pub fn check_braces(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if (line.contains("if (") || line.contains("for (") || line.contains("while ("))
                && !line.trim().ends_with('{')
                && i + 1 < lines.len()
            {
                let next = lines[i + 1].trim();
                if next == "{" {
                    // Allman style detected
                } else if next.starts_with('{') && !line.ends_with('{') {
                    diags.push(CheckerDiagnostic {
                        checker: "style".into(),
                        rule_id: "brace_style".into(),
                        severity: DiagLevel::Note,
                        file: "input.cpp".into(),
                        line: i + 1,
                        column: 1,
                        message: "Inconsistent brace style".into(),
                        fixit: Some("use consistent brace placement".into()),
                    });
                }
            }
        }
        diags
    }

    pub fn check_indentation(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        let mut prev_indent = 0;
        for (i, line) in lines.iter().enumerate() {
            if line.trim().is_empty() {
                continue;
            }
            let indent = line.len() - line.trim_start().len();
            if i > 0 && indent > prev_indent + 8 {
                diags.push(CheckerDiagnostic {
                    checker: "style".into(),
                    rule_id: "indentation".into(),
                    severity: DiagLevel::Note,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: indent + 1,
                    message: "Suspicious indentation (more than 8 spaces increase)".into(),
                    fixit: Some("use consistent 2 or 4 space indentation".into()),
                });
            }
            prev_indent = indent;
        }
        diags
    }

    pub fn check_comments(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.trim().starts_with("// TODO") || line.trim().starts_with("// FIXME") {
                diags.push(CheckerDiagnostic {
                    checker: "style".into(),
                    rule_id: "todo_comment".into(),
                    severity: DiagLevel::Note,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "TODO/FIXME comment found".into(),
                    fixit: None,
                });
            }
        }
        diags
    }
}

impl StaticChecker for StyleChecker {
    fn name(&self) -> &str {
        "style"
    }
    fn description(&self) -> &str {
        "Checks naming conventions, brace style, indentation, and comments"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result.diagnostics.extend(self.check_naming(source));
        result.diagnostics.extend(self.check_braces(source));
        result.diagnostics.extend(self.check_indentation(source));
        result.diagnostics.extend(self.check_comments(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// DocumentationChecker
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct DocumentationChecker {
    pub require_public_api_docs: bool,
    pub require_params_docs: bool,
}

impl DocumentationChecker {
    pub fn new() -> Self {
        Self {
            require_public_api_docs: true,
            require_params_docs: true,
        }
    }

    pub fn check_missing_docs(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        let mut has_doc = false;
        for (i, line) in lines.iter().enumerate() {
            if line.trim().starts_with("///")
                || line.trim().starts_with("//!")
                || line.trim().starts_with("/**")
                || line.trim().starts_with("/*!")
            {
                has_doc = true;
            }
            // Check for public functions without documentation
            if (line.contains("void ") || line.contains("int ") || line.contains("auto "))
                && line.contains('(')
                && line.contains(')')
                && !has_doc
                && !line.contains("private:")
                && !line.contains("static")
            {
                diags.push(CheckerDiagnostic {
                    checker: "documentation".into(),
                    rule_id: "missing_doc".into(),
                    severity: DiagLevel::Warning,
                    file: "input.cpp".into(),
                    line: i + 1,
                    column: 1,
                    message: "Missing documentation for public API".into(),
                    fixit: Some("add /// doc comment before function".into()),
                });
            }
            if line.contains(';') || line.contains('}') {
                has_doc = false;
            }
        }
        diags
    }

    pub fn check_param_docs(&self, source: &str) -> Vec<CheckerDiagnostic> {
        let mut diags = Vec::new();
        let lines: Vec<&str> = source.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            if line.contains('(') && line.contains(')') && !line.contains("()") {
                if i > 0 && !lines[i - 1].contains("@param") && !lines[i - 1].contains("\\param") {
                    let doc_above = if i >= 2 {
                        lines[i - 2].contains("///")
                    } else {
                        false
                    };
                    if !doc_above {
                        // Check if this is a function definition (simplified)
                        if line.contains("void ") || line.contains("int ") || line.contains("auto ")
                        {
                            diags.push(CheckerDiagnostic {
                                checker: "documentation".into(),
                                rule_id: "missing_param_doc".into(),
                                severity: DiagLevel::Note,
                                file: "input.cpp".into(),
                                line: i + 1,
                                column: 1,
                                message: "Function has parameters but no @param documentation"
                                    .into(),
                                fixit: Some("add @param tags for each parameter".into()),
                            });
                        }
                    }
                }
            }
        }
        diags
    }
}

impl StaticChecker for DocumentationChecker {
    fn name(&self) -> &str {
        "documentation"
    }
    fn description(&self) -> &str {
        "Checks missing documentation for public APIs and parameters"
    }
    fn check(&self, source: &str) -> CheckerResult {
        let mut result = CheckerResult::new(self.name());
        result.diagnostics.extend(self.check_missing_docs(source));
        result.diagnostics.extend(self.check_param_docs(source));
        result.files_checked = 1;
        result
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Checker Registry Phase 2
// ═══════════════════════════════════════════════════════════════════════════════

pub struct Checker2Registry {
    checkers: Vec<Box<dyn StaticChecker>>,
}

impl Checker2Registry {
    pub fn new() -> Self {
        let mut registry = Self {
            checkers: Vec::new(),
        };
        registry
            .checkers
            .push(Box::new(CppCoreGuidelinesChecker::new()));
        registry.checkers.push(Box::new(ThreadSafetyChecker::new()));
        registry.checkers.push(Box::new(PerformanceAnalyzer::new()));
        registry.checkers.push(Box::new(ModernizeChecker::new()));
        registry.checkers.push(Box::new(PortabilityChecker::new()));
        registry.checkers.push(Box::new(SecurityChecker::new()));
        registry.checkers.push(Box::new(StyleChecker::new()));
        registry
            .checkers
            .push(Box::new(DocumentationChecker::new()));
        registry
    }

    pub fn add_checker(&mut self, checker: Box<dyn StaticChecker>) {
        self.checkers.push(checker);
    }

    pub fn run_all(&self, source: &str) -> Vec<CheckerResult> {
        self.checkers.iter().map(|c| c.check(source)).collect()
    }

    pub fn checker_names(&self) -> Vec<&str> {
        self.checkers.iter().map(|c| c.name()).collect()
    }

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

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

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

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

    #[test]
    fn test_diag_level_as_str() {
        assert_eq!(DiagLevel::Warning.as_str(), "warning");
        assert_eq!(DiagLevel::Error.as_str(), "error");
    }

    #[test]
    fn test_cppcoreguidelines_c128_virtual_override() {
        let checker = CppCoreGuidelinesChecker::new();
        let source = "virtual void foo() override;";
        let diags = checker.check_c128(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_cppcoreguidelines_es23() {
        let checker = CppCoreGuidelinesChecker::new();
        let source = "int x = 0;";
        let diags = checker.check_es23(source);
        // Should detect = 0 initialization on int
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_cppcoreguidelines_i3() {
        let checker = CppCoreGuidelinesChecker::new();
        let source = "static Foo* getInstance();";
        let diags = checker.check_i3(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_cppcoreguidelines_f6() {
        let checker = CppCoreGuidelinesChecker::new();
        let source = "// precondition: x > 0";
        let diags = checker.check_f6(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_cppcoreguidelines_full_check() {
        let checker = CppCoreGuidelinesChecker::new();
        let source = "virtual void f() override;\nint x = 0;\nstatic Foo* getInstance();";
        let result = checker.check(source);
        assert!(!result.diagnostics.is_empty());
    }

    #[test]
    fn test_lock_annotation_parsing() {
        assert!(matches!(
            LockAnnotation::from_attribute("guarded_by(mu)"),
            Some(LockAnnotation::GuardedBy(_))
        ));
        assert!(matches!(
            LockAnnotation::from_attribute("exclusive_lock_function"),
            Some(LockAnnotation::ExclusiveLockFunction)
        ));
        assert!(LockAnnotation::from_attribute("bogus").is_none());
    }

    #[test]
    fn test_thread_safety_double_lock() {
        let checker = ThreadSafetyChecker::new();
        let source = "mu.lock();\nmu.lock();";
        let diags = checker.check_double_lock("mu", source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_thread_safety_missing_lock() {
        let checker = ThreadSafetyChecker::new();
        let result = checker.check("std::mutex mu;\nint x = 42;");
        assert!(!result.diagnostics.is_empty());
    }

    #[test]
    fn test_performance_unnecessary_copy() {
        let analyzer = PerformanceAnalyzer::new();
        let source = "auto x = vec[0];";
        let diags = analyzer.check_unnecessary_copies(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_performance_pass_by_value() {
        let analyzer = PerformanceAnalyzer::new();
        let source = "void f(const std::string& s)";
        let diags = analyzer.check_pass_by_value_sink(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_performance_emplace_back() {
        let analyzer = PerformanceAnalyzer::new();
        let source = "v.push_back(std::make_pair(1, 2));";
        let diags = analyzer.check_emplace_vs_push(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_modernize_nullptr() {
        let checker = ModernizeChecker::new();
        let source = "char* p = NULL;";
        let diags = checker.check_nullptr(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_modernize_override_redundant() {
        let checker = ModernizeChecker::new();
        let source = "virtual void f() override;";
        let diags = checker.check_override(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_modernize_auto() {
        let checker = ModernizeChecker::new();
        let source = "std::vector<int>::iterator it = v.begin();";
        let diags = checker.check_auto(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_modernize_range_for() {
        let checker = ModernizeChecker::new();
        let source = "for (auto it = v.begin(); it != v.end(); ++it)";
        let diags = checker.check_range_for(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_portability_type_sizes() {
        let checker = PortabilityChecker::new();
        let source = "int n = sizeof(int);";
        let diags = checker.check_type_sizes(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_portability_alignment() {
        let checker = PortabilityChecker::new();
        let source = "auto* p = reinterpret_cast<char*>(&x);";
        let diags = checker.check_alignment(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_portability_undefined_behavior() {
        let checker = PortabilityChecker::new();
        let source = "int x = a << 32;";
        let diags = checker.check_undefined_behavior(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_security_buffer_overflow() {
        let checker = SecurityChecker::new();
        let source = "strcpy(buf, src);";
        let diags = checker.check_buffer_overflow(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_security_format_string() {
        let checker = SecurityChecker::new();
        let source = "printf(user_input);";
        let diags = checker.check_format_string(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_security_integer_overflow() {
        let checker = SecurityChecker::new();
        let source = "char* p = malloc(n * sizeof(int));";
        let diags = checker.check_integer_overflow(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_style_naming() {
        let checker = StyleChecker::new();
        let source = "void MY_FUNCTION() { }";
        let diags = checker.check_naming(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_style_todo_comment() {
        let checker = StyleChecker::new();
        let source = "// TODO: fix this";
        let diags = checker.check_comments(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_doc_missing_public_api() {
        let checker = DocumentationChecker::new();
        let source = "void doWork() { }";
        let diags = checker.check_missing_docs(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_doc_missing_params() {
        let checker = DocumentationChecker::new();
        let source = "void f(int a, int b) { }";
        let diags = checker.check_param_docs(source);
        assert!(!diags.is_empty());
    }

    #[test]
    fn test_checker2_registry() {
        let reg = Checker2Registry::new();
        assert_eq!(reg.count(), 8);
        let names = reg.checker_names();
        assert!(names.contains(&"cppcoreguidelines"));
        assert!(names.contains(&"security"));
        assert!(names.contains(&"style"));
    }

    #[test]
    fn test_checker2_registry_run_all() {
        let reg = Checker2Registry::new();
        let source = "virtual void f() override;\nstrcpy(buf, src);\nvoid MY_FUNC() { }";
        let results = reg.run_all(source);
        assert_eq!(results.len(), 8);
        for r in &results {
            assert!(
                !r.diagnostics.is_empty() || r.files_checked > 0,
                "checker {} found nothing",
                r.checker_name
            );
        }
    }
}