linthis 0.17.1

A fast, cross-platform multi-language linter and formatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! C/C++ language checker using clang-tidy or cpplint.

use crate::checkers::Checker;
use crate::utils::types::{LintIssue, Severity};
use crate::{Language, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Cpplint configuration for different languages
#[derive(Debug, Clone, Default)]
pub struct CpplintConfig {
    /// Line length limit
    pub linelength: Option<u32>,
    /// Filter rules (e.g., "-build/c++11,-build/header_guard")
    pub filter: Option<String>,
}

/// C/C++ checker using clang-tidy (preferred) or cpplint.
pub struct CppChecker {
    /// Custom .clang-tidy config path
    config_path: Option<PathBuf>,
    /// Custom compile_commands.json directory path
    compile_commands_dir: Option<PathBuf>,
    /// Cpplint config for C++ files
    cpplint_cpp_config: CpplintConfig,
    /// Cpplint config for Objective-C files
    cpplint_oc_config: CpplintConfig,
    /// Clang-tidy checks to ignore for C++ files
    cpp_ignored_checks: Vec<String>,
    /// Clang-tidy checks to ignore for Objective-C files
    oc_ignored_checks: Vec<String>,
    /// Max ObjC method SLOC threshold. Loaded from config, default 80.
    oc_fn_length: u32,
}

impl CppChecker {
    /// Get config search directories: current_dir first, then git project root as fallback.
    /// This ensures configs are found when:
    /// - Running from project root (normal case)
    /// - Running from a subdirectory (cwd misses .linthis/, git root has it)
    /// - Running with `-i /external/path` (cwd has user's config, git root may differ)
    /// - Running from editor plugins (cwd is set by editor to project root)
    fn config_search_dirs() -> Vec<PathBuf> {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let git_root = crate::utils::get_project_root();
        if cwd == git_root {
            vec![cwd]
        } else {
            vec![cwd, git_root]
        }
    }

    pub fn new() -> Self {
        // Try to load cpplint config from linthis config files
        let (cpp_config, oc_config) = Self::load_cpplint_configs();

        // Load clang-tidy config from linthis plugin configs
        let clang_tidy_config = Self::find_plugin_clang_tidy_config();

        // Load ignored checks for clang-tidy
        let (cpp_ignored, oc_ignored) = Self::load_ignored_checks();

        Self {
            config_path: clang_tidy_config,
            compile_commands_dir: None,
            cpplint_cpp_config: cpp_config,
            cpplint_oc_config: oc_config,
            cpp_ignored_checks: cpp_ignored,
            oc_ignored_checks: oc_ignored,
            oc_fn_length: Self::load_oc_fn_length(),
        }
    }

    /// Find clang-tidy config from linthis plugin configs.
    fn find_plugin_clang_tidy_config() -> Option<PathBuf> {
        let search_dirs = Self::config_search_dirs();

        // Check for cpp config first (across all search dirs)
        for dir in &search_dirs {
            let cpp_clang_tidy = dir.join(".linthis/configs/cpp/.clang-tidy");
            if cpp_clang_tidy.exists() {
                return Some(cpp_clang_tidy);
            }
        }

        // OC config as fallback
        for dir in &search_dirs {
            let oc_clang_tidy = dir.join(".linthis/configs/oc/.clang-tidy");
            if oc_clang_tidy.exists() {
                return Some(oc_clang_tidy);
            }
        }

        None
    }

    /// Load cpplint configs from linthis configuration
    fn load_cpplint_configs() -> (CpplintConfig, CpplintConfig) {
        use crate::config::Config;

        // Default configs with sensible defaults for each language
        let mut cpp_config = CpplintConfig {
            linelength: Some(120),
            filter: Some("-build/c++11,-build/c++14".to_string()),
        };

        // OC default: disable checks not applicable to Objective-C
        // -whitespace/parens: OC uses @property (attr) syntax which has space before (
        // -whitespace/operators: OC uses getter=xxx syntax which cpplint misinterprets
        let mut oc_config = CpplintConfig {
            linelength: Some(150),
            filter: Some("-build/c++11,-build/c++14,-build/header_guard,-build/include,-legal/copyright,-readability/casting,-runtime/references,-runtime/int,-whitespace/parens,-whitespace/braces,-whitespace/blank_line,-readability/braces,-whitespace/empty_if_body,-whitespace/operators".to_string()),
        };

        let search_dirs = Self::config_search_dirs();

        // Load from .linthis/configs/{lang}/CPPLINT.cfg (plugin configs)
        // Merge filters instead of replacing to preserve essential OC defaults
        // Search current_dir first, then git root as fallback
        for dir in &search_dirs {
            let cpp_cfg_path = dir.join(".linthis/configs/cpp/CPPLINT.cfg");
            if let Some(cfg) = Self::parse_cpplint_cfg(&cpp_cfg_path) {
                if cfg.linelength.is_some() {
                    cpp_config.linelength = cfg.linelength;
                }
                if let Some(ref f) = cfg.filter {
                    cpp_config.filter = Some(Self::merge_filters(cpp_config.filter.as_deref(), f));
                }
                break;
            }
        }
        for dir in &search_dirs {
            let oc_cfg_path = dir.join(".linthis/configs/oc/CPPLINT.cfg");
            if let Some(cfg) = Self::parse_cpplint_cfg(&oc_cfg_path) {
                if cfg.linelength.is_some() {
                    oc_config.linelength = cfg.linelength;
                }
                if let Some(ref f) = cfg.filter {
                    oc_config.filter = Some(Self::merge_filters(oc_config.filter.as_deref(), f));
                }
                break;
            }
        }

        // Priority 2: Override with config.toml settings (if specified)
        // Use first dir that has config (cwd first, then git root)
        let config_dir = search_dirs.first().cloned().unwrap_or_default();
        let merged = Config::load_merged(&config_dir);

        if let Some(ref cpp) = merged.language_overrides.cpp {
            if cpp.linelength.is_some() {
                cpp_config.linelength = cpp.linelength;
            }
            if cpp.cpplint_filter.is_some() {
                cpp_config.filter = cpp.cpplint_filter.clone();
            }
        }

        if let Some(ref oc) = merged.language_overrides.oc {
            if oc.linelength.is_some() {
                oc_config.linelength = oc.linelength;
            }
            if oc.cpplint_filter.is_some() {
                oc_config.filter = oc.cpplint_filter.clone();
            }
        }

        (cpp_config, oc_config)
    }

    /// Load clang-tidy ignored checks from linthis configuration
    fn load_ignored_checks() -> (Vec<String>, Vec<String>) {
        use crate::config::Config;

        let search_dirs = Self::config_search_dirs();
        let config_dir = search_dirs.first().cloned().unwrap_or_default();
        let merged = Config::load_merged(&config_dir);

        // Default ignored checks for Objective-C (ARC-related false positives)
        let default_oc_ignored = vec![
            "clang-analyzer-osx.cocoa.RetainCount".to_string(),
            "clang-analyzer-osx.cocoa.Dealloc".to_string(),
        ];

        let cpp_ignored = merged
            .language_overrides
            .cpp
            .and_then(|c| c.clang_tidy_ignored_checks)
            .unwrap_or_default();

        let oc_ignored = merged
            .language_overrides
            .oc
            .and_then(|c| c.clang_tidy_ignored_checks)
            .unwrap_or(default_oc_ignored);

        (cpp_ignored, oc_ignored)
    }

    /// Load ObjC method length threshold from config.toml.
    /// Priority: [oc] fn_length in config.toml > default 80.
    fn load_oc_fn_length() -> u32 {
        use crate::config::Config;
        let search_dirs = Self::config_search_dirs();
        let config_dir = search_dirs.first().cloned().unwrap_or_default();
        let merged = Config::load_merged(&config_dir);
        merged
            .language_overrides
            .oc
            .and_then(|c| c.fn_length)
            .unwrap_or(80)
    }

    /// Merge two filter strings, removing duplicates
    fn merge_filters(base: Option<&str>, additional: &str) -> String {
        use std::collections::HashSet;

        let mut filters: HashSet<&str> = HashSet::new();

        // Add base filters
        if let Some(base) = base {
            for f in base.split(',') {
                let f = f.trim();
                if !f.is_empty() {
                    filters.insert(f);
                }
            }
        }

        // Add additional filters
        for f in additional.split(',') {
            let f = f.trim();
            if !f.is_empty() {
                filters.insert(f);
            }
        }

        filters.into_iter().collect::<Vec<_>>().join(",")
    }

    /// Parse CPPLINT.cfg file and extract linelength and filter settings
    fn parse_cpplint_cfg(path: &Path) -> Option<CpplintConfig> {
        let content = std::fs::read_to_string(path).ok()?;

        let mut linelength = None;
        let mut filters = Vec::new();

        for line in content.lines() {
            let line = line.trim();
            // Skip comments and empty lines
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            if let Some(value) = line.strip_prefix("linelength=") {
                linelength = value.trim().parse().ok();
            } else if let Some(value) = line.strip_prefix("filter=") {
                filters.push(value.trim().to_string());
            }
        }

        // Combine all filter lines into one comma-separated string
        let filter = if filters.is_empty() {
            None
        } else {
            Some(filters.join(","))
        };

        Some(CpplintConfig { linelength, filter })
    }

    /// Set custom .clang-tidy config path
    pub fn with_config(mut self, path: PathBuf) -> Self {
        self.config_path = Some(path);
        self
    }

    /// Set custom compile_commands.json directory path
    /// This is the directory containing compile_commands.json, not the file itself
    pub fn with_compile_commands_dir(mut self, path: PathBuf) -> Self {
        self.compile_commands_dir = Some(path);
        self
    }

    /// Set cpplint config for C++ files
    pub fn with_cpplint_cpp_config(mut self, config: CpplintConfig) -> Self {
        self.cpplint_cpp_config = config;
        self
    }

    /// Set cpplint config for Objective-C files
    pub fn with_cpplint_oc_config(mut self, config: CpplintConfig) -> Self {
        self.cpplint_oc_config = config;
        self
    }

    /// Detect if a file is Objective-C (uses smart detection from Language)
    fn is_objective_c(path: &Path) -> bool {
        // Use the same smart detection logic as Language::from_path
        crate::Language::from_path(path)
            .map(|lang| lang == crate::Language::ObjectiveC)
            .unwrap_or(false)
    }

    /// Find .clang-tidy config file by walking up from file path
    fn find_clang_tidy_config(start_path: &Path) -> Option<PathBuf> {
        let mut current = if start_path.is_file() {
            start_path.parent()?.to_path_buf()
        } else {
            start_path.to_path_buf()
        };

        loop {
            let config_path = current.join(".clang-tidy");
            if config_path.exists() {
                return Some(config_path);
            }

            // Also check for _clang-tidy (alternative name)
            let alt_config = current.join("_clang-tidy");
            if alt_config.exists() {
                return Some(alt_config);
            }

            if !current.pop() {
                break;
            }
        }
        None
    }

    /// Find compile_commands.json for better analysis
    /// Searches in common build directories recursively (up to max_depth levels)
    fn find_compile_commands(start_path: &Path) -> Option<PathBuf> {
        let mut current = if start_path.is_file() {
            start_path.parent()?.to_path_buf()
        } else {
            start_path.to_path_buf()
        };

        loop {
            // 1. Check in current directory directly
            let direct = current.join("compile_commands.json");
            if direct.exists() {
                return Some(current.clone());
            }

            // 2. Check common fixed build directory names (1 level)
            for build_dir in &[
                "build",
                "Build",
                "out",
                "output",
                "cmake-build-debug",
                "cmake-build-release",
                "cmake-build-relwithdebinfo",
                "cmake-build-minsizerel",
                ".build",
                "_build",
            ] {
                let compile_db = current.join(build_dir).join("compile_commands.json");
                if compile_db.exists() {
                    return Some(current.join(build_dir));
                }
            }

            // 3. Recursively search in directories matching build patterns (up to 6 levels deep)
            if let Some(found) = Self::find_compile_commands_recursive(&current, 0, 6) {
                return Some(found);
            }

            if !current.pop() {
                break;
            }
        }
        None
    }

    /// Recursively search for compile_commands.json in build-like directories
    fn find_compile_commands_recursive(
        dir: &Path,
        depth: usize,
        max_depth: usize,
    ) -> Option<PathBuf> {
        if depth >= max_depth {
            return None;
        }

        let entries = std::fs::read_dir(dir).ok()?;

        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }

            let name = path.file_name().and_then(|n| n.to_str())?;
            let name_lower = name.to_lowercase();

            // Only recurse into build-related directories
            let is_build_dir = name_lower.starts_with("cmake")
                || name_lower.starts_with("build")
                || name_lower.starts_with("out")
                || name_lower.ends_with("-build")
                || name_lower.ends_with("_build")
                // Also allow platform/arch subdirectories inside build dirs
                || (depth > 0
                    && (name_lower.contains("android")
                        || name_lower.contains("ios")
                        || name_lower.contains("linux")
                        || name_lower.contains("windows")
                        || name_lower.contains("macos")
                        || name_lower.contains("darwin")
                        || name_lower.contains("arm")
                        || name_lower.contains("x86")
                        || name_lower.contains("x64")
                        || name_lower.contains("static")
                        || name_lower.contains("shared")
                        || name_lower.contains("debug")
                        || name_lower.contains("release")));

            if is_build_dir {
                // Check if compile_commands.json exists here
                let compile_db = path.join("compile_commands.json");
                if compile_db.exists() {
                    return Some(path);
                }

                // Recurse deeper
                if let Some(found) =
                    Self::find_compile_commands_recursive(&path, depth + 1, max_depth)
                {
                    return Some(found);
                }
            }
        }
        None
    }

    /// Check if clang-tidy is available
    fn has_clang_tidy() -> bool {
        Command::new("clang-tidy")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Check if cpplint is available
    fn has_cpplint() -> bool {
        Command::new("cpplint")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Run clang-tidy on a file (check only, no fix)
    fn run_clang_tidy(&self, path: &Path) -> Result<Vec<LintIssue>> {
        // Skip clang-tidy if LINTHIS_SKIP_CLANG_TIDY env var is set
        if std::env::var("LINTHIS_SKIP_CLANG_TIDY").is_ok() {
            return Ok(vec![]);
        }

        // Canonicalize file path to absolute so clang-tidy resolves it consistently.
        // Run clang-tidy from the git project root to ensure consistent header resolution
        // and include paths regardless of which directory linthis was invoked from.
        let abs_path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir().unwrap_or_default().join(path)
        };
        let project_root = crate::utils::get_project_root();

        let mut cmd = Command::new("clang-tidy");
        cmd.current_dir(&project_root);
        cmd.arg(&abs_path);

        // Add config file if specified or found
        if let Some(ref config) = self.config_path {
            cmd.arg(format!("--config-file={}", config.display()));
        } else if let Some(config) = Self::find_clang_tidy_config(&abs_path) {
            cmd.arg(format!("--config-file={}", config.display()));
        }

        // Add compile_commands.json path: user-specified > auto-detected
        if let Some(ref build_path) = self.compile_commands_dir {
            cmd.arg(format!("-p={}", build_path.display()));
        } else if let Some(build_path) = Self::find_compile_commands(&abs_path) {
            cmd.arg(format!("-p={}", build_path.display()));
        } else {
            // Use -- to separate clang-tidy args from compiler args
            cmd.arg("--");
        }

        let output = cmd.output().map_err(|e| {
            crate::LintisError::checker("clang-tidy", path, format!("Failed to run: {}", e))
        })?;

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Select ignored checks based on file type
        let is_oc = Self::is_objective_c(path);
        let ignored_checks = if is_oc {
            &self.oc_ignored_checks
        } else {
            &self.cpp_ignored_checks
        };

        let issues = Self::parse_clang_tidy_output(&stdout, path, ignored_checks);

        Ok(issues)
    }

    /// Run cpplint on a file with language-specific config
    fn run_cpplint(&self, path: &Path) -> Result<Vec<LintIssue>> {
        let mut cmd = Command::new("cpplint");

        // Select config based on file type (Objective-C vs C++)
        let is_oc = Self::is_objective_c(path);
        let config = if is_oc {
            &self.cpplint_oc_config
        } else {
            &self.cpplint_cpp_config
        };

        // Add extensions for Objective-C files (cpplint doesn't recognize .m/.mm by default)
        if is_oc {
            cmd.arg("--extensions=m,mm,h");
        }

        // Apply linelength if configured
        if let Some(linelength) = config.linelength {
            cmd.arg(format!("--linelength={}", linelength));
        }

        // Apply filter if configured
        if let Some(ref filter) = config.filter {
            cmd.arg(format!("--filter={}", filter));
        }

        cmd.arg(path);

        let output = cmd.output().map_err(|e| {
            crate::LintisError::checker("cpplint", path, format!("Failed to run: {}", e))
        })?;

        // cpplint outputs to stderr
        let stderr = String::from_utf8_lossy(&output.stderr);
        let issues = Self::parse_cpplint_output(&stderr, path);

        Ok(issues)
    }

    /// Parse clang-tidy output
    /// Format: file:line:col: severity: message [check-name]
    fn parse_clang_tidy_output(
        output: &str,
        file_path: &Path,
        ignored_checks: &[String],
    ) -> Vec<LintIssue> {
        let mut issues = Vec::new();

        for line in output.lines() {
            if let Some(issue) = Self::parse_clang_tidy_line(line, file_path) {
                // Filter out ignored checks
                if let Some(ref code) = issue.code {
                    if ignored_checks.iter().any(|ignored| code == ignored) {
                        continue;
                    }
                }
                issues.push(issue);
            }
        }

        issues
    }

    fn parse_clang_tidy_line(line: &str, default_path: &Path) -> Option<LintIssue> {
        // clang-tidy format: file:line:col: warning/error: message [check-name]
        // Example: test.cpp:10:5: warning: use nullptr [modernize-use-nullptr]
        if !line.contains(": warning:") && !line.contains(": error:") {
            return None;
        }

        let parts: Vec<&str> = line.splitn(5, ':').collect();
        if parts.len() < 5 {
            return None;
        }

        let file_path_parsed = std::path::PathBuf::from(parts[0]);

        // Filter out issues from third_party and other excluded directories
        // Check both the parsed path and individual components
        let path_str = file_path_parsed.to_string_lossy();
        if path_str.contains("third_party")
            || path_str.contains("thirdparty")
            || path_str.contains("third-party")
            || path_str.contains("3rdparty")
            || path_str.contains("3rd_party")
            || path_str.contains("3rd-party")
            || path_str.contains("external")
            || path_str.contains("externals")
            || path_str.contains("vendor")
            || path_str.contains("node_modules")
        {
            return None;
        }

        let line_num = parts[1].trim().parse::<usize>().ok()?;
        let col = parts[2].trim().parse::<usize>().ok();

        let severity_str = parts[3].trim();
        let message_part = parts[4].trim();

        let severity = if severity_str.contains("error") {
            Severity::Error
        } else {
            Severity::Warning
        };

        // Extract message and check name
        let (message, code) = if let Some(bracket_start) = message_part.rfind('[') {
            let msg = message_part[..bracket_start].trim();
            let check = message_part[bracket_start..]
                .trim_matches(|c| c == '[' || c == ']')
                .to_string();
            (msg.to_string(), Some(check))
        } else {
            (message_part.to_string(), None)
        };

        // Filter out all clang-diagnostic-* errors: these are compiler diagnostics
        // (missing headers, type errors, etc.) not actual code style/quality issues
        if let Some(ref c) = code {
            if c.starts_with("clang-diagnostic-") {
                return None;
            }
        }

        let file_path = if file_path_parsed.exists() {
            file_path_parsed
        } else {
            default_path.to_path_buf()
        };

        let mut issue = LintIssue::new(file_path.clone(), line_num, message, severity)
            .with_source("clang-tidy".to_string());

        if let Some(c) = col {
            issue = issue.with_column(c);
        }
        if let Some(c) = code {
            issue = issue.with_code(c);
        }

        // Read the source code line with context
        if let Some(ctx) = crate::utils::read_file_line_with_context(&file_path, line_num, 1) {
            issue = issue
                .with_code_line(ctx.line)
                .with_context_before(ctx.before)
                .with_context_after(ctx.after);
        }

        Some(issue)
    }

    /// Parse cpplint output and extract issues.
    /// Format: file:line: message [category] [confidence]
    fn parse_cpplint_output(output: &str, file_path: &Path) -> Vec<LintIssue> {
        let mut issues = Vec::new();

        for line in output.lines() {
            if let Some(issue) = Self::parse_cpplint_line(line, file_path) {
                issues.push(issue);
            }
        }

        issues
    }

    fn parse_cpplint_line(line: &str, default_path: &Path) -> Option<LintIssue> {
        // cpplint format: file:line: message [category] [confidence]
        // Example: test.cpp:10: Missing space after comma [whitespace/comma] [3]
        if !line.contains(':')
            || line.starts_with("Done processing")
            || line.starts_with("Total errors")
        {
            return None;
        }

        // Filter out cpplint's own limitation warnings - these are not actionable code issues
        // "Multi-line string found. This lint script doesn't do well with such strings..."
        if line.contains("Multi-line string") && line.contains("bogus warnings") {
            return None;
        }

        let parts: Vec<&str> = line.splitn(3, ':').collect();
        if parts.len() < 3 {
            return None;
        }

        let file_path_parsed = std::path::PathBuf::from(parts[0]);
        let line_num = parts[1].trim().parse::<usize>().ok()?;
        let rest = parts[2].trim();

        // Parse message and extract category
        let (message, code) = if let Some(bracket_start) = rest.find('[') {
            let msg = rest[..bracket_start].trim();
            let category = rest[bracket_start..].trim_matches(|c| c == '[' || c == ']');
            // Extract just the first bracketed category
            let cat = category.split("] [").next().unwrap_or(category);
            (msg.to_string(), Some(cat.to_string()))
        } else {
            (rest.to_string(), None)
        };

        let severity = if message.to_lowercase().contains("error") {
            Severity::Error
        } else {
            Severity::Warning
        };

        let file_path = if file_path_parsed.exists() {
            file_path_parsed
        } else {
            default_path.to_path_buf()
        };

        // Read the source code line with context
        let ctx = crate::utils::read_file_line_with_context(&file_path, line_num, 1);

        // Filter out whitespace issues that appear to be inside multi-line string literals
        // Multi-line strings in C/C++/ObjC use line continuation with backslash
        if let (Some(ref cat), Some(ref context)) = (&code, &ctx) {
            if cat.starts_with("whitespace/") {
                // Check if previous line ends with \ (line continuation in string)
                let in_multiline_string = context.before.iter().any(|(_, line)| {
                    let trimmed = line.trim_end();
                    trimmed.ends_with('\\') || trimmed.ends_with("\\\"")
                });

                // Also check if this line looks like string content
                // Common patterns for multi-line string endings in ObjC/C++:
                // - ends with \  (line continuation)
                // - contains );" (JS code ending inside string literal)
                // - contains "; (semicolon inside string, common in embedded JS/SQL)
                let line_trimmed = context.line.trim_end();
                let looks_like_string_content = line_trimmed.ends_with('\\')
                    || line_trimmed.contains(");\"")   // e.g., })();"
                    || line_trimmed.contains("();\"")  // e.g., foo();"
                    || line_trimmed.contains("; \\")   // e.g., return x; \
                    ;

                if in_multiline_string || looks_like_string_content {
                    return None;
                }
            }
        }

        let mut issue = LintIssue::new(file_path.clone(), line_num, message, severity)
            .with_source("cpplint".to_string());

        if let Some(c) = code {
            issue = issue.with_code(c);
        }

        if let Some(context) = ctx {
            issue = issue
                .with_code_line(context.line)
                .with_context_before(context.before)
                .with_context_after(context.after);
        }

        Some(issue)
    }

    /// Count SLOC in a slice of lines: skip blank lines, line comments, and block comments.
    pub(crate) fn count_sloc(lines: &[&str]) -> u32 {
        let mut count = 0u32;
        let mut in_block_comment = false;

        for line in lines {
            let trimmed = line.trim();

            if in_block_comment {
                if trimmed.contains("*/") {
                    in_block_comment = false;
                }
                continue;
            }

            if trimmed.is_empty() || trimmed.starts_with("//") {
                continue;
            }

            if trimmed == "{" || trimmed == "}" {
                continue;
            }

            if trimmed.starts_with("/*") {
                if trimmed.contains("*/") {
                    // Single-line block comment: /* ... */
                    continue;
                }
                in_block_comment = true;
                continue;
            }

            count += 1;
        }
        count
    }

    /// Extract the ObjC method selector name from a signature line.
    ///
    /// Examples:
    ///   "- (void)viewDidLoad {"                 → "viewDidLoad"
    ///   "- (NSString *)stringForKey:(NSString *)key" → "stringForKey:"
    ///   "+ (instancetype)sharedInstance"         → "sharedInstance"
    ///   "- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)ip {" → "tableView:didSelectRowAtIndexPath:"
    pub(crate) fn extract_method_name(signature: &str) -> String {
        // Find closing ")" of return type, then parse what follows
        let after_return = match signature.find(')') {
            Some(i) => signature[i + 1..].trim(),
            None => return signature.to_string(),
        };

        // Walk the remaining text, collecting selector parts
        let mut selector = String::new();
        let mut word = String::new();
        let mut chars = after_return.chars().peekable();

        while let Some(c) = chars.next() {
            match c {
                '{' => break,
                '(' => {
                    // Skip argument type in parens, e.g. "(UITableView *)"
                    // The word before '(' was already a selector keyword collected at ':'
                    word.clear();
                    let mut depth = 1usize;
                    for inner in chars.by_ref() {
                        match inner {
                            '(' => depth += 1,
                            ')' => {
                                depth -= 1;
                                if depth == 0 {
                                    break;
                                }
                            }
                            _ => {}
                        }
                    }
                }
                ':' => {
                    // Current word is a selector component
                    let kw = word.trim().to_string();
                    if !kw.is_empty() {
                        selector.push_str(&kw);
                        selector.push(':');
                    }
                    word.clear();
                }
                c if c.is_ascii_whitespace() => {
                    // Space between tokens — if we already have a selector component,
                    // the current word is an argument variable name: discard it.
                    // If selector is empty and word is non-empty, it might be the method
                    // name itself (no-arg method). Keep word as-is until '{' or end.
                    if !selector.is_empty() {
                        word.clear();
                    }
                }
                c => word.push(c),
            }
        }

        // If no colon was found, the word is the whole method name
        if selector.is_empty() {
            word.trim().to_string()
        } else {
            selector
        }
    }

    /// Check ObjC file content for methods exceeding the SLOC threshold.
    /// Returns a LintIssue for each method whose SLOC exceeds `threshold`.
    pub(crate) fn check_objc_method_lengths(
        content: &str,
        path: &Path,
        threshold: u32,
    ) -> Vec<LintIssue> {
        let lines: Vec<&str> = content.lines().collect();
        let mut issues = Vec::new();

        // Collect (1-based line number, method name) for each method signature
        // ObjC method signature starts with "- (" or "+ ("
        let mut method_starts: Vec<(usize, String)> = Vec::new();
        for (idx, line) in lines.iter().enumerate() {
            let trimmed = line.trim();
            if (trimmed.starts_with("- (")
                || trimmed.starts_with("+ (")
                || trimmed.starts_with("-(")
                || trimmed.starts_with("+("))
                && !trimmed.ends_with(';')
            {
                let name = Self::extract_method_name(trimmed);
                method_starts.push((idx + 1, name)); // 1-based line number
            }
        }

        for (i, (start_line, name)) in method_starts.iter().enumerate() {
            // Skip the signature line itself; count only body lines
            let body_start_idx = *start_line; // 0-based index of line after signature
            let body_end_idx = if i + 1 < method_starts.len() {
                method_starts[i + 1].0 - 1 // exclusive end (0-based index)
            } else {
                lines.len()
            };

            let body = if body_start_idx < body_end_idx {
                &lines[body_start_idx..body_end_idx]
            } else {
                &lines[0..0]
            };
            let sloc = Self::count_sloc(body);

            if sloc > threshold {
                let message = format!(
                    "Method '{}' has {} lines of code (limit is {}) [readability/fn_size]",
                    name, sloc, threshold
                );
                let issue =
                    LintIssue::new(path.to_path_buf(), *start_line, message, Severity::Warning)
                        .with_code("readability/fn_size".to_string())
                        .with_source("objc-method-length".to_string());
                issues.push(issue);
            }
        }

        issues
    }

    /// Run native ObjC method length check on a file.
    fn run_objc_method_length(&self, path: &Path) -> Result<Vec<LintIssue>> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            crate::LintisError::checker(
                "objc-method-length",
                path,
                format!("Failed to read file: {}", e),
            )
        })?;
        Ok(Self::check_objc_method_lengths(
            &content,
            path,
            self.oc_fn_length,
        ))
    }
}

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

