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
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
use super::{
    MaintainabilityImpact, OrganizationAntiPattern, OrganizationDetector, Parameter,
    ParameterGroup, ParameterRefactoring,
};
use crate::common::{capitalize_first, SourceLocation};
use std::collections::HashMap;
use syn::{self, visit::Visit};

pub struct ParameterAnalyzer {
    max_parameters: usize,
}

impl Default for ParameterAnalyzer {
    fn default() -> Self {
        Self { max_parameters: 5 }
    }
}

impl ParameterAnalyzer {
    pub fn new() -> Self {
        Self::default()
    }

    fn suggest_parameter_refactoring(
        &self,
        function: &FunctionInfo,
        data_clumps: &[ParameterGroup],
    ) -> ParameterRefactoring {
        if !data_clumps.is_empty() {
            ParameterRefactoring::ExtractStruct
        } else if function.parameters.len() > 8 {
            ParameterRefactoring::UseBuilder
        } else if self.has_many_boolean_parameters(function) {
            ParameterRefactoring::UseConfiguration
        } else {
            ParameterRefactoring::SplitFunction
        }
    }

    fn has_many_boolean_parameters(&self, function: &FunctionInfo) -> bool {
        let bool_count = function
            .parameters
            .iter()
            .filter(|p| p.type_name == "bool")
            .count();

        bool_count > 2
    }

    fn find_data_clumps(&self, parameters: &[Parameter]) -> Vec<ParameterGroup> {
        let mut clumps = Vec::new();

        // Group parameters by semantic similarity
        let groups = self.group_parameters_by_semantics(parameters);

        for (semantic_group, group_params) in groups {
            if group_params.len() >= 3 {
                clumps.push(ParameterGroup {
                    parameters: group_params,
                    group_name: semantic_group.clone(),
                    semantic_relationship: semantic_group,
                });
            }
        }

        clumps
    }

    fn group_parameters_by_semantics(
        &self,
        parameters: &[Parameter],
    ) -> HashMap<String, Vec<Parameter>> {
        let mut groups: HashMap<String, Vec<Parameter>> = HashMap::new();

        for param in parameters {
            let semantic_group = self.identify_semantic_group(param);
            groups
                .entry(semantic_group)
                .or_default()
                .push(param.clone());
        }

        groups
    }

    fn identify_semantic_group(&self, parameter: &Parameter) -> String {
        let name = parameter.name.to_lowercase();

        // Define semantic patterns
        const SEMANTIC_PATTERNS: &[(&str, &[&str])] = &[
            ("coordinate", &["x", "y", "z", "width", "height", "depth"]),
            ("time", &["start", "end", "duration", "timeout", "delay"]),
            ("user", &["user", "username", "userid", "email", "name"]),
            ("config", &["config", "setting", "option", "preference"]),
            ("network", &["host", "port", "url", "endpoint", "address"]),
            ("file", &["path", "filename", "directory", "extension"]),
            (
                "authentication",
                &["token", "key", "secret", "auth", "credential"],
            ),
            ("pagination", &["page", "limit", "offset", "size", "count"]),
        ];

        for (group_name, keywords) in SEMANTIC_PATTERNS {
            if keywords.iter().any(|keyword| name.contains(keyword)) {
                return group_name.to_string();
            }
        }

        // If no semantic pattern matches, group by type
        format!("type_{}", parameter.type_name)
    }

    fn count_clump_occurrences(&self, clump: &ParameterGroup, functions: &[FunctionInfo]) -> usize {
        functions
            .iter()
            .filter(|f| self.function_has_clump(f, clump))
            .count()
    }

    fn function_has_clump(&self, function: &FunctionInfo, clump: &ParameterGroup) -> bool {
        // Check if function contains the same parameter pattern
        let clump_names: Vec<_> = clump.parameters.iter().map(|p| &p.name).collect();
        let function_names: Vec<_> = function.parameters.iter().map(|p| &p.name).collect();

        clump_names.iter().all(|name| function_names.contains(name))
    }

    fn suggest_struct_name(&self, clump: &ParameterGroup) -> String {
        if !clump.group_name.is_empty() {
            format!("{}Config", capitalize_first(&clump.group_name))
        } else {
            "ConfigParameters".to_string()
        }
    }
}

