rust-doctor 0.1.18

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
use crate::diagnostics::Diagnostic;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

const DISABLE_NEXT_LINE: &str = "rust-doctor-disable-next-line";
const DISABLE_LINE: &str = "rust-doctor-disable-line";

/// A suppression directive found in source code.
#[derive(Debug)]
struct Suppression {
    /// The line this suppression applies to (1-based).
    target_line: u32,
    /// Rule name to suppress, or None for all rules.
    rule: Option<String>,
}

/// Apply inline suppression comments to filter diagnostics.
///
/// Reads source files referenced by diagnostics, finds `rust-doctor-disable-*`
/// comments, and removes matching diagnostics. Returns the filtered list and
/// the count of suppressed diagnostics.
pub fn apply_inline_suppressions(
    diagnostics: Vec<Diagnostic>,
    project_root: &Path,
) -> (Vec<Diagnostic>, usize) {
    if diagnostics.is_empty() {
        return (diagnostics, 0);
    }

    // Collect unique file paths that have diagnostics with line numbers
    let file_set: std::collections::HashSet<PathBuf> = diagnostics
        .iter()
        .filter(|d| d.line.is_some())
        .map(|d| d.file_path.clone())
        .collect();
    let files_to_check: Vec<PathBuf> = file_set.into_iter().collect();

    // Parse suppression comments from each file
    let mut suppressions: HashMap<PathBuf, Vec<Suppression>> = HashMap::new();
    for file_path in files_to_check {
        // Try absolute path first, then relative to project root
        let abs_buf;
        let abs_path: &Path = if file_path.is_absolute() {
            &file_path
        } else {
            abs_buf = project_root.join(&file_path);
            &abs_buf
        };

        // Guard: only read files under the project root to prevent path traversal
        if let Ok(canonical) = abs_path.canonicalize()
            && let Ok(root_canonical) = project_root.canonicalize()
            && !canonical.starts_with(&root_canonical)
        {
            continue; // skip out-of-tree files
        }

        if let Ok(content) = fs::read_to_string(abs_path) {
            let file_suppressions = parse_suppressions(&content);
            if !file_suppressions.is_empty() {
                suppressions.insert(file_path, file_suppressions);
            }
        }
    }

    if suppressions.is_empty() {
        return (diagnostics, 0);
    }

    // Filter diagnostics
    let original_count = diagnostics.len();
    let filtered: Vec<Diagnostic> = diagnostics
        .into_iter()
        .filter(|d| !is_suppressed(d, &suppressions))
        .collect();
    let suppressed_count = original_count - filtered.len();

    (filtered, suppressed_count)
}

/// Parse suppression comments from file content.
fn parse_suppressions(content: &str) -> Vec<Suppression> {
    let mut suppressions = Vec::new();

    for (line_idx, line) in content.lines().enumerate() {
        let line_num = (line_idx + 1) as u32;
        let trimmed = line.trim();

        // Check for // rust-doctor-disable-next-line [rule]
        if let Some(rest) = extract_comment_directive(trimmed, DISABLE_NEXT_LINE) {
            let rule = parse_rule_name(rest);
            suppressions.push(Suppression {
                target_line: line_num + 1, // applies to the NEXT line
                rule,
            });
        }

        // Check for // rust-doctor-disable-line [rule]
        if let Some(rest) = extract_comment_directive(trimmed, DISABLE_LINE) {
            let rule = parse_rule_name(rest);
            suppressions.push(Suppression {
                target_line: line_num, // applies to THIS line
                rule,
            });
        }

        // Also check for inline comments at end of line: `code // rust-doctor-disable-line`
        // We must avoid matching `//` inside string literals. Use a simple heuristic:
        // find the last `//` on the line that is NOT preceded by `:` (to skip URLs like https://)
        // and is outside string literals (approximate: count unescaped `"` before the `//`).
        if !trimmed.starts_with("//")
            && let Some(comment_start) = find_line_comment_start(line)
        {
            let comment = line[comment_start + 2..].trim();
            if let Some(rest) = comment.strip_prefix(DISABLE_LINE) {
                let rule = parse_rule_name(rest);
                suppressions.push(Suppression {
                    target_line: line_num,
                    rule,
                });
            }
        }
    }

    suppressions
}

