gruff-rs 0.4.0

Rust static analyzer and quality linter for CI: dead-code, complexity, security, secrets, and architecture rules with deterministic SARIF/JSON output and baseline support.
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
use super::*;

#[test]
pub(crate) fn dead_code_project_candidates_use_conservative_cross_file_evidence() {
    let _guard = analysis_lock();
    let positive_dir = tempdir().expect("tempdir");
    fs::create_dir_all(positive_dir.path().join("src")).expect("src dir");
    fs::write(positive_dir.path().join("README.md"), "# Fixture\n").expect("readme write");
    fs::write(
        positive_dir.path().join("Cargo.toml"),
        r#"[package]
name = "dead-code-positive-fixture"
version = "0.1.0"
edition = "2021"
description = "Synthetic fixture for dead-code rule tests."
license = "MIT"
"#,
    )
    .expect("manifest write");
    fs::write(
        positive_dir.path().join("src/lib.rs"),
        r#"fn isolated_helper() {}

const UNUSED_LIMIT: usize = 1;

static UNUSED_STATE: &str = "off";

type HiddenAlias = usize;

struct HiddenType;

enum HiddenEnum {
    Ready,
}

trait HiddenTrait {}

fn referenced_helper() {}

pub fn entry() {
    referenced_helper();
}
"#,
    )
    .expect("positive lib write");

    let positive = run_project_analysis(
        positive_dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("dead-code positive analysis succeeds");
    assert_has_rule(&positive, "dead-code.unused-private-item-candidate");
    let candidate = positive
        .findings
        .iter()
        .find(|finding| {
            finding.rule_id == "dead-code.unused-private-item-candidate"
                && finding.symbol.as_deref() == Some("isolated_helper")
        })
        .expect("isolated helper candidate");
    assert!(candidate.message.contains("candidate"));
    assert!(matches!(candidate.confidence, Confidence::Medium));
    assert_eq!(candidate.metadata["candidate"], json!(true));
    assert_eq!(candidate.fingerprint, "395572648fc5a9b0");
    for symbol in ["UNUSED_LIMIT", "UNUSED_STATE", "HiddenAlias"] {
        assert!(
            positive.findings.iter().any(|finding| {
                finding.rule_id == "dead-code.unused-private-item-candidate"
                    && finding.symbol.as_deref() == Some(symbol)
            }),
            "expected new private item candidate `{symbol}`; findings={:?}",
            positive
                .findings
                .iter()
                .map(|finding| (&finding.rule_id, finding.symbol.as_deref()))
                .collect::<Vec<_>>()
        );
    }

    let negative_dir = tempdir().expect("tempdir");
    fs::create_dir_all(negative_dir.path().join("src")).expect("src dir");
    fs::write(negative_dir.path().join("README.md"), "# Fixture\n").expect("readme write");
    fs::write(
        negative_dir.path().join("Cargo.toml"),
        r#"[package]
name = "dead-code-negative-fixture"
version = "0.1.0"
edition = "2021"
description = "Synthetic fixture for dead-code rule tests."
license = "MIT"
"#,
    )
    .expect("manifest write");
    fs::write(
        negative_dir.path().join("src/lib.rs"),
        r#"macro_rules! register {
    ($item:ident) => {};
}

fn macro_registered() {}
register!(macro_registered);

#[cfg(feature = "optional")]
fn cfg_only() {}

#[test]
fn test_only_helper() {}

mod tests {
    fn module_test_helper() {}
}

struct Worker;

impl Worker {
    fn new() -> Self {
        Worker
    }

    fn len(&self) -> usize {
        0
    }
}

trait Job {
    fn poll(&self);
}

impl Job for Worker {
    fn poll(&self) {}
}

fn referenced_helper() {}

pub fn entry() {
    referenced_helper();
}
"#,
    )
    .expect("negative lib write");

    let negative = run_project_analysis(
        negative_dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("dead-code negative analysis succeeds");
    assert_missing_rule(&negative, "dead-code.unused-private-item-candidate");
}

#[test]
pub(crate) fn project_dead_code_ignores_comment_mentions_and_test_cfg_helpers() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    baseline_with_lib(
        dir.path(),
        r#"fn comment_only_reference() {}
// comment_only_reference is only mentioned in prose.

#[cfg(test)] fn cfg_test_helper() {}
#[cfg_attr(test, allow(dead_code))] struct CfgAttrStillProduction;
"#,
    );

    let report = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("analysis succeeds");

    let has_dead_item = |symbol| {
        report.findings.iter().any(|finding| {
            finding.rule_id == "dead-code.unused-private-item-candidate"
                && finding.symbol.as_deref() == Some(symbol)
        })
    };
    assert!(has_dead_item("comment_only_reference"));
    assert!(!has_dead_item("cfg_test_helper"));
    assert!(has_dead_item("CfgAttrStillProduction"));
}

