Skip to main content

fallow_engine/
duplicates.rs

1//! Duplication result types exposed through the engine boundary.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::DuplicatesConfig;
6use fallow_types::discover::DiscoveredFile;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use crate::results::DuplicationAnalysis;
10use crate::workspace_scope::WorkspaceScope;
11
12#[path = "duplication_detector/mod.rs"]
13mod detector;
14
15#[cfg(test)]
16pub(crate) use detector::token_types;
17pub(crate) use detector::types;
18
19pub use detector::DUPES_DEFAULT_IGNORES;
20
21/// Detector internals re-exported for the engine's own benches and
22/// integration tests; not part of the supported engine API surface.
23#[doc(hidden)]
24pub use detector::{detect, normalize, tokenize};
25
26/// Engine alias for [`fallow_types::duplicates::CloneGroup`].
27pub type CloneGroup = fallow_types::duplicates::CloneGroup;
28/// Engine alias for [`fallow_types::duplicates::CloneGroupKind`].
29pub type CloneGroupKind = fallow_types::duplicates::CloneGroupKind;
30/// Engine alias for [`fallow_types::duplicates::CloneInstance`].
31pub type CloneInstance = fallow_types::duplicates::CloneInstance;
32/// Engine alias for [`fallow_types::duplicates::DefaultIgnoreSkips`].
33pub type DefaultIgnoreSkips = fallow_types::duplicates::DefaultIgnoreSkips;
34/// Engine alias for [`fallow_types::duplicates::DuplicationReport`].
35pub type DuplicationReport = fallow_types::duplicates::DuplicationReport;
36/// Engine alias for [`fallow_types::duplicates::DuplicationStats`].
37pub type DuplicationStats = fallow_types::duplicates::DuplicationStats;
38/// Engine alias for [`fallow_types::duplicates::RefactoringSuggestion`].
39pub type RefactoringSuggestion = fallow_types::duplicates::RefactoringSuggestion;
40
41pub use detector::{
42    CloneFingerprintKey, CloneFingerprintSet, FINGERPRINT_PREFIX, clone_fingerprint,
43    dominant_identifier,
44};
45pub(crate) use detector::{group_refactoring_suggestion, is_unparsed_collision_key};
46
47/// Refresh clone-family and mirrored-directory fields after clone groups change.
48pub fn refresh_clone_families(report: &mut DuplicationReport, root: &Path) {
49    report.clone_families = detector::families::group_into_families(&report.clone_groups, root);
50    report.mirrored_directories =
51        detector::families::detect_mirrored_directories(&report.clone_families, root);
52}
53
54/// Rebuild the fields that a scope filter invalidates: clone families,
55/// mirrored directories, statistics and the report order.
56///
57/// A scope filter (`--changed-since`, `--workspace`, a diff) narrows the corpus,
58/// so `stats` describes the narrowed corpus after this call. A presentation cap
59/// such as `--top` must not call this.
60pub(crate) fn refresh_scoped_report(report: &mut DuplicationReport, root: &Path) {
61    refresh_clone_families(report, root);
62    report.stats = recompute_stats(report);
63    report.sort();
64}
65
66/// Size of the corpus that a duplication run measured.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct CorpusTotals {
69    /// Number of files in the corpus.
70    pub files: usize,
71    /// Number of source lines in the corpus.
72    pub lines: usize,
73    /// Number of tokens in the corpus.
74    pub tokens: usize,
75}
76
77impl CorpusTotals {
78    /// The totals that `stats` records.
79    #[must_use]
80    pub const fn of(stats: &DuplicationStats) -> Self {
81        Self {
82            files: stats.total_files,
83            lines: stats.total_lines,
84            tokens: stats.total_tokens,
85        }
86    }
87}
88
89/// Counters that a statistics computation copies and does not derive from
90/// the clone groups.
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub struct CarriedCounters {
93    /// Number of clone families of the report.
94    pub clone_families: usize,
95    /// Number of clone groups that the `minOccurrences` filter hid.
96    pub clone_groups_below_min_occurrences: usize,
97    /// Number of clone groups that `ignoredClones` hid.
98    pub clone_groups_ignored: usize,
99    /// Number of near-clone candidates that the work bound skipped.
100    pub near_candidates_skipped: usize,
101}
102
103/// Accumulates the clone groups of one scope into duplication statistics.
104///
105/// Covered lines are the union of the line ranges of each file, so
106/// overlapping clone instances do not count a line two times.
107#[derive(Debug, Default)]
108pub struct CloneCoverage<'a> {
109    ranges_by_file: FxHashMap<&'a Path, Vec<(usize, usize)>>,
110    duplicated_tokens: usize,
111    clone_groups: usize,
112    clone_instances: usize,
113}
114
115impl<'a> CloneCoverage<'a> {
116    /// Add one clone group.
117    ///
118    /// `instances` are the instances that this scope counts. Each instance
119    /// after the first adds `token_count` redundant tokens.
120    pub fn add_group(
121        &mut self,
122        instances: impl IntoIterator<Item = &'a CloneInstance>,
123        token_count: usize,
124    ) {
125        self.clone_groups += 1;
126        let mut count = 0usize;
127        for instance in instances {
128            count += 1;
129            let ranges = self
130                .ranges_by_file
131                .entry(instance.file.as_path())
132                .or_default();
133            if instance.start_line <= instance.end_line {
134                ranges.push((instance.start_line, instance.end_line));
135            }
136        }
137        self.clone_instances += count;
138        self.duplicated_tokens = self
139            .duplicated_tokens
140            .saturating_add(token_count.saturating_mul(count.saturating_sub(1)));
141    }
142
143    /// Build the statistics against `totals`.
144    ///
145    /// `duplication_percentage` divides by `totals.lines`, and
146    /// `duplicated_tokens` does not exceed `totals.tokens`.
147    #[must_use]
148    pub fn into_stats(
149        mut self,
150        totals: CorpusTotals,
151        carried: CarriedCounters,
152    ) -> DuplicationStats {
153        let duplicated_lines: usize = self
154            .ranges_by_file
155            .values_mut()
156            .map(|ranges| count_covered_lines(ranges))
157            .sum();
158        DuplicationStats {
159            total_files: totals.files,
160            files_with_clones: self.ranges_by_file.len(),
161            total_lines: totals.lines,
162            duplicated_lines,
163            total_tokens: totals.tokens,
164            duplicated_tokens: self.duplicated_tokens.min(totals.tokens),
165            clone_groups: self.clone_groups,
166            clone_families: carried.clone_families,
167            clone_instances: self.clone_instances,
168            duplication_percentage: if totals.lines > 0 {
169                (duplicated_lines as f64 / totals.lines as f64) * 100.0
170            } else {
171                0.0
172            },
173            clone_groups_below_min_occurrences: carried.clone_groups_below_min_occurrences,
174            clone_groups_ignored: carried.clone_groups_ignored,
175            near_candidates_skipped: carried.near_candidates_skipped,
176        }
177    }
178}
179
180/// Statistics of `groups`, with every instance of each group, against
181/// `totals`.
182#[must_use]
183pub(crate) fn duplication_stats(
184    groups: &[CloneGroup],
185    totals: CorpusTotals,
186    carried: CarriedCounters,
187) -> DuplicationStats {
188    let mut coverage = CloneCoverage::default();
189    for group in groups {
190        coverage.add_group(&group.instances, group.token_count);
191    }
192    coverage.into_stats(totals, carried)
193}
194
195/// Number of lines that the inclusive ranges cover. Sorts `ranges`.
196fn count_covered_lines(ranges: &mut [(usize, usize)]) -> usize {
197    ranges.sort_unstable();
198    let Some(&(mut current_start, mut current_end)) = ranges.first() else {
199        return 0;
200    };
201
202    let mut covered = 0usize;
203    for &(start, end) in &ranges[1..] {
204        if start <= current_end.saturating_add(1) {
205            current_end = current_end.max(end);
206            continue;
207        }
208
209        covered += current_end - current_start + 1;
210        (current_start, current_end) = (start, end);
211    }
212
213    covered + current_end - current_start + 1
214}
215
216/// The scope of one duplication run, as the surface resolved it.
217///
218/// Every field is optional. A field that is `None` does not narrow the run.
219#[derive(Debug, Clone, Copy)]
220pub struct DuplicationScope<'a> {
221    /// The resolved change scope: a global changed-file set or the
222    /// configured package baselines.
223    pub changes: Option<&'a crate::change_scope::ChangeScope>,
224    /// A unified diff. Finding paths resolve against the report root.
225    pub diff: Option<&'a fallow_output::DiffIndex>,
226    /// `--workspace`, `--changed-workspaces` and a positional path.
227    pub workspace_roots: Option<&'a WorkspaceScope>,
228}
229
230/// Narrow a duplication report to the scope of the run.
231///
232/// The CLI, the programmatic API and the MCP typed path call this one function,
233/// so a scope narrows the same way on every surface. Each filter keeps a clone
234/// group when at least one instance is in scope, and keeps every instance of
235/// that group: a reviewer sees the full clone family. The filters run in this
236/// order: changed files, the diff, the workspace roots.
237pub fn apply_scope(report: &mut DuplicationReport, scope: &DuplicationScope<'_>, root: &Path) {
238    if let Some(changes) = scope.changes {
239        changes.retain_duplication(report, root);
240    }
241    if let Some(diff) = scope.diff {
242        crate::diff_scope::filter_duplication_by_diff(report, diff, root);
243    }
244    if let Some(roots) = scope.workspace_roots {
245        filter_to_workspaces(report, roots, root);
246    }
247}
248
249/// Keep only the clone groups with at least one instance in the workspace
250/// scope.
251///
252/// The full cross-workspace index is still built, so a group can hold an
253/// instance in the selected workspace and one in another workspace. The group
254/// stays whole: the documented rule is that a group is in scope when one of
255/// its instances is. Clone families, statistics and the order are rebuilt from
256/// the groups that stay.
257pub fn filter_to_workspaces(report: &mut DuplicationReport, scope: &WorkspaceScope, root: &Path) {
258    report.clone_groups.retain(|group| {
259        group
260            .instances
261            .iter()
262            .any(|instance| scope.contains(&instance.file))
263    });
264    report
265        .range_marker_problems
266        .retain(|finding| scope.contains(&finding.path));
267    refresh_scoped_report(report, root);
268}
269
270/// Keep only the `n` highest-ranked clone groups (`--top`).
271///
272/// `stats` keeps describing the corpus the run measured. Truncation is a
273/// presentation choice, so rewriting `clone_groups` or `clone_instances` from
274/// the truncated array would put two scopes in one object next to the
275/// untouched `files_with_clones` and `duplication_percentage`. Consumers read
276/// the shown and omitted split from `DuplicationReport::clone_groups_shown`
277/// and `clone_groups_omitted`.
278pub fn apply_top(report: &mut DuplicationReport, n: usize, root: &Path) {
279    report.sort();
280    report.clone_groups.truncate(n);
281    refresh_clone_families(report, root);
282    report.sort();
283}
284
285/// Recompute duplication statistics after clone groups have been filtered.
286///
287/// Uses [`CloneCoverage`], as the detector does, so overlapping clone
288/// instances do not inflate the duplicated line count.
289///
290/// `clone_families` is read from `report.clone_families`, so a scope filter
291/// must call [`refresh_clone_families`] before this. A presentation cap such
292/// as `--top` must not call this at all: it truncates the arrays while `stats`
293/// keeps describing the corpus the run measured.
294#[must_use]
295pub(crate) fn recompute_stats(report: &DuplicationReport) -> DuplicationStats {
296    duplication_stats(
297        &report.clone_groups,
298        CorpusTotals::of(&report.stats),
299        CarriedCounters {
300            clone_families: report.clone_families.len(),
301            clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
302            clone_groups_ignored: report.stats.clone_groups_ignored,
303            near_candidates_skipped: report.stats.near_candidates_skipped,
304        },
305    )
306}
307
308/// Compare JS/TS sources for audit-safe reuse of the current analysis at base.
309///
310/// Token kinds retain identifiers, ordinary literal values and the cooked
311/// static text of templates. Regex token kinds omit content, and template
312/// token kinds omit the raw spelling of their text, so the raw source spans
313/// of both must also match.
314/// Whole-template comparison conservatively rejects formatting changes inside
315/// interpolation expressions. The boolean is forwarded as tokenizer `skip_imports`.
316#[must_use]
317pub fn source_token_kinds_equivalent(
318    path: &Path,
319    current: &str,
320    base: &str,
321    cross_language: bool,
322) -> bool {
323    let current_tokens = detector::tokenize::tokenize_file(path, current, cross_language);
324    let base_tokens = detector::tokenize::tokenize_file(path, base, cross_language);
325    if current_tokens.tokens.len() != base_tokens.tokens.len() {
326        return false;
327    }
328    current_tokens
329        .tokens
330        .iter()
331        .zip(&base_tokens.tokens)
332        .all(|(current_token, base_token)| {
333            if current_token.kind != base_token.kind {
334                return false;
335            }
336            if matches!(
337                current_token.kind,
338                detector::token_types::TokenKind::TemplateLiteral(_)
339                    | detector::token_types::TokenKind::RegExpLiteral
340            ) {
341                return match (
342                    current.get(current_token.span.start as usize..current_token.span.end as usize),
343                    base.get(base_token.span.start as usize..base_token.span.end as usize),
344                ) {
345                    (Some(current_literal), Some(base_literal)) => current_literal == base_literal,
346                    _ => false,
347                };
348            }
349            true
350        })
351}
352
353/// Run duplication detection on a discovered file set.
354#[must_use]
355pub fn find_duplicates(
356    root: &Path,
357    files: &[DiscoveredFile],
358    config: &DuplicatesConfig,
359) -> DuplicationReport {
360    detector::find_duplicates(root, files, config)
361}
362
363/// Run duplication detection and include metadata about built-in ignored files.
364#[must_use]
365pub fn find_duplicates_with_defaults(
366    root: &Path,
367    files: &[DiscoveredFile],
368    config: &DuplicatesConfig,
369    cache_dir: Option<&Path>,
370) -> DuplicationAnalysis {
371    detector::detect_duplicates(root, files, config, None, cache_dir)
372}
373
374/// Run focused duplication detection and include metadata about built-in ignored files.
375#[must_use]
376pub fn find_duplicates_touching_files_with_defaults(
377    root: &Path,
378    files: &[DiscoveredFile],
379    config: &DuplicatesConfig,
380    changed_files: &[PathBuf],
381    cache_dir: Option<&Path>,
382) -> DuplicationAnalysis {
383    let changed_files = changed_files.iter().cloned().collect::<FxHashSet<_>>();
384    detector::detect_duplicates(root, files, config, Some(&changed_files), cache_dir)
385}
386
387#[cfg(test)]
388mod tests {
389    use std::path::PathBuf;
390
391    use super::*;
392
393    fn instance(file: &str, start_line: usize, end_line: usize) -> CloneInstance {
394        CloneInstance {
395            is_symlink: false,
396            file: PathBuf::from(file),
397            start_line,
398            end_line,
399            start_col: 0,
400            end_col: 0,
401            fragment: String::new(),
402        }
403    }
404
405    fn report(clone_groups: Vec<CloneGroup>) -> DuplicationReport {
406        DuplicationReport {
407            clone_groups,
408            clone_families: Vec::new(),
409            mirrored_directories: Vec::new(),
410            range_marker_problems: Vec::new(),
411            stats: DuplicationStats {
412                total_files: 3,
413                total_lines: 100,
414                total_tokens: 1_000,
415                clone_groups_below_min_occurrences: 4,
416                ..DuplicationStats::default()
417            },
418        }
419    }
420
421    #[test]
422    fn recompute_stats_deduplicates_overlapping_lines_per_file() {
423        let report = report(vec![
424            CloneGroup {
425                instances: vec![instance("src/a.ts", 1, 10), instance("src/b.ts", 20, 24)],
426                token_count: 30,
427                line_count: 10,
428                similarity: None,
429            },
430            CloneGroup {
431                instances: vec![instance("src/a.ts", 5, 12), instance("src/c.ts", 40, 44)],
432                token_count: 20,
433                line_count: 8,
434                similarity: None,
435            },
436        ]);
437
438        let stats = recompute_stats(&report);
439
440        assert_eq!(stats.total_files, 3);
441        assert_eq!(stats.files_with_clones, 3);
442        assert_eq!(stats.total_lines, 100);
443        assert_eq!(stats.duplicated_lines, 22);
444        assert_eq!(stats.total_tokens, 1_000);
445        assert_eq!(stats.duplicated_tokens, 50);
446        assert_eq!(stats.clone_groups, 2);
447        assert_eq!(stats.clone_instances, 4);
448        assert!((stats.duplication_percentage - 22.0).abs() < f64::EPSILON);
449        assert_eq!(stats.clone_groups_below_min_occurrences, 4);
450    }
451
452    #[test]
453    fn recompute_stats_handles_zero_total_lines() {
454        let mut report = report(vec![CloneGroup {
455            instances: vec![instance("src/a.ts", 1, 1)],
456            token_count: 5,
457            line_count: 1,
458            similarity: None,
459        }]);
460        report.stats.total_lines = 0;
461
462        let stats = recompute_stats(&report);
463
464        assert_eq!(stats.duplicated_lines, 1);
465        assert!(stats.duplication_percentage.abs() < f64::EPSILON);
466    }
467
468    #[test]
469    fn clone_fingerprint_set_delegates_without_leaking_core_type() {
470        let groups = vec![CloneGroup {
471            instances: vec![
472                CloneInstance {
473                    fragment: "const value = 1;".to_string(),
474                    ..instance("src/a.ts", 1, 1)
475                },
476                CloneInstance {
477                    fragment: "const value = 1;".to_string(),
478                    ..instance("src/b.ts", 2, 2)
479                },
480            ],
481            token_count: 5,
482            line_count: 1,
483            similarity: None,
484        }];
485        let fingerprints = CloneFingerprintSet::from_groups(&groups);
486        let fingerprint = fingerprints.fingerprint_for_group(&groups[0]);
487
488        assert!(fingerprint.starts_with(FINGERPRINT_PREFIX));
489        assert!(fingerprints.find_group(&groups, &fingerprint).is_some());
490    }
491
492    fn group(instances: Vec<CloneInstance>, token_count: usize) -> CloneGroup {
493        CloneGroup {
494            instances,
495            token_count,
496            line_count: 0,
497            similarity: None,
498        }
499    }
500
501    const fn totals(files: usize, lines: usize, tokens: usize) -> CorpusTotals {
502        CorpusTotals {
503            files,
504            lines,
505            tokens,
506        }
507    }
508
509    #[test]
510    fn duplication_stats_matches_a_line_set_reference() {
511        let groups = vec![
512            group(
513                vec![instance("src/a.ts", 1, 10), instance("src/a.ts", 5, 12)],
514                10,
515            ),
516            group(
517                vec![instance("src/a.ts", 20, 24), instance("src/a.ts", 25, 30)],
518                10,
519            ),
520            group(
521                vec![instance("src/a.ts", 40, 60), instance("src/a.ts", 45, 50)],
522                10,
523            ),
524            group(
525                vec![instance("src/a.ts", 9, 3), instance("src/d.ts", 9, 3)],
526                10,
527            ),
528            group(
529                vec![instance("src/a.ts", 70, 75), instance("src/a.ts", 70, 75)],
530                10,
531            ),
532            group(
533                vec![instance("src/b.ts", 1, 4), instance("src/c.ts", 3, 9)],
534                10,
535            ),
536        ];
537
538        let mut covered: FxHashSet<(&Path, usize)> = FxHashSet::default();
539        let mut files: FxHashSet<&Path> = FxHashSet::default();
540        for group in &groups {
541            for instance in &group.instances {
542                files.insert(&instance.file);
543                for line in instance.start_line..=instance.end_line {
544                    covered.insert((&instance.file, line));
545                }
546            }
547        }
548
549        let stats = duplication_stats(
550            &groups,
551            totals(4, 1_000, 10_000),
552            CarriedCounters::default(),
553        );
554
555        assert_eq!(stats.duplicated_lines, covered.len());
556        assert_eq!(stats.files_with_clones, files.len());
557    }
558
559    #[test]
560    fn duplication_stats_clamps_tokens_and_guards_zero_lines() {
561        let groups = vec![group(
562            vec![
563                instance("src/a.ts", 1, 5),
564                instance("src/b.ts", 1, 5),
565                instance("src/c.ts", 1, 5),
566            ],
567            1_000,
568        )];
569
570        let stats = duplication_stats(&groups, totals(3, 0, 500), CarriedCounters::default());
571
572        assert!(stats.duplication_percentage.abs() < f64::EPSILON);
573        assert_eq!(stats.duplicated_tokens, 500);
574    }
575
576    #[test]
577    fn duplication_stats_copies_carried_counters() {
578        let carried = CarriedCounters {
579            clone_families: 1,
580            clone_groups_below_min_occurrences: 2,
581            clone_groups_ignored: 3,
582            near_candidates_skipped: 4,
583        };
584
585        let stats = duplication_stats(&[], totals(1, 10, 100), carried);
586
587        assert_eq!(stats.clone_families, 1);
588        assert_eq!(stats.clone_groups_below_min_occurrences, 2);
589        assert_eq!(stats.clone_groups_ignored, 3);
590        assert_eq!(stats.near_candidates_skipped, 4);
591    }
592
593    #[test]
594    fn clone_coverage_counts_only_the_instances_it_receives() {
595        let clone_group = group(
596            vec![instance("src/a.ts", 1, 10), instance("src/b.ts", 20, 40)],
597            50,
598        );
599        let mut coverage = CloneCoverage::default();
600        coverage.add_group(
601            clone_group.instances.iter().take(1),
602            clone_group.token_count,
603        );
604
605        let stats = coverage.into_stats(totals(2, 100, 1_000), CarriedCounters::default());
606
607        assert_eq!(stats.clone_groups, 1);
608        assert_eq!(stats.clone_instances, 1);
609        assert_eq!(stats.duplicated_tokens, 0);
610        assert_eq!(stats.duplicated_lines, 10);
611    }
612}