cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
//! Fast-Tier orchestration shared by the bare combined run and its tests.
//!
//! The phase boundaries are intentional: they are the same lifecycle exposed
//! through `cargo judge --progress PATH`, while each phase owns only the
//! findings and analysis errors it contributes.

use crate::*;

use super::combined;

pub(crate) struct CollectedFindings {
    pub(crate) findings: Vec<Finding>,
    pub(crate) analysis_errors: Vec<String>,
    pub(crate) rule_revisions: std::collections::HashMap<String, u32>,
    pub(crate) boundary_rules_checked: usize,
    pub(crate) boundaries_config_path: PathBuf,
    /// How many findings an inline `// judge-ignore: <rule> — <reason>`
    /// comment dropped (see [`judge::suppression::apply_inline_suppressions`]).
    pub(crate) suppressed_inline: usize,
}

/// Runs every default current-state detector (complexity, duplication,
/// dependency hygiene, and structural checks) plus boundaries if a
/// `judge.toml` exists, and merges their findings. This is deliberately
/// *not* the numeric 0-100 health score from §4 — that needs crate-type
/// profiles and a weighting scheme that don't exist yet; merging findings
/// doesn't require either. Findings are returned unsorted; callers that show
/// them worst-first must sort explicitly (see [`judge::finding::sort_by_severity_desc`]).
pub(crate) fn collect_findings(
    workspace: &judge::ingest::Workspace,
) -> Result<CollectedFindings, CliError> {
    collect_findings_with_progress(workspace, &mut |_| Ok(()))
}

/// Same analysis as [`collect_findings`], with lifecycle events at the
/// natural Fast-Tier phase boundaries. The observer is optional to callers:
/// tests keep a simple wrapper above,
/// while the bare combined command can expose live progress separately from
/// its final stdout report.
pub(crate) fn collect_findings_with_progress(
    workspace: &judge::ingest::Workspace,
    progress: &mut dyn FnMut(combined::ProgressEvent) -> Result<(), CliError>,
) -> Result<CollectedFindings, CliError> {
    let mut findings = Vec::new();
    let mut analysis_errors = Vec::new();
    let mut rule_revisions = default_rule_revisions();

    progress(combined::ProgressEvent::started("complexity"))?;
    collect_complexity_and_history(workspace, &mut findings, &mut analysis_errors);
    progress(combined::ProgressEvent::completed("complexity"))?;

    progress(combined::ProgressEvent::started("slop"))?;
    collect_slop(workspace, &mut findings, &mut analysis_errors)?;
    progress(combined::ProgressEvent::completed("slop"))?;

    progress(combined::ProgressEvent::started("duplication"))?;
    collect_duplication(workspace, &mut findings, &mut analysis_errors);
    progress(combined::ProgressEvent::completed("duplication"))?;

    progress(combined::ProgressEvent::started("structural"))?;
    collect_structural(workspace, &mut findings);
    progress(combined::ProgressEvent::completed("structural"))?;

    progress(combined::ProgressEvent::started("security"))?;
    collect_security(workspace, &mut findings, &mut analysis_errors, false);
    progress(combined::ProgressEvent::completed("security"))?;

    progress(combined::ProgressEvent::started("dependencies"))?;
    collect_dependencies(workspace, &mut findings, &mut analysis_errors);
    progress(combined::ProgressEvent::completed("dependencies"))?;

    progress(combined::ProgressEvent::started("boundaries"))?;
    let (boundaries_config_path, boundary_rules_checked) = collect_boundaries(
        workspace,
        &mut findings,
        &mut analysis_errors,
        &mut rule_revisions,
    )?;
    progress(combined::ProgressEvent::completed("boundaries"))?;

    progress(combined::ProgressEvent::started("suppression"))?;
    let (findings, suppressed_inline) = collect_suppression(workspace, findings)?;
    progress(combined::ProgressEvent::completed("suppression"))?;

    Ok(CollectedFindings {
        findings,
        analysis_errors,
        rule_revisions,
        boundary_rules_checked,
        boundaries_config_path,
        suppressed_inline,
    })
}

fn default_rule_revisions() -> std::collections::HashMap<String, u32> {
    let mut revisions = deps_rule_revisions();
    revisions.insert(
        judge::rules::duplication::DUPLICATE_RULE.to_string(),
        judge::rules::duplication::DUPLICATE_RULE_REVISION,
    );
    revisions.extend(slop_structural_security_rule_revisions());
    revisions.insert(
        judge::rules::complexity::MAINTAINABILITY_INDEX_RULE.to_string(),
        judge::rules::complexity::MAINTAINABILITY_INDEX_RULE_REVISION,
    );
    revisions
}

