rust-doctor 0.6.0

Local-first health audit for Cargo workspaces: curated Clippy lints and native detectors, scored out of 100
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
use std::path::Path;

use cargo_metadata::{Metadata, MetadataCommand};

use std::collections::BTreeSet;

use super::*;
use crate::policy::{
    Producer, STRUCTURE_COMPLEX_FUNCTION, STRUCTURE_OVERSIZED_UNIT, STRUCTURE_UNREASONED_ALLOW,
};
use crate::source_kernel::enumerate;

fn metadata(relative: &str) -> Metadata {
    let manifest = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(relative)
        .join("Cargo.toml");
    MetadataCommand::new()
        .manifest_path(manifest)
        .no_deps()
        .other_options(["--offline".to_owned(), "--locked".to_owned()])
        .exec()
        .expect("fixture metadata should load")
}

/// This repository, as the pass reads it. Two tests scan it: what the
/// nomination recalls, and which of its own hotspots it names.
pub(super) fn repository() -> Metadata {
    let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
    MetadataCommand::new()
        .manifest_path(manifest)
        .no_deps()
        .other_options(["--offline".to_owned(), "--locked".to_owned()])
        .exec()
        .expect("this repository should describe itself")
}

/// Every rule the catalogue publishes under this producer is a rule the
/// pass runs, and the reverse. A rule declared in the catalogue and left
/// out of a family's table would be published by `rules list`, scored
/// against, and never actually observed.
#[test]
fn the_pass_produces_every_catalogued_structural_rule() {
    let mut produced: Vec<&str> = rules().map(|rule| rule.id).collect();
    produced.sort_unstable();
    let mut catalogued: Vec<&str> = crate::policy::CATALOG
        .iter()
        .filter(|rule| matches!(rule.producer, Producer::Structure))
        .map(|rule| rule.id)
        .collect();
    catalogued.sort_unstable();
    assert_eq!(produced, catalogued);
    assert_eq!(
        produced.len(),
        produced.iter().collect::<BTreeSet<_>>().len(),
        "a rule is declared by two families: {produced:?}"
    );
}

/// A workspace with no unit at all returns an empty result and no error:
/// there is nothing to be partial about.
#[test]
fn an_empty_enumeration_produces_neither_finding_nor_error() {
    let scan = analyze(
        &metadata("structure/empty"),
        &Enumeration::default(),
        &PolicyPlan::default(),
        &StructureSettings::default(),
    );
    assert_eq!(scan, StructureScan::default());
}

/// A unit the parser could not read is skipped and named, and the pass
/// completes over every other unit of the same workspace.
#[test]
fn an_unparseable_unit_is_skipped_named_and_never_aborts_the_pass() {
    let errors = metadata("source-kernel/errors");
    let enumeration = enumerate(&errors);
    let scan = analyze(
        &errors,
        &enumeration,
        &PolicyPlan::default(),
        &StructureSettings::default(),
    );

    let skipped: Vec<&str> = scan
        .errors
        .iter()
        .map(|error| {
            assert_eq!(error.code, "parse-error");
            error.message.as_str()
        })
        .collect();
    assert!(!skipped.is_empty(), "the fixture parses cleanly after all");
    assert!(
        skipped
            .iter()
            .all(|message| !message.contains(env!("CARGO_MANIFEST_DIR"))),
        "{skipped:?}"
    );
    let analysed = enumeration
        .units()
        .filter(|unit| unit.parses_cleanly())
        .count();
    assert!(
        analysed > 0,
        "the pass stopped at the first unreadable unit"
    );
}

/// US-009, FR-10: a budget the pass cannot meet stops it rather than
/// letting it run, and the stop is published as an error under the
/// `structure` stage, which is what takes the authoritative flag off the
/// score.
#[test]
fn an_exhausted_budget_stops_the_pass_and_says_so() {
    let duplicates = metadata("structure/duplicate-function");
    let enumeration = enumerate(&duplicates);
    let stopped = analyze_within(
        &duplicates,
        &enumeration,
        &PolicyPlan::default(),
        &StructureSettings::default(),
        Duration::ZERO,
    );
    assert_eq!(
        stopped
            .errors
            .iter()
            .map(|error| error.code)
            .collect::<Vec<_>>(),
        ["time-budget"],
        "{:?}",
        stopped.errors
    );
    assert!(
        stopped.errors.iter().all(|error| !error
            .message
            .contains(env!("CARGO_MANIFEST_DIR"))),
        "{:?}",
        stopped.errors
    );

    // The same workspace under the shipped budget finishes, so the stop
    // above is the budget and not the workspace.
    let complete = analyze(
        &duplicates,
        &enumeration,
        &PolicyPlan::default(),
        &StructureSettings::default(),
    );
    assert!(complete.errors.is_empty(), "{:?}", complete.errors);
    assert!(!complete.findings.is_empty());
}

