debtmap 0.17.0

Code complexity and technical debt analyzer
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
use debtmap::complexity::if_else_analyzer::IfElseChainAnalyzer;
use debtmap::complexity::if_else_analyzer::RefactoringPattern;
use debtmap::complexity::message_generator::{
    format_enhanced_message, generate_enhanced_message, ActionableRecommendation,
    ComplexityBreakdown, ComplexityDetail, ComplexityIssueType, EnhancedComplexityMessage,
    EstimatedEffort, RefactoringExample, Severity, SourceLocation,
};
use debtmap::complexity::recursive_detector::RecursiveMatchDetector;
use debtmap::complexity::threshold_manager::{ComplexityThresholds, FunctionRole, ThresholdPreset};
use debtmap::core::FunctionMetrics;
use std::path::PathBuf;

#[test]
fn test_recursive_match_detection() {
    let code = r#"
        fn process_data(value: Option<u32>) -> u32 {
            match value {
                Some(v) => {
                    // Nested match inside closure
                    let result = (0..10).filter_map(|i| {
                        match i {
                            0..=3 => Some(i * 2),
                            4..=6 => Some(i * 3),
                            _ => None,
                        }
                    }).sum();
                    
                    // Another nested match in async block
                    let async_result = async {
                        match v {
                            0..=10 => 1,
                            11..=20 => 2,
                            _ => 3,
                        }
                    };
                    
                    result
                }
                None => 0,
            }
        }
    "#;

    let file = syn::parse_str::<syn::File>(code).unwrap();
    let func = match &file.items[0] {
        syn::Item::Fn(f) => f,
        _ => panic!("Expected function"),
    };

    let mut detector = RecursiveMatchDetector::new();
    let matches = detector.find_matches_in_block(&func.block);

    // Should find 3 match expressions (outer + 2 nested)
    assert_eq!(matches.len(), 3, "Should detect all nested matches");

    // Verify contexts
    assert!(!matches[0].context.in_closure);
    assert!(matches.iter().any(|m| m.context.in_closure));
}

#[test]
fn test_threshold_filtering() {
    let thresholds = ComplexityThresholds::from_preset(ThresholdPreset::Strict);

    let simple_func = FunctionMetrics {
        name: "simple".to_string(),
        file: PathBuf::from("test.rs"),
        line: 1,
        cyclomatic: 2,
        cognitive: 3,
        nesting: 1,
        length: 10,
        is_test: false,
        visibility: Some("pub".to_string()),
        is_trait_method: false,
        in_test_module: false,
        entropy_score: None,
        is_pure: Some(true),
        purity_confidence: Some(0.9),
        detected_patterns: None,
        upstream_callers: None,
        downstream_callees: None,
        mapping_pattern_result: None,
        adjusted_complexity: None,
        composition_metrics: None,
        language_specific: None,
        purity_reason: None,
        call_dependencies: None,
        purity_level: None,
        error_swallowing_count: None,
        error_swallowing_patterns: None,
        entropy_analysis: None,
    };

    let complex_func = FunctionMetrics {
        name: "complex".to_string(),
        file: PathBuf::from("test.rs"),
        line: 20,
        cyclomatic: 15,
        cognitive: 25,
        nesting: 4,
        length: 100,
        is_test: false,
        visibility: Some("pub".to_string()),
        is_trait_method: false,
        in_test_module: false,
        entropy_score: None,
        is_pure: Some(false),
        purity_confidence: Some(0.8),
        detected_patterns: None,
        upstream_callers: None,
        downstream_callees: None,
        mapping_pattern_result: None,
        adjusted_complexity: None,
        composition_metrics: None,
        language_specific: None,
        purity_reason: None,
        call_dependencies: None,
        purity_level: None,
        error_swallowing_count: None,
        error_swallowing_patterns: None,
        entropy_analysis: None,
    };

    // Simple function should not be flagged
    assert!(!thresholds.should_flag_function(&simple_func, FunctionRole::CoreLogic));

    // Complex function should be flagged
    assert!(thresholds.should_flag_function(&complex_func, FunctionRole::CoreLogic));

    // Test functions get higher threshold
    let test_func = FunctionMetrics {
        name: "test_something".to_string(),
        file: PathBuf::from("test.rs"),
        line: 1,
        cyclomatic: 8,
        cognitive: 12,
        nesting: 2,
        length: 30,
        is_test: true,
        visibility: None,
        is_trait_method: false,
        in_test_module: true,
        entropy_score: None,
        is_pure: Some(false),
        purity_confidence: Some(0.5),
        detected_patterns: None,
        upstream_callers: None,
        downstream_callees: None,
        mapping_pattern_result: None,
        adjusted_complexity: None,
        composition_metrics: None,
        language_specific: None,
        purity_reason: None,
        call_dependencies: None,
        purity_level: None,
        error_swallowing_count: None,
        error_swallowing_patterns: None,
        entropy_analysis: None,
    };

    // Test function with moderate complexity should not be flagged due to multiplier
    assert!(!thresholds.should_flag_function(&test_func, FunctionRole::Test));
}