impl OrganizationDetector for ParameterAnalyzer {
    fn detect_anti_patterns(&self, file: &syn::File) -> Vec<OrganizationAntiPattern> {
        let mut patterns = Vec::new();
        let mut visitor = FunctionVisitor::new();
        visitor.visit_file(file);

        let functions = visitor.functions;

        for function in &functions {
            // Check for long parameter lists
            if function.parameters.len() > self.max_parameters {
                let data_clumps = self.find_data_clumps(&function.parameters);
                let refactoring = self.suggest_parameter_refactoring(function, &data_clumps);

                patterns.push(OrganizationAntiPattern::LongParameterList {
                    function_name: function.name.clone(),
                    parameter_count: function.parameters.len(),
                    data_clumps,
                    suggested_refactoring: refactoring,
                    location: SourceLocation::default(), // TODO: Extract actual location
                });
            }

            // Check for data clumps even in shorter parameter lists
            let data_clumps = self.find_data_clumps(&function.parameters);
            for clump in data_clumps {
                if clump.parameters.len() >= 3 {
                    patterns.push(OrganizationAntiPattern::DataClump {
                        parameter_group: clump.clone(),
                        occurrence_count: self.count_clump_occurrences(&clump, &functions),
                        suggested_struct_name: self.suggest_struct_name(&clump),
                        locations: vec![SourceLocation::default()], // TODO: Extract actual locations
                    });
                }
            }
        }

        patterns
    }

    fn detector_name(&self) -> &'static str {
        "ParameterAnalyzer"
    }

    fn estimate_maintainability_impact(
        &self,
        pattern: &OrganizationAntiPattern,
    ) -> MaintainabilityImpact {
        match pattern {
            OrganizationAntiPattern::LongParameterList {
                parameter_count, ..
            } => ParameterAnalyzer::classify_parameter_list_impact(*parameter_count),
            OrganizationAntiPattern::DataClump {
                occurrence_count, ..
            } => ParameterAnalyzer::classify_data_clump_impact(*occurrence_count),
            _ => MaintainabilityImpact::Low,
        }
    }
}

impl ParameterAnalyzer {
    /// Classify the maintainability impact based on parameter count
    fn classify_parameter_list_impact(parameter_count: usize) -> MaintainabilityImpact {
        match parameter_count {
            count if count > 10 => MaintainabilityImpact::High,
            count if count > 7 => MaintainabilityImpact::Medium,
            _ => MaintainabilityImpact::Low,
        }
    }

    /// Classify the maintainability impact based on data clump occurrences
    fn classify_data_clump_impact(occurrence_count: usize) -> MaintainabilityImpact {
        match occurrence_count {
            count if count > 5 => MaintainabilityImpact::Medium,
            _ => MaintainabilityImpact::Low,
        }
    }
}

struct FunctionInfo {
    name: String,
    parameters: Vec<Parameter>,
}

struct FunctionVisitor {
    functions: Vec<FunctionInfo>,
}

impl FunctionVisitor {
    fn new() -> Self {
        Self {
            functions: Vec::new(),
        }
    }

    fn extract_parameters(
        &self,
        inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
    ) -> Vec<Parameter> {
        let mut parameters = Vec::new();
        let mut position = 0;

        for input in inputs {
            if let syn::FnArg::Typed(pat_type) = input {
                if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
                    let name = pat_ident.ident.to_string();
                    let type_name = self.extract_type_name(&pat_type.ty);

                    parameters.push(Parameter {
                        name,
                        type_name,
                        position,
                    });
                    position += 1;
                }
            }
        }

        parameters
    }

    #[allow(clippy::only_used_in_recursion)]
    fn extract_type_name(&self, ty: &syn::Type) -> String {
        match ty {
            syn::Type::Path(type_path) => type_path
                .path
                .segments
                .last()
                .map(|seg| seg.ident.to_string())
                .unwrap_or_else(|| "Unknown".to_string()),
            syn::Type::Reference(type_ref) => self.extract_type_name(&type_ref.elem),
            _ => "Unknown".to_string(),
        }
    }
}

impl<'ast> Visit<'ast> for FunctionVisitor {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        let function = FunctionInfo {
            name: node.sig.ident.to_string(),
            parameters: self.extract_parameters(&node.sig.inputs),
        };
        self.functions.push(function);

        syn::visit::visit_item_fn(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        let function = FunctionInfo {
            name: node.sig.ident.to_string(),
            parameters: self.extract_parameters(&node.sig.inputs),
        };
        self.functions.push(function);

        syn::visit::visit_impl_item_fn(self, node);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::organization::{
        OrganizationAntiPattern, ParameterGroup, ParameterRefactoring, ValueContext,
    };

    #[test]
    fn test_classify_parameter_list_impact_high() {
        // Test high impact for more than 10 parameters
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(11),
            MaintainabilityImpact::High
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(15),
            MaintainabilityImpact::High
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(100),
            MaintainabilityImpact::High
        );
    }