#[test]
pub(crate) fn project_dead_code_skips_attribute_exported_and_allowed_items() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    baseline_with_lib(
        dir.path(),
        r#"#[no_mangle]
unsafe extern "C" fn ffi_entry() -> i32 {
    0
}

#[export_name = "renamed_entry"]
fn renamed_entry() {}

#[unsafe(no_mangle)]
unsafe extern "C" fn ffi_entry_2024() -> i32 {
    0
}

#[unsafe(export_name = "renamed_entry_2024")]
fn renamed_entry_2024() {}

#[pymodule]
fn plugin_module() {}

#[pyfunction]
fn plugin_function() {}

#[allow(dead_code)]
fn intentionally_registered() {}

#[allow(dead_code)]
mod plugin_generated {
    fn module_registered() {}
}

fn ordinary_unused() {}

pub fn entry() {}
"#,
    );

    let report = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("analysis succeeds");

    let candidate_symbols: BTreeSet<&str> = report
        .findings
        .iter()
        .filter(|finding| finding.rule_id == "dead-code.unused-private-item-candidate")
        .filter_map(|finding| finding.symbol.as_deref())
        .collect();
    assert!(
        candidate_symbols.contains("ordinary_unused"),
        "ordinary unused private item must still flag; symbols={candidate_symbols:?}"
    );
    for exported in [
        "ffi_entry",
        "renamed_entry",
        "ffi_entry_2024",
        "renamed_entry_2024",
        "plugin_module",
        "plugin_function",
        "intentionally_registered",
        "module_registered",
    ] {
        assert!(
            !candidate_symbols.contains(exported),
            "attribute-exported or allow(dead_code) item `{exported}` must stay silent; symbols={candidate_symbols:?}"
        );
    }
}

#[test]
pub(crate) fn dead_code_single_file_crate_reports_unused_private_item_on_narrow_path() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    fs::create_dir_all(dir.path().join("src")).expect("src dir");
    fs::write(dir.path().join("README.md"), "# Fixture\n").expect("readme write");
    fs::write(
        dir.path().join("Cargo.toml"),
        r#"[package]
name = "dead-code-single-file-fixture"
version = "0.1.0"
edition = "2021"
description = "Synthetic fixture for dead-code partial-context tests."
license = "MIT"
"#,
    )
    .expect("manifest write");
    fs::write(
        dir.path().join("src/lib.rs"),
        r#"fn genuinely_unused() {}

pub fn entry() {}
"#,
    )
    .expect("lib write");

    let whole = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("whole-crate analysis succeeds");
    assert!(
        has_dead_code_symbol(&whole, "genuinely_unused"),
        "whole-crate scan should report unused private item"
    );

    let narrow = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from("src/lib.rs")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("single-file analysis succeeds");
    assert!(
        has_dead_code_symbol(&narrow, "genuinely_unused"),
        "single-file crate narrow scan should still report unused private item"
    );
}

#[test]
pub(crate) fn dead_code_partial_context_suppresses_cross_file_candidate() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    write_cross_file_dead_code_fixture(dir.path());

    let whole = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("whole-crate analysis succeeds");
    assert!(
        !has_dead_code_symbol(&whole, "helper_used_by_child"),
        "whole-crate scan sees sibling reference"
    );

    let narrow = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from("src/lib.rs")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("narrow analysis succeeds");
    assert!(
        !has_dead_code_symbol(&narrow, "helper_used_by_child"),
        "partial-context scan must not claim sibling-referenced item is unused"
    );
    assert!(
        has_partial_context_diagnostic(&narrow),
        "partial-context suppression should be visible in analyse diagnostics"
    );
}

#[test]
pub(crate) fn dead_code_diff_patch_partial_context_suppresses_candidate() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    write_cross_file_dead_code_fixture(dir.path());
    fs::write(
        dir.path().join("lib.patch"),
        "diff --git a/src/lib.rs b/src/lib.rs\n\
--- a/src/lib.rs\n\
+++ b/src/lib.rs\n\
@@ -0,0 +1,3 @@\n\
+mod child;\n\
+fn helper_used_by_child() {}\n\
+pub fn entry() {}\n",
    )
    .expect("patch write");

    let report = run_project_analysis(
        dir.path(),
        AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            diff: Some(DiffSelection::Patch {
                path: PathBuf::from("lib.patch"),
                scope: ChangedScope::Symbol,
            }),
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
    )
    .expect("diff-patch analysis succeeds");
    assert!(
        !has_dead_code_symbol(&report, "helper_used_by_child"),
        "diff-patch partial-context scan must not claim sibling-referenced item is unused"
    );
    assert!(
        has_partial_context_diagnostic(&report),
        "diff-patch suppression should be visible in analyse diagnostics"
    );
}