#[test]
fn test_if_else_chain_detection() {
    let code = r#"
        fn categorize_value(value: u32) -> &'static str {
            if value == 0 {
                "zero"
            } else if value == 1 {
                "one"
            } else if value == 2 {
                "two"
            } else if value == 3 {
                "three"
            } else if value == 4 {
                "four"
            } else {
                "many"
            }
        }
    "#;

    let file = syn::parse_str::<syn::File>(code).unwrap();
    let func = match &file.items[0] {
        syn::Item::Fn(f) => f,
        _ => panic!("Expected function"),
    };

    let mut analyzer = IfElseChainAnalyzer::new();
    let chains = analyzer.analyze_block(&func.block);

    assert_eq!(chains.len(), 1, "Should detect one if-else chain");
    assert_eq!(
        chains[0].length, 6,
        "Chain should have 6 branches (5 conditions + else)"
    );
    assert!(chains[0].has_final_else);
}

#[test]
fn test_enhanced_message_generation() {
    let metrics = FunctionMetrics {
        name: "complex_handler".to_string(),
        file: PathBuf::from("handler.rs"),
        line: 42,
        cyclomatic: 20,
        cognitive: 30,
        nesting: 5,
        length: 150,
        is_test: false,
        visibility: Some("pub".to_string()),
        is_trait_method: false,
        in_test_module: false,
        entropy_score: None,
        is_pure: Some(false),
        purity_confidence: Some(0.7),
        detected_patterns: None,
        upstream_callers: None,
        downstream_callees: None,
        mapping_pattern_result: None,
        adjusted_complexity: None,
        composition_metrics: None,
        language_specific: None,
        purity_reason: None,
        call_dependencies: None,
        purity_level: None,
        error_swallowing_count: None,
        error_swallowing_patterns: None,
        entropy_analysis: None,
    };

    let thresholds = ComplexityThresholds::from_preset(ThresholdPreset::Balanced);

    let message = generate_enhanced_message(
        &metrics,
        &[], // No matches for this test
        &[], // No if-else chains
        &thresholds,
    );

    // Verify message contains expected elements
    assert!(!message.summary.is_empty());
    assert!(!message.details.is_empty());
    assert!(!message.recommendations.is_empty());

    // Should identify high complexity
    assert!(message.summary.contains("complex") || message.summary.contains("Complex"));
}

#[test]
fn test_format_enhanced_message_includes_all_sections() {
    let message = EnhancedComplexityMessage {
        summary: "Function 'sample' has high complexity".to_string(),
        details: vec![ComplexityDetail {
            issue_type: ComplexityIssueType::HighCyclomaticComplexity {
                value: 12,
                sources: vec!["if/else statements".to_string()],
            },
            location: SourceLocation {
                file: PathBuf::from("src/sample.rs"),
                line: 17,
                column: None,
            },
            description: "High cyclomatic complexity of 12".to_string(),
            severity: Severity::High,
        }],
        recommendations: vec![ActionableRecommendation {
            title: "Reduce Branching Complexity".to_string(),
            description: "Extract complex conditions into named functions.".to_string(),
            effort: EstimatedEffort::Medium,
            pattern: RefactoringPattern::GuardClauses,
            code_example: None,
        }],
        code_examples: Some(RefactoringExample {
            before: "if condition {\n    work();\n}".to_string(),
            after: "if !condition {\n    return;\n}\nwork();".to_string(),
            explanation: "Guard clauses reduce nesting".to_string(),
            estimated_effort: EstimatedEffort::Low,
        }),
        complexity_breakdown: ComplexityBreakdown {
            cyclomatic_sources: vec!["if/else statements".to_string()],
            cognitive_sources: vec!["nested control flow".to_string()],
            match_complexity: 3,
            if_else_complexity: 4,
            loop_complexity: 0,
            nesting_penalty: 2,
            total_complexity: 21,
        },
    };

    let formatted = format_enhanced_message(&message);

    assert!(formatted.contains("Function 'sample' has high complexity"));
    assert!(formatted.contains("COMPLEXITY ISSUES:"));
    assert!(formatted.contains("1. [ERROR] High cyclomatic complexity of 12"));
    assert!(formatted.contains("Location: src/sample.rs:17"));
    assert!(formatted.contains("[TIP] RECOMMENDATIONS:"));
    assert!(formatted.contains("Reduce Branching Complexity"));
    assert!(formatted.contains("[REFACTORING EXAMPLE]"));
    assert!(formatted.contains("Total: 21 (Cyclomatic: 7, Cognitive: 2)"));
}