/// The two `[[boundary]]`-gated rule revisions, shared between `run_boundaries`'s
/// own baseline map (see `analysis_commands::run_boundaries`, which layers
/// its Fast-Tier-only `module-boundary-violation` entry and, in a `--features
/// deep` build, the Deep-Tier upgrade rule on top) and this module's
/// `collect_boundaries`, which only ever needs these two — mirroring
/// `deps_rule_revisions`'s same "both build this identical static core"
/// precedent.
pub(crate) fn boundaries_rule_revisions() -> std::collections::HashMap<String, u32> {
    std::collections::HashMap::from([
        (
            judge::rules::boundaries::BOUNDARY_VIOLATION_RULE.to_string(),
            judge::rules::boundaries::BOUNDARY_VIOLATION_RULE_REVISION,
        ),
        (
            judge::rules::boundaries::DEPENDENCY_CYCLE_RULE.to_string(),
            judge::rules::boundaries::DEPENDENCY_CYCLE_RULE_REVISION,
        ),
    ])
}

/// Dependency-hygiene and dependency-graph rule revisions, plus the one G5
/// slopsquatting rule that's fully local and always on
/// (`name-collision-risk`). Shared between this module's own default map and
/// `run_deps`'s baseline map (see `analysis_commands::run_deps`) — both build
/// this identical static core before `run_deps` layers its
/// `--check-crates-io`/`--check-rustc-lints`/`--audit-json` opt-in extras on
/// top.
pub(crate) fn deps_rule_revisions() -> std::collections::HashMap<String, u32> {
    std::collections::HashMap::from([
        (
            judge::rules::deps::MISPLACED_DEPENDENCY_KIND_RULE.to_string(),
            judge::rules::deps::MISPLACED_DEPENDENCY_KIND_RULE_REVISION,
        ),
        (
            judge::rules::deps::UNUSED_DEV_DEPENDENCY_RULE.to_string(),
            judge::rules::deps::UNUSED_DEV_DEPENDENCY_RULE_REVISION,
        ),
        (
            judge::rules::deps::HEAVY_DEPENDENCY_RULE.to_string(),
            judge::rules::deps::HEAVY_DEPENDENCY_RULE_REVISION,
        ),
        (
            judge::rules::deps::UNUSED_FEATURE_FLAG_RULE.to_string(),
            judge::rules::deps::UNUSED_FEATURE_FLAG_RULE_REVISION,
        ),
        (
            judge::rules::deps::DEFAULT_FEATURES_UNUSED_RULE.to_string(),
            judge::rules::deps::DEFAULT_FEATURES_UNUSED_RULE_REVISION,
        ),
        (
            judge::rules::deps::UNUSED_FEATURE_RULE.to_string(),
            judge::rules::deps::UNUSED_FEATURE_RULE_REVISION,
        ),
        (
            judge::rules::deps::DEP_WITHOUT_REPO_RULE.to_string(),
            judge::rules::deps::DEP_WITHOUT_REPO_RULE_REVISION,
        ),
        (
            judge::rules::dep_graph::DUPLICATE_CRATE_VERSIONS_RULE.to_string(),
            judge::rules::dep_graph::DUPLICATE_CRATE_VERSIONS_RULE_REVISION,
        ),
        (
            judge::rules::dep_graph::MSRV_DRIFT_RULE.to_string(),
            judge::rules::dep_graph::MSRV_DRIFT_RULE_REVISION,
        ),
        (
            judge::rules::dep_graph::WORKSPACE_DEP_DRIFT_RULE.to_string(),
            judge::rules::dep_graph::WORKSPACE_DEP_DRIFT_RULE_REVISION,
        ),
        (
            judge::rules::slopsquat::NAME_COLLISION_RISK_RULE.to_string(),
            judge::rules::slopsquat::NAME_COLLISION_RISK_RULE_REVISION,
        ),
    ])
}