    #[test]
    fn test_classify_parameter_list_impact_medium() {
        // Test medium impact for 8-10 parameters
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(8),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(9),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(10),
            MaintainabilityImpact::Medium
        );
    }

    #[test]
    fn test_classify_parameter_list_impact_low() {
        // Test low impact for 7 or fewer parameters
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(0),
            MaintainabilityImpact::Low
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(5),
            MaintainabilityImpact::Low
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(7),
            MaintainabilityImpact::Low
        );
    }

    #[test]
    fn test_classify_data_clump_impact_medium() {
        // Test medium impact for more than 5 occurrences
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(6),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(10),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(100),
            MaintainabilityImpact::Medium
        );
    }

    #[test]
    fn test_classify_data_clump_impact_low() {
        // Test low impact for 5 or fewer occurrences
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(0),
            MaintainabilityImpact::Low
        );
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(3),
            MaintainabilityImpact::Low
        );
        assert_eq!(
            ParameterAnalyzer::classify_data_clump_impact(5),
            MaintainabilityImpact::Low
        );
    }

    #[test]
    fn test_estimate_maintainability_impact_long_parameter_list() {
        let analyzer = ParameterAnalyzer::new();

        // Test with high parameter count
        let pattern = OrganizationAntiPattern::LongParameterList {
            function_name: "test_function".to_string(),
            parameter_count: 12,
            data_clumps: vec![],
            suggested_refactoring: ParameterRefactoring::ExtractStruct,
            location: SourceLocation::default(),
        };
        assert_eq!(
            analyzer.estimate_maintainability_impact(&pattern),
            MaintainabilityImpact::High
        );

        // Test with medium parameter count
        let pattern = OrganizationAntiPattern::LongParameterList {
            function_name: "test_function".to_string(),
            parameter_count: 8,
            data_clumps: vec![],
            suggested_refactoring: ParameterRefactoring::ExtractStruct,
            location: SourceLocation::default(),
        };
        assert_eq!(
            analyzer.estimate_maintainability_impact(&pattern),
            MaintainabilityImpact::Medium
        );
    }

    #[test]
    fn test_estimate_maintainability_impact_data_clump() {
        let analyzer = ParameterAnalyzer::new();

        // Test with high occurrence count
        let pattern = OrganizationAntiPattern::DataClump {
            parameter_group: ParameterGroup {
                parameters: vec![],
                group_name: "test_group".to_string(),
                semantic_relationship: "related".to_string(),
            },
            occurrence_count: 7,
            suggested_struct_name: "TestStruct".to_string(),
            locations: vec![],
        };
        assert_eq!(
            analyzer.estimate_maintainability_impact(&pattern),
            MaintainabilityImpact::Medium
        );

        // Test with low occurrence count
        let pattern = OrganizationAntiPattern::DataClump {
            parameter_group: ParameterGroup {
                parameters: vec![],
                group_name: "test_group".to_string(),
                semantic_relationship: "related".to_string(),
            },
            occurrence_count: 3,
            suggested_struct_name: "TestStruct".to_string(),
            locations: vec![],
        };
        assert_eq!(
            analyzer.estimate_maintainability_impact(&pattern),
            MaintainabilityImpact::Low
        );
    }

    #[test]
    fn test_estimate_maintainability_impact_other_patterns() {
        let analyzer = ParameterAnalyzer::new();

        // Test with other pattern types (should return Low)
        let pattern = OrganizationAntiPattern::MagicValue {
            value_type: crate::organization::MagicValueType::NumericLiteral,
            value: "42".to_string(),
            occurrence_count: 5,
            suggested_constant_name: "ANSWER".to_string(),
            context: ValueContext::BusinessLogic,
            locations: vec![],
        };
        assert_eq!(
            analyzer.estimate_maintainability_impact(&pattern),
            MaintainabilityImpact::Low
        );
    }

    #[test]
    fn test_parameter_list_boundary_values() {
        // Test boundary values for parameter list impact classification
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(7),
            MaintainabilityImpact::Low
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(8),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(10),
            MaintainabilityImpact::Medium
        );
        assert_eq!(
            ParameterAnalyzer::classify_parameter_list_impact(11),
            MaintainabilityImpact::High
        );
    }
}