impl Checker for CppChecker {
    fn name(&self) -> &str {
        match (Self::has_clang_tidy(), Self::has_cpplint()) {
            (true, true) => "clang-tidy+cpplint",
            (true, false) => "clang-tidy",
            (false, true) => "cpplint",
            (false, false) => "cpp-checker",
        }
    }

    fn supported_languages(&self) -> &[Language] {
        &[Language::Cpp, Language::ObjectiveC]
    }

    fn check(&self, path: &Path) -> Result<Vec<LintIssue>> {
        let mut all_issues = Vec::new();

        // Run clang-tidy for code quality, static analysis, and modernization
        if Self::has_clang_tidy() {
            match self.run_clang_tidy(path) {
                Ok(issues) => all_issues.extend(issues),
                Err(e) => {
                    // Log error but continue with cpplint
                    log::warn!("clang-tidy failed: {}", e);
                }
            }
        }

        // Run cpplint for style guide compliance (whitespace, comments, naming, etc.)
        if Self::has_cpplint() {
            match self.run_cpplint(path) {
                Ok(issues) => all_issues.extend(issues),
                Err(e) => {
                    // Log error but return what we have
                    log::warn!("cpplint failed: {}", e);
                }
            }
        }

        // Run native ObjC method length check (no external tool needed)
        if Self::is_objective_c(path) {
            match self.run_objc_method_length(path) {
                Ok(method_issues) => all_issues.extend(method_issues),
                Err(e) => log::warn!("objc method length check failed: {}", e),
            }
        }

        // Deduplicate issues by (file_path, line, message) to avoid duplicates
        all_issues.sort_by(|a, b| {
            (&a.file_path, a.line, &a.message).cmp(&(&b.file_path, b.line, &b.message))
        });
        all_issues.dedup_by(|a, b| {
            a.file_path == b.file_path && a.line == b.line && a.message == b.message
        });

        Ok(all_issues)
    }