/// AI-slop, G4 structural, and security rule revisions. Shared between this
/// module's own default map and `cargo judge health`'s `--save-baseline`/
/// `--baseline` map (see `health_command::run`) — both commands compute these
/// findings identically over the whole workspace.
pub(crate) fn slop_structural_security_rule_revisions() -> std::collections::HashMap<String, u32> {
    std::collections::HashMap::from([
        (
            judge::rules::slop::SWALLOWED_RESULT_RULE.to_string(),
            judge::rules::slop::SWALLOWED_RESULT_RULE_REVISION,
        ),
        (
            judge::rules::slop::EMPTY_ERROR_ARM_RULE.to_string(),
            judge::rules::slop::EMPTY_ERROR_ARM_RULE_REVISION,
        ),
        (
            judge::rules::slop::CATCH_ALL_ERROR_RULE.to_string(),
            judge::rules::slop::CATCH_ALL_ERROR_RULE_REVISION,
        ),
        (
            judge::rules::slop::SUPPRESSION_DEBT_RULE.to_string(),
            judge::rules::slop::SUPPRESSION_DEBT_RULE_REVISION,
        ),
        (
            judge::rules::slop::MERGED_STUB_RULE.to_string(),
            judge::rules::slop::MERGED_STUB_RULE_REVISION,
        ),
        (
            judge::rules::slop::EMPTY_IMPL_RULE.to_string(),
            judge::rules::slop::EMPTY_IMPL_RULE_REVISION,
        ),
        (
            judge::rules::slop::ASSERTION_FREE_TEST_RULE.to_string(),
            judge::rules::slop::ASSERTION_FREE_TEST_RULE_REVISION,
        ),
        (
            judge::rules::slop::TAUTOLOGICAL_TEST_RULE.to_string(),
            judge::rules::slop::TAUTOLOGICAL_TEST_RULE_REVISION,
        ),
        (
            judge::rules::slop::IGNORED_TEST_ACCUMULATION_RULE.to_string(),
            judge::rules::slop::IGNORED_TEST_ACCUMULATION_RULE_REVISION,
        ),
        (
            judge::rules::slop::CONVERSATIONAL_ARTIFACT_RULE.to_string(),
            judge::rules::slop::CONVERSATIONAL_ARTIFACT_RULE_REVISION,
        ),
        (
            judge::rules::slop::RESTATING_COMMENT_RULE.to_string(),
            judge::rules::slop::RESTATING_COMMENT_RULE_REVISION,
        ),
        (
            judge::rules::slop::STEP_COMMENT_INFLATION_RULE.to_string(),
            judge::rules::slop::STEP_COMMENT_INFLATION_RULE_REVISION,
        ),
        (
            judge::rules::slop::GENERIC_NAMING_RULE.to_string(),
            judge::rules::slop::GENERIC_NAMING_RULE_REVISION,
        ),
        (
            judge::rules::slop::DOC_RESTATES_SIGNATURE_RULE.to_string(),
            judge::rules::slop::DOC_RESTATES_SIGNATURE_RULE_REVISION,
        ),
        (
            judge::rules::slop_structural::COMPLEXITY_INFLATION_RULE.to_string(),
            judge::rules::slop_structural::COMPLEXITY_INFLATION_RULE_REVISION,
        ),
        (
            judge::rules::complexity::SIGNATURE_COMPLEXITY_RULE.to_string(),
            judge::rules::complexity::SIGNATURE_COMPLEXITY_RULE_REVISION,
        ),
        (
            judge::rules::slop_structural::ABSTRACTION_INFLATION_RULE.to_string(),
            judge::rules::slop_structural::ABSTRACTION_INFLATION_RULE_REVISION,
        ),
        (
            judge::rules::slop_structural::FRAGILE_SUBSTRING_CLASSIFICATION_RULE.to_string(),
            judge::rules::slop_structural::FRAGILE_SUBSTRING_CLASSIFICATION_RULE_REVISION,
        ),
        (
            judge::rules::security::UNSAFE_SURFACE_RULE.to_string(),
            judge::rules::security::UNSAFE_SURFACE_RULE_REVISION,
        ),
        (
            judge::rules::security::UNSAFE_DENSITY_RULE.to_string(),
            judge::rules::security::UNSAFE_DENSITY_RULE_REVISION,
        ),
        (
            judge::rules::security::INTEGER_CAST_RISK_RULE.to_string(),
            judge::rules::security::INTEGER_CAST_RISK_RULE_REVISION,
        ),
        (
            judge::rules::security::PANIC_IN_LIB_RULE.to_string(),
            judge::rules::security::PANIC_IN_LIB_RULE_REVISION,
        ),
        (
            judge::rules::security::HARDCODED_SECRET_RULE.to_string(),
            judge::rules::security::HARDCODED_SECRET_RULE_REVISION,
        ),
    ])
}

fn collect_complexity_and_history(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
) {
    let complexity_source_files = super::analysis_commands::workspace_source_files(workspace);
    let complexity = judge::rules::complexity::analyze_workspace(complexity_source_files, false);
    append_analysis_errors(analysis_errors, &complexity.errors);
    findings.extend(judge::rules::slop_structural::complexity_inflation(
        &complexity.functions,
    ));
    findings.extend(judge::rules::complexity::signature_complexity(
        &complexity.functions,
    ));
    findings.extend(judge::rules::complexity::maintainability_index(
        &complexity.functions,
    ));
}

fn collect_slop(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
) -> Result<(), CliError> {
    let slop = super::analysis_commands::analyze_slop_workspace(workspace, false)?;
    append_analysis_errors(analysis_errors, &slop.errors);
    findings.extend(slop.findings);
    Ok(())
}

