pmat 3.29.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
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
//! Dead Code Analysis Handler
//!
//! Extracted from complexity_handlers.rs for file health compliance (CB-040).
//! Contains dead code analysis handler and all related helper functions.
//!
//! Submodule layout (include! pattern):
//! - dead_code_handlers_analysis.rs: Core analysis logic and cargo integration
//! - dead_code_handlers_output.rs: Output formatting (JSON, SARIF, summary, markdown)

#![cfg_attr(coverage_nightly, coverage(off))]
use crate::cli::DeadCodeOutputFormat;
use anyhow::Result;
use std::path::{Path, PathBuf};

/// Configuration for dead code analysis
#[allow(clippy::too_many_arguments)]
struct DeadCodeAnalysisFilters {
    include_unreachable: bool,
    include_tests: bool,
    min_dead_lines: usize,
    top_files: Option<usize>,
    include: Vec<String>,
    exclude: Vec<String>,
    max_depth: usize,
}

/// Handle dead code analysis command - REFACTORED
/// Cognitive complexity reduced from 244 to ~10
#[allow(clippy::too_many_arguments)]
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_analyze_dead_code(
    path: PathBuf,
    format: DeadCodeOutputFormat,
    top_files: Option<usize>,
    include_unreachable: bool,
    min_dead_lines: usize,
    include_tests: bool,
    output: Option<PathBuf>,
    fail_on_violation: bool,
    max_percentage: f64,
    timeout: u64,
    include: Vec<String>,
    exclude: Vec<String>,
    max_depth: usize,
) -> Result<()> {
    eprintln!("☠️ Analyzing dead code in project...");
    eprintln!("⏰ Analysis timeout set to {timeout} seconds");

    // Apply include/exclude filters if specified
    if !include.is_empty() || !exclude.is_empty() {
        eprintln!("🔍 Applying file filters...");
        if !include.is_empty() {
            eprintln!("  Include patterns: {include:?}");
        }
        if !exclude.is_empty() {
            eprintln!("  Exclude patterns: {exclude:?}");
        }
    }

    // Run analysis with timeout
    let timeout_duration = tokio::time::Duration::from_secs(timeout);
    let result = tokio::time::timeout(timeout_duration, async {
        run_dead_code_analysis_with_filters(
            &path,
            DeadCodeAnalysisFilters {
                include_unreachable,
                include_tests,
                min_dead_lines,
                top_files,
                include,
                exclude,
                max_depth,
            },
        )
        .await
    })
    .await
    .map_err(|_| anyhow::anyhow!("Dead code analysis timed out after {timeout} seconds"))??;

    eprintln!(
        "📊 Analysis complete: {} files analyzed, {} with dead code",
        result.summary.total_files_analyzed, result.summary.files_with_dead_code
    );

    // Format output
    let formatted_output = format_dead_code_result(&result, &format)?;

    // Write output
    write_dead_code_output(formatted_output, output).await?;

    // Check for violations and exit with error code if requested
    if fail_on_violation {
        let dead_code_percentage = result.summary.dead_percentage;
        if dead_code_percentage > max_percentage as f32 {
            eprintln!(
                "\n❌ Dead code violations found: {dead_code_percentage:.1}% exceeds threshold of {max_percentage:.1}%"
            );
            std::process::exit(1);
        }
    }

    Ok(())
}

// --- Submodule includes ---

