code-graph-cli 3.0.1

Code intelligence engine for TypeScript/JavaScript/Rust/Python/Go — query the dependency graph instead of reading source files.
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
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use petgraph::Direction;
use petgraph::visit::EdgeRef;

use crate::graph::{
    CodeGraph,
    edge::EdgeKind,
    node::{GraphNode, SymbolInfo, SymbolKind},
};

// ---------------------------------------------------------------------------
// Data structures
// ---------------------------------------------------------------------------

/// Structural signature of a symbol for clone detection.
///
/// Two symbols with the same `StructuralSignature` are considered structural clones.
/// Components: (SymbolKind, body_size, outgoing_edge_count, incoming_edge_count, decorator_count).
#[derive(Debug, Clone, PartialEq, Eq)]
struct StructuralSignature {
    kind: SymbolKind,
    body_size: usize,
    outgoing_edges: usize,
    incoming_edges: usize,
    decorator_count: usize,
}

/// Compute a deterministic u64 hash from a `StructuralSignature`.
///
/// Uses multiply-and-xor combining so the result is stable across runs
/// (unlike `DefaultHasher` which is randomly seeded).
fn deterministic_signature_hash(sig: &StructuralSignature) -> u64 {
    let kind_val: u64 = match sig.kind {
        SymbolKind::Function => 1,
        SymbolKind::Class => 2,
        SymbolKind::Interface => 3,
        SymbolKind::Variable => 4,
        SymbolKind::TypeAlias => 5,
        SymbolKind::Enum => 6,
        SymbolKind::Trait => 7,
        SymbolKind::Method => 8,
        SymbolKind::Struct => 9,
        SymbolKind::Component => 10,
        SymbolKind::Property => 11,
        SymbolKind::ImplMethod => 12,
        SymbolKind::Const => 13,
        SymbolKind::Static => 14,
        SymbolKind::Macro => 15,
    };
    // FNV-1a-style deterministic combine
    let mut h: u64 = 0xcbf29ce484222325;
    let mix = |h: &mut u64, v: u64| {
        *h ^= v;
        *h = h.wrapping_mul(0x100000001b3);
    };
    mix(&mut h, kind_val);
    mix(&mut h, sig.body_size as u64);
    mix(&mut h, sig.outgoing_edges as u64);
    mix(&mut h, sig.incoming_edges as u64);
    mix(&mut h, sig.decorator_count as u64);
    h
}

/// A single symbol member within a clone group.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CloneMember {
    pub name: String,
    pub kind: String,
    pub file: PathBuf,
    pub line: usize,
    pub body_size: usize,
}

/// A group of structurally identical symbols (clones).
#[derive(Debug, Clone, serde::Serialize)]
pub struct CloneGroup {
    /// Hash identifying this structural signature.
    pub hash: u64,
    /// Human-readable description of the structural signature.
    pub signature: String,
    /// Members of this clone group.
    pub members: Vec<CloneMember>,
}

/// Result of clone detection analysis.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CloneGroupResult {
    /// Clone groups with >= min_group members.
    pub groups: Vec<CloneGroup>,
    /// Total number of symbols analyzed.
    pub total_symbols_analyzed: usize,
}

// ---------------------------------------------------------------------------
// Main query function
// ---------------------------------------------------------------------------

