debtmap 0.16.4

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
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
use super::{
    AttributedComplexity, CodeLocation, ComplexityComponent, ComplexitySourceType,
    RecognizedPattern,
};
use crate::core::FunctionMetrics;
use std::collections::HashMap;

/// Pattern analysis and tracking
pub struct PatternTracker {
    pattern_detectors: Vec<Box<dyn PatternDetector>>,
}

impl Default for PatternTracker {
    fn default() -> Self {
        Self {
            pattern_detectors: vec![
                Box::new(ErrorHandlingDetector::new()),
                Box::new(ValidationDetector::new()),
                Box::new(DataTransformationDetector::new()),
                Box::new(StateManagementDetector::new()),
                Box::new(IteratorDetector::new()),
            ],
        }
    }
}

impl PatternTracker {
    /// Creates a new pattern tracker with default pattern detectors.
    ///
    /// Includes detectors for error handling, validation, data transformation,
    /// state management, and iterator patterns.
    pub fn new() -> Self {
        Self::default()
    }

    /// Analyzes functions for recognized patterns and returns attributed complexity.
    ///
    /// Scans each function through all registered pattern detectors, accumulating
    /// complexity adjustments based on detected patterns. Returns an attribution
    /// with a confidence score based on pattern consistency across the codebase.
    pub fn analyze_patterns(&self, functions: &[FunctionMetrics]) -> AttributedComplexity {
        let mut total = 0u32;
        let mut breakdown = Vec::new();
        let mut pattern_counts = HashMap::new();

        for func in functions {
            for detector in &self.pattern_detectors {
                if let Some(pattern_info) = detector.detect(func) {
                    *pattern_counts
                        .entry(pattern_info.pattern_type.clone())
                        .or_insert(0) += 1;

                    // Patterns typically reduce perceived complexity
                    let adjustment =
                        (func.cyclomatic as f32 * pattern_info.adjustment_factor) as u32;
                    let reduction = func.cyclomatic.saturating_sub(adjustment);

                    if reduction > 0 {
                        breakdown.push(ComplexityComponent {
                            source_type: ComplexitySourceType::PatternRecognition {
                                pattern_type: pattern_info.pattern_type,
                                adjustment_factor: pattern_info.adjustment_factor,
                            },
                            contribution: reduction,
                            location: CodeLocation {
                                file: func.file.to_string_lossy().to_string(),
                                line: func.line as u32,
                                column: 0,
                                span: Some((func.line as u32, (func.line + func.length) as u32)),
                            },
                            description: format!("{} pattern in {}", pattern_info.name, func.name),
                            suggestions: pattern_info.optimization_suggestions,
                        });

                        total += reduction;
                    }
                }
            }
        }

        // Calculate confidence based on pattern consistency
        let confidence = if !pattern_counts.is_empty() {
            let max_count = *pattern_counts.values().max().unwrap_or(&0);
            let pattern_variety = pattern_counts.len();

            // Higher confidence when we see consistent patterns
            let consistency_score = (max_count as f32 / functions.len().max(1) as f32).min(1.0);
            let variety_score = (pattern_variety as f32 / 5.0).min(1.0);

            (consistency_score * 0.6 + variety_score * 0.4).min(0.9)
        } else {
            0.3 // Low confidence when no patterns detected
        };

        AttributedComplexity {
            total,
            breakdown,
            confidence,
        }
    }
}

/// Trait for pattern detection
trait PatternDetector: Send + Sync {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo>;
}

/// Information about a detected pattern
struct PatternInfo {
    name: String,
    pattern_type: RecognizedPattern,
    adjustment_factor: f32,
    optimization_suggestions: Vec<String>,
}

/// Detector for error handling patterns
struct ErrorHandlingDetector;

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

impl PatternDetector for ErrorHandlingDetector {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo> {
        // Simple heuristic: functions with "error", "handle", "catch" in name
        let name_lower = func.name.to_lowercase();
        if name_lower.contains("error")
            || name_lower.contains("handle")
            || name_lower.contains("catch")
        {
            Some(PatternInfo {
                name: "Error Handling".to_string(),
                pattern_type: RecognizedPattern::ErrorHandling,
                adjustment_factor: 0.8, // Error handling is expected complexity
                optimization_suggestions: vec![
                    "Consider using Result type consistently".to_string(),
                    "Extract error transformation logic".to_string(),
                ],
            })
        } else {
            None
        }
    }
}

/// Detector for validation patterns
struct ValidationDetector;

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

impl PatternDetector for ValidationDetector {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo> {
        let name_lower = func.name.to_lowercase();
        if name_lower.contains("valid")
            || name_lower.contains("check")
            || name_lower.contains("verify")
        {
            Some(PatternInfo {
                name: "Validation".to_string(),
                pattern_type: RecognizedPattern::Validation,
                adjustment_factor: 0.85,
                optimization_suggestions: vec![
                    "Consider using validation libraries".to_string(),
                    "Extract validation rules into constants".to_string(),
                ],
            })
        } else {
            None
        }
    }
}

