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