#[test]
pub(crate) fn dead_code_partial_context_coverage_tracks_actual_rust_file_universe() {
    let _guard = analysis_lock();
    let dir = tempdir().expect("tempdir");
    write_cross_file_dead_code_fixture(dir.path());

    let whole = project_coverage_for_test(
        dir.path(),
        &AnalysisOptions {
            paths: vec![PathBuf::from(".")],
            no_config: true,
            no_baseline: true,
            ..default_test_options()
        },
        &load_config(
            dir.path(),
            &AnalysisOptions {
                paths: vec![PathBuf::from(".")],
                no_config: true,
                no_baseline: true,
                ..default_test_options()
            },
        )
        .expect("config loads"),
    )
    .expect("coverage resolves");
    assert!(
        !whole.is_partial(),
        "whole-project analysis covers every discoverable Rust source"
    );

    let narrow_options = AnalysisOptions {
        paths: vec![PathBuf::from("src/lib.rs")],
        no_config: true,
        no_baseline: true,
        ..default_test_options()
    };
    let narrow_config = load_config(dir.path(), &narrow_options).expect("config loads");
    let narrow =
        project_coverage_for_test(dir.path(), &narrow_options, &narrow_config).expect("coverage");
    assert!(
        narrow.is_partial(),
        "multi-file crate with only src/lib.rs analysed is partial"
    );

    let single = tempdir().expect("tempdir");
    fs::create_dir_all(single.path().join("src")).expect("single src dir");
    fs::write(single.path().join("README.md"), "# Fixture\n").expect("readme write");
    fs::write(
        single.path().join("Cargo.toml"),
        r#"[package]
name = "single-file-coverage-fixture"
version = "0.1.0"
edition = "2021"
description = "Synthetic fixture for coverage tests."
license = "MIT"
"#,
    )
    .expect("manifest write");
    fs::write(single.path().join("src/lib.rs"), "fn unused() {}\n").expect("lib write");
    let single_options = AnalysisOptions {
        paths: vec![PathBuf::from("src/lib.rs")],
        no_config: true,
        no_baseline: true,
        ..default_test_options()
    };
    let single_config = load_config(single.path(), &single_options).expect("config loads");
    let single_coverage = project_coverage_for_test(single.path(), &single_options, &single_config)
        .expect("coverage resolves");
    assert!(
        !single_coverage.is_partial(),
        "single-file crate remains complete even when that file is named directly"
    );

    let ignored = tempdir().expect("tempdir");
    write_cross_file_dead_code_fixture(ignored.path());
    write_config(ignored.path(), "paths:\n  ignore:\n    - src/child.rs\n");
    let ignored_options = AnalysisOptions {
        paths: vec![PathBuf::from("src/lib.rs")],
        no_config: false,
        no_baseline: true,
        ..default_test_options()
    };
    let ignored_config = load_config(ignored.path(), &ignored_options).expect("config loads");
    let ignored_coverage =
        project_coverage_for_test(ignored.path(), &ignored_options, &ignored_config)
            .expect("coverage resolves");
    assert!(
        !ignored_coverage.is_partial(),
        "config-ignored Rust siblings are outside the discoverable universe"
    );

    fs::write(
        dir.path().join("lib.patch"),
        "diff --git a/src/lib.rs b/src/lib.rs\n\
--- a/src/lib.rs\n\
+++ b/src/lib.rs\n\
@@ -0,0 +1,3 @@\n\
+mod child;\n\
+fn helper_used_by_child() {}\n\
+pub fn entry() {}\n",
    )
    .expect("patch write");
    let patch_options = AnalysisOptions {
        paths: vec![PathBuf::from(".")],
        diff: Some(DiffSelection::Patch {
            path: PathBuf::from("lib.patch"),
            scope: ChangedScope::Symbol,
        }),
        no_config: true,
        no_baseline: true,
        ..default_test_options()
    };
    let patch_config = load_config(dir.path(), &patch_options).expect("config loads");
    let patch_coverage = project_coverage_for_test(dir.path(), &patch_options, &patch_config)
        .expect("coverage resolves");
    assert!(
        patch_coverage.is_partial(),
        "patch file selection is partial when it removes discoverable Rust sources"
    );
}

pub(super) fn has_dead_code_symbol(report: &AnalysisReport, symbol: &str) -> bool {
    report.findings.iter().any(|finding| {
        finding.rule_id == "dead-code.unused-private-item-candidate"
            && finding.symbol.as_deref() == Some(symbol)
    })
}

fn has_partial_context_diagnostic(report: &AnalysisReport) -> bool {
    report.diagnostics.iter().any(|diagnostic| {
        diagnostic.diagnostic_type == "partial-context-rule-suppressed"
            && diagnostic
                .message
                .contains("dead-code.unused-private-item-candidate")
    })
}

fn write_cross_file_dead_code_fixture(root: &Path) {
    fs::create_dir_all(root.join("src")).expect("src dir");
    fs::write(root.join("README.md"), "# Fixture\n").expect("readme write");
    fs::write(
        root.join("Cargo.toml"),
        r#"[package]
name = "dead-code-partial-context-fixture"
version = "0.1.0"
edition = "2021"
description = "Synthetic fixture for dead-code partial-context tests."
license = "MIT"
"#,
    )
    .expect("manifest write");
    fs::write(
        root.join("src/lib.rs"),
        r#"mod child;
fn helper_used_by_child() {}
pub fn entry() {}
"#,
    )
    .expect("lib write");
    fs::write(
        root.join("src/child.rs"),
        r#"pub fn call() {
    crate::helper_used_by_child();
}
"#,
    )
    .expect("child write");
}