repotoire 0.3.112

Graph-powered code analysis CLI. 114 detectors for security, architecture, and code quality.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Data Clumps Detector
//!
//! Graph-aware detection of parameter groups that appear together across functions.
//! Uses function parameter data from the graph to identify missing abstractions.
//!
//! Enhanced with call graph analysis:
//! - Higher severity if functions with same params CALL each other (strong coupling)
//! - Lower severity if functions are in different modules with no call relationship
//! - Identifies refactoring opportunities where params travel through call chains

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphStore;
use crate::models::{Finding, Severity};
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use tracing::{debug, info};

/// Thresholds for data clumps detection
#[derive(Debug, Clone)]
pub struct DataClumpsThresholds {
    /// Minimum parameters to form a clump
    pub min_params: usize,
    /// Minimum functions sharing the clump
    pub min_occurrences: usize,
}

impl Default for DataClumpsThresholds {
    fn default() -> Self {
        Self {
            min_params: 3,
            min_occurrences: 3,
        }
    }
}

/// Known parameter patterns and suggested names
fn suggest_struct_name(params: &[String]) -> String {
    let param_set: HashSet<&str> = params.iter().map(|s| s.as_str()).collect();

    // Check known patterns
    let patterns: &[(&[&str], &str)] = &[
        (&["x", "y"], "Point"),
        (&["x", "y", "z"], "Point3D"),
        (&["width", "height"], "Size"),
        (&["start", "end"], "Range"),
        (&["min", "max"], "Range"),
        (&["host", "port"], "Address"),
        (&["first_name", "last_name"], "Name"),
        (&["first_name", "last_name", "email"], "PersonInfo"),
        (&["latitude", "longitude"], "Coordinates"),
        (&["lat", "lng"], "Coordinates"),
        (&["red", "green", "blue"], "RGB"),
        (&["r", "g", "b"], "RGB"),
        (&["username", "password"], "Credentials"),
        (&["user", "password"], "Credentials"),
        (&["path", "filename"], "FilePath"),
        (&["name", "email"], "Contact"),
        (&["start_date", "end_date"], "DateRange"),
        (&["created_at", "updated_at"], "Timestamps"),
    ];

    for (pattern_params, name) in patterns {
        let pattern_set: HashSet<&str> = pattern_params.iter().copied().collect();
        if pattern_set.is_subset(&param_set) {
            return name.to_string();
        }
    }

    // Generate from first param
    if let Some(first) = params.first() {
        let base: String = first
            .split('_')
            .map(|w| {
                let mut c = w.chars();
                match c.next() {
                    None => String::new(),
                    Some(f) => f.to_uppercase().chain(c).collect(),
                }
            })
            .collect();
        return format!("{}Params", base);
    }

    "ParamGroup".to_string()
}

pub struct DataClumpsDetector {
    config: DetectorConfig,
    thresholds: DataClumpsThresholds,
}

impl DataClumpsDetector {
    pub fn new() -> Self {
        Self {
            config: DetectorConfig::new(),
            thresholds: DataClumpsThresholds::default(),
        }
    }

    #[allow(dead_code)] // Builder pattern method
    pub fn with_config(config: DetectorConfig) -> Self {
        let thresholds = DataClumpsThresholds {
            min_params: config.get_option_or("min_params", 3),
            min_occurrences: config.get_option_or("min_occurrences", 3),
        };
        Self { config, thresholds }
    }

    /// Extract parameter names from function's parameter property
    fn extract_params(&self, func: &crate::graph::CodeNode) -> Vec<String> {
        // Try to get params from properties
        if let Some(params_str) = func.get_str("params") {
            return params_str
                .split(',')
                .map(|p| p.trim().to_lowercase())
                .filter(|p| !p.is_empty() && !p.starts_with('_') && p != "self" && p != "this")
                .collect();
        }

        // Try param_count to see if function has parameters
        if let Some(count) = func.param_count() {
            if count >= self.thresholds.min_params as i64 {
                // We know it has params but can't extract names
                // Return empty - will need parser enhancement
            }
        }

        vec![]
    }