/// Detector for data transformation patterns
struct DataTransformationDetector;

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

impl PatternDetector for DataTransformationDetector {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo> {
        let name_lower = func.name.to_lowercase();
        if name_lower.contains("transform")
            || name_lower.contains("convert")
            || name_lower.contains("map")
            || name_lower.contains("parse")
        {
            Some(PatternInfo {
                name: "Data Transformation".to_string(),
                pattern_type: RecognizedPattern::DataTransformation,
                adjustment_factor: 0.9,
                optimization_suggestions: vec![
                    "Consider using functional transformations".to_string(),
                    "Extract transformation logic into pure functions".to_string(),
                ],
            })
        } else {
            None
        }
    }
}

/// Detector for state management patterns
struct StateManagementDetector;

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

impl PatternDetector for StateManagementDetector {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo> {
        let name_lower = func.name.to_lowercase();
        if name_lower.contains("state")
            || name_lower.contains("update")
            || name_lower.contains("sync")
        {
            Some(PatternInfo {
                name: "State Management".to_string(),
                pattern_type: RecognizedPattern::StateManagement,
                adjustment_factor: 0.75, // State management can be complex
                optimization_suggestions: vec![
                    "Consider immutable state updates".to_string(),
                    "Use state machines for complex state logic".to_string(),
                ],
            })
        } else {
            None
        }
    }
}

/// Detector for iterator patterns
struct IteratorDetector;

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

impl PatternDetector for IteratorDetector {
    fn detect(&self, func: &FunctionMetrics) -> Option<PatternInfo> {
        let name_lower = func.name.to_lowercase();
        if name_lower.contains("iter")
            || name_lower.contains("next")
            || name_lower.contains("collect")
            || name_lower.contains("fold")
        {
            Some(PatternInfo {
                name: "Iterator".to_string(),
                pattern_type: RecognizedPattern::Iterator,
                adjustment_factor: 0.95,
                optimization_suggestions: vec![
                    "Consider using iterator combinators".to_string(),
                    "Avoid unnecessary intermediate collections".to_string(),
                ],
            })
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_pattern_tracker_new() {
        let tracker = PatternTracker::new();
        assert!(!tracker.pattern_detectors.is_empty());
    }

    #[test]
    fn test_error_handling_detection() {
        let detector = ErrorHandlingDetector::new();

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

        let pattern = detector.detect(&func);
        assert!(pattern.is_some());

        let info = pattern.unwrap();
        assert_eq!(info.pattern_type, RecognizedPattern::ErrorHandling);
        assert_eq!(info.adjustment_factor, 0.8);
    }

    #[test]
    fn test_validation_detection() {
        let detector = ValidationDetector::new();

        let func = FunctionMetrics {
            name: "validate_input".to_string(),
            file: PathBuf::from("test.rs"),
            line: 20,
            cyclomatic: 8,
            cognitive: 5,
            nesting: 2,
            length: 30,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        };

        let pattern = detector.detect(&func);
        assert!(pattern.is_some());

        let info = pattern.unwrap();
        assert_eq!(info.pattern_type, RecognizedPattern::Validation);
    }

    #[test]
    fn test_no_pattern_detection() {
        let detector = ErrorHandlingDetector::new();

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

        let pattern = detector.detect(&func);
        assert!(pattern.is_none());
    }

    #[test]
    fn test_analyze_patterns_empty() {
        let tracker = PatternTracker::new();
        let functions = vec![];

        let result = tracker.analyze_patterns(&functions);
        assert_eq!(result.total, 0);
        assert_eq!(result.confidence, 0.3);
    }

    #[test]
    fn test_analyze_patterns_with_functions() {
        let tracker = PatternTracker::new();
        let functions = vec![FunctionMetrics {
            name: "handle_request_error".to_string(),
            file: PathBuf::from("test.rs"),
            line: 10,
            cyclomatic: 10,
            cognitive: 8,
            nesting: 2,
            length: 40,
            is_test: false,
            visibility: None,
            is_trait_method: false,
            in_test_module: false,
            entropy_score: None,
            is_pure: None,
            purity_confidence: None,
            purity_reason: None,
            call_dependencies: None,
            detected_patterns: None,
            upstream_callers: None,
            downstream_callees: None,
            mapping_pattern_result: None,
            adjusted_complexity: None,
            composition_metrics: None,
            language_specific: None,
            purity_level: None,
            error_swallowing_count: None,
            error_swallowing_patterns: None,
            entropy_analysis: None,
        }];

        let result = tracker.analyze_patterns(&functions);
        assert!(result.total > 0);
        assert!(!result.breakdown.is_empty());
    }
}