/// FR-10: partiality is what a phase reports, never what a clock reads
/// afterwards. A pass that analysed every unit publishes a complete report
/// even when it finished after its own budget, because calling it partial
/// costs the score its authoritative flag for nothing.
#[test]
fn a_pass_that_finished_late_is_not_a_partial_pass() {
    let duplicates = metadata("structure/duplicate-function");
    let enumeration = enumerate(&duplicates);
    // A budget of one nanosecond is spent by the time the first unit is
    // read, so every phase of this scan ran with an exceeded clock. The
    // walk itself is what decides, and it decided to stop.
    let stopped = analyze_within(
        &duplicates,
        &enumeration,
        &PolicyPlan::default(),
        &StructureSettings::default(),
        Duration::from_nanos(1),
    );
    assert!(stopped.errors.iter().any(|error| error.code == "time-budget"));

    // The same scan under a budget it cannot exceed reports nothing, and
    // that is the only difference between the two.
    let complete = analyze_within(
        &duplicates,
        &enumeration,
        &PolicyPlan::default(),
        &StructureSettings::default(),
        Duration::from_secs(3_600),
    );
    assert!(complete.errors.is_empty(), "{:?}", complete.errors);
}

/// The pass is switched off by the policy like any other producer, and
/// costs nothing when it is.
#[test]
fn an_inactive_rule_leaves_the_pass_with_nothing_to_do() {
    let allows = metadata("structure/unreasoned-allow");
    let enumeration = enumerate(&allows);
    let input = crate::policy::PolicyInput::default()
        .with_rule(STRUCTURE_UNREASONED_ALLOW.id, crate::policy::RuleLevel::Off);
    let plan = PolicyPlan::compile(&input).expect("policy should compile");
    assert!(
        analyze(&allows, &enumeration, &plan, &StructureSettings::default())
            .findings
            .iter()
            .all(|finding| finding.definition.id != STRUCTURE_UNREASONED_ALLOW.id),
        "an inactive structural rule still produced a finding"
    );
    assert!(
        !analyze(
            &allows,
            &enumeration,
            &PolicyPlan::default(),
            &StructureSettings::default()
        )
        .findings
        .is_empty()
    );
}

/// Every rule off, and the pass does not even look at the units.
#[test]
fn a_policy_with_no_structural_rule_returns_the_empty_scan() {
    let mut input = crate::policy::PolicyInput::default();
    for rule in rules() {
        input = input.with_rule(rule.id, crate::policy::RuleLevel::Off);
    }
    let plan = PolicyPlan::compile(&input).expect("policy should compile");
    let allows = metadata("structure/unreasoned-allow");
    let scan = analyze(
        &allows,
        &enumerate(&allows),
        &plan,
        &StructureSettings::default(),
    );
    assert_eq!(scan, StructureScan::default());
}

/// The identity of a family is its rule and its key, and nothing else.
#[test]
fn the_structural_hash_depends_only_on_the_rule_and_the_key() {
    let hash = structural_hash("rust_doctor::structure::unreasoned_allow_attribute", "outer|a");
    assert_eq!(
        hash,
        structural_hash("rust_doctor::structure::unreasoned_allow_attribute", "outer|a")
    );
    assert_ne!(
        hash,
        structural_hash("rust_doctor::structure::unreasoned_allow_attribute", "outer|b")
    );
    assert_ne!(hash, structural_hash("rust_doctor::structure::other", "outer|a"));
    assert_eq!(hash.len(), 64);
}

fn member(path: &str) -> Member {
    Member {
        path: path.to_owned(),
        span: SourceSpan {
            line_start: 1,
            column_start: 1,
            line_end: 1,
            column_end: 2,
        },
        context: None,
    }
}

#[test]
fn a_family_is_marked_only_when_every_member_agrees() {
    let production = member("src/lib.rs");
    let tested = Member {
        context: Some(DiagnosticContext::Tests),
        ..production.clone()
    };
    assert_eq!(
        unanimous_context(std::slice::from_ref(&tested)),
        Some(DiagnosticContext::Tests)
    );
    assert_eq!(
        unanimous_context(&[tested.clone(), tested.clone()]),
        Some(DiagnosticContext::Tests)
    );
    assert_eq!(unanimous_context(&[tested, production.clone()]), None);
    assert_eq!(unanimous_context(&[production]), None);
    assert_eq!(unanimous_context(&[]), None);
}