    /// Find parameter clumps across functions
    fn find_clumps(&self, graph: &dyn crate::graph::GraphQuery) -> Vec<DataClump> {
        let functions = graph.get_functions();

        // Build map of param sets to functions
        let mut param_to_funcs: HashMap<Vec<String>, Vec<FuncInfo>> = HashMap::new();

        for func in &functions {
            let params = self.extract_params(func);
            if params.len() < self.thresholds.min_params {
                continue;
            }

            // Generate all combinations of min_params or more
            for size in self.thresholds.min_params..=params.len().min(6) {
                for combo in combinations(&params, size) {
                    let mut key = combo;
                    key.sort();

                    param_to_funcs.entry(key).or_default().push(FuncInfo {
                        name: func.name.clone(),
                        qualified_name: func.qualified_name.clone(),
                        file: func.file_path.clone(),
                        line: func.line_start,
                    });
                }
            }
        }

        // Filter to clumps meeting threshold and analyze call relationships
        let mut clumps: Vec<DataClump> = param_to_funcs
            .into_iter()
            .filter(|(_, funcs)| funcs.len() >= self.thresholds.min_occurrences)
            .map(|(params, funcs)| {
                // Analyze call relationships between functions in this clump
                let (call_count, is_chain) = self.analyze_call_relationships(graph, &funcs);
                DataClump {
                    params,
                    funcs,
                    call_relationships: call_count,
                    is_call_chain: is_chain,
                }
            })
            .collect();

        // Remove subsets
        clumps = self.remove_subsets(clumps);

        // Sort by call relationships first (stronger signal), then by function count
        clumps.sort_by(|a, b| {
            b.call_relationships
                .cmp(&a.call_relationships)
                .then(b.funcs.len().cmp(&a.funcs.len()))
        });

        clumps
    }

    /// Analyze call relationships between functions that share parameters
    fn analyze_call_relationships(
        &self,
        graph: &dyn crate::graph::GraphQuery,
        funcs: &[FuncInfo],
    ) -> (usize, bool) {
        let func_qns: HashSet<&str> = funcs.iter().map(|f| f.qualified_name.as_str()).collect();
        let mut call_count = 0;
        let mut has_chain = false;

        for func in funcs {
            let callees = graph.get_callees(&func.qualified_name);
            for callee in &callees {
                if func_qns.contains(callee.qualified_name.as_str()) {
                    call_count += 1;

                    // Check if callee also calls another function in the clump (chain)
                    let callee_callees = graph.get_callees(&callee.qualified_name);
                    for cc in &callee_callees {
                        if func_qns.contains(cc.qualified_name.as_str())
                            && cc.qualified_name != func.qualified_name
                        {
                            has_chain = true;
                        }
                    }
                }
            }
        }

        (call_count, has_chain)
    }

    /// Remove clumps that are subsets of larger ones
    fn remove_subsets(&self, mut clumps: Vec<DataClump>) -> Vec<DataClump> {
        clumps.sort_by(|a, b| b.params.len().cmp(&a.params.len()));

        let mut result = Vec::new();

        for clump in clumps {
            let param_set: HashSet<&String> = clump.params.iter().collect();
            let func_set: HashSet<&str> = clump.funcs.iter().map(|f| f.name.as_str()).collect();

            let is_subset = result.iter().any(|existing: &DataClump| {
                let existing_params: HashSet<&String> = existing.params.iter().collect();
                let existing_funcs: HashSet<&str> =
                    existing.funcs.iter().map(|f| f.name.as_str()).collect();
                param_set.is_subset(&existing_params) && func_set.is_subset(&existing_funcs)
            });

            if !is_subset {
                result.push(clump);
            }
        }

        result
    }

    /// Calculate severity based on function count and call relationships
    fn calculate_severity(&self, clump: &DataClump) -> Severity {
        let func_count = clump.funcs.len();
        let call_rels = clump.call_relationships;

        // Base severity from function count
        let base = if func_count >= 6 {
            Severity::High
        } else if func_count >= 4 {
            Severity::Medium
        } else {
            Severity::Low
        };

        // Upgrade severity if there are call relationships (stronger signal)
        // Functions that call each other with the same params = definite refactor target
        if clump.is_call_chain {
            // Params traveling through a call chain = HIGH priority
            return match base {
                Severity::Low => Severity::Medium,
                Severity::Medium => Severity::High,
                _ => Severity::High,
            };
        }

        if call_rels >= 3 {
            // Many mutual calls = boost severity
            return match base {
                Severity::Low => Severity::Medium,
                _ => base,
            };
        }

        base
    }
}

struct DataClump {
    params: Vec<String>,
    funcs: Vec<FuncInfo>,
    /// Number of call relationships between functions in this clump
    call_relationships: usize,
    /// Whether functions form a call chain (A->B->C all have same params)
    is_call_chain: bool,
}

struct FuncInfo {
    name: String,
    qualified_name: String,
    file: String,
    line: u32,
}

