dupes-core 0.2.0

Core library for detecting duplicate and near-duplicate code blocks
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
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
use std::collections::HashMap;

/// Kinds of literals — preserves type but erases value.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LiteralKind {
    Int,
    Float,
    Str,
    ByteStr,
    CStr,
    Byte,
    Char,
    Bool,
}

/// Kinds of placeholders — what the original identifier referred to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PlaceholderKind {
    Variable,
    Function,
    Type,
    Lifetime,
    Label,
}

/// Binary operators.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BinOpKind {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    And,
    Or,
    BitXor,
    BitAnd,
    BitOr,
    Shl,
    Shr,
    Eq,
    Lt,
    Le,
    Ne,
    Ge,
    Gt,
    AddAssign,
    SubAssign,
    MulAssign,
    DivAssign,
    RemAssign,
    BitXorAssign,
    BitAndAssign,
    BitOrAssign,
    ShlAssign,
    ShrAssign,
    Other,
}

/// Unary operators.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UnOpKind {
    Deref,
    Not,
    Neg,
    Other,
}

/// The kind of a normalized AST node. Carries only non-child data
/// (operator kinds, literal kinds, placeholder indices, mutability flags, macro names).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NodeKind {
    // Blocks and statements
    Block,
    LetBinding,
    Semi,
    Paren,

    // Literals and identifiers
    Literal(LiteralKind),
    Placeholder(PlaceholderKind, usize),

    // Operations
    BinaryOp(BinOpKind),
    UnaryOp(UnOpKind),
    Range,

    // Calls and access
    Call,
    MethodCall,
    FieldAccess,
    Index,
    Path,

    // Closures and functions
    Closure,
    FnSignature,

    // Control flow
    Return,
    Break,
    Continue,
    Assign,

    // References and pointers
    Reference {
        mutable: bool,
    },

    // Compound types
    Tuple,
    Array,
    Repeat,

    // Type operations
    Cast,
    StructInit,

    // Async/error
    Await,
    Try,

    // Control flow structures
    If,
    Match,
    MatchArm,
    Loop,
    While,
    ForLoop,
    LetExpr,

    // Patterns
    PatWild,
    PatPlaceholder(PlaceholderKind, usize),
    PatTuple,
    PatStruct,
    PatOr,
    PatLiteral,
    PatReference {
        mutable: bool,
    },
    PatSlice,
    PatRest,
    PatRange,

    // Types
    TypePlaceholder(PlaceholderKind, usize),
    TypeReference {
        mutable: bool,
    },
    TypeTuple,
    TypeSlice,
    TypeArray,
    TypePath,
    TypeImplTrait,
    TypeInfer,
    TypeUnit,
    TypeNever,

    // Field initializer (name = value)
    FieldValue,

    // Macro invocations
    MacroCall {
        name: String,
    },

    // Opaque — unsupported constructs
    Opaque,

    /// Sentinel for absent optional children, ensuring fixed child positions
    /// for correct zip alignment in similarity comparison.
    None,
}

/// A normalized AST node. Uses a data-driven `{ kind, children }` representation
/// instead of a large enum with differently-shaped variants. This allows generic
/// traversal algorithms (count_nodes, reindex, count_matching, extract) to work
/// without exhaustive matching on every variant.
///
/// ## Child ordering conventions
///
/// - **Fixed with None sentinels** (always same child count):
///   - `If` -> [condition, then_branch, else_or_None]
///   - `LetBinding` -> [pattern, type_or_None, init_or_None, diverge_or_None]
///   - `Range` / `PatRange` -> [from_or_None, to_or_None]
///   - `MatchArm` -> [pattern, guard_or_None, body]
/// - **Fixed children first, variable after** (for zip alignment):
///   - `Call` -> [func, arg0, arg1, ...]
///   - `MethodCall` -> [receiver, method, arg0, ...]
///   - `Closure` -> [body, param0, ...]
///   - `FnSignature` -> [return_type_or_None, param0, ...]
///   - `Match` -> [expr, arm0, arm1, ...]
///   - `StructInit` -> [rest_or_None, field0, field1, ...]
///   - `MacroCall` -> [arg0, arg1, ...]
/// - **Variable-length (0 or 1)**: `Return`, `Break` -> [] or [value]
/// - **Homogeneous**: `Block`, `Tuple`, `Array`, `Path`, `PatTuple`, etc. -> [elem0, ...]
/// - **All other fixed**: e.g. `BinaryOp` -> [left, right], `ForLoop` -> [pat, iter, body]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NormalizedNode {
    pub kind: NodeKind,
    pub children: Vec<Self>,
}