/// A family no member of which ships takes the mark of its anchor.
///
/// The members disagree on which non-production context they carry, and each of
/// them is right about itself: this is the family layer, where the question is
/// not what one unit is but whether the family weighs, and it does not. The
/// abstention `source_kernel::unanimous` performs over a unit reached by
/// disagreeing traversals answers a different question, and stays.
///
/// The anchor rather than one of the two kinds because the anchor is the site
/// the family is reported at, so the mark the reader is shown is the mark of
/// the file they are sent to.
#[test]
fn a_family_no_member_of_which_ships_takes_the_mark_of_its_anchor() {
    let benched = Member {
        context: Some(DiagnosticContext::Benchmark),
        ..member("benches/throughput.rs")
    };
    let tested = Member {
        context: Some(DiagnosticContext::Tests),
        ..member("tests/integration.rs")
    };

    assert_eq!(
        unanimous_context(&[benched.clone(), tested.clone()]),
        Some(DiagnosticContext::Benchmark)
    );
    assert_eq!(
        unanimous_context(&[tested.clone(), benched.clone()]),
        Some(DiagnosticContext::Tests)
    );
    // One member that ships is the whole family shipping: the straddling case
    // keeps abstaining to production, unchanged.
    assert_eq!(unanimous_context(&[benched, tested, member("src/lib.rs")]), None);
}

/// One key, one family: the first arrival says what the family is, and
/// every later one adds a member to it. Recording is a merge, never a
/// replacement, whichever producer the members come from.
#[test]
fn recording_the_same_key_twice_merges_instead_of_replacing() {
    let mut families = BTreeMap::new();
    let rule = STRUCTURE_OVERSIZED_UNIT.id;
    record_family(
        &mut families,
        rule,
        "file|a".to_owned(),
        Summary::of("first".to_owned()),
        [member("src/a.rs")],
    );
    record_family(
        &mut families,
        rule,
        "file|a".to_owned(),
        Summary::of("second".to_owned()),
        [member("src/b.rs")],
    );
    let family = families
        .get(&(rule, "file|a".to_owned()))
        .expect("the family is under its key");
    assert_eq!(family.summary.subject, "first");
    assert_eq!(family.members.len(), 2);

    // An empty subject is a subject, not a signal: nothing later overwrites
    // it.
    let mut empty = BTreeMap::new();
    record_family(
        &mut empty,
        rule,
        "file|b".to_owned(),
        Summary::of(String::new()),
        [member("src/a.rs")],
    );
    record_family(
        &mut empty,
        rule,
        "file|b".to_owned(),
        Summary::of("later".to_owned()),
        [member("src/b.rs")],
    );
    assert_eq!(
        empty
            .get(&(rule, "file|b".to_owned()))
            .map(|family| family.summary.subject.as_str()),
        Some("")
    );
}

/// US-011: a recognized generator header excludes the file from the whole
/// structural pass, silently.
#[test]
fn a_generated_file_is_excluded() {
    for header in [
        "// @generated by prost-build",
        "// DO NOT EDIT: regenerated on every build",
        "// Automatically generated by bindgen.",
    ] {
        assert!(is_generated(&format!("{header}\nfn free() {{}}\n")), "{header}");
    }
    assert!(!is_generated("fn free() {}\n"));
    // The markers this file documents are not a header of it.
    assert!(!is_generated(include_str!("../structure.rs")));
}

/// The inventory is one walk, and it is the one every family reads.
#[test]
fn the_inventory_collects_every_kind_the_detectors_read() {
    let unit = Unit::probe(
        "#![allow(dead_code)]\nmod inner { impl Probe { fn method() { println!(\"a\"); } } }\n",
        "src/lib.rs",
    );
    assert_eq!(unit.inventory.attributes.len(), 1);
    assert_eq!(unit.inventory.functions.len(), 1);
    assert_eq!(unit.inventory.implementations.len(), 1);
    assert_eq!(unit.inventory.modules.len(), 1);
    assert_eq!(unit.inventory.macro_calls.len(), 1);
}