/// Generate combinations of k items
fn combinations(items: &[String], k: usize) -> Vec<Vec<String>> {
    if k > items.len() {
        return vec![];
    }
    if k == items.len() {
        return vec![items.to_vec()];
    }
    if k == 0 {
        return vec![vec![]];
    }

    let mut result = Vec::new();
    let mut indices: Vec<usize> = (0..k).collect();
    let n = items.len();

    loop {
        result.push(indices.iter().map(|&i| items[i].clone()).collect());

        let mut i = k;
        while i > 0 {
            i -= 1;
            if indices[i] < n - k + i {
                break;
            }
        }

        if i == 0 && indices[0] >= n - k {
            break;
        }

        indices[i] += 1;
        for j in (i + 1)..k {
            indices[j] = indices[j - 1] + 1;
        }
    }

    result
}

impl Default for DataClumpsDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl Detector for DataClumpsDetector {
    fn name(&self) -> &'static str {
        "DataClumpsDetector"
    }

    fn description(&self) -> &'static str {
        "Detects parameter groups that appear together across functions"
    }

    fn category(&self) -> &'static str {
        "code_smell"
    }

    fn config(&self) -> Option<&DetectorConfig> {
        Some(&self.config)
    }

    fn detect(&self, graph: &dyn crate::graph::GraphQuery) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();

        let clumps = self.find_clumps(graph);

        for clump in clumps {
            let severity = self.calculate_severity(&clump);
            let struct_name = suggest_struct_name(&clump.params);
            let params_str = clump.params.join(", ");

            let func_list: String = clump
                .funcs
                .iter()
                .take(5)
                .map(|f| format!("  - {} ({}:{})", f.name, f.file, f.line))
                .collect::<Vec<_>>()
                .join("\n");

            let more_note = if clump.funcs.len() > 5 {
                format!("\n  ... and {} more functions", clump.funcs.len() - 5)
            } else {
                String::new()
            };

            // Add call relationship info if present
            let call_info = if clump.is_call_chain {
                "\n\n⚠️ **Call chain detected**: These parameters travel through a call chain, \
                 making refactoring especially valuable."
                    .to_string()
            } else if clump.call_relationships > 0 {
                format!(
                    "\n\n📞 **{} call relationships** found between these functions.",
                    clump.call_relationships
                )
            } else {
                String::new()
            };

            let files: Vec<PathBuf> = clump
                .funcs
                .iter()
                .map(|f| PathBuf::from(&f.file))
                .collect::<HashSet<_>>()
                .into_iter()
                .collect();

            findings.push(Finding {
                id: String::new(),
                detector: "DataClumpsDetector".to_string(),
                severity,
                title: format!("Data clump: ({})", params_str),
                description: format!(
                    "Parameters **({})** appear together in **{} functions**.\n\n\
                     This suggests a missing abstraction - consider extracting a `{}` struct.\n\n\
                     **Affected functions:**\n{}{}{}",
                    params_str,
                    clump.funcs.len(),
                    struct_name,
                    func_list,
                    more_note,
                    call_info
                ),
                affected_files: files,
                line_start: clump.funcs.first().map(|f| f.line),
                line_end: None,
                suggested_fix: Some(format!(
                    "Extract parameters into a struct:\n\n\
                     ```rust\n\
                     struct {} {{\n\
                     {}\n\
                     }}\n\
                     ```\n\n\
                     Then refactor functions to accept `{}` instead of {} separate parameters.{}",
                    struct_name,
                    clump.params.iter().map(|p| format!("    {}: Type,", p)).collect::<Vec<_>>().join("\n"),
                    struct_name,
                    clump.params.len(),
                    if clump.is_call_chain {
                        "\n\nSince these functions call each other, the refactoring can be done incrementally."
                    } else { "" }
                )),
                estimated_effort: Some(if clump.funcs.len() >= 6 || clump.is_call_chain {
                    "Large (2-4 hours)".to_string()
                } else {
                    "Medium (1-2 hours)".to_string()
                }),
                category: Some("code_smell".to_string()),
                cwe_id: None,
                why_it_matters: Some(
                    "Data clumps indicate missing abstractions. Grouping related parameters \
                     into a struct improves readability, type safety, and makes changes easier."
                        .to_string()
                ),
                ..Default::default()
            });
        }

        info!(
            "DataClumpsDetector found {} findings (graph-aware)",
            findings.len()
        );
        Ok(findings)
    }
}

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

    #[test]
    fn test_suggest_struct_name() {
        assert_eq!(
            suggest_struct_name(&["x".to_string(), "y".to_string()]),
            "Point"
        );
        assert_eq!(
            suggest_struct_name(&["host".to_string(), "port".to_string()]),
            "Address"
        );
        assert_eq!(
            suggest_struct_name(&["foo".to_string(), "bar".to_string(), "baz".to_string()]),
            "FooParams"
        );
    }

    #[test]
    fn test_combinations() {
        let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let combos = combinations(&items, 2);
        assert_eq!(combos.len(), 3); // ab, ac, bc
    }

    #[test]
    fn test_severity() {
        let detector = DataClumpsDetector::new();

        // Test base severity from function count
        let clump_3 = DataClump {
            params: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            funcs: vec![
                FuncInfo {
                    name: "f1".to_string(),
                    qualified_name: "mod::f1".to_string(),
                    file: "a.rs".to_string(),
                    line: 1,
                },
                FuncInfo {
                    name: "f2".to_string(),
                    qualified_name: "mod::f2".to_string(),
                    file: "a.rs".to_string(),
                    line: 10,
                },
                FuncInfo {
                    name: "f3".to_string(),
                    qualified_name: "mod::f3".to_string(),
                    file: "a.rs".to_string(),
                    line: 20,
                },
            ],
            call_relationships: 0,
            is_call_chain: false,
        };
        assert_eq!(detector.calculate_severity(&clump_3), Severity::Low);

        let clump_4 = DataClump {
            params: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            funcs: vec![
                FuncInfo {
                    name: "f1".to_string(),
                    qualified_name: "mod::f1".to_string(),
                    file: "a.rs".to_string(),
                    line: 1,
                },
                FuncInfo {
                    name: "f2".to_string(),
                    qualified_name: "mod::f2".to_string(),
                    file: "a.rs".to_string(),
                    line: 10,
                },
                FuncInfo {
                    name: "f3".to_string(),
                    qualified_name: "mod::f3".to_string(),
                    file: "a.rs".to_string(),
                    line: 20,
                },
                FuncInfo {
                    name: "f4".to_string(),
                    qualified_name: "mod::f4".to_string(),
                    file: "a.rs".to_string(),
                    line: 30,
                },
            ],
            call_relationships: 0,
            is_call_chain: false,
        };
        assert_eq!(detector.calculate_severity(&clump_4), Severity::Medium);

        let clump_6 = DataClump {
            params: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            funcs: vec![
                FuncInfo {
                    name: "f1".to_string(),
                    qualified_name: "mod::f1".to_string(),
                    file: "a.rs".to_string(),
                    line: 1,
                },
                FuncInfo {
                    name: "f2".to_string(),
                    qualified_name: "mod::f2".to_string(),
                    file: "a.rs".to_string(),
                    line: 10,
                },
                FuncInfo {
                    name: "f3".to_string(),
                    qualified_name: "mod::f3".to_string(),
                    file: "a.rs".to_string(),
                    line: 20,
                },
                FuncInfo {
                    name: "f4".to_string(),
                    qualified_name: "mod::f4".to_string(),
                    file: "a.rs".to_string(),
                    line: 30,
                },
                FuncInfo {
                    name: "f5".to_string(),
                    qualified_name: "mod::f5".to_string(),
                    file: "a.rs".to_string(),
                    line: 40,
                },
                FuncInfo {
                    name: "f6".to_string(),
                    qualified_name: "mod::f6".to_string(),
                    file: "a.rs".to_string(),
                    line: 50,
                },
            ],
            call_relationships: 0,
            is_call_chain: false,
        };
        assert_eq!(detector.calculate_severity(&clump_6), Severity::High);

        // Test call chain boost
        let clump_chain = DataClump {
            params: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            funcs: vec![
                FuncInfo {
                    name: "f1".to_string(),
                    qualified_name: "mod::f1".to_string(),
                    file: "a.rs".to_string(),
                    line: 1,
                },
                FuncInfo {
                    name: "f2".to_string(),
                    qualified_name: "mod::f2".to_string(),
                    file: "a.rs".to_string(),
                    line: 10,
                },
                FuncInfo {
                    name: "f3".to_string(),
                    qualified_name: "mod::f3".to_string(),
                    file: "a.rs".to_string(),
                    line: 20,
                },
            ],
            call_relationships: 2,
            is_call_chain: true, // Call chain boosts Low -> Medium
        };
        assert_eq!(detector.calculate_severity(&clump_chain), Severity::Medium);
    }
}