impl NormalizedNode {
    /// Create a leaf node (no children).
    #[must_use]
    pub const fn leaf(kind: NodeKind) -> Self {
        Self {
            kind,
            children: vec![],
        }
    }

    /// Create a node with children.
    #[must_use]
    pub const fn with_children(kind: NodeKind, children: Vec<Self>) -> Self {
        Self { kind, children }
    }

    /// Create a None sentinel node.
    #[must_use]
    pub const fn none() -> Self {
        Self::leaf(NodeKind::None)
    }

    /// Convert an Option<NormalizedNode> to a node, using None sentinel for absent values.
    pub fn opt(node: Option<Self>) -> Self {
        node.unwrap_or_else(Self::none)
    }

    /// Check if this is a None sentinel node.
    #[must_use]
    pub const fn is_none(&self) -> bool {
        matches!(self.kind, NodeKind::None)
    }
}

/// Tracks identifier-to-placeholder mappings during normalization.
pub struct NormalizationContext {
    /// Maps (identifier_string, kind) -> placeholder index
    mappings: HashMap<(String, PlaceholderKind), usize>,
    /// Per-kind counters
    counters: HashMap<PlaceholderKind, usize>,
}

impl NormalizationContext {
    #[must_use]
    pub fn new() -> Self {
        Self {
            mappings: HashMap::new(),
            counters: HashMap::new(),
        }
    }

    /// Get or assign a placeholder index for the given identifier and kind.
    pub fn placeholder(&mut self, name: &str, kind: PlaceholderKind) -> usize {
        let key = (name.to_string(), kind);
        if let Some(&idx) = self.mappings.get(&key) {
            return idx;
        }
        let counter = self.counters.entry(kind).or_insert(0);
        let idx = *counter;
        *counter += 1;
        self.mappings.insert(key, idx);
        idx
    }
}

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

// -- Placeholder re-indexing --------------------------------------------------

/// Collects all placeholder occurrences in depth-first order, building
/// a mapping from (kind, old_index) -> new_sequential_index.
fn collect_placeholder_order(
    node: &NormalizedNode,
    order: &mut Vec<(PlaceholderKind, usize)>,
    seen: &mut std::collections::HashSet<(PlaceholderKind, usize)>,
) {
    match &node.kind {
        NodeKind::Placeholder(kind, idx)
        | NodeKind::PatPlaceholder(kind, idx)
        | NodeKind::TypePlaceholder(kind, idx) => {
            if seen.insert((*kind, *idx)) {
                order.push((*kind, *idx));
            }
        }
        _ => {}
    }
    for child in &node.children {
        collect_placeholder_order(child, order, seen);
    }
}

/// Applies the reindex mapping to a node, returning a new node with remapped indices.
fn apply_reindex(
    node: &NormalizedNode,
    mapping: &HashMap<(PlaceholderKind, usize), usize>,
) -> NormalizedNode {
    let kind = match &node.kind {
        NodeKind::Placeholder(kind, idx) => {
            let new_idx = mapping.get(&(*kind, *idx)).copied().unwrap_or(*idx);
            NodeKind::Placeholder(*kind, new_idx)
        }
        NodeKind::PatPlaceholder(kind, idx) => {
            let new_idx = mapping.get(&(*kind, *idx)).copied().unwrap_or(*idx);
            NodeKind::PatPlaceholder(*kind, new_idx)
        }
        NodeKind::TypePlaceholder(kind, idx) => {
            let new_idx = mapping.get(&(*kind, *idx)).copied().unwrap_or(*idx);
            NodeKind::TypePlaceholder(*kind, new_idx)
        }
        other => other.clone(),
    };
    let children = node
        .children
        .iter()
        .map(|c| apply_reindex(c, mapping))
        .collect();
    NormalizedNode { kind, children }
}