/// Find the start of a line comment (`//`) that is NOT inside a string literal.
/// Returns the byte offset of the `//` or `None` if no valid comment is found.
fn find_line_comment_start(line: &str) -> Option<usize> {
    let mut in_string = false;
    let mut prev_backslash = false;
    let bytes = line.as_bytes();
    let mut i = 0;
    while let Some(&b) = bytes.get(i) {
        if in_string {
            if b == b'\\' && !prev_backslash {
                prev_backslash = true;
                i += 1;
                continue;
            }
            if b == b'"' && !prev_backslash {
                in_string = false;
            }
            prev_backslash = false;
        } else if b == b'"' {
            in_string = true;
        } else if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Extract the rest of a comment after a directive prefix.
fn extract_comment_directive<'a>(line: &'a str, directive: &str) -> Option<&'a str> {
    // Match: // directive [rest]
    let stripped = line.strip_prefix("//")?;
    let stripped = stripped.trim_start();
    stripped.strip_prefix(directive).map(str::trim)
}

/// Parse an optional rule name from the rest of a directive.
fn parse_rule_name(rest: &str) -> Option<String> {
    let name = rest.trim();
    if name.is_empty() {
        None // No rule = suppress all
    } else {
        Some(name.to_string())
    }
}

/// Check if a diagnostic is suppressed by any suppression in its file.
fn is_suppressed(diag: &Diagnostic, suppressions: &HashMap<PathBuf, Vec<Suppression>>) -> bool {
    let Some(line) = diag.line else {
        return false; // Diagnostics without line numbers can't be suppressed inline
    };

    // Try exact path match first, then try matching by file name suffix
    // (handles absolute vs relative path mismatches between clippy and rule engine diagnostics)
    let file_suppressions = suppressions.get(&diag.file_path).or_else(|| {
        suppressions.iter().find_map(|(k, v)| {
            if diag.file_path.ends_with(k) || k.ends_with(&diag.file_path) {
                Some(v)
            } else {
                None
            }
        })
    });

    let Some(file_suppressions) = file_suppressions else {
        return false;
    };

    file_suppressions.iter().any(|s| {
        s.target_line == line && (s.rule.is_none() || s.rule.as_deref() == Some(diag.rule.as_str()))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diagnostics::{Category, Severity};

    fn make_diag(file: &str, rule: &str, line: u32) -> Diagnostic {
        Diagnostic {
            file_path: PathBuf::from(file),
            rule: rule.to_string(),
            category: Category::Style,
            severity: Severity::Warning,
            message: "test".to_string(),
            help: None,
            line: Some(line),
            column: None,
            fix: None,
        }
    }

    // --- parse_suppressions ---

    #[test]
    fn test_parse_disable_next_line_with_rule() {
        let content =
            "// rust-doctor-disable-next-line unwrap-in-production\nlet x = foo.unwrap();\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 1);
        assert_eq!(supps[0].target_line, 2);
        assert_eq!(supps[0].rule, Some("unwrap-in-production".to_string()));
    }

    #[test]
    fn test_parse_disable_next_line_no_rule() {
        let content = "// rust-doctor-disable-next-line\nlet x = foo.unwrap();\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 1);
        assert_eq!(supps[0].target_line, 2);
        assert_eq!(supps[0].rule, None);
    }

    #[test]
    fn test_parse_disable_line() {
        let content = "let x = foo.unwrap(); // rust-doctor-disable-line\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 1);
        assert_eq!(supps[0].target_line, 1);
        assert_eq!(supps[0].rule, None);
    }

    #[test]
    fn test_parse_disable_line_with_rule() {
        let content = "let x = foo.unwrap(); // rust-doctor-disable-line unwrap-in-production\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 1);
        assert_eq!(supps[0].rule, Some("unwrap-in-production".to_string()));
    }

    #[test]
    fn test_parse_standalone_disable_line_comment() {
        let content = "// rust-doctor-disable-line some-rule\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 1);
        assert_eq!(supps[0].target_line, 1);
        assert_eq!(supps[0].rule, Some("some-rule".to_string()));
    }

    #[test]
    fn test_parse_no_suppressions() {
        let content = "fn main() {\n    println!(\"hello\");\n}\n";
        let supps = parse_suppressions(content);
        assert!(supps.is_empty());
    }

    #[test]
    fn test_parse_multiple_suppressions() {
        let content = "// rust-doctor-disable-next-line rule-a\nline1\n// rust-doctor-disable-next-line rule-b\nline2\n";
        let supps = parse_suppressions(content);
        assert_eq!(supps.len(), 2);
    }

    // --- is_suppressed ---

    #[test]
    fn test_suppressed_by_specific_rule() {
        let diag = make_diag("test.rs", "unwrap-in-production", 5);
        let mut suppressions = HashMap::new();
        suppressions.insert(
            PathBuf::from("test.rs"),
            vec![Suppression {
                target_line: 5,
                rule: Some("unwrap-in-production".to_string()),
            }],
        );
        assert!(is_suppressed(&diag, &suppressions));
    }

    #[test]
    fn test_suppressed_by_wildcard() {
        let diag = make_diag("test.rs", "any-rule", 5);
        let mut suppressions = HashMap::new();
        suppressions.insert(
            PathBuf::from("test.rs"),
            vec![Suppression {
                target_line: 5,
                rule: None,
            }],
        );
        assert!(is_suppressed(&diag, &suppressions));
    }

    #[test]
    fn test_not_suppressed_wrong_rule() {
        let diag = make_diag("test.rs", "rule-a", 5);
        let mut suppressions = HashMap::new();
        suppressions.insert(
            PathBuf::from("test.rs"),
            vec![Suppression {
                target_line: 5,
                rule: Some("rule-b".to_string()),
            }],
        );
        assert!(!is_suppressed(&diag, &suppressions));
    }

    #[test]
    fn test_not_suppressed_wrong_line() {
        let diag = make_diag("test.rs", "rule-a", 5);
        let mut suppressions = HashMap::new();
        suppressions.insert(
            PathBuf::from("test.rs"),
            vec![Suppression {
                target_line: 10,
                rule: Some("rule-a".to_string()),
            }],
        );
        assert!(!is_suppressed(&diag, &suppressions));
    }

    #[test]
    fn test_not_suppressed_no_line_number() {
        let mut diag = make_diag("test.rs", "rule-a", 5);
        diag.line = None;
        let mut suppressions = HashMap::new();
        suppressions.insert(
            PathBuf::from("test.rs"),
            vec![Suppression {
                target_line: 5,
                rule: None,
            }],
        );
        assert!(!is_suppressed(&diag, &suppressions));
    }

    // --- apply_inline_suppressions with real files ---

    #[test]
    fn test_apply_with_temp_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test.rs");
        std::fs::write(
            &file_path,
            "// rust-doctor-disable-next-line test-rule\nlet x = 1;\nlet y = 2;\n",
        )
        .unwrap();

        let diags = vec![
            Diagnostic {
                file_path: file_path.clone(),
                rule: "test-rule".to_string(),
                category: Category::Style,
                severity: Severity::Warning,
                message: "test".to_string(),
                help: None,
                line: Some(2),
                column: None,
                fix: None,
            },
            Diagnostic {
                file_path,
                rule: "other-rule".to_string(),
                category: Category::Style,
                severity: Severity::Warning,
                message: "test".to_string(),
                help: None,
                line: Some(3),
                column: None,
                fix: None,
            },
        ];

        let (filtered, suppressed) = apply_inline_suppressions(diags, dir.path());
        assert_eq!(suppressed, 1);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].rule, "other-rule");
    }

    // --- find_line_comment_start ---

    #[test]
    fn test_find_comment_in_normal_code() {
        assert_eq!(find_line_comment_start("let x = 1; // comment"), Some(11));
    }

    #[test]
    fn test_find_comment_ignores_string_literal() {
        // The // inside "https://example.com" should NOT be found as a comment
        assert_eq!(
            find_line_comment_start(r#"let url = "https://example.com"; // real comment"#),
            Some(33)
        );
    }

    #[test]
    fn test_find_comment_only_string_no_comment() {
        assert_eq!(
            find_line_comment_start(r#"let url = "https://example.com";"#),
            None
        );
    }

    #[test]
    fn test_find_comment_no_comment_at_all() {
        assert_eq!(find_line_comment_start("let x = 1;"), None);
    }

    #[test]
    fn test_suppression_not_triggered_by_string_literal() {
        // A string literal containing "// rust-doctor-disable-line" should NOT create a suppression
        let content = r#"let msg = "see // rust-doctor-disable-line for details";"#;
        let supps = parse_suppressions(content);
        assert!(supps.is_empty());
    }
}