fn collect_duplication(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
) {
    let dupes_source_files = super::analysis_commands::workspace_source_files(workspace);
    let dupes = judge::rules::duplication::analyze_workspace_with_options(
        dupes_source_files,
        DupeMode::Mild,
        judge::rules::duplication::DEFAULT_MIN_TOKENS,
        false,
        false,
    );
    append_analysis_errors(analysis_errors, &dupes.errors);
    findings.extend(dupes.to_findings());
}

/// G4 structural slop (see todo.md §3.G). Shared with `cargo judge health`
/// (see `health_command::run`), which computes these same two findings sets
/// over the same whole-workspace scope.
pub(crate) fn collect_structural(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
) {
    let abstraction_source_files = super::analysis_commands::workspace_source_files(workspace);
    findings.extend(judge::rules::slop_structural::analyze_workspace_structural(
        abstraction_source_files,
    ));

    let fragile_substring_source_files =
        super::analysis_commands::workspace_source_files(workspace);
    findings.extend(
        judge::rules::slop_structural::fragile_substring_classification(
            fragile_substring_source_files,
        ),
    );
}

/// Shared with `cargo judge health` (see `health_command::run`), which needs
/// `include_generated` to be a parameter rather than always-off, and needs
/// the excluded-generated count back to fold into its own total; the bare
/// combined run ignores both (bare `cargo judge`/`audit` never expose
/// `--include-generated`, so this collector's own call site below always
/// passes `false` and drops the returned count).
pub(crate) fn collect_security(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
    include_generated: bool,
) -> usize {
    let security_source_files = super::analysis_commands::workspace_source_files(workspace);
    let security =
        judge::rules::security::analyze_workspace(security_source_files, include_generated);
    append_analysis_errors(analysis_errors, &security.errors);
    findings.extend(security.findings);
    security.excluded_generated
}

fn collect_dependencies(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
) {
    let deps = judge::rules::deps::analyze_workspace(workspace);
    append_analysis_errors(analysis_errors, &deps.errors);
    findings.extend(deps.findings);

    let dep_graph = judge::rules::dep_graph::analyze_workspace(workspace);
    append_analysis_errors(analysis_errors, &dep_graph.errors);
    findings.extend(dep_graph.findings);

    // `name-collision-risk` is fully local (no network), so it runs in the
    // combined bare `cargo judge`/`audit` pass too. The other three G5
    // rules (`phantom-crate`/`phantom-version`/`fresh-low-reputation-dep`)
    // need real crates.io network access and are opt-in only via
    // `cargo judge deps --check-crates-io` (see `run_deps`).
    findings.extend(judge::rules::slopsquat::analyze_name_collision(workspace));
}

fn collect_boundaries(
    workspace: &judge::ingest::Workspace,
    findings: &mut Vec<Finding>,
    analysis_errors: &mut Vec<String>,
    rule_revisions: &mut std::collections::HashMap<String, u32>,
) -> Result<(PathBuf, usize), CliError> {
    let boundaries_config_path = workspace.root.join("judge.toml");
    let mut boundary_rules_checked = 0;
    if boundaries_config_path.exists() {
        let config = parse_boundary_config(&boundaries_config_path)?;
        boundary_rules_checked = config.boundaries.len();
        let evaluated = judge::rules::boundaries::evaluate(workspace, &config)?;
        findings.extend(evaluated.findings);
        rule_revisions.extend(boundaries_rule_revisions());
    }

    // `feature-graph-cycle` is always-on, unlike the `judge.toml`-gated
    // boundary rules above — see `judge::rules::boundaries` module docs
    // "`feature-graph-cycle`" for why: a `[features]` table is either
    // cyclic or it isn't, a fact needing no project-intent config to
    // interpret.
    let feature_graph_manifest = workspace.root.join("Cargo.toml");
    match judge::rules::boundaries::feature_graph_cycles(Some(&feature_graph_manifest)) {
        Ok(cycle_findings) => {
            findings.extend(cycle_findings);
            rule_revisions.insert(
                judge::rules::boundaries::FEATURE_GRAPH_CYCLE_RULE.to_string(),
                judge::rules::boundaries::FEATURE_GRAPH_CYCLE_RULE_REVISION,
            );
        }
        Err(err) => analysis_errors.push(err.to_string()),
    }
    Ok((boundaries_config_path, boundary_rules_checked))
}

fn collect_suppression(
    workspace: &judge::ingest::Workspace,
    findings: Vec<Finding>,
) -> Result<(Vec<Finding>, usize), CliError> {
    let (findings, suppressed_inline) =
        judge::suppression::apply_inline_suppressions(findings, &workspace.root)?;
    Ok((findings, suppressed_inline))
}