rust-doctor 0.1.9

A unified code health tool for Rust — scan, score, and fix your codebase
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
use crate::diagnostics::{Category, Diagnostic, Severity};
use crate::scanner::AnalysisPass;
use cargo_metadata::Message;
use cargo_metadata::diagnostic::DiagnosticLevel;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

// Note: clippy uses a streaming parser (Message::parse_stream) so it cannot use
// the process::run_with_timeout helper which reads all stdout into a String.
// The watchdog pattern is kept inline here for that reason.

/// Timeout for clippy subprocess in seconds.
const CLIPPY_TIMEOUT_SECS: u64 = 120;

// ---------------------------------------------------------------------------
// Lint registry — data-driven mapping of clippy lints to categories/severities
// ---------------------------------------------------------------------------

/// A single entry in the lint-to-category mapping table.
struct LintEntry {
    /// Lint name without the `clippy::` prefix.
    name: &'static str,
    category: Category,
    /// Severity override — takes precedence over clippy's default.
    severity: Severity,
    /// Whether this lint belongs to clippy's `restriction` group (allow-by-default).
    /// Restriction lints are downgraded to Info in test code because they are opt-in
    /// style checks, not correctness issues.
    is_restriction: bool,
}

/// Registry of 55+ impactful clippy lints with explicit category and severity.
/// Lints NOT in this table inherit clippy's default severity and map to `Style`.
static LINT_REGISTRY: &[LintEntry] = &[
    // ── Error Handling (restriction group — allow-by-default in clippy) ─
    LintEntry {
        name: "unwrap_used",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "expect_used",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "panic",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "indexing_slicing",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "unwrap_in_result",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "panic_in_result_fn",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "exit",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "map_unwrap_or",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "option_if_let_else",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "question_mark",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "manual_ok_or",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "result_unit_err",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "result_large_err",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "let_underscore_must_use",
        category: Category::ErrorHandling,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Performance ─────────────────────────────────────────────────────
    LintEntry {
        name: "box_collection",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "clone_on_copy",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "redundant_clone",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "needless_collect",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "large_enum_variant",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "inefficient_to_string",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "unnecessary_to_owned",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "large_stack_arrays",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "large_futures",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "single_char_pattern",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cmp_owned",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cloned_instead_of_copied",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "suboptimal_flops",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "or_fun_call",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "trivially_copy_pass_by_ref",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "useless_vec",
        category: Category::Performance,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Security ────────────────────────────────────────────────────────
    LintEntry {
        name: "undocumented_unsafe_blocks",
        category: Category::Security,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "multiple_unsafe_ops_per_block",
        category: Category::Security,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "transmute_ptr_to_ref",
        category: Category::Security,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "cast_ptr_alignment",
        category: Category::Security,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "fn_to_numeric_cast",
        category: Category::Security,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "mem_forget",
        category: Category::Security,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "cast_possible_truncation",
        category: Category::Security,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Correctness ─────────────────────────────────────────────────────
    LintEntry {
        name: "almost_swapped",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "approx_constant",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "bad_bit_mask",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "absurd_extreme_comparisons",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "invalid_regex",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "wrong_self_convention",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cast_sign_loss",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cast_possible_wrap",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cast_lossless",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "float_cmp",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "eq_op",
        category: Category::Correctness,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "match_overlapping_arm",
        category: Category::Correctness,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Cargo ───────────────────────────────────────────────────────────
    LintEntry {
        name: "wildcard_dependencies",
        category: Category::Cargo,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "multiple_crate_versions",
        category: Category::Cargo,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cargo_common_metadata",
        category: Category::Cargo,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "negative_feature_names",
        category: Category::Cargo,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "redundant_feature_names",
        category: Category::Cargo,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Async ───────────────────────────────────────────────────────────
    LintEntry {
        name: "await_holding_lock",
        category: Category::Async,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "await_holding_refcell_ref",
        category: Category::Async,
        severity: Severity::Error,
        is_restriction: false,
    },
    LintEntry {
        name: "unused_async",
        category: Category::Async,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "redundant_async_block",
        category: Category::Async,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Architecture ────────────────────────────────────────────────────
    LintEntry {
        name: "struct_excessive_bools",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "fn_params_excessive_bools",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "too_many_lines",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "cognitive_complexity",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "type_complexity",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "too_many_arguments",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "module_name_repetitions",
        category: Category::Architecture,
        severity: Severity::Warning,
        is_restriction: false,
    },
    // ── Style (restriction-group lints) ─────────────────────────────────
    LintEntry {
        name: "dbg_macro",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "todo",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "unimplemented",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "unreachable",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
    // ── Style (non-restriction) ─────────────────────────────────────────
    LintEntry {
        name: "wildcard_imports",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "missing_errors_doc",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "missing_panics_doc",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: false,
    },
    LintEntry {
        name: "print_stdout",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
    LintEntry {
        name: "print_stderr",
        category: Category::Style,
        severity: Severity::Warning,
        is_restriction: true,
    },
];

/// Restriction-group lints that must be explicitly enabled via `-W` flags
/// since they are not covered by `clippy::all`, `pedantic`, `nursery`, or `cargo`.
const RESTRICTION_LINTS: &[&str] = &[
    "clippy::unwrap_used",
    "clippy::expect_used",
    "clippy::panic",
    "clippy::indexing_slicing",
    "clippy::unwrap_in_result",
    "clippy::panic_in_result_fn",
    "clippy::exit",
    "clippy::undocumented_unsafe_blocks",
    "clippy::multiple_unsafe_ops_per_block",
    "clippy::mem_forget",
    "clippy::cognitive_complexity",
    "clippy::dbg_macro",
    "clippy::print_stdout",
    "clippy::print_stderr",
    "clippy::unimplemented",
    "clippy::unreachable",
];

/// Look up a lint in the registry. Returns `(category, severity, is_restriction)` if found.
fn lookup_lint(lint: &str) -> Option<(Category, Severity, bool)> {
    let name = lint.strip_prefix("clippy::").unwrap_or(lint);
    LINT_REGISTRY
        .iter()
        .find(|e| e.name == name)
        .map(|e| (e.category.clone(), e.severity, e.is_restriction))
}

/// Map a clippy lint name to a rust-doctor category. Falls back to `Style`.
fn map_lint_category(lint: &str) -> Category {
    match lint {
        "compiler-error" | "compiler-ice" => Category::Correctness,
        _ => lookup_lint(lint).map_or(Category::Style, |(cat, _, _)| cat),
    }
}

/// Apply severity override from the registry if the lint is known.
/// Otherwise, keep clippy's original severity.
fn resolve_severity(lint: &str, clippy_severity: Severity) -> Severity {
    match lint {
        "compiler-error" | "compiler-ice" => Severity::Error,
        _ => lookup_lint(lint).map_or(clippy_severity, |(_, sev, _)| sev),
    }
}

/// Returns `true` if the lint is in clippy's `restriction` group (allow-by-default).
fn is_restriction_lint(lint: &str) -> bool {
    lookup_lint(lint).is_some_and(|(_, _, restriction)| restriction)
}

/// Returns `true` if the file path looks like test code.
/// Matches: `tests/`, `test_`, `_test.rs`, and paths containing `/tests/`.
fn is_test_file(path: &Path) -> bool {
    let s = path.to_string_lossy();
    s.contains("/tests/") || s.starts_with("tests/")
}

/// Returns `true` if `line` (1-based) falls within a `#[cfg(test)]` module.
/// Uses a simple heuristic: finds the first `#[cfg(test)]` line in the file
/// and considers everything at or below it as test code.
fn is_line_in_test_module(content: &str, line: u32) -> bool {
    for (i, text) in content.lines().enumerate() {
        let trimmed = text.trim();
        if trimmed == "#[cfg(test)]" || trimmed.starts_with("#[cfg(test)]") {
            // Everything from this line onward is test code
            return line >= (i + 1) as u32;
        }
    }
    false
}

/// Return the list of all known lint names (for config validation).
pub fn known_lint_names() -> Vec<&'static str> {
    LINT_REGISTRY.iter().map(|e| e.name).collect()
}

// ---------------------------------------------------------------------------
// Clippy pass implementation
// ---------------------------------------------------------------------------

/// Clippy analysis pass — runs `cargo clippy --message-format=json` and
/// converts the output to rust-doctor diagnostics.
pub struct ClippyPass;

impl AnalysisPass for ClippyPass {
    fn name(&self) -> &'static str {
        "clippy"
    }

    fn run(&self, project_root: &Path) -> Result<Vec<Diagnostic>, crate::error::PassError> {
        if !is_clippy_available() {
            return Err(crate::error::PassError::Skipped {
                pass: "clippy".to_string(),
                reason: "clippy is not installed — lint analysis disabled. \
                         Install with: rustup component add clippy"
                    .to_string(),
            });
        }
        run_clippy(project_root).map_err(|message| crate::error::PassError::Failed {
            pass: "clippy".to_string(),
            message,
        })
    }
}

/// Check if `cargo clippy` is available. Result is cached for the process lifetime.
fn is_clippy_available() -> bool {
    static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *AVAILABLE.get_or_init(|| {
        Command::new("cargo")
            .args(["clippy", "--version"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    })
}

/// Build the full list of `-W` flags for clippy, including group-level
/// flags and individual restriction-group lints.
fn build_clippy_warn_flags() -> Vec<String> {
    let mut flags = Vec::new();

    // Group-level flags (override #[allow] directives)
    for group in [
        "clippy::all",
        "clippy::pedantic",
        "clippy::nursery",
        "clippy::cargo",
    ] {
        flags.push("-W".to_string());
        flags.push(group.to_string());
    }

    // Individual restriction-group lints
    for lint in RESTRICTION_LINTS {
        flags.push("-W".to_string());
        flags.push((*lint).to_string());
    }

    flags
}

/// Clippy config content that allows restriction lints in test code.
const CLIPPY_TEST_ALLOW_CONFIG: &str = "\
allow-unwrap-in-tests = true\n\
allow-expect-in-tests = true\n\
allow-indexing-slicing-in-tests = true\n\
allow-panic-in-tests = true\n\
allow-print-in-tests = true\n\
allow-dbg-in-tests = true\n\
allow-useless-vec-in-tests = true\n";

/// A guard that creates a temporary `clippy.toml` on construction
/// and removes it on drop, unless the project already had one.
struct ClippyConfigGuard {
    path: Option<PathBuf>,
}

impl ClippyConfigGuard {
    /// Write a temporary `clippy.toml` into `dir`. Returns `None` if one already exists.
    fn new(dir: &Path) -> Self {
        if dir.join("clippy.toml").exists() || dir.join(".clippy.toml").exists() {
            return Self { path: None };
        }
        let config_path = dir.join("clippy.toml");
        if std::fs::write(&config_path, CLIPPY_TEST_ALLOW_CONFIG).is_ok() {
            Self {
                path: Some(config_path),
            }
        } else {
            Self { path: None }
        }
    }
}

impl Drop for ClippyConfigGuard {
    fn drop(&mut self) {
        if let Some(ref path) = self.path {
            let _ = std::fs::remove_file(path);
        }
    }
}

/// Process a single clippy compiler message into a `Diagnostic`, if applicable.
fn process_compiler_message(
    diag: &mut cargo_metadata::diagnostic::Diagnostic,
) -> Option<Diagnostic> {
    // Filter: only process error and warning level messages
    let clippy_severity = match &diag.level {
        DiagnosticLevel::Error | DiagnosticLevel::Ice => Severity::Error,
        DiagnosticLevel::Warning => Severity::Warning,
        _ => return None,
    };
    let is_ice = diag.level == DiagnosticLevel::Ice;

    // Extract code (lint name) — take() avoids cloning
    let rule = match diag.code.take() {
        Some(code) => code.code,
        None if clippy_severity == Severity::Error => if is_ice {
            "compiler-ice"
        } else {
            "compiler-error"
        }
        .to_string(),
        None => return None,
    };

    // Extract primary span
    let primary_span = diag.spans.iter().find(|s| s.is_primary);
    let (file_path, line, column) = primary_span.map_or_else(
        || (PathBuf::from("<unknown>"), None, None),
        |span| {
            (
                PathBuf::from(&span.file_name),
                Some(span.line_start as u32),
                Some(span.column_start as u32),
            )
        },
    );

    // Apply registry: category and severity override
    let category = map_lint_category(&rule);
    let severity = resolve_severity(&rule, clippy_severity);

    // Extract help: prefer children help message, fall back to rendered
    // Move fields via std::mem::take to avoid cloning
    let rendered = diag.rendered.take();
    let help = std::mem::take(&mut diag.children)
        .into_iter()
        .find(|c| c.level == DiagnosticLevel::Help)
        .map(|c| c.message)
        .or(rendered);

    Some(Diagnostic {
        file_path,
        rule,
        category,
        severity,
        message: std::mem::take(&mut diag.message),
        help,
        line,
        column,
        fix: None,
    })
}

/// Build a fallback compiler-error diagnostic from stderr when the build
/// failed but no JSON error diagnostics were produced.
fn build_stderr_fallback(stderr: std::process::ChildStderr) -> Option<Diagnostic> {
    use std::io::Read;

    const MAX_STDERR_BYTES: u64 = 4 * 1024; // 4 KB
    let mut stderr_output = String::new();
    let _ = stderr
        .take(MAX_STDERR_BYTES)
        .read_to_string(&mut stderr_output);

    if stderr_output.is_empty() {
        return None;
    }

    let first_error = stderr_output
        .lines()
        .find(|l| l.starts_with("error"))
        .unwrap_or("project failed to compile");

    // Truncate to 200 chars to avoid leaking verbose internal details
    let truncated: String = if first_error.chars().count() > 200 {
        let mut s: String = first_error.chars().take(200).collect();
        s.push('');
        s
    } else {
        first_error.to_string()
    };

    Some(Diagnostic {
        file_path: PathBuf::from("Cargo.toml"),
        rule: "compiler-error".to_string(),
        category: Category::Correctness,
        severity: Severity::Error,
        message: truncated,
        help: Some("Run `cargo build` to see the full error output".to_string()),
        line: None,
        column: None,
        fix: None,
    })
}

/// Remove restriction-group lints originating from test code and
/// print_stdout/print_stderr lints from binary crates.
fn filter_test_and_binary_lints(diagnostics: &mut Vec<Diagnostic>, project_root: &Path) {
    // Drop restriction-group lints from test code
    diagnostics.retain(|d| {
        if !is_restriction_lint(&d.rule) {
            return true;
        }
        if is_test_file(&d.file_path) {
            return false;
        }
        // For source files, check if line is in a #[cfg(test)] region
        if let Some(line) = d.line {
            let abs_path = if d.file_path.is_absolute() {
                d.file_path.clone()
            } else {
                project_root.join(&d.file_path)
            };
            if let Ok(content) = std::fs::read_to_string(&abs_path) {
                if is_line_in_test_module(&content, line) {
                    return false;
                }
            }
        }
        true
    });

    // Drop print_stdout/print_stderr for binary crates
    if project_root.join("src/main.rs").exists() {
        diagnostics.retain(|d| {
            !matches!(
                d.rule.as_str(),
                "clippy::print_stdout" | "clippy::print_stderr"
            )
        });
    }
}

/// Run cargo clippy and parse JSON output into diagnostics.
fn run_clippy(project_root: &Path) -> Result<Vec<Diagnostic>, String> {
    let manifest_path = project_root.join("Cargo.toml");

    let warn_flags = build_clippy_warn_flags();

    // Write a temporary clippy.toml that allows restriction lints in test code.
    // The guard removes it when dropped (even on early return via `?`).
    let _clippy_config_guard = ClippyConfigGuard::new(project_root);

    let mut cmd = Command::new("cargo");
    cmd.args([
        "clippy",
        "--message-format=json",
        "--all-targets",
        "--all-features",
        "--manifest-path",
    ])
    .arg(&manifest_path)
    .arg("--");

    for flag in &warn_flags {
        cmd.arg(flag);
    }

    let mut child = cmd
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("failed to spawn cargo clippy: {e}"))?;

    let stdout = child
        .stdout
        .take()
        .ok_or("failed to capture clippy stdout")?;
    let stderr = child.stderr.take();

    // Cancellable timeout watchdog
    let (cancel_tx, cancel_rx) = mpsc::channel::<()>();
    let child = Arc::new(Mutex::new(child));
    let child_watcher = Arc::clone(&child);
    let timed_out = Arc::new(AtomicBool::new(false));
    let timed_out_watcher = Arc::clone(&timed_out);

    let watcher = thread::spawn(move || {
        if cancel_rx
            .recv_timeout(Duration::from_secs(CLIPPY_TIMEOUT_SECS))
            .is_err()
            && let Ok(mut c) = child_watcher.lock()
            && matches!(c.try_wait(), Ok(None))
        {
            let _ = c.kill();
            let _ = c.wait(); // Reap the child to avoid zombie process
            timed_out_watcher.store(true, Ordering::Relaxed);
        }
    });

    // Parse JSON messages from clippy stdout
    let reader = BufReader::new(stdout);
    let mut diagnostics = Vec::new();
    let mut build_succeeded = true;

    for message in Message::parse_stream(reader) {
        let Ok(message) = message else {
            continue;
        };
        match message {
            Message::CompilerMessage(compiler_msg) => {
                let mut diag = compiler_msg.message;
                if let Some(diagnostic) = process_compiler_message(&mut diag) {
                    diagnostics.push(diagnostic);
                }
            }
            Message::BuildFinished(finished) => {
                build_succeeded = finished.success;
            }
            _ => {}
        }
    }

    // Cancel the watchdog thread
    let _ = cancel_tx.send(());
    let _ = watcher.join();

    // Reap the child process
    if let Ok(mut c) = child.lock() {
        let _ = c.wait();
    }

    // Check if we timed out
    if timed_out.load(Ordering::Relaxed) {
        eprintln!(
            "Warning: clippy timed out after {CLIPPY_TIMEOUT_SECS}s — reporting partial results"
        );
    }

    // If the build failed and we got no error diagnostics from JSON,
    // capture stderr as a compiler-error diagnostic
    if !build_succeeded && !diagnostics.iter().any(|d| d.severity == Severity::Error) {
        if let Some(stderr) = stderr {
            if let Some(fallback) = build_stderr_fallback(stderr) {
                diagnostics.push(fallback);
            }
        }
    }

    filter_test_and_binary_lints(&mut diagnostics, project_root);

    Ok(diagnostics)
}

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

    // --- Registry tests ---

    #[test]
    fn test_registry_has_50_plus_entries() {
        assert!(
            LINT_REGISTRY.len() >= 50,
            "Registry has {} entries, expected 50+",
            LINT_REGISTRY.len()
        );
    }

    #[test]
    fn test_registry_no_duplicate_names() {
        let names: Vec<&str> = LINT_REGISTRY.iter().map(|e| e.name).collect();
        let mut seen = std::collections::HashSet::new();
        for name in &names {
            assert!(seen.insert(name), "Duplicate lint name in registry: {name}");
        }
    }

    // --- Lookup tests ---

    #[test]
    fn test_lookup_known_lint() {
        let result = lookup_lint("clippy::unwrap_used");
        assert!(result.is_some());
        let (cat, sev, restriction) = result.unwrap();
        assert_eq!(cat, Category::ErrorHandling);
        assert_eq!(sev, Severity::Warning);
        assert!(restriction, "unwrap_used should be marked as restriction");
    }

    #[test]
    fn test_lookup_without_prefix() {
        let result = lookup_lint("unwrap_used");
        assert!(result.is_some());
        assert_eq!(result.unwrap().0, Category::ErrorHandling);
    }

    #[test]
    fn test_lookup_unknown_lint() {
        assert!(lookup_lint("clippy::some_unknown_lint").is_none());
    }

    // --- Category mapping tests ---

    #[test]
    fn test_map_error_handling() {
        assert_eq!(
            map_lint_category("clippy::unwrap_used"),
            Category::ErrorHandling
        );
        assert_eq!(
            map_lint_category("clippy::expect_used"),
            Category::ErrorHandling
        );
        assert_eq!(map_lint_category("clippy::panic"), Category::ErrorHandling);
    }

    #[test]
    fn test_map_performance() {
        assert_eq!(
            map_lint_category("clippy::clone_on_copy"),
            Category::Performance
        );
        assert_eq!(
            map_lint_category("clippy::needless_collect"),
            Category::Performance
        );
    }

    #[test]
    fn test_map_security() {
        assert_eq!(
            map_lint_category("clippy::transmute_ptr_to_ref"),
            Category::Security
        );
        assert_eq!(
            map_lint_category("clippy::undocumented_unsafe_blocks"),
            Category::Security
        );
    }

    #[test]
    fn test_map_correctness() {
        assert_eq!(
            map_lint_category("clippy::float_cmp"),
            Category::Correctness
        );
        assert_eq!(
            map_lint_category("clippy::almost_swapped"),
            Category::Correctness
        );
        assert_eq!(map_lint_category("compiler-error"), Category::Correctness);
        assert_eq!(map_lint_category("compiler-ice"), Category::Correctness);
    }

    #[test]
    fn test_map_cargo() {
        assert_eq!(
            map_lint_category("clippy::wildcard_dependencies"),
            Category::Cargo
        );
    }

    #[test]
    fn test_map_async() {
        assert_eq!(
            map_lint_category("clippy::await_holding_lock"),
            Category::Async
        );
        assert_eq!(map_lint_category("clippy::unused_async"), Category::Async);
    }

    #[test]
    fn test_map_architecture() {
        assert_eq!(
            map_lint_category("clippy::cognitive_complexity"),
            Category::Architecture
        );
        assert_eq!(
            map_lint_category("clippy::too_many_arguments"),
            Category::Architecture
        );
    }

    #[test]
    fn test_map_style() {
        assert_eq!(map_lint_category("clippy::dbg_macro"), Category::Style);
        assert_eq!(map_lint_category("clippy::todo"), Category::Style);
    }

    #[test]
    fn test_map_unknown_falls_to_style() {
        assert_eq!(
            map_lint_category("clippy::some_unknown_lint"),
            Category::Style
        );
    }

    // --- Severity override tests ---

    #[test]
    fn test_severity_restriction_lints_are_warning() {
        // Restriction-group lints should be Warning, not Error (aligned with clippy)
        let sev = resolve_severity("clippy::unwrap_used", Severity::Warning);
        assert_eq!(sev, Severity::Warning);
        let sev = resolve_severity("clippy::expect_used", Severity::Warning);
        assert_eq!(sev, Severity::Warning);
        let sev = resolve_severity("clippy::panic", Severity::Warning);
        assert_eq!(sev, Severity::Warning);
    }

    #[test]
    fn test_severity_override_keeps_registered_warning() {
        // clone_on_copy is registered as Warning
        let sev = resolve_severity("clippy::clone_on_copy", Severity::Warning);
        assert_eq!(sev, Severity::Warning);
    }

    #[test]
    fn test_severity_unknown_lint_keeps_clippy_default() {
        let sev = resolve_severity("clippy::some_unknown_lint", Severity::Warning);
        assert_eq!(sev, Severity::Warning);
    }

    #[test]
    fn test_severity_compiler_error_always_error() {
        assert_eq!(
            resolve_severity("compiler-error", Severity::Warning),
            Severity::Error
        );
        assert_eq!(
            resolve_severity("compiler-ice", Severity::Warning),
            Severity::Error
        );
    }

    // --- Known lint names ---

    #[test]
    fn test_known_lint_names_count() {
        let names = known_lint_names();
        assert!(names.len() >= 50);
        assert!(names.contains(&"unwrap_used"));
        assert!(names.contains(&"await_holding_lock"));
    }

    // --- Restriction flags ---

    #[test]
    fn test_build_clippy_warn_flags_contains_groups() {
        let flags = build_clippy_warn_flags();
        assert!(flags.contains(&"clippy::all".to_string()));
        assert!(flags.contains(&"clippy::pedantic".to_string()));
        assert!(flags.contains(&"clippy::nursery".to_string()));
        assert!(flags.contains(&"clippy::cargo".to_string()));
    }

    #[test]
    fn test_build_clippy_warn_flags_contains_restriction_lints() {
        let flags = build_clippy_warn_flags();
        assert!(flags.contains(&"clippy::unwrap_used".to_string()));
        assert!(flags.contains(&"clippy::expect_used".to_string()));
        assert!(flags.contains(&"clippy::dbg_macro".to_string()));
    }

    // --- Restriction lint detection ---

    #[test]
    fn test_is_restriction_lint() {
        assert!(is_restriction_lint("clippy::unwrap_used"));
        assert!(is_restriction_lint("clippy::expect_used"));
        assert!(is_restriction_lint("clippy::panic"));
        assert!(is_restriction_lint("clippy::indexing_slicing"));
        assert!(is_restriction_lint("clippy::print_stdout"));
        assert!(is_restriction_lint("clippy::dbg_macro"));
        assert!(!is_restriction_lint("clippy::clone_on_copy"));
        assert!(!is_restriction_lint("clippy::almost_swapped"));
        assert!(!is_restriction_lint("clippy::some_unknown_lint"));
    }

    #[test]
    fn test_is_test_file() {
        assert!(is_test_file(Path::new("tests/integration.rs")));
        assert!(is_test_file(Path::new("/home/user/project/tests/foo.rs")));
        assert!(!is_test_file(Path::new("src/main.rs")));
        assert!(!is_test_file(Path::new("src/rules/mod.rs")));
    }

    // --- Integration ---

    #[test]
    fn test_clippy_is_available() {
        assert!(is_clippy_available());
    }

    #[test]
    fn test_run_clippy_on_self() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let result = run_clippy(manifest_dir);
        assert!(result.is_ok(), "clippy failed: {:?}", result.err());
        // Verify that diagnostics from registered lints get severity overrides
        let diags = result.unwrap();
        for d in &diags {
            if let Some((_, expected_sev, _)) = lookup_lint(&d.rule) {
                assert_eq!(
                    d.severity, expected_sev,
                    "Lint {} should have severity {:?} but got {:?}",
                    d.rule, expected_sev, d.severity
                );
            }
        }
        // Verify no restriction lints from test files survived filtering
        for d in &diags {
            if is_test_file(&d.file_path) {
                assert!(
                    !is_restriction_lint(&d.rule),
                    "Restriction lint {} should have been filtered from test file {:?}",
                    d.rule,
                    d.file_path
                );
            }
        }
    }
}