/// Re-index all placeholders in a sub-tree so that indices start from 0
/// per kind, assigned by first-occurrence depth-first order.
/// This allows comparing sub-trees extracted from different function contexts.
#[must_use]
pub fn reindex_placeholders(node: &NormalizedNode) -> NormalizedNode {
    let mut order = Vec::new();
    let mut seen = std::collections::HashSet::new();
    collect_placeholder_order(node, &mut order, &mut seen);

    // Build mapping: (kind, old_index) -> new sequential index per kind
    let mut counters: HashMap<PlaceholderKind, usize> = HashMap::new();
    let mut mapping: HashMap<(PlaceholderKind, usize), usize> = HashMap::new();
    for (kind, old_idx) in order {
        let counter = counters.entry(kind).or_insert(0);
        mapping.insert((kind, old_idx), *counter);
        *counter += 1;
    }

    apply_reindex(node, &mapping)
}

/// Count the number of nodes in a normalized tree.
/// None sentinel nodes are not counted.
pub fn count_nodes(node: &NormalizedNode) -> usize {
    if node.is_none() {
        return 0;
    }
    1 + node.children.iter().map(count_nodes).sum::<usize>()
}

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

    #[test]
    fn reindex_remaps_from_zero() {
        let node = NormalizedNode::with_children(
            NodeKind::BinaryOp(BinOpKind::Add),
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 5)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 8)),
            ],
        );
        let reindexed = reindex_placeholders(&node);
        let expected = NormalizedNode::with_children(
            NodeKind::BinaryOp(BinOpKind::Add),
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 1)),
            ],
        );
        assert_eq!(reindexed, expected);
    }

    #[test]
    fn reindex_preserves_same_placeholder_identity() {
        let node = NormalizedNode::with_children(
            NodeKind::BinaryOp(BinOpKind::Add),
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 3)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 3)),
            ],
        );
        let reindexed = reindex_placeholders(&node);
        let expected = NormalizedNode::with_children(
            NodeKind::BinaryOp(BinOpKind::Add),
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
            ],
        );
        assert_eq!(reindexed, expected);
    }

    #[test]
    fn reindex_makes_equivalent_subtrees_equal() {
        let subtree1 = NormalizedNode::with_children(
            NodeKind::Block,
            vec![
                NormalizedNode::with_children(
                    NodeKind::LetBinding,
                    vec![
                        NormalizedNode::leaf(NodeKind::PatPlaceholder(
                            PlaceholderKind::Variable,
                            2,
                        )),
                        NormalizedNode::none(),
                        NormalizedNode::with_children(
                            NodeKind::BinaryOp(BinOpKind::Add),
                            vec![
                                NormalizedNode::leaf(NodeKind::Placeholder(
                                    PlaceholderKind::Variable,
                                    0,
                                )),
                                NormalizedNode::leaf(NodeKind::Literal(LiteralKind::Int)),
                            ],
                        ),
                        NormalizedNode::none(),
                    ],
                ),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 2)),
            ],
        );
        let subtree2 = NormalizedNode::with_children(
            NodeKind::Block,
            vec![
                NormalizedNode::with_children(
                    NodeKind::LetBinding,
                    vec![
                        NormalizedNode::leaf(NodeKind::PatPlaceholder(
                            PlaceholderKind::Variable,
                            7,
                        )),
                        NormalizedNode::none(),
                        NormalizedNode::with_children(
                            NodeKind::BinaryOp(BinOpKind::Add),
                            vec![
                                NormalizedNode::leaf(NodeKind::Placeholder(
                                    PlaceholderKind::Variable,
                                    5,
                                )),
                                NormalizedNode::leaf(NodeKind::Literal(LiteralKind::Int)),
                            ],
                        ),
                        NormalizedNode::none(),
                    ],
                ),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 7)),
            ],
        );

        assert_ne!(subtree1, subtree2);
        assert_eq!(
            reindex_placeholders(&subtree1),
            reindex_placeholders(&subtree2)
        );
    }

    #[test]
    fn reindex_handles_multiple_placeholder_kinds() {
        let node = NormalizedNode::with_children(
            NodeKind::Call,
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Function, 3)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 5)),
                NormalizedNode::with_children(
                    NodeKind::Cast,
                    vec![
                        NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 5)),
                        NormalizedNode::leaf(NodeKind::TypePlaceholder(PlaceholderKind::Type, 2)),
                    ],
                ),
            ],
        );
        let reindexed = reindex_placeholders(&node);
        let expected = NormalizedNode::with_children(
            NodeKind::Call,
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Function, 0)),
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                NormalizedNode::with_children(
                    NodeKind::Cast,
                    vec![
                        NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                        NormalizedNode::leaf(NodeKind::TypePlaceholder(PlaceholderKind::Type, 0)),
                    ],
                ),
            ],
        );
        assert_eq!(reindexed, expected);
    }

    #[test]
    fn count_nodes_skips_none_sentinels() {
        let node = NormalizedNode::with_children(
            NodeKind::If,
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                NormalizedNode::with_children(NodeKind::Block, vec![]),
                NormalizedNode::none(),
            ],
        );
        // If(1) + Placeholder(1) + Block(1) = 3 (None is not counted)
        assert_eq!(count_nodes(&node), 3);
    }

    // -- NormalizationContext tests --

    #[test]
    fn context_assigns_sequential_indices() {
        let mut ctx = NormalizationContext::new();
        assert_eq!(ctx.placeholder("x", PlaceholderKind::Variable), 0);
        assert_eq!(ctx.placeholder("y", PlaceholderKind::Variable), 1);
        assert_eq!(ctx.placeholder("z", PlaceholderKind::Variable), 2);
    }

    #[test]
    fn context_returns_same_index_for_same_name() {
        let mut ctx = NormalizationContext::new();
        let first = ctx.placeholder("x", PlaceholderKind::Variable);
        let second = ctx.placeholder("x", PlaceholderKind::Variable);
        assert_eq!(first, second);
        assert_eq!(first, 0);
    }

    #[test]
    fn context_per_kind_counters_are_independent() {
        let mut ctx = NormalizationContext::new();
        let var_idx = ctx.placeholder("foo", PlaceholderKind::Variable);
        let fn_idx = ctx.placeholder("foo", PlaceholderKind::Function);
        let type_idx = ctx.placeholder("foo", PlaceholderKind::Type);
        // Each kind starts from 0 independently
        assert_eq!(var_idx, 0);
        assert_eq!(fn_idx, 0);
        assert_eq!(type_idx, 0);
    }

    #[test]
    fn context_same_name_different_kind_are_distinct() {
        let mut ctx = NormalizationContext::new();
        ctx.placeholder("x", PlaceholderKind::Variable);
        ctx.placeholder("x", PlaceholderKind::Function);
        // Second variable should get index 1, not 0
        let y_var = ctx.placeholder("y", PlaceholderKind::Variable);
        assert_eq!(y_var, 1);
        let y_fn = ctx.placeholder("y", PlaceholderKind::Function);
        assert_eq!(y_fn, 1);
    }

    // -- count_nodes tests --

    #[test]
    fn count_nodes_basic() {
        let node = NormalizedNode::with_children(
            NodeKind::BinaryOp(BinOpKind::Add),
            vec![
                NormalizedNode::leaf(NodeKind::Placeholder(PlaceholderKind::Variable, 0)),
                NormalizedNode::leaf(NodeKind::Literal(LiteralKind::Int)),
            ],
        );
        assert_eq!(count_nodes(&node), 3);
    }
}