include!("dead_code_handlers_analysis.rs");
include!("dead_code_handlers_output.rs");

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod output_tests {
    //! Covers format_dead_code_* + write_*_section helpers in
    //! dead_code_handlers_output.rs (315 uncov on broad, 0% cov).
    //! The async write_dead_code_output is skipped (requires fs/IO setup).
    use super::*;
    use crate::models::dead_code::{
        ConfidenceLevel, DeadCodeItem, DeadCodeResult, DeadCodeSummary, DeadCodeType,
        FileDeadCodeMetrics,
    };

    fn item(ty: DeadCodeType, line: u32, name: &str, reason: &str) -> DeadCodeItem {
        DeadCodeItem {
            item_type: ty,
            name: name.to_string(),
            line,
            reason: reason.to_string(),
        }
    }

    fn file(path: &str, conf: ConfidenceLevel, items: Vec<DeadCodeItem>) -> FileDeadCodeMetrics {
        FileDeadCodeMetrics {
            path: path.to_string(),
            dead_lines: 10,
            total_lines: 100,
            dead_percentage: 10.0,
            dead_functions: 1,
            dead_classes: 0,
            dead_modules: 0,
            unreachable_blocks: 0,
            dead_score: 0.0,
            confidence: conf,
            items,
        }
    }

    fn empty_summary() -> DeadCodeSummary {
        DeadCodeSummary {
            total_files_analyzed: 5,
            files_with_dead_code: 0,
            total_dead_lines: 0,
            dead_percentage: 0.0,
            dead_functions: 0,
            dead_classes: 0,
            dead_modules: 0,
            unreachable_blocks: 0,
        }
    }

    fn full_summary() -> DeadCodeSummary {
        DeadCodeSummary {
            total_files_analyzed: 5,
            files_with_dead_code: 2,
            total_dead_lines: 20,
            dead_percentage: 12.0,
            dead_functions: 3,
            dead_classes: 2,
            dead_modules: 1,
            unreachable_blocks: 4,
        }
    }

    fn populated_result() -> DeadCodeResult {
        DeadCodeResult {
            summary: full_summary(),
            files: vec![
                file(
                    "src/a.rs",
                    ConfidenceLevel::High,
                    vec![
                        item(DeadCodeType::Function, 10, "f", "no callers"),
                        item(DeadCodeType::Class, 20, "C", "unused"),
                    ],
                ),
                file(
                    "src/b.rs",
                    ConfidenceLevel::Medium,
                    vec![item(DeadCodeType::Variable, 5, "x", "never read")],
                ),
                file(
                    "src/c.rs",
                    ConfidenceLevel::Low,
                    vec![item(
                        DeadCodeType::UnreachableCode,
                        99,
                        "block",
                        "after panic",
                    )],
                ),
            ],
            total_files: 5,
            analyzed_files: 5,
            files_with_dead_code_found: 2,
            files_truncated: false,
        }
    }

    fn empty_result() -> DeadCodeResult {
        DeadCodeResult {
            summary: empty_summary(),
            files: vec![],
            total_files: 5,
            analyzed_files: 5,
            files_with_dead_code_found: 2,
            files_truncated: false,
        }
    }

    // ── format_dead_code_result dispatcher ──

    #[test]
    fn test_format_dispatcher_json_arm() {
        let r = format_dead_code_result(&empty_result(), &DeadCodeOutputFormat::Json).unwrap();
        // serde_json output is non-empty even for empty data.
        assert!(r.contains("summary") || r.contains("files"));
    }

    #[test]
    fn test_format_dispatcher_sarif_arm() {
        let r = format_dead_code_result(&populated_result(), &DeadCodeOutputFormat::Sarif).unwrap();
        assert!(r.contains("\"version\": \"2.1.0\""));
        assert!(r.contains("dead-code"));
    }

    #[test]
    fn test_format_dispatcher_summary_arm() {
        let r =
            format_dead_code_result(&populated_result(), &DeadCodeOutputFormat::Summary).unwrap();
        assert!(!r.is_empty());
    }

    #[test]
    fn test_format_dispatcher_markdown_arm() {
        let r =
            format_dead_code_result(&populated_result(), &DeadCodeOutputFormat::Markdown).unwrap();
        assert!(r.contains("# Dead Code Analysis Report"));
    }

    // ── format_dead_code_as_sarif: confidence + item type arms ──

    #[test]
    fn test_sarif_levels_for_each_confidence() {
        // High → "error", Medium → "warning", Low → "note".
        let r = format_dead_code_as_sarif(&populated_result()).unwrap();
        assert!(r.contains("\"error\""));
        assert!(r.contains("\"warning\""));
        assert!(r.contains("\"note\""));
    }

    #[test]
    fn test_sarif_message_for_each_dead_code_type() {
        // Function/Class/Variable/UnreachableCode label arms.
        let r = format_dead_code_as_sarif(&populated_result()).unwrap();
        assert!(r.contains("Dead function"));
        assert!(r.contains("Dead class"));
        assert!(r.contains("Dead variable"));
        assert!(r.contains("Unreachable code"));
    }

    #[test]
    fn test_sarif_empty_files_yields_empty_results_array() {
        let r = format_dead_code_as_sarif(&empty_result()).unwrap();
        assert!(r.contains("\"results\": []"));
    }

    // ── format_dead_code_as_summary: branch arms ──

    #[test]
    fn test_summary_with_dead_functions_emits_breakdown_section() {
        let r = format_dead_code_as_summary(&populated_result()).unwrap();
        assert!(r.contains("Dead Code by Type"));
        assert!(r.contains("Top Files"));
    }

    #[test]
    /// UPDATED in round 3: this asserted that the breakdown is skipped whenever
    /// `dead_functions == 0`, which hid it exactly when it was needed — on the
    /// real repo every dead item was a field, so 26 dead lines were reported
    /// with no types at all. Dead code that is not a function is still dead
    /// code, and it now has a row of its own.
    fn test_summary_without_dead_functions_still_breaks_down_by_type() {
        let mut res = populated_result();
        res.summary.dead_functions = 0;
        let r = format_dead_code_as_summary(&res).unwrap();
        assert!(r.contains("Dead Code by Type"));
        assert!(r.contains("Other (fields, constants, statics):"));
        // Top Files still emitted (files non-empty).
        assert!(r.contains("Top Files"));
    }

    #[test]
    fn test_summary_empty_files_skips_top_files_section() {
        let r = format_dead_code_as_summary(&empty_result()).unwrap();
        assert!(!r.contains("Top Files"));
    }

    // ── format_dead_code_as_markdown: section gating ──

    #[test]
    fn test_markdown_with_full_data_emits_all_sections() {
        let r = format_dead_code_as_markdown(&populated_result()).unwrap();
        assert!(r.contains("# Dead Code Analysis Report"));
        assert!(r.contains("## Summary"));
        assert!(r.contains("## Dead Code Breakdown"));
        assert!(r.contains("## File Details"));
        assert!(r.contains("## Recommendations"));
    }

    #[test]
    fn test_markdown_empty_skips_breakdown_and_files() {
        let r = format_dead_code_as_markdown(&empty_result()).unwrap();
        // Always includes summary + recommendations.
        assert!(r.contains("## Summary"));
        assert!(r.contains("## Recommendations"));
        // Skipped when dead_functions == 0 and files empty.
        assert!(!r.contains("## Dead Code Breakdown"));
        assert!(!r.contains("## File Details"));
    }

    #[test]
    fn test_markdown_file_details_section_takes_first_20_files() {
        let mut res = populated_result();
        // Bloat to 30 files; details section caps at 20.
        for i in 0..30 {
            res.files.push(file(
                &format!("src/extra-{i}.rs"),
                ConfidenceLevel::High,
                vec![],
            ));
        }
        let r = format_dead_code_as_markdown(&res).unwrap();
        // First file always included.
        assert!(r.contains("src/a.rs"));
        // 20-cap means "src/extra-29.rs" must NOT appear.
        assert!(!r.contains("src/extra-29.rs"));
    }

    #[test]
    fn test_summary_top_files_section_takes_first_10_files() {
        let mut res = populated_result();
        for i in 0..15 {
            res.files.push(file(
                &format!("src/extra-{i}.rs"),
                ConfidenceLevel::High,
                vec![],
            ));
        }
        let r = format_dead_code_as_summary(&res).unwrap();
        // 10-file cap → extra-14 must NOT appear.
        assert!(!r.contains("src/extra-14.rs"));
    }

    #[test]
    fn test_recommendations_section_is_static_text() {
        // Pure static-text helper; no inputs.
        let r = format_dead_code_recommendations_section();
        assert!(r.contains("## Recommendations"));
        assert!(r.contains("High Confidence Dead Code"));
        assert!(r.contains("Test Coverage"));
    }

    // ── round 3: measured line counts and self-consistent summaries ─────────

    use crate::services::cargo_dead_code_analyzer::{
        DeadCodeKind, DeadItem, FileDeadCode as CargoFileDeadCode,
    };

    fn cargo_item(name: &str, kind: DeadCodeKind, line: usize) -> DeadItem {
        DeadItem {
            name: name.to_string(),
            kind,
            line,
            column: 1,
            message: format!("`{name}` is never used"),
        }
    }

    /// Observed on the real repo: every listed file reported `total_lines: 100`
    /// — a 370-line file, a 503-line file and a 1287-line file alike — next to
    /// a `dead_percentage` computed from the REAL count, so the two disagreed
    /// by up to 13x (dead_lines 24 / total_lines 100 printed as 6.49%).
    #[test]
    fn test_per_file_total_lines_is_the_measured_count() {
        let files = vec![
            CargoFileDeadCode {
                file_path: std::path::PathBuf::from("src/big.rs"),
                dead_items: vec![
                    cargo_item("f", DeadCodeKind::Function, 10),
                    cargo_item("S", DeadCodeKind::Struct, 20),
                ],
                file_dead_percentage: 8.0 / 370.0 * 100.0,
                total_lines: Some(370),
            },
            CargoFileDeadCode {
                file_path: std::path::PathBuf::from("src/small.rs"),
                dead_items: vec![cargo_item("g", DeadCodeKind::Function, 3)],
                file_dead_percentage: 5.0 / 20.0 * 100.0,
                total_lines: Some(20),
            },
        ];

        let metrics = convert_cargo_files_to_metrics(files, 0);

        assert_eq!(metrics.len(), 2);
        let by_path = |name: &str| {
            metrics
                .iter()
                .find(|m| m.path.ends_with(name))
                .unwrap_or_else(|| panic!("{name} missing"))
        };
        let big = by_path("big.rs");
        let small = by_path("small.rs");
        assert_eq!(big.total_lines, 370, "the constant 100 is the bug");
        assert_eq!(small.total_lines, 20);
        assert_ne!(
            big.total_lines, small.total_lines,
            "two files of different length cannot share one line count"
        );
        // dead_lines uses the shared estimator: 5 (fn) + 3 (struct) = 8.
        assert_eq!(big.dead_lines, 8);
        assert_eq!(small.dead_lines, 5);
        // The percentage beside it must be that ratio, not a different one.
        let expected = 8.0 / 370.0 * 100.0;
        assert!(
            (big.dead_percentage - expected).abs() < 0.01,
            "dead_percentage {} does not match dead_lines/total_lines {expected}",
            big.dead_percentage
        );
        // Items are carried, so the counts above are checkable.
        assert_eq!(big.items.len(), 2);
    }

    /// Observed on the real repo: `summary.files_with_dead_code: 26` above a
    /// 4-entry `files` array (and `1` above an EMPTY array on a fixture), with
    /// `total_dead_lines: 94` while the rows summed to 76.
    #[test]
    fn test_summary_agrees_with_the_list_it_heads() {
        let listed = vec![
            file("src/a.rs", ConfidenceLevel::High, vec![]),
            file("src/b.rs", ConfidenceLevel::High, vec![]),
        ];
        let mut summary = DeadCodeSummary {
            total_files_analyzed: 4257,
            files_with_dead_code: 26, // the pre-fix value
            total_dead_lines: 94,     // from a different estimator
            dead_percentage: 9.9,
            dead_functions: 11,
            dead_classes: 5,
            dead_modules: 2,
            unreachable_blocks: 0,
        };

        resummarize_from_listed_files(&mut summary, &listed, 10_000);

        assert_eq!(summary.files_with_dead_code, listed.len());
        assert_eq!(
            summary.total_dead_lines,
            listed.iter().map(|f| f.dead_lines).sum::<usize>()
        );
        assert_eq!(
            summary.dead_functions,
            listed.iter().map(|f| f.dead_functions).sum::<usize>()
        );
        // percentage = listed dead lines / project lines, and never above 100.
        assert!((summary.dead_percentage - 0.2).abs() < 1e-4);
        assert!(summary.dead_percentage <= 100.0);
    }

    /// An empty list must summarise as zeros, not as the pre-filter counts.
    #[test]
    fn test_empty_list_summarises_as_empty() {
        let mut summary = DeadCodeSummary {
            total_files_analyzed: 10,
            files_with_dead_code: 1,
            total_dead_lines: 40,
            dead_percentage: 4.0,
            dead_functions: 2,
            dead_classes: 0,
            dead_modules: 0,
            unreachable_blocks: 0,
        };

        resummarize_from_listed_files(&mut summary, &[], 1000);

        assert_eq!(summary.files_with_dead_code, 0);
        assert_eq!(summary.total_dead_lines, 0);
        assert_eq!(summary.dead_percentage, 0.0);
    }
}