#[test]
fn test_depth_limit_protection() {
    // Create a deeply nested structure that approaches our depth limit
    // Using 45 levels to be safe with the 50 depth limit
    let mut code = String::from("fn deep() { ");
    for i in 0..45 {
        code.push_str(&format!("match {} {{ _ => {{ ", i));
    }
    code.push_str("42");
    for _ in 0..45 {
        code.push_str("} }");
    }
    code.push_str(" }");

    // This should not panic due to depth limits
    if let Ok(file) = syn::parse_str::<syn::File>(&code) {
        if let syn::Item::Fn(func) = &file.items[0] {
            let mut detector = RecursiveMatchDetector::new();
            let matches = detector.find_matches_in_block(&func.block);
            // Should complete without stack overflow and find some matches
            assert!(!matches.is_empty(), "Should find at least some matches");
            // Should find a reasonable number of matches
            assert!(
                matches.len() >= 10,
                "Should find a reasonable number of matches"
            );
            // The exact count depends on how depth is tracked
            eprintln!("Found {} matches out of 45 nested levels", matches.len());
        }
    }
}

#[test]
fn test_threshold_presets() {
    let strict = ComplexityThresholds::from_preset(ThresholdPreset::Strict);
    let balanced = ComplexityThresholds::from_preset(ThresholdPreset::Balanced);
    let lenient = ComplexityThresholds::from_preset(ThresholdPreset::Lenient);

    // Verify thresholds increase from strict to lenient
    assert!(strict.minimum_cyclomatic_complexity < balanced.minimum_cyclomatic_complexity);
    assert!(balanced.minimum_cyclomatic_complexity < lenient.minimum_cyclomatic_complexity);

    assert!(strict.minimum_cognitive_complexity < balanced.minimum_cognitive_complexity);
    assert!(balanced.minimum_cognitive_complexity < lenient.minimum_cognitive_complexity);

    assert!(strict.minimum_function_length < balanced.minimum_function_length);
    assert!(balanced.minimum_function_length < lenient.minimum_function_length);
}

#[test]
fn test_role_based_thresholds() {
    let thresholds = ComplexityThresholds::default();

    // Different roles should have different multipliers
    assert_ne!(
        thresholds.get_role_multiplier(FunctionRole::Test),
        thresholds.get_role_multiplier(FunctionRole::CoreLogic)
    );

    assert_ne!(
        thresholds.get_role_multiplier(FunctionRole::EntryPoint),
        thresholds.get_role_multiplier(FunctionRole::Utility)
    );

    // Test functions should be most lenient
    assert!(
        thresholds.get_role_multiplier(FunctionRole::Test)
            > thresholds.get_role_multiplier(FunctionRole::CoreLogic)
    );
}

#[test]
fn test_false_positive_reduction() {
    // Test that trivial functions are not flagged
    let trivial_functions = vec![
        ("getter", 1, 2, 5),
        ("setter", 2, 3, 8),
        ("simple_calc", 3, 4, 10),
        ("is_valid", 2, 2, 7),
    ];

    let thresholds = ComplexityThresholds::from_preset(ThresholdPreset::Balanced);

    for (name, cyclo, cog, lines) in trivial_functions {
        let func = FunctionMetrics {
            name: name.to_string(),
            file: PathBuf::from("test.rs"),
            line: 1,
            cyclomatic: cyclo,
            cognitive: cog,
            nesting: 1,
            length: lines,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: Some(true),
            purity_confidence: Some(0.9),
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_reason: None,
            call_dependencies: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        };

        assert!(
            !thresholds.should_flag_function(&func, FunctionRole::Utility),
            "Trivial function '{}' should not be flagged",
            name
        );
    }
}