/// EP-003, definition of done, inverted: a scan of this repository names no
/// oversized unit and no complexity hotspot anywhere under `src/`, through the
/// same pass `inspect` runs.
///
/// It used to assert the opposite, that `src/report.rs` was named oversized,
/// which froze the crate's largest self-violation in place: repairing the file
/// failed the suite. The rule's own evidence that it fires belongs on a
/// fixture, and `tests/rule_evidence.json` names the two tests that carry it.
/// What belongs here is the gate: the tool has to pass what it reports.
///
/// The nine `the_X_holds_the_size_bound` tests scattered across the crate stay,
/// because each of them fails on its own module and says which one. This one
/// covers every file none of them names, and the three units below the file
/// level that none of them can see.
#[test]
fn no_unit_of_this_crate_s_own_source_is_a_hotspot() {
    let metadata = repository();
    let scan = analyze(
        &metadata,
        &enumerate(&metadata),
        &PolicyPlan::default(),
        &StructureSettings::default(),
    );

    let named = |rule: &str| -> Vec<String> {
        scan.findings
            .iter()
            .filter(|finding| finding.definition.id == rule && finding.path.starts_with("src/"))
            .map(|finding| format!("{}: {}", finding.path, finding.message))
            .collect()
    };

    let oversized = named(STRUCTURE_OVERSIZED_UNIT.id);
    assert!(
        oversized.is_empty(),
        "the crate reports itself oversized:\n{}",
        oversized.join("\n")
    );

    let tangled = named(STRUCTURE_COMPLEX_FUNCTION.id);
    assert!(
        tangled.is_empty(),
        "the crate reports its own complexity hotspots:\n{}",
        tangled.join("\n")
    );
}

/// A family every member of which is test material is never published as
/// production, on this repository's own source.
///
/// Separate from the hotspot gate above, which asks a different question of a
/// different population: that one filters on `src/` and names two rules, this
/// one reads every finding the pass publishes and asks what context it carries.
///
/// The structural pass is where the whole population lives. It is the only
/// producer whose finding spans several files, so it is the only one that can
/// straddle a test file and a shipped one, and it is the only one that reads
/// every enumerated file: the scan runs `cargo clippy --workspace` without
/// `--all-targets`, so no Clippy diagnostic is ever raised inside a
/// `#[cfg(test)]` module.
///
/// `src/cargo_health/tests.rs` and `tests/cargo_health_product_proof.rs` are
/// what this froze. The two carry one near-duplicate family, the second is an
/// integration test target Cargo names, and the first was reached only through
/// `#[cfg(test)] mod tests;`, which nothing read: the family straddled a test
/// context and a production one, abstained, and the tool charged itself for a
/// duplication between two test files.
#[test]
fn no_finding_of_this_crate_s_own_test_code_is_published_as_production() {
    let metadata = repository();
    let scan = analyze(
        &metadata,
        &enumerate(&metadata),
        &PolicyPlan::default(),
        &StructureSettings::default(),
    );

    /// Is this path test material by its position alone? Read here from the
    /// path and nowhere else, so the assertion cannot agree with the scan by
    /// asking the scan.
    fn is_test_path(path: &str) -> bool {
        let mut components = path.split('/').collect::<Vec<_>>();
        let file = components.pop().unwrap_or_default();
        components
            .iter()
            .any(|component| matches!(*component, "tests" | "benches" | "examples"))
            || file == "tests.rs"
    }

    let misfiled: Vec<String> = scan
        .findings
        .iter()
        .filter(|finding| finding.context.is_none())
        .filter(|finding| {
            is_test_path(&finding.path)
                && finding
                    .related
                    .iter()
                    .all(|member| is_test_path(&member.path))
        })
        .map(|finding| {
            let members: Vec<&str> = std::iter::once(finding.path.as_str())
                .chain(finding.related.iter().map(|member| member.path.as_str()))
                .collect();
            format!("{}: {}", finding.definition.id, members.join(", "))
        })
        .collect();

    assert!(
        misfiled.is_empty(),
        "the crate charges itself for findings that are entirely test code:\n{}",
        misfiled.join("\n")
    );
}

/// The pass no longer names its own root as oversized: extracting the
/// suppression rules and the benchmark is what took it back under the bound
/// it publishes.
#[test]
fn the_pass_holds_its_own_size_bound() {
    for own in [
        include_str!("../structure.rs"),
        include_str!("benchmark.rs"),
        include_str!("duplication.rs"),
        include_str!("duplication/tests.rs"),
        include_str!("hotspots.rs"),
        include_str!("manifest.rs"),
        include_str!("normalize.rs"),
        include_str!("suppression.rs"),
        include_str!("tests.rs"),
    ] {
        let lines = own.lines().count();
        assert!(
            lines < hotspots::FILE_LINES,
            "a file of the structural pass is {lines} lines long, over the {} it reports",
            hotspots::FILE_LINES
        );
    }
}