    fn is_available(&self) -> bool {
        Self::has_clang_tidy() || Self::has_cpplint()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    // ==================== merge_filters tests ====================

    #[test]
    fn test_merge_filters_both_present() {
        let result =
            CppChecker::merge_filters(Some("-build/c++11,-build/c++14"), "-whitespace/tab");
        // Result should contain all three filters
        assert!(result.contains("-build/c++11"));
        assert!(result.contains("-build/c++14"));
        assert!(result.contains("-whitespace/tab"));
    }

    #[test]
    fn test_merge_filters_base_none() {
        let result = CppChecker::merge_filters(None, "-build/c++11,-whitespace/tab");
        assert!(result.contains("-build/c++11"));
        assert!(result.contains("-whitespace/tab"));
    }

    #[test]
    fn test_merge_filters_removes_duplicates() {
        let result =
            CppChecker::merge_filters(Some("-build/c++11"), "-build/c++11,-whitespace/tab");
        // Should not have duplicate -build/c++11
        let count = result.matches("-build/c++11").count();
        assert_eq!(count, 1);
        assert!(result.contains("-whitespace/tab"));
    }

    #[test]
    fn test_merge_filters_trims_whitespace() {
        let result =
            CppChecker::merge_filters(Some(" -build/c++11 , -build/c++14 "), " -whitespace/tab ");
        assert!(result.contains("-build/c++11"));
        assert!(result.contains("-build/c++14"));
        assert!(result.contains("-whitespace/tab"));
    }

    #[test]
    fn test_merge_filters_empty_strings() {
        let result = CppChecker::merge_filters(Some(""), "");
        assert!(result.is_empty());
    }

    // ==================== parse_cpplint_cfg tests ====================

    fn create_temp_cfg(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file.flush().unwrap();
        file
    }

    #[test]
    fn test_parse_cpplint_cfg_linelength() {
        let file = create_temp_cfg("linelength=120\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        assert_eq!(config.linelength, Some(120));
        assert!(config.filter.is_none());
    }

    #[test]
    fn test_parse_cpplint_cfg_filter() {
        let file = create_temp_cfg("filter=-build/c++11,-whitespace/tab\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        assert!(config.linelength.is_none());
        assert_eq!(
            config.filter,
            Some("-build/c++11,-whitespace/tab".to_string())
        );
    }

    #[test]
    fn test_parse_cpplint_cfg_both() {
        let file = create_temp_cfg("linelength=100\nfilter=-build/header_guard\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        assert_eq!(config.linelength, Some(100));
        assert_eq!(config.filter, Some("-build/header_guard".to_string()));
    }

    #[test]
    fn test_parse_cpplint_cfg_multiple_filters() {
        let file = create_temp_cfg("filter=-build/c++11\nfilter=-whitespace/tab\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        // Multiple filter lines should be joined
        let filter = config.filter.unwrap();
        assert!(filter.contains("-build/c++11"));
        assert!(filter.contains("-whitespace/tab"));
    }

    #[test]
    fn test_parse_cpplint_cfg_with_comments() {
        let file = create_temp_cfg("# This is a comment\nlinelength=80\n# Another comment\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        assert_eq!(config.linelength, Some(80));
    }

    #[test]
    fn test_parse_cpplint_cfg_empty_lines() {
        let file = create_temp_cfg("\n\nlinelength=150\n\n");
        let config = CppChecker::parse_cpplint_cfg(file.path()).unwrap();
        assert_eq!(config.linelength, Some(150));
    }

    #[test]
    fn test_parse_cpplint_cfg_nonexistent_file() {
        let result = CppChecker::parse_cpplint_cfg(Path::new("/nonexistent/path/CPPLINT.cfg"));
        assert!(result.is_none());
    }

    // ==================== parse_clang_tidy_line tests ====================

    #[test]
    fn test_parse_clang_tidy_warning() {
        let line = "test.cpp:10:5: warning: use nullptr [modernize-use-nullptr]";
        let default_path = Path::new("default.cpp");
        let issue = CppChecker::parse_clang_tidy_line(line, default_path).unwrap();

        assert_eq!(issue.line, 10);
        assert_eq!(issue.column, Some(5));
        assert_eq!(issue.severity, Severity::Warning);
        assert!(issue.message.contains("use nullptr"));
        assert_eq!(issue.code, Some("modernize-use-nullptr".to_string()));
        assert_eq!(issue.source, Some("clang-tidy".to_string()));
    }

    #[test]
    fn test_parse_clang_tidy_error() {
        // Use a non-clang-diagnostic error (clang-diagnostic-* are filtered out)
        let line = "main.cpp:5:1: error: no matching function for call [misc-error]";
        let default_path = Path::new("default.cpp");
        let issue = CppChecker::parse_clang_tidy_line(line, default_path).unwrap();

        assert_eq!(issue.line, 5);
        assert_eq!(issue.column, Some(1));
        assert_eq!(issue.severity, Severity::Error);
        assert!(issue.message.contains("no matching function"));
        assert_eq!(issue.code, Some("misc-error".to_string()));
    }

    #[test]
    fn test_parse_clang_tidy_clang_diagnostic_filtered() {
        // clang-diagnostic-* errors are compiler diagnostics, should be filtered out
        let line = "main.cpp:5:1: error: unknown type name 'foo' [clang-diagnostic-error]";
        let default_path = Path::new("default.cpp");
        let result = CppChecker::parse_clang_tidy_line(line, default_path);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_clang_tidy_no_bracket() {
        let line = "test.cpp:20:3: warning: some warning without bracket";
        let default_path = Path::new("default.cpp");
        let issue = CppChecker::parse_clang_tidy_line(line, default_path).unwrap();

        assert_eq!(issue.line, 20);
        assert!(issue.code.is_none());
        assert!(issue.message.contains("some warning without bracket"));
    }

    #[test]
    fn test_parse_clang_tidy_irrelevant_line() {
        let line = "In file included from test.cpp:1:";
        let default_path = Path::new("default.cpp");
        let result = CppChecker::parse_clang_tidy_line(line, default_path);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_clang_tidy_note_line() {
        let line = "test.cpp:10:5: note: previous declaration is here";
        let default_path = Path::new("default.cpp");
        let result = CppChecker::parse_clang_tidy_line(line, default_path);
        assert!(result.is_none()); // notes are not warnings or errors
    }

    // ==================== parse_cpplint_line tests ====================

    #[test]
    fn test_parse_cpplint_standard_warning() {
        let line = "test.cpp:10: Missing space after comma [whitespace/comma] [3]";
        let default_path = Path::new("default.cpp");
        let issue = CppChecker::parse_cpplint_line(line, default_path).unwrap();

        assert_eq!(issue.line, 10);
        assert_eq!(issue.severity, Severity::Warning);
        assert!(issue.message.contains("Missing space after comma"));
        assert_eq!(issue.code, Some("whitespace/comma".to_string()));
        assert_eq!(issue.source, Some("cpplint".to_string()));
    }

    #[test]
    fn test_parse_cpplint_header_guard() {
        let line = "test.h:0: No #ifndef header guard found, suggested CPP variable is: TEST_H_ [build/header_guard] [5]";
        let default_path = Path::new("test.h");
        let issue = CppChecker::parse_cpplint_line(line, default_path).unwrap();

        assert_eq!(issue.line, 0);
        assert!(issue.message.contains("header guard"));
        assert_eq!(issue.code, Some("build/header_guard".to_string()));
    }

    #[test]
    fn test_parse_cpplint_endif_comment() {
        let line =
            r##"test.h:50: #endif line should be "#endif  // TEST_H_" [build/header_guard] [5]"##;
        let default_path = Path::new("test.h");
        let issue = CppChecker::parse_cpplint_line(line, default_path).unwrap();

        assert_eq!(issue.line, 50);
        assert!(issue.message.contains("#endif"));
        assert_eq!(issue.code, Some("build/header_guard".to_string()));
    }

    #[test]
    fn test_parse_cpplint_line_length() {
        let line =
            "main.cpp:25: Lines should be <= 120 characters long [whitespace/line_length] [2]";
        let default_path = Path::new("main.cpp");
        let issue = CppChecker::parse_cpplint_line(line, default_path).unwrap();

        assert_eq!(issue.line, 25);
        assert!(issue.message.contains("120 characters"));
        assert_eq!(issue.code, Some("whitespace/line_length".to_string()));
    }

    #[test]
    fn test_parse_cpplint_done_processing() {
        let line = "Done processing test.cpp";
        let default_path = Path::new("test.cpp");
        let result = CppChecker::parse_cpplint_line(line, default_path);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_cpplint_total_errors() {
        let line = "Total errors found: 5";
        let default_path = Path::new("test.cpp");
        let result = CppChecker::parse_cpplint_line(line, default_path);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_cpplint_comment_spacing() {
        let line =
            "test.cpp:15: Should have a space between // and comment [whitespace/comments] [4]";
        let default_path = Path::new("test.cpp");
        let issue = CppChecker::parse_cpplint_line(line, default_path).unwrap();

        assert_eq!(issue.line, 15);
        assert!(issue.message.contains("space between //"));
        assert_eq!(issue.code, Some("whitespace/comments".to_string()));
    }

    #[test]
    fn test_parse_cpplint_multiline_string_filtered() {
        // cpplint's own limitation warning should be filtered out - it's not an actionable code issue
        let line = r#"test.m:710: Multi-line string ("...") found.  This lint script doesn't do well with such strings, and may give bogus warnings.  Use C++11 raw strings or concatenation instead.  [readability/multiline_string] [5]"#;
        let default_path = Path::new("test.m");
        let result = CppChecker::parse_cpplint_line(line, default_path);
        assert!(result.is_none());
    }

    // ==================== CpplintConfig tests ====================

    #[test]
    fn test_cpplint_config_default() {
        let config = CpplintConfig::default();
        assert!(config.linelength.is_none());
        assert!(config.filter.is_none());
    }

    // ==================== CppChecker builder tests ====================

    #[test]
    fn test_cpp_checker_with_config() {
        let checker = CppChecker::new().with_config(PathBuf::from("/custom/.clang-tidy"));
        assert_eq!(
            checker.config_path,
            Some(PathBuf::from("/custom/.clang-tidy"))
        );
    }

    #[test]
    fn test_cpp_checker_with_compile_commands_dir() {
        let checker = CppChecker::new().with_compile_commands_dir(PathBuf::from("/build"));
        assert_eq!(checker.compile_commands_dir, Some(PathBuf::from("/build")));
    }

    #[test]
    fn test_cpp_checker_with_cpplint_cpp_config() {
        let config = CpplintConfig {
            linelength: Some(80),
            filter: Some("-build/c++11".to_string()),
        };
        let checker = CppChecker::new().with_cpplint_cpp_config(config.clone());
        assert_eq!(checker.cpplint_cpp_config.linelength, Some(80));
    }

    #[test]
    fn test_cpp_checker_with_cpplint_oc_config() {
        let config = CpplintConfig {
            linelength: Some(200),
            filter: Some("-whitespace/parens".to_string()),
        };
        let checker = CppChecker::new().with_cpplint_oc_config(config);
        assert_eq!(checker.cpplint_oc_config.linelength, Some(200));
    }

    #[test]
    fn test_cpp_checker_default_oc_fn_length() {
        // Without any config file, oc_fn_length should default to 80
        let checker = CppChecker::new();
        assert_eq!(checker.oc_fn_length, 80);
    }

    // ==================== count_sloc tests ====================

    #[test]
    fn test_count_sloc_plain_code() {
        let lines = vec!["int x = 1;", "int y = 2;", "return x + y;"];
        assert_eq!(CppChecker::count_sloc(&lines), 3);
    }

    #[test]
    fn test_count_sloc_skips_blank_lines() {
        let lines = vec!["int x = 1;", "", "   ", "return x;"];
        assert_eq!(CppChecker::count_sloc(&lines), 2);
    }

    #[test]
    fn test_count_sloc_skips_line_comments() {
        let lines = vec!["// comment", "int x = 1;", "// another"];
        assert_eq!(CppChecker::count_sloc(&lines), 1);
    }

    #[test]
    fn test_count_sloc_skips_single_line_block_comment() {
        let lines = vec!["/* inline comment */", "int x = 1;"];
        assert_eq!(CppChecker::count_sloc(&lines), 1);
    }

    #[test]
    fn test_count_sloc_skips_multiline_block_comment() {
        let lines = vec!["/*", " * block comment", " */", "int x = 1;"];
        assert_eq!(CppChecker::count_sloc(&lines), 1);
    }

    #[test]
    fn test_count_sloc_trailing_comment_counts_as_code() {
        let lines = vec!["int x = 1; // set x"];
        assert_eq!(CppChecker::count_sloc(&lines), 1);
    }

    // ==================== extract_method_name tests ====================

    #[test]
    fn test_extract_method_name_simple() {
        assert_eq!(
            CppChecker::extract_method_name("- (void)viewDidLoad {"),
            "viewDidLoad"
        );
    }

    #[test]
    fn test_extract_method_name_with_single_arg() {
        assert_eq!(
            CppChecker::extract_method_name("- (NSString *)stringForKey:(NSString *)key"),
            "stringForKey:"
        );
    }

    #[test]
    fn test_extract_method_name_class_method() {
        assert_eq!(
            CppChecker::extract_method_name("+ (instancetype)sharedInstance"),
            "sharedInstance"
        );
    }

    #[test]
    fn test_extract_method_name_multi_arg() {
        assert_eq!(
            CppChecker::extract_method_name(
                "- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)ip {"
            ),
            "tableView:didSelectRowAtIndexPath:"
        );
    }

    // ==================== check_objc_method_lengths tests ====================

    fn make_objc_content_with_sloc(method_name: &str, sloc: usize) -> String {
        let mut lines = vec![format!("- (void){} {{", method_name)];
        for i in 0..sloc {
            lines.push(format!("    int var{} = {};", i, i));
        }
        lines.push("}".to_string());
        lines.join("\n")
    }

    #[test]
    fn test_check_objc_method_lengths_under_threshold_no_issue() {
        let content = make_objc_content_with_sloc("shortMethod", 5);
        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.m"), 80);
        assert!(
            issues.is_empty(),
            "Expected no issues for 5 SLOC, got: {:?}",
            issues
        );
    }

    #[test]
    fn test_check_objc_method_lengths_over_threshold_reports_issue() {
        let content = make_objc_content_with_sloc("longMethod", 85);
        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.m"), 80);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].line, 1);
        assert!(
            issues[0].message.contains("longMethod"),
            "message: {}",
            issues[0].message
        );
        assert!(
            issues[0].message.contains("readability/fn_size"),
            "message: {}",
            issues[0].message
        );
        assert!(
            issues[0].message.contains("85 lines of code"),
            "Expected '85 lines of code' in message: {}",
            issues[0].message
        );
        assert_eq!(issues[0].code.as_deref(), Some("readability/fn_size"));
        assert_eq!(issues[0].source.as_deref(), Some("objc-method-length"));
    }

    #[test]
    fn test_check_objc_method_lengths_exactly_at_threshold_no_issue() {
        // 80 SLOC at threshold 80: sloc > threshold is false, no issue
        let content = make_objc_content_with_sloc("boundaryMethod", 80);
        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.m"), 80);
        assert!(
            issues.is_empty(),
            "Expected no issue at exactly threshold, got: {:?}",
            issues
        );
    }

    #[test]
    fn test_check_objc_method_lengths_blank_and_comments_not_counted() {
        // 79 SLOC + blank/comment lines → SLOC = 79, no issue
        let mut lines = vec!["- (void)almostLongMethod {".to_string()];
        for i in 0..79 {
            lines.push(format!("    int var{} = {};", i, i));
            if i % 4 == 0 {
                lines.push(String::new());
                lines.push("    // a comment".to_string());
            }
        }
        lines.push("}".to_string());
        let content = lines.join("\n");

        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.mm"), 80);
        assert!(
            issues.is_empty(),
            "Expected no issues (79 SLOC), got: {:?}",
            issues
        );
    }

    #[test]
    fn test_check_objc_method_lengths_multiple_methods_each_checked() {
        // First method: 5 SLOC (ok). Second method: 85 SLOC (over).
        let mut lines = vec!["- (void)shortMethod {".to_string()];
        for i in 0..5 {
            lines.push(format!("    int a{} = {};", i, i));
        }
        lines.push("}".to_string());

        let long_method_line = lines.len() + 1; // 1-based
        lines.push("- (void)longMethod {".to_string());
        for i in 0..85 {
            lines.push(format!("    int b{} = {};", i, i));
        }
        lines.push("}".to_string());

        let content = lines.join("\n");
        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.m"), 80);
        assert_eq!(issues.len(), 1, "Expected 1 issue, got: {:?}", issues);
        assert!(
            issues[0].message.contains("longMethod"),
            "message: {}",
            issues[0].message
        );
        assert_eq!(
            issues[0].line, long_method_line,
            "Expected issue at line {}",
            long_method_line
        );
    }

    #[test]
    fn test_check_objc_method_lengths_custom_threshold() {
        let content = make_objc_content_with_sloc("mediumMethod", 50);
        let issues =
            CppChecker::check_objc_method_lengths(&content, std::path::Path::new("test.mm"), 30);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("mediumMethod"));
        assert_eq!(issues[0].code.as_deref(), Some("readability/fn_size"));
        assert_eq!(issues[0].source.as_deref(), Some("objc-method-length"));
    }
}