Skip to main content

fallow_engine/duplication_detector/
deepdive.rs

1//! Deep-dive helpers for the `fallow dupes --trace` inspector: a stable
2//! content fingerprint that addresses a clone group across runs, a group-level
3//! refactoring suggestion, and a best-effort "dominant identifier" name for the
4//! extracted function.
5//!
6//! These are pure functions over [`CloneInstance`] / [`CloneGroup`] so every
7//! surface (human listing, `--trace dup:<fp>` lookup, the typed JSON wrappers,
8//! and `trace_clone`) computes the same values without storing a field on the
9//! core [`CloneGroup`] struct.
10
11use std::path::Path;
12
13use fallow_config::DetectionMode;
14use rustc_hash::{FxHashMap, FxHashSet};
15use xxhash_rust::xxh3::{Xxh3, xxh3_64};
16
17use super::tokenize::{
18    FragmentTokenizationKind, FragmentTokenizationStrategy, fragment_tokenization_kind,
19};
20use super::types::{CloneGroup, CloneInstance, RefactoringKind, RefactoringSuggestion};
21
22/// Prefix marking a clone-group fingerprint addressable via `--trace`.
23pub const FINGERPRINT_PREFIX: &str = "dup:";
24
25/// Canonical identity for a clone group when assigning report-scoped handles.
26///
27/// Compact digests of canonically sorted fragments and locations make report
28/// entries addressable without retaining a second copy of every source fragment
29/// and path. Collision suffixes use lexical locations instead of these digests
30/// so a different checkout prefix cannot change their order.
31/// The separately hashed, sorted, deduplicated normalized instance sequences
32/// provide the public content identity.
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct CloneFingerprintKey {
35    fragments_digest: u128,
36    locations_digest: u128,
37    token_count: usize,
38    line_count: usize,
39    instance_count: usize,
40}
41
42const _: () = assert!(std::mem::size_of::<CloneFingerprintKey>() <= 64);
43
44impl CloneFingerprintKey {
45    /// Build a fingerprint key from clone-group parts.
46    #[must_use]
47    fn from_parts(instances: &[CloneInstance], token_count: usize, line_count: usize) -> Self {
48        Self {
49            fragments_digest: hash_distinct_fragments(instances),
50            locations_digest: hash_sorted_locations(instances),
51            token_count,
52            line_count,
53            instance_count: instances.len(),
54        }
55    }
56
57    fn from_group(group: &CloneGroup) -> Self {
58        Self::from_parts(&group.instances, group.token_count, group.line_count)
59    }
60}
61
62/// Report-scoped clone fingerprint assignment.
63///
64/// Most reports retain the short `dup:<8hex>` handle. If two report entries
65/// collide on those low 32 bits, only the colliding entries widen to
66/// `dup:<16hex>`. If a full 64-bit collision ever occurs inside one report,
67/// every entry in that collision bucket receives a deterministic `-rN` suffix.
68/// Legacy `-N` suffixes deliberately do not resolve, since their assignment
69/// depended on the absolute checkout path and could address a different group.
70#[derive(Debug, Clone)]
71pub struct CloneFingerprintSet {
72    by_key: FxHashMap<CloneFingerprintKey, String>,
73    key_by_fingerprint: FxHashMap<String, CloneFingerprintKey>,
74}
75
76impl CloneFingerprintSet {
77    /// Assign collision-free fingerprints for the report's clone groups.
78    #[must_use]
79    pub fn from_groups(groups: &[CloneGroup]) -> Self {
80        let entries: Vec<_> = groups
81            .iter()
82            .map(|group| (group, hash_instances(&group.instances)))
83            .collect();
84        Self::from_hashed_entries(&entries)
85    }
86
87    /// Assign collision-free fingerprints for borrowed clone groups, with the
88    /// same result as [`Self::from_groups`] for the same groups.
89    #[must_use]
90    pub fn from_group_refs(groups: &[&CloneGroup]) -> Self {
91        let entries: Vec<_> = groups
92            .iter()
93            .map(|group| (*group, hash_instances(&group.instances)))
94            .collect();
95        Self::from_hashed_entries(&entries)
96    }
97
98    /// Return the assigned fingerprint for a clone group.
99    #[must_use]
100    pub fn fingerprint_for_group(&self, group: &CloneGroup) -> String {
101        self.by_key
102            .get(&CloneFingerprintKey::from_group(group))
103            .cloned()
104            .unwrap_or_else(|| clone_fingerprint(&group.instances))
105    }
106
107    /// Return the config key used by `duplicates.ignoredClones` for a group.
108    #[must_use]
109    pub fn ignored_clone_key_for_group(&self, group: &CloneGroup) -> String {
110        format!(
111            "{}:{}",
112            self.fingerprint_for_group(group),
113            group.instances.len()
114        )
115    }
116
117    /// Return the assigned fingerprint for clone-group parts.
118    #[must_use]
119    pub fn fingerprint_for_parts(
120        &self,
121        instances: &[CloneInstance],
122        token_count: usize,
123        line_count: usize,
124    ) -> String {
125        let key = CloneFingerprintKey::from_parts(instances, token_count, line_count);
126        self.by_key
127            .get(&key)
128            .cloned()
129            .unwrap_or_else(|| clone_fingerprint(instances))
130    }
131
132    /// Find the group addressed by an assigned fingerprint.
133    ///
134    /// Ambiguous short handles created by low-32 collisions are intentionally
135    /// absent from the lookup table, so callers get `None` instead of the first
136    /// matching group.
137    #[must_use]
138    pub fn find_group<'a>(
139        &self,
140        groups: &'a [CloneGroup],
141        fingerprint: &str,
142    ) -> Option<&'a CloneGroup> {
143        let key = self.key_by_fingerprint.get(fingerprint)?;
144        groups
145            .iter()
146            .find(|group| CloneFingerprintKey::from_group(group) == *key)
147    }
148
149    fn from_hashed_entries(entries: &[(&CloneGroup, u64)]) -> Self {
150        let mut short_counts: FxHashMap<u32, usize> = FxHashMap::default();
151        let mut full_counts: FxHashMap<u64, usize> = FxHashMap::default();
152        for (_, hash) in entries {
153            *short_counts.entry(*hash as u32).or_insert(0) += 1;
154            *full_counts.entry(*hash).or_insert(0) += 1;
155        }
156
157        // Only full collisions need location ordering. Within one report, a
158        // shared checkout prefix cancels in lexical comparisons. Hashing that
159        // prefix instead would arbitrarily reorder groups after relocation.
160        let mut sorted_entries: Vec<_> = entries
161            .iter()
162            .map(|(group, hash)| {
163                let locations = if full_counts.get(hash).copied().unwrap_or(0) > 1 {
164                    sorted_locations(&group.instances)
165                } else {
166                    Vec::new()
167                };
168                (CloneFingerprintKey::from_group(group), *hash, locations)
169            })
170            .collect();
171        sorted_entries.sort_unstable_by(
172            |(left, left_hash, left_locations), (right, right_hash, right_locations)| {
173                left.fragments_digest
174                    .cmp(&right.fragments_digest)
175                    .then_with(|| left_locations.cmp(right_locations))
176                    .then_with(|| left.token_count.cmp(&right.token_count))
177                    .then_with(|| left.line_count.cmp(&right.line_count))
178                    .then_with(|| left.instance_count.cmp(&right.instance_count))
179                    .then_with(|| left_hash.cmp(right_hash))
180            },
181        );
182
183        let mut full_ordinals: FxHashMap<u64, usize> = FxHashMap::default();
184        let mut ambiguous_short_handles: FxHashSet<String> = FxHashSet::default();
185        let mut by_key = FxHashMap::default();
186        let mut key_by_fingerprint = FxHashMap::default();
187
188        for (key, hash, _) in &sorted_entries {
189            let short = *hash as u32;
190            let short_handle = format!("{FINGERPRINT_PREFIX}{short:08x}");
191            let fingerprint = if short_counts.get(&short).copied().unwrap_or(0) == 1 {
192                short_handle
193            } else {
194                ambiguous_short_handles.insert(short_handle);
195                let full_handle = format!("{FINGERPRINT_PREFIX}{hash:016x}");
196                if full_counts.get(hash).copied().unwrap_or(0) == 1 {
197                    full_handle
198                } else {
199                    let ordinal = full_ordinals.entry(*hash).or_insert(0);
200                    *ordinal += 1;
201                    format!("{full_handle}-r{ordinal}")
202                }
203            };
204
205            key_by_fingerprint.insert(fingerprint.clone(), key.clone());
206            by_key.insert(key.clone(), fingerprint);
207        }
208
209        for handle in ambiguous_short_handles {
210            key_by_fingerprint.remove(&handle);
211        }
212
213        Self {
214            by_key,
215            key_by_fingerprint,
216        }
217    }
218}
219
220/// Compute a mode-independent normalized short content fingerprint for a clone
221/// group from all distinct instance token sequences.
222///
223/// Whitespace, comments, and line endings are absent from the normalized token
224/// hashes. Sorting and deduplicating sequences makes the fingerprint independent
225/// of instance order while ensuring a token edit in any distinct instance
226/// changes the group identity. Instance count is deliberately excluded and is
227/// appended separately by [`CloneFingerprintSet::ignored_clone_key_for_group`].
228///
229/// Use [`CloneFingerprintSet`] for user-facing report output, since it widens
230/// only the rare colliding handles while preserving this short form for the
231/// common case.
232///
233/// Hashes the empty string for an empty group (never produced by the detector,
234/// which guarantees `>= 2` instances), so the result is still a well-formed
235/// `dup:<8hex>` handle.
236#[must_use]
237pub fn clone_fingerprint(instances: &[CloneInstance]) -> String {
238    fingerprint_for_hash(hash_instances(instances))
239}
240
241/// The digest leaves out `\r`. It orders the groups of one full-hash
242/// collision, so a `\r` would swap their `-rN` suffixes between a CRLF and
243/// an LF checkout.
244fn hash_distinct_fragments(instances: &[CloneInstance]) -> u128 {
245    let mut fragments = instances
246        .iter()
247        .map(|instance| without_carriage_returns(&instance.fragment))
248        .collect::<Vec<_>>();
249    fragments.sort_unstable();
250    fragments.dedup();
251
252    let mut hasher = Xxh3::new();
253    for fragment in fragments {
254        update_hash_bytes(&mut hasher, fragment.as_bytes());
255    }
256    hasher.digest128()
257}
258
259fn without_carriage_returns(fragment: &str) -> std::borrow::Cow<'_, str> {
260    if fragment.contains('\r') {
261        std::borrow::Cow::Owned(fragment.replace('\r', ""))
262    } else {
263        std::borrow::Cow::Borrowed(fragment)
264    }
265}
266
267fn sorted_locations(instances: &[CloneInstance]) -> Vec<(&Path, usize, usize)> {
268    let mut locations = instances
269        .iter()
270        .map(|instance| {
271            (
272                instance.file.as_path(),
273                instance.start_line,
274                instance.end_line,
275            )
276        })
277        .collect::<Vec<_>>();
278    locations.sort_unstable();
279    locations
280}
281
282fn hash_sorted_locations(instances: &[CloneInstance]) -> u128 {
283    let mut hasher = Xxh3::new();
284    for (path, start_line, end_line) in sorted_locations(instances) {
285        update_hash_bytes(&mut hasher, path.as_os_str().as_encoded_bytes());
286        hasher.update(&start_line.to_le_bytes());
287        hasher.update(&end_line.to_le_bytes());
288    }
289    hasher.digest128()
290}
291
292fn update_hash_bytes(hasher: &mut Xxh3, bytes: &[u8]) {
293    hasher.update(&bytes.len().to_le_bytes());
294    hasher.update(bytes);
295}
296
297fn hash_instances(instances: &[CloneInstance]) -> u64 {
298    let mut sequences = distinct_fragment_inputs(instances)
299        .into_iter()
300        .map(|(kind, fragment)| normalized_fragment_sequence(kind.path(), fragment))
301        .collect::<Vec<_>>();
302    sequences.sort_unstable();
303    sequences.dedup();
304    hash_normalized_sequences(&sequences)
305}
306
307fn distinct_fragment_inputs(instances: &[CloneInstance]) -> Vec<(FragmentTokenizationKind, &str)> {
308    let mut fragments = instances
309        .iter()
310        .map(|instance| {
311            (
312                fragment_tokenization_kind(
313                    &instance.file,
314                    FragmentTokenizationStrategy::Fingerprint,
315                ),
316                instance.fragment.as_str(),
317            )
318        })
319        .collect::<Vec<_>>();
320    fragments.sort_unstable();
321    fragments.dedup();
322    fragments
323}
324
325fn normalized_fragment_sequence(path: &Path, fragment: &str) -> Vec<u64> {
326    let mut tokens = super::tokenize::tokenize_file(path, fragment, false).tokens;
327    if tokens.is_empty() {
328        // A clone can stop inside a block, so its fragment may not parse on its
329        // own. Without this fallback, every such group hashes to the same empty
330        // sequence and the baseline matches groups by report order.
331        tokens = super::tokenize::tokenize_unparsed_fragment(fragment);
332    }
333    super::normalize::normalize_and_hash(&tokens, DetectionMode::Strict)
334        .into_iter()
335        .map(|token| token.hash)
336        .collect()
337}
338
339fn hash_normalized_sequences(sequences: &[Vec<u64>]) -> u64 {
340    let byte_len = sequences
341        .iter()
342        .map(|sequence| sequence.len().saturating_add(1))
343        .sum::<usize>()
344        .saturating_mul(std::mem::size_of::<u64>());
345    let mut bytes = Vec::with_capacity(byte_len);
346    for sequence in sequences {
347        bytes.extend_from_slice(&(sequence.len() as u64).to_le_bytes());
348        for hash in sequence {
349            bytes.extend_from_slice(&hash.to_le_bytes());
350        }
351    }
352    xxh3_64(&bytes)
353}
354
355/// Report whether a baseline key comes from the shared empty-sequence bucket.
356///
357/// Versions before the fix for issue #3290 gave every clone group whose code
358/// did not parse on its own the hash of an empty token sequence, with a `-rN`
359/// suffix in report order. Such a key cannot address one group, so a baseline
360/// that contains one must be saved again. A report with only one such group
361/// had no suffix, so its key is not detected here. That group shows as new
362/// once, until the next save.
363#[must_use]
364pub fn is_unparsed_collision_key(key: &str) -> bool {
365    let bucket = format!(
366        "{FINGERPRINT_PREFIX}{:016x}-r",
367        hash_normalized_sequences(&[Vec::new()])
368    );
369    key.starts_with(&bucket)
370}
371
372fn fingerprint_for_hash(hash: u64) -> String {
373    format!("{FINGERPRINT_PREFIX}{:08x}", hash as u32)
374}
375
376/// Build a per-group `ExtractFunction` refactoring suggestion.
377///
378/// Mirrors the per-group branch of the families suggestion generator:
379/// the savings is `(instances - 1)` copies of the group's line count, since one
380/// copy survives as the extracted function and the rest collapse to call sites.
381#[must_use]
382pub fn group_refactoring_suggestion(group: &CloneGroup) -> RefactoringSuggestion {
383    let estimated_savings = group.line_count * group.instances.len().saturating_sub(1);
384    RefactoringSuggestion {
385        kind: RefactoringKind::ExtractFunction,
386        description: format!(
387            "Extract the shared {}-line block into one function and call it from {} sites",
388            group.line_count,
389            group.instances.len(),
390        ),
391        estimated_savings,
392    }
393}
394
395/// Best-effort name for the extracted function, derived from the most frequent
396/// non-generic identifier in the representative fragment.
397///
398/// Returns `None` when the dominant identifier is generic (`data`, `result`,
399/// loop counters), appears only once, or ties with another, so absence is the
400/// low-confidence signal for both human and agent consumers. This is a
401/// lexical heuristic over the raw fragment, not an AST analysis; it is advisory
402/// and consumers should verify before applying.
403#[must_use]
404pub fn dominant_identifier(group: &CloneGroup) -> Option<String> {
405    let fragment = group.instances.first().map(|inst| inst.fragment.as_str())?;
406    let mut counts: FxHashMap<&str, usize> = FxHashMap::default();
407    for word in identifier_words(fragment) {
408        if is_generic_identifier(word) {
409            continue;
410        }
411        *counts.entry(word).or_insert(0) += 1;
412    }
413
414    let mut candidates: Vec<_> = counts
415        .into_iter()
416        .map(|(word, count)| IdentifierCandidate {
417            word,
418            count,
419            score: identifier_score(word, count),
420        })
421        .collect();
422    candidates.sort_by(|a, b| {
423        b.score
424            .cmp(&a.score)
425            .then_with(|| b.count.cmp(&a.count))
426            .then_with(|| a.word.cmp(b.word))
427    });
428
429    let best = candidates.first()?;
430    if best.count < 2 {
431        return None;
432    }
433
434    let runner_up = candidates.get(1);
435    if runner_up.is_some_and(|next| best.score.saturating_sub(next.score) < 2) {
436        return None;
437    }
438
439    if is_plain_single_token(best.word) {
440        let next_count = runner_up.map_or(0, |candidate| candidate.count);
441        if best.count < 3 || best.count < next_count + 2 {
442            return None;
443        }
444    }
445
446    Some(best.word.to_string())
447}
448
449#[derive(Debug)]
450struct IdentifierCandidate<'a> {
451    word: &'a str,
452    count: usize,
453    score: usize,
454}
455
456fn identifier_score(word: &str, count: usize) -> usize {
457    let quality_bonus = if has_identifier_separator_or_case_transition(word) {
458        5
459    } else if word.chars().count() >= 8 {
460        2
461    } else {
462        0
463    };
464    count * 5 + quality_bonus
465}
466
467fn is_plain_single_token(word: &str) -> bool {
468    !has_identifier_separator_or_case_transition(word) && word.chars().count() < 8
469}
470
471fn has_identifier_separator_or_case_transition(word: &str) -> bool {
472    if word.contains('_') || word.contains('$') {
473        return true;
474    }
475
476    let mut previous = None;
477    for ch in word.chars() {
478        if previous.is_some_and(|prev: char| prev.is_ascii_lowercase() && ch.is_ascii_uppercase()) {
479            return true;
480        }
481        previous = Some(ch);
482    }
483    false
484}
485
486/// Yield identifier-like words (`[A-Za-z_$][A-Za-z0-9_$]*`) from raw source.
487fn identifier_words(source: &str) -> impl Iterator<Item = &str> {
488    source
489        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
490        .filter(|word| {
491            !word.is_empty()
492                && word
493                    .chars()
494                    .next()
495                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
496        })
497}
498
499/// Identifiers too generic to make a useful extracted-function name, plus the
500/// reserved words that show up as bare tokens in a fragment.
501const GENERIC_IDENTIFIERS: &[&str] = &[
502    "data",
503    "result",
504    "results",
505    "item",
506    "items",
507    "value",
508    "values",
509    "val",
510    "obj",
511    "object",
512    "arr",
513    "array",
514    "list",
515    "map",
516    "set",
517    "key",
518    "keys",
519    "tmp",
520    "temp",
521    "acc",
522    "cur",
523    "curr",
524    "prev",
525    "next",
526    "node",
527    "el",
528    "elem",
529    "element",
530    "args",
531    "arg",
532    "opts",
533    "options",
534    "params",
535    "param",
536    "props",
537    "ctx",
538    "context",
539    "res",
540    "req",
541    "err",
542    "error",
543    "fn",
544    "cb",
545    "callback",
546    "out",
547    "input",
548    "output",
549    "name",
550    "id",
551    "index",
552    "idx",
553    "x",
554    "y",
555    "z",
556    "i",
557    "j",
558    "k",
559    "n",
560    "m",
561    "a",
562    "b",
563    "c",
564    "e",
565    "_",
566    "const",
567    "let",
568    "var",
569    "function",
570    "return",
571    "if",
572    "else",
573    "for",
574    "while",
575    "do",
576    "switch",
577    "case",
578    "break",
579    "continue",
580    "new",
581    "this",
582    "true",
583    "false",
584    "null",
585    "undefined",
586    "void",
587    "typeof",
588    "instanceof",
589    "in",
590    "of",
591    "class",
592    "extends",
593    "super",
594    "import",
595    "export",
596    "from",
597    "default",
598    "async",
599    "await",
600    "yield",
601    "type",
602    "interface",
603    "enum",
604    "as",
605    "is",
606    "keyof",
607    "readonly",
608    "public",
609    "private",
610    "protected",
611    "static",
612    "get",
613    "delete",
614    "throw",
615    "try",
616    "catch",
617    "finally",
618    "string",
619    "number",
620    "boolean",
621    "any",
622    "unknown",
623    "never",
624    "bigint",
625    "symbol",
626    "Math",
627    "JSON",
628    "Object",
629    "Array",
630    "Promise",
631    "BigInt",
632    "Number",
633    "String",
634    "Boolean",
635    "Symbol",
636    "RegExp",
637    "Date",
638];
639
640fn is_generic_identifier(word: &str) -> bool {
641    word.chars().count() == 1 || GENERIC_IDENTIFIERS.contains(&word)
642}
643
644#[cfg(test)]
645mod tests {
646    use std::path::PathBuf;
647
648    use super::*;
649
650    fn instance(fragment: &str) -> CloneInstance {
651        CloneInstance {
652            is_symlink: false,
653            file: PathBuf::from("a.ts"),
654            start_line: 1,
655            end_line: 5,
656            start_col: 0,
657            end_col: 0,
658            fragment: fragment.to_string(),
659        }
660    }
661
662    fn group(fragments: &[&str], line_count: usize) -> CloneGroup {
663        CloneGroup {
664            instances: fragments.iter().map(|f| instance(f)).collect(),
665            token_count: 40,
666            line_count,
667            similarity: None,
668        }
669    }
670
671    fn relocated_collision_groups(root: &Path) -> Vec<CloneGroup> {
672        ["src", "other"]
673            .into_iter()
674            .map(|directory| {
675                let mut clone = group(&["alpha()", "alpha()"], 2);
676                for (index, instance) in clone.instances.iter_mut().enumerate() {
677                    instance.file = root.join(directory).join(format!("file-{index}.ts"));
678                }
679                clone
680            })
681            .collect()
682    }
683
684    /// A clone that stops before the closing brace of its function does not
685    /// parse on its own.
686    fn unclosed_function_fragment(constant: u32) -> String {
687        format!(
688            "export function scale(items: number[]): number[] {{\n  const out = items.map((item) => item * {constant});\n  return out;\n"
689        )
690    }
691
692    #[test]
693    fn unparseable_fragments_keep_distinct_fingerprints() {
694        let first = unclosed_function_fragment(7);
695        let second = unclosed_function_fragment(13);
696        assert_ne!(
697            hash_instances(&group(&[&first, &first], 3).instances),
698            hash_instances(&group(&[&second, &second], 3).instances),
699            "different code must not share the empty-sequence hash"
700        );
701    }
702
703    #[test]
704    fn detects_keys_from_the_old_empty_sequence_bucket() {
705        assert!(is_unparsed_collision_key("dup:c77b3abb6f87acd9-r3:2"));
706        assert!(!is_unparsed_collision_key("dup:c77b3abb6f87acd9:2"));
707        assert!(!is_unparsed_collision_key("dup:6f87acd9:2"));
708        let fragment = unclosed_function_fragment(7);
709        let fingerprints = CloneFingerprintSet::from_groups(&[group(&[&fragment, &fragment], 3)]);
710        let key = fingerprints.ignored_clone_key_for_group(&group(&[&fragment, &fragment], 3));
711        assert!(!is_unparsed_collision_key(&key));
712    }
713
714    #[test]
715    fn unparseable_fragments_ignore_whitespace_and_comments() {
716        let compact = unclosed_function_fragment(7);
717        let spaced = compact.replace("  return out;", "  // done\n    return   out;");
718        assert_eq!(
719            hash_instances(&group(&[&compact], 3).instances),
720            hash_instances(&group(&[&spaced], 3).instances),
721        );
722    }
723
724    #[test]
725    fn baseline_reports_only_the_new_unparseable_clone() {
726        use super::super::types::DuplicationReport;
727        use crate::baseline::{DuplicationBaselineData, filter_new_clone_groups};
728
729        let root = Path::new("/project");
730        let pair = |constant: u32, name: &str| {
731            let fragment = unclosed_function_fragment(constant);
732            let mut clone = group(&[&fragment, &fragment], 3);
733            for (index, instance) in clone.instances.iter_mut().enumerate() {
734                instance.file = root.join(format!("src/{name}-{index}.ts"));
735            }
736            clone
737        };
738        let baseline_report = DuplicationReport {
739            clone_groups: vec![pair(7, "a"), pair(13, "c"), pair(29, "e")],
740            ..Default::default()
741        };
742        let baseline = DuplicationBaselineData::from_report(&baseline_report, root);
743
744        let mut current = baseline_report.clone_groups;
745        current.push(pair(3, "g"));
746        let filtered = filter_new_clone_groups(
747            DuplicationReport {
748                clone_groups: current,
749                ..Default::default()
750            },
751            &baseline,
752            root,
753        );
754        let files: Vec<_> = filtered
755            .clone_groups
756            .iter()
757            .flat_map(|clone| clone.instances.iter().map(|i| i.file.clone()))
758            .collect();
759        assert_eq!(
760            files,
761            vec![root.join("src/g-0.ts"), root.join("src/g-1.ts")]
762        );
763    }
764
765    #[test]
766    fn fingerprint_set_relocation_preserves_collision_identity() {
767        const RELOCATIONS: usize = 32;
768        let groups = relocated_collision_groups(Path::new("/original/checkout"));
769        let fingerprints = CloneFingerprintSet::from_groups(&groups);
770        let expected = fingerprints.fingerprint_for_group(&groups[0]);
771        for index in 0..RELOCATIONS {
772            let root = PathBuf::from(format!("/different/checkout-{index}/with spaces/café"));
773            let mut relocated = relocated_collision_groups(&root);
774            relocated.reverse();
775            for group in &mut relocated {
776                group.instances.reverse();
777            }
778            let actual = CloneFingerprintSet::from_groups(&relocated);
779            assert_eq!(
780                actual.fingerprint_for_group(&relocated[1]),
781                expected,
782                "{root:?}"
783            );
784            assert!(std::ptr::eq(
785                actual
786                    .find_group(&relocated, &expected)
787                    .expect("relocated trace handle resolves"),
788                &raw const relocated[1],
789            ));
790            assert_eq!(
791                actual.fingerprint_for_parts(
792                    &relocated[1].instances,
793                    relocated[1].token_count,
794                    relocated[1].line_count
795                ),
796                expected,
797            );
798        }
799    }
800
801    #[test]
802    fn corrected_collision_handles_do_not_alias_legacy_ordinals() {
803        let groups = relocated_collision_groups(Path::new("/project"));
804        let fingerprints = CloneFingerprintSet::from_groups(&groups);
805        for group in &groups {
806            let corrected = fingerprints.fingerprint_for_group(group);
807            assert!(corrected.contains("-r"));
808            let legacy = corrected.replacen("-r", "-", 1);
809            assert!(fingerprints.find_group(&groups, &legacy).is_none());
810            assert!(fingerprints.find_group(&groups, &corrected).is_some());
811        }
812    }
813
814    #[test]
815    fn relocated_collision_suppression_matches_only_corrected_handles() {
816        use super::super::types::DuplicationReport;
817        use crate::baseline::{DuplicationBaselineData, filter_new_clone_groups};
818
819        let original = DuplicationReport {
820            clone_groups: relocated_collision_groups(Path::new("/original/checkout")),
821            ..Default::default()
822        };
823        let fingerprints = CloneFingerprintSet::from_groups(&original.clone_groups);
824        let reviewed = fingerprints.ignored_clone_key_for_group(&original.clone_groups[0]);
825        let baseline =
826            DuplicationBaselineData::from_report(&original, Path::new("/original/checkout"));
827        let root = Path::new("/relocated/with spaces/café");
828        let mut relocated = DuplicationReport {
829            clone_groups: relocated_collision_groups(root),
830            ..Default::default()
831        };
832        relocated.clone_groups.reverse();
833        for group in &mut relocated.clone_groups {
834            group.instances.reverse();
835        }
836        let remaining_location = relocated.clone_groups[0].instances[0].file.clone();
837
838        let mut ignored = relocated.clone();
839        super::super::apply_ignored_clones_filter(&mut ignored, std::slice::from_ref(&reviewed));
840        assert_eq!(ignored.clone_groups.len(), 1);
841        assert_eq!(
842            ignored.clone_groups[0].instances[0].file,
843            remaining_location
844        );
845        assert_eq!(ignored.stats.clone_groups_ignored, 1);
846
847        let mut partial_baseline =
848            DuplicationBaselineData::from_report(&original, Path::new("/original/checkout"));
849        partial_baseline.normalized_clone_fingerprints = vec![reviewed.clone()];
850        // The baseline filter returns the report order, so the instance order
851        // of the reversed input does not survive. The location still names
852        // the group that stays.
853        let filtered = filter_new_clone_groups(relocated.clone(), &partial_baseline, root);
854        assert_eq!(filtered.clone_groups.len(), 1);
855        assert!(
856            filtered.clone_groups[0]
857                .instances
858                .iter()
859                .any(|instance| instance.file == remaining_location)
860        );
861        assert!(
862            filter_new_clone_groups(relocated.clone(), &baseline, root)
863                .clone_groups
864                .is_empty()
865        );
866
867        let legacy = reviewed.replacen("-r", "-", 1);
868        super::super::apply_ignored_clones_filter(&mut relocated, std::slice::from_ref(&legacy));
869        assert_eq!(relocated.clone_groups.len(), original.clone_groups.len());
870        partial_baseline.normalized_clone_fingerprints = vec![legacy];
871        // Populated old raw/location fields must not turn a normalized-key miss
872        // into an ambiguous fallback suppression.
873        let filtered = filter_new_clone_groups(relocated, &partial_baseline, root);
874        assert_eq!(filtered.clone_groups.len(), original.clone_groups.len());
875    }
876
877    #[test]
878    fn fingerprint_is_stable_and_prefixed() {
879        let g = group(&["foo(bar)", "foo(baz)"], 3);
880        let fp1 = clone_fingerprint(&g.instances);
881        let fp2 = clone_fingerprint(&g.instances);
882        assert_eq!(fp1, fp2);
883        assert!(fp1.starts_with("dup:"));
884        assert_eq!(fp1.len(), "dup:".len() + 8);
885    }
886
887    #[test]
888    fn compact_fingerprint_key_is_independent_of_instance_order() {
889        let mut original = group(&["alpha()", "beta()"], 3);
890        original.instances[0].file = PathBuf::from("src/a.ts");
891        original.instances[0].start_line = 2;
892        original.instances[1].file = PathBuf::from("src/b.ts");
893        original.instances[1].start_line = 8;
894        let mut reordered = original.clone();
895        reordered.instances.reverse();
896
897        assert_eq!(
898            CloneFingerprintKey::from_group(&original),
899            CloneFingerprintKey::from_group(&reordered)
900        );
901    }
902
903    #[test]
904    fn duplicate_fragments_are_deduplicated_before_tokenization() {
905        let mut clones = group(&["alpha()", "alpha()", "alpha()"], 2);
906        clones.instances[0].file = PathBuf::from("src/a.ts");
907        clones.instances[1].file = PathBuf::from("src/b.ts");
908        clones.instances[2].file = PathBuf::from("src/c.ts");
909        assert_eq!(distinct_fragment_inputs(&clones.instances).len(), 1);
910
911        clones.instances[2].file = PathBuf::from("src/c.css");
912        assert_eq!(
913            distinct_fragment_inputs(&clones.instances).len(),
914            2,
915            "equal source still needs separate tokenization when syntax differs"
916        );
917    }
918
919    #[test]
920    fn fingerprint_is_sibling_stable() {
921        let group_a = group(&["computeInvoiceTotal(order)", "computeInvoiceTotal(o)"], 4);
922        let before = clone_fingerprint(&group_a.instances);
923        let _group_b_edited = group(&["totallyDifferentBody()"], 2);
924        let after = clone_fingerprint(&group_a.instances);
925        assert_eq!(before, after);
926    }
927
928    #[test]
929    fn fingerprint_differs_for_different_content() {
930        let a = group(&["alpha()"], 2);
931        let b = group(&["beta()"], 2);
932        assert_ne!(
933            clone_fingerprint(&a.instances),
934            clone_fingerprint(&b.instances)
935        );
936    }
937
938    /// Two groups whose fragments differ only in a comment share one full
939    /// hash, so the `-rN` suffix follows the order of their fragment digests.
940    fn colliding_groups(variant: usize, line_ending: &str) -> Vec<CloneGroup> {
941        ["left", "right"]
942            .into_iter()
943            .map(|side| {
944                let fragment = format!("alpha();{line_ending}// {side} {variant}{line_ending}");
945                let mut clone = group(&[&fragment, &fragment], 2);
946                for (index, instance) in clone.instances.iter_mut().enumerate() {
947                    instance.file = PathBuf::from(format!("{side}-{index}.ts"));
948                }
949                clone
950            })
951            .collect()
952    }
953
954    #[test]
955    fn collision_suffixes_ignore_line_endings() {
956        for variant in 0..16 {
957            let lf = colliding_groups(variant, "\n");
958            let crlf = colliding_groups(variant, "\r\n");
959            let lf_set = CloneFingerprintSet::from_groups(&lf);
960            let crlf_set = CloneFingerprintSet::from_groups(&crlf);
961            let lf_handles: Vec<_> = lf.iter().map(|g| lf_set.fingerprint_for_group(g)).collect();
962            let crlf_handles: Vec<_> = crlf
963                .iter()
964                .map(|g| crlf_set.fingerprint_for_group(g))
965                .collect();
966            assert!(lf_handles[0].ends_with("-r1") || lf_handles[0].ends_with("-r2"));
967            assert_eq!(lf_handles, crlf_handles, "variant {variant}");
968        }
969    }
970
971    #[test]
972    fn fingerprint_ignores_formatting_comments_and_line_endings() {
973        let compact = group(
974            &["const total = left + right;", "const total = left + right;"],
975            2,
976        );
977        let formatted = group(
978            &[
979                "const  total=left + right; // reviewed\r\n",
980                "/* reviewed */\nconst total = left + right;",
981            ],
982            3,
983        );
984
985        assert_eq!(
986            clone_fingerprint(&compact.instances),
987            clone_fingerprint(&formatted.instances)
988        );
989    }
990
991    #[test]
992    fn fingerprint_changes_when_any_distinct_instance_changes_tokens() {
993        let reviewed = group(&["alpha()", "alpha()"], 2);
994        let edited = group(&["alpha()", "beta()"], 2);
995
996        assert_ne!(
997            clone_fingerprint(&reviewed.instances),
998            clone_fingerprint(&edited.instances)
999        );
1000    }
1001
1002    #[test]
1003    fn fingerprint_is_independent_of_instance_order_and_count() {
1004        let two = group(&["alpha()", "beta()"], 2);
1005        let three_reordered = group(&["beta()", "alpha()", "alpha()"], 2);
1006
1007        assert_eq!(
1008            clone_fingerprint(&two.instances),
1009            clone_fingerprint(&three_reordered.instances)
1010        );
1011
1012        let two_set = CloneFingerprintSet::from_groups(std::slice::from_ref(&two));
1013        let three_set = CloneFingerprintSet::from_groups(std::slice::from_ref(&three_reordered));
1014        assert_ne!(
1015            two_set.ignored_clone_key_for_group(&two),
1016            three_set.ignored_clone_key_for_group(&three_reordered)
1017        );
1018    }
1019
1020    #[test]
1021    fn fingerprint_set_widens_only_colliding_short_handles() {
1022        let a = group(&["alpha()"], 2);
1023        let b = group(&["beta()"], 2);
1024        let c = group(&["gamma()"], 2);
1025        let entries = vec![
1026            (&a, 0x0000_0001_1234_5678_u64),
1027            (&b, 0x0000_0002_1234_5678_u64),
1028            (&c, 0x0000_0003_8765_4321_u64),
1029        ];
1030
1031        let fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1032
1033        assert_eq!(
1034            fingerprints.fingerprint_for_group(&a),
1035            "dup:0000000112345678"
1036        );
1037        assert_eq!(
1038            fingerprints.fingerprint_for_group(&b),
1039            "dup:0000000212345678"
1040        );
1041        assert_eq!(fingerprints.fingerprint_for_group(&c), "dup:87654321");
1042        assert!(
1043            fingerprints
1044                .find_group(&[a.clone(), b.clone(), c.clone()], "dup:12345678")
1045                .is_none()
1046        );
1047        assert_eq!(
1048            fingerprints
1049                .find_group(&[a, b, c], "dup:0000000212345678")
1050                .and_then(|group| group.instances.first())
1051                .map(|inst| inst.fragment.as_str()),
1052            Some("beta()")
1053        );
1054    }
1055
1056    #[test]
1057    fn fingerprint_set_suffixes_full_hash_collisions() {
1058        let a = group(&["alpha()"], 2);
1059        let b = group(&["beta()"], 2);
1060        let mut entries = vec![
1061            (&a, 0x0000_0001_1234_5678_u64),
1062            (&b, 0x0000_0001_1234_5678_u64),
1063        ];
1064
1065        let fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1066        entries.reverse();
1067        let reversed_fingerprints = CloneFingerprintSet::from_hashed_entries(&entries);
1068
1069        let a_fingerprint = fingerprints.fingerprint_for_group(&a);
1070        let b_fingerprint = fingerprints.fingerprint_for_group(&b);
1071        assert_eq!(
1072            a_fingerprint,
1073            reversed_fingerprints.fingerprint_for_group(&a)
1074        );
1075        assert_eq!(
1076            b_fingerprint,
1077            reversed_fingerprints.fingerprint_for_group(&b)
1078        );
1079        let mut assigned = vec![a_fingerprint, b_fingerprint];
1080        assigned.sort_unstable();
1081        assert_eq!(
1082            assigned,
1083            ["dup:0000000112345678-r1", "dup:0000000112345678-r2"]
1084        );
1085        assert!(
1086            fingerprints
1087                .find_group(&[a.clone(), b.clone()], "dup:12345678")
1088                .is_none()
1089        );
1090        assert!(
1091            fingerprints
1092                .find_group(&[a, b], "dup:0000000112345678")
1093                .is_none()
1094        );
1095    }
1096
1097    #[test]
1098    fn group_suggestion_savings_is_lines_times_extra_copies() {
1099        let g = group(&["x", "x", "x"], 10); // 3 instances, 10 lines
1100        let suggestion = group_refactoring_suggestion(&g);
1101        assert_eq!(suggestion.kind, RefactoringKind::ExtractFunction);
1102        assert_eq!(suggestion.estimated_savings, 20); // 10 * (3 - 1)
1103    }
1104
1105    #[test]
1106    fn dominant_identifier_picks_repeated_domain_name() {
1107        let g = group(
1108            &["function buildInvoice(invoice) { return invoice.total + invoice.tax; }"],
1109            3,
1110        );
1111        assert_eq!(dominant_identifier(&g).as_deref(), Some("invoice"));
1112    }
1113
1114    #[test]
1115    fn dominant_identifier_none_on_generic() {
1116        let g = group(&["const data = result.map((item) => item.value);"], 3);
1117        assert_eq!(dominant_identifier(&g), None);
1118    }
1119
1120    #[test]
1121    fn dominant_identifier_skips_ts_primitive_keywords_and_globals() {
1122        let g = group(
1123            &["const parseUser = z.string(); parseUser(z.number()); parseUser.or(z.string());"],
1124            4,
1125        );
1126        assert_eq!(dominant_identifier(&g).as_deref(), Some("parseUser"));
1127        let only_keywords = group(&["const x: string = y as string; return x as any;"], 3);
1128        assert_eq!(dominant_identifier(&only_keywords), None);
1129        let g_global = group(&["Math.max(Math.floor(Math.abs(v)), 0)"], 3);
1130        assert_eq!(dominant_identifier(&g_global), None);
1131    }
1132
1133    #[test]
1134    fn dominant_identifier_none_on_single_letter_type_param() {
1135        let g = group(
1136            &["function id<T>(x: T): T { const a: T = x; return a as T; }"],
1137            3,
1138        );
1139        assert_eq!(dominant_identifier(&g), None);
1140    }
1141
1142    #[test]
1143    fn dominant_identifier_none_on_tie() {
1144        let g = group(&["alpha(); beta();"], 2); // each appears once, no count >= 2
1145        assert_eq!(dominant_identifier(&g), None);
1146    }
1147
1148    #[test]
1149    fn dominant_identifier_prefers_structured_names() {
1150        let g = group(
1151            &["parseSchema(input); parseSchema(cache); helper(); helper();"],
1152            3,
1153        );
1154        assert_eq!(dominant_identifier(&g).as_deref(), Some("parseSchema"));
1155    }
1156
1157    #[test]
1158    fn dominant_identifier_requires_plain_token_margin() {
1159        let low_signal = group(&["schema(); schema(); parseUser();"], 3);
1160        assert_eq!(dominant_identifier(&low_signal), None);
1161
1162        let strong = group(&["schema(); schema(); schema(); schema(); parseUser();"], 3);
1163        assert_eq!(dominant_identifier(&strong).as_deref(), Some("schema"));
1164    }
1165
1166    #[test]
1167    fn dominant_identifier_is_stable_across_word_order() {
1168        let first = group(
1169            &["helper(); parseSchema(input); helper(); parseSchema(cache);"],
1170            3,
1171        );
1172        let second = group(
1173            &["parseSchema(input); helper(); parseSchema(cache); helper();"],
1174            3,
1175        );
1176
1177        assert_eq!(dominant_identifier(&first), dominant_identifier(&second));
1178        assert_eq!(dominant_identifier(&first).as_deref(), Some("parseSchema"));
1179    }
1180}