/// Detect structural clones: symbols with identical structural signatures.
///
/// - `graph`: the code graph to analyze
/// - `root`: the project root path (used for relative path computation)
/// - `scope`: optional path scope; if provided, only analyze symbols under this path
/// - `min_group`: minimum group size to report (default 2)
///
/// Returns a `CloneGroupResult` with groups of structurally identical symbols.
pub fn find_clones(
    graph: &CodeGraph,
    root: &Path,
    scope: Option<&Path>,
    min_group: usize,
) -> CloneGroupResult {
    // Compute absolute scope path if provided
    let abs_scope: Option<PathBuf> = scope.map(|s| {
        if s.is_absolute() {
            s.to_path_buf()
        } else {
            root.join(s)
        }
    });

    // Helper: check if a path is under the scope
    let in_scope = |path: &Path| -> bool {
        match &abs_scope {
            None => true,
            Some(scope_path) => path.starts_with(scope_path),
        }
    };

    // Single pass: for each Symbol node, find its containing file via incoming
    // Contains edge, check scope, compute the structural signature, and group.
    let mut hash_groups: HashMap<u64, (StructuralSignature, Vec<CloneMember>)> = HashMap::new();
    let mut total_symbols_analyzed: usize = 0;

    for node_idx in graph.graph.node_indices() {
        let sym = match &graph.graph[node_idx] {
            GraphNode::Symbol(s) => s,
            _ => continue,
        };

        // Walk incoming edges to find the containing file
        let file_path = graph
            .graph
            .edges_directed(node_idx, Direction::Incoming)
            .find_map(|edge| {
                if matches!(edge.weight(), EdgeKind::Contains)
                    && let GraphNode::File(fi) = &graph.graph[edge.source()]
                {
                    return Some(fi.path.clone());
                }
                None
            });

        let file_path = match file_path {
            Some(p) => p,
            None => continue, // orphan symbol, skip
        };

        // Check scope
        if !in_scope(&file_path) {
            continue;
        }

        total_symbols_analyzed += 1;

        // Compute structural signature and deterministic hash
        let sig = compute_signature(graph, node_idx, sym);
        let hash = deterministic_signature_hash(&sig);

        let kind_str = crate::query::find::kind_to_str(&sym.kind).to_string();
        let body_size = sig.body_size;
        let member = CloneMember {
            name: sym.name.clone(),
            kind: kind_str,
            file: file_path,
            line: sym.line,
            body_size,
        };

        hash_groups
            .entry(hash)
            .or_insert_with(|| (sig, Vec::new()))
            .1
            .push(member);
    }

    // Filter groups by min_group and build result
    let mut groups: Vec<CloneGroup> = hash_groups
        .into_iter()
        .filter(|(_, (_, members))| members.len() >= min_group)
        .map(|(hash, (sig, mut members))| {
            // Sort members for deterministic output: by file path, then line
            members.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
            CloneGroup {
                hash,
                signature: format_signature(&sig),
                members,
            }
        })
        .collect();

    // Sort groups by member count descending, then by hash for determinism
    groups.sort_by(|a, b| {
        b.members
            .len()
            .cmp(&a.members.len())
            .then(a.hash.cmp(&b.hash))
    });

    CloneGroupResult {
        groups,
        total_symbols_analyzed,
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Compute the structural signature for a symbol node.
fn compute_signature(
    graph: &CodeGraph,
    node_idx: petgraph::stable_graph::NodeIndex,
    sym: &SymbolInfo,
) -> StructuralSignature {
    let body_size = sym.line_end.saturating_sub(sym.line);

    let outgoing_edges = graph
        .graph
        .edges_directed(node_idx, Direction::Outgoing)
        .count();

    let incoming_edges = graph
        .graph
        .edges_directed(node_idx, Direction::Incoming)
        .count();

    let decorator_count = sym.decorators.len();

    StructuralSignature {
        kind: sym.kind.clone(),
        body_size,
        outgoing_edges,
        incoming_edges,
        decorator_count,
    }
}

/// Format a structural signature as a human-readable string.
fn format_signature(sig: &StructuralSignature) -> String {
    format!(
        "kind={} body={} out={} in={} decorators={}",
        crate::query::find::kind_to_str(&sig.kind),
        sig.body_size,
        sig.outgoing_edges,
        sig.incoming_edges,
        sig.decorator_count,
    )
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    use super::*;
    use crate::graph::{
        CodeGraph,
        node::{DecoratorInfo, SymbolInfo, SymbolKind},
    };

    fn make_symbol(name: &str, kind: SymbolKind, line: usize, line_end: usize) -> SymbolInfo {
        SymbolInfo {
            name: name.into(),
            kind,
            line,
            line_end,
            ..Default::default()
        }
    }

    fn make_symbol_with_decorators(
        name: &str,
        kind: SymbolKind,
        line: usize,
        line_end: usize,
        decorator_count: usize,
    ) -> SymbolInfo {
        let decorators: Vec<DecoratorInfo> = (0..decorator_count)
            .map(|i| DecoratorInfo {
                name: format!("decorator_{}", i),
                ..Default::default()
            })
            .collect();
        SymbolInfo {
            name: name.into(),
            kind,
            line,
            line_end,
            decorators,
            ..Default::default()
        }
    }

    #[test]
    fn test_identical_symbols_grouped() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");
        let file_a = root.join("src/utils.rs");
        let file_b = root.join("src/helpers.rs");
        let file_a_idx = graph.add_file(file_a.clone(), "rust");
        let file_b_idx = graph.add_file(file_b.clone(), "rust");

        // Two functions with identical structural signatures:
        // same kind (Function), same body_size (10), same edge counts (0), same decorators (0)
        graph.add_symbol(
            file_a_idx,
            make_symbol("process_data", SymbolKind::Function, 1, 11),
        );
        graph.add_symbol(
            file_b_idx,
            make_symbol("transform_data", SymbolKind::Function, 1, 11),
        );

        let result = find_clones(&graph, &root, None, 2);
        assert_eq!(
            result.groups.len(),
            1,
            "Two identical symbols should form one clone group"
        );
        assert_eq!(
            result.groups[0].members.len(),
            2,
            "Clone group should have 2 members"
        );

        let names: Vec<&str> = result.groups[0]
            .members
            .iter()
            .map(|m| m.name.as_str())
            .collect();
        assert!(names.contains(&"process_data"));
        assert!(names.contains(&"transform_data"));
    }

    #[test]
    fn test_distinct_symbols_not_grouped() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");
        let file_idx = graph.add_file(root.join("src/lib.rs"), "rust");

        // Different kind
        graph.add_symbol(file_idx, make_symbol("my_fn", SymbolKind::Function, 1, 11));
        // Different body_size
        graph.add_symbol(file_idx, make_symbol("my_class", SymbolKind::Class, 1, 51));
        // Another function but different body size
        graph.add_symbol(
            file_idx,
            make_symbol("small_fn", SymbolKind::Function, 1, 4),
        );

        let result = find_clones(&graph, &root, None, 2);
        assert_eq!(
            result.groups.len(),
            0,
            "Distinct symbols should not form clone groups"
        );
    }

    #[test]
    fn test_min_group_filter() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");
        let file_idx = graph.add_file(root.join("src/mod.rs"), "rust");

        // Three identical functions
        graph.add_symbol(file_idx, make_symbol("fn_a", SymbolKind::Function, 1, 6));
        graph.add_symbol(file_idx, make_symbol("fn_b", SymbolKind::Function, 10, 15));
        graph.add_symbol(file_idx, make_symbol("fn_c", SymbolKind::Function, 20, 25));

        // With min_group=2, should find one group of 3
        let result = find_clones(&graph, &root, None, 2);
        assert_eq!(result.groups.len(), 1);
        assert_eq!(result.groups[0].members.len(), 3);

        // With min_group=4, should find no groups
        let result = find_clones(&graph, &root, None, 4);
        assert_eq!(
            result.groups.len(),
            0,
            "Group of 3 should be filtered out when min_group=4"
        );
    }

    #[test]
    fn test_scope_filter() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");

        // File inside scope
        let in_scope_file = root.join("src/module/a.rs");
        let in_scope_idx = graph.add_file(in_scope_file.clone(), "rust");
        graph.add_symbol(
            in_scope_idx,
            make_symbol("fn_in_scope_1", SymbolKind::Function, 1, 11),
        );

        // Another file inside scope with same signature
        let in_scope_file2 = root.join("src/module/b.rs");
        let in_scope_idx2 = graph.add_file(in_scope_file2.clone(), "rust");
        graph.add_symbol(
            in_scope_idx2,
            make_symbol("fn_in_scope_2", SymbolKind::Function, 1, 11),
        );

        // File outside scope with same signature
        let out_scope_file = root.join("other/c.rs");
        let out_scope_idx = graph.add_file(out_scope_file.clone(), "rust");
        graph.add_symbol(
            out_scope_idx,
            make_symbol("fn_out_scope", SymbolKind::Function, 1, 11),
        );

        // Run with scope = "src/module"
        let scope_path = PathBuf::from("src/module");
        let result = find_clones(&graph, &root, Some(&scope_path), 2);

        assert_eq!(
            result.groups.len(),
            1,
            "Should find 1 clone group within scope"
        );
        assert_eq!(
            result.groups[0].members.len(),
            2,
            "Clone group should have 2 in-scope members"
        );

        let names: Vec<&str> = result.groups[0]
            .members
            .iter()
            .map(|m| m.name.as_str())
            .collect();
        assert!(names.contains(&"fn_in_scope_1"));
        assert!(names.contains(&"fn_in_scope_2"));
        assert!(
            !names.contains(&"fn_out_scope"),
            "Out-of-scope symbol should be excluded"
        );
    }

    #[test]
    fn test_decorator_count_differentiates() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");
        let file_idx = graph.add_file(root.join("src/app.rs"), "rust");

        // Same kind and body_size but different decorator counts
        graph.add_symbol(
            file_idx,
            make_symbol_with_decorators("fn_no_dec", SymbolKind::Function, 1, 11, 0),
        );
        graph.add_symbol(
            file_idx,
            make_symbol_with_decorators("fn_with_dec", SymbolKind::Function, 15, 25, 2),
        );

        let result = find_clones(&graph, &root, None, 2);
        assert_eq!(
            result.groups.len(),
            0,
            "Different decorator counts should prevent grouping"
        );
    }

    #[test]
    fn test_total_symbols_analyzed() {
        let mut graph = CodeGraph::new();
        let root = PathBuf::from("/project");
        let file_idx = graph.add_file(root.join("src/lib.rs"), "rust");

        graph.add_symbol(file_idx, make_symbol("fn_a", SymbolKind::Function, 1, 6));
        graph.add_symbol(file_idx, make_symbol("fn_b", SymbolKind::Function, 10, 15));
        graph.add_symbol(file_idx, make_symbol("cls_a", SymbolKind::Class, 20, 50));

        let result = find_clones(&graph, &root, None, 2);
        assert_eq!(
            result.total_symbols_analyzed, 3,
            "Should count all analyzed symbols"
        );
    }
}