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;
10
11#[path = "duplication_detector/mod.rs"]
12mod detector;
13
14#[cfg(test)]
15pub(crate) use detector::token_types;
16pub(crate) use detector::types;
17
18/// Detector internals re-exported for the engine's own benches and
19/// integration tests; not part of the supported engine API surface.
20#[doc(hidden)]
21pub use detector::{detect, normalize, tokenize};
22
23/// Engine alias for [`fallow_types::duplicates::CloneGroup`].
24pub type CloneGroup = fallow_types::duplicates::CloneGroup;
25/// Engine alias for [`fallow_types::duplicates::CloneGroupKind`].
26pub type CloneGroupKind = fallow_types::duplicates::CloneGroupKind;
27/// Engine alias for [`fallow_types::duplicates::CloneInstance`].
28pub type CloneInstance = fallow_types::duplicates::CloneInstance;
29/// Engine alias for [`fallow_types::duplicates::DefaultIgnoreSkips`].
30pub type DefaultIgnoreSkips = fallow_types::duplicates::DefaultIgnoreSkips;
31/// Engine alias for [`fallow_types::duplicates::DuplicationReport`].
32pub type DuplicationReport = fallow_types::duplicates::DuplicationReport;
33/// Engine alias for [`fallow_types::duplicates::DuplicationStats`].
34pub type DuplicationStats = fallow_types::duplicates::DuplicationStats;
35/// Engine alias for [`fallow_types::duplicates::RefactoringKind`].
36pub type RefactoringKind = fallow_types::duplicates::RefactoringKind;
37/// Engine alias for [`fallow_types::duplicates::RefactoringSuggestion`].
38pub type RefactoringSuggestion = fallow_types::duplicates::RefactoringSuggestion;
39
40pub use detector::{
41    CloneFingerprintKey, CloneFingerprintSet, FINGERPRINT_PREFIX, clone_fingerprint,
42    dominant_identifier, group_refactoring_suggestion,
43};
44
45/// Refresh clone-family and mirrored-directory fields after clone groups change.
46pub fn refresh_clone_families(report: &mut DuplicationReport, root: &Path) {
47    report.clone_families = detector::families::group_into_families(&report.clone_groups, root);
48    report.mirrored_directories =
49        detector::families::detect_mirrored_directories(&report.clone_families, root);
50}
51
52/// Rebuild the fields that a scope filter invalidates: clone families,
53/// mirrored directories, statistics and the report order.
54///
55/// A scope filter (`--changed-since`, `--workspace`, a diff) narrows the corpus,
56/// so `stats` describes the narrowed corpus after this call. A presentation cap
57/// such as `--top` must not call this.
58pub fn refresh_scoped_report(report: &mut DuplicationReport, root: &Path) {
59    refresh_clone_families(report, root);
60    report.stats = recompute_stats(report);
61    report.sort();
62}
63
64/// The scope of one duplication run, as the surface resolved it.
65///
66/// Every field is optional. A field that is `None` does not narrow the run.
67#[derive(Debug, Clone, Copy)]
68pub struct DuplicationScope<'a> {
69    /// The resolved change scope: a global changed-file set or the
70    /// configured package baselines.
71    pub changes: Option<&'a crate::change_scope::ChangeScope>,
72    /// A unified diff. Finding paths resolve against the report root.
73    pub diff: Option<&'a fallow_output::DiffIndex>,
74    /// `--workspace`, `--changed-workspaces` and a positional path: the union
75    /// of these roots.
76    pub workspace_roots: Option<&'a [PathBuf]>,
77}
78
79/// Narrow a duplication report to the scope of the run.
80///
81/// The CLI, the programmatic API and the MCP typed path call this one function,
82/// so a scope narrows the same way on every surface. Each filter keeps a clone
83/// group when at least one instance is in scope, and keeps every instance of
84/// that group: a reviewer sees the full clone family. The filters run in this
85/// order: changed files, the diff, the workspace roots.
86pub fn apply_scope(report: &mut DuplicationReport, scope: &DuplicationScope<'_>, root: &Path) {
87    if let Some(changes) = scope.changes {
88        changes.retain_duplication(report, root);
89    }
90    if let Some(diff) = scope.diff {
91        crate::diff_scope::filter_duplication_by_diff(report, diff, root);
92    }
93    if let Some(roots) = scope.workspace_roots {
94        filter_to_workspaces(report, roots, root);
95    }
96}
97
98/// Keep only the clone groups with at least one instance under one of the
99/// workspace roots.
100///
101/// The full cross-workspace index is still built, so a group can hold an
102/// instance in the selected workspace and one in another workspace. The group
103/// stays whole: the documented rule is that a group is in scope when one of
104/// its instances is. Clone families, statistics and the order are rebuilt from
105/// the groups that stay.
106pub fn filter_to_workspaces(report: &mut DuplicationReport, roots: &[PathBuf], root: &Path) {
107    report.clone_groups.retain(|group| {
108        group
109            .instances
110            .iter()
111            .any(|instance| roots.iter().any(|scope| instance.file.starts_with(scope)))
112    });
113    refresh_scoped_report(report, root);
114}
115
116/// Keep only the `n` highest-ranked clone groups (`--top`).
117///
118/// `stats` keeps describing the corpus the run measured. Truncation is a
119/// presentation choice, so rewriting `clone_groups` or `clone_instances` from
120/// the truncated array would put two scopes in one object next to the
121/// untouched `files_with_clones` and `duplication_percentage`. Consumers read
122/// the shown and omitted split from `DuplicationReport::clone_groups_shown`
123/// and `clone_groups_omitted`.
124pub fn apply_top(report: &mut DuplicationReport, n: usize, root: &Path) {
125    report.sort();
126    report.clone_groups.truncate(n);
127    refresh_clone_families(report, root);
128    report.sort();
129}
130
131/// Recompute duplication statistics after clone groups have been filtered.
132///
133/// Uses per-file line deduplication, matching the detector's stats model, so
134/// overlapping clone instances do not inflate the duplicated line count.
135///
136/// `clone_families` is read from `report.clone_families`, so a scope filter
137/// must call [`refresh_clone_families`] before this. A presentation cap such
138/// as `--top` must not call this at all: it truncates the arrays while `stats`
139/// keeps describing the corpus the run measured.
140#[must_use]
141pub fn recompute_stats(report: &DuplicationReport) -> DuplicationStats {
142    let mut files_with_clones: FxHashSet<&Path> = FxHashSet::default();
143    let mut file_dup_lines: FxHashMap<&Path, FxHashSet<usize>> = FxHashMap::default();
144    let mut duplicated_tokens = 0usize;
145    let mut clone_instances = 0usize;
146
147    for group in &report.clone_groups {
148        for instance in &group.instances {
149            files_with_clones.insert(&instance.file);
150            clone_instances += 1;
151            let lines = file_dup_lines.entry(&instance.file).or_default();
152            for line in instance.start_line..=instance.end_line {
153                lines.insert(line);
154            }
155        }
156        duplicated_tokens += group.token_count * group.instances.len().saturating_sub(1);
157    }
158
159    let duplicated_lines: usize = file_dup_lines.values().map(FxHashSet::len).sum();
160
161    DuplicationStats {
162        total_files: report.stats.total_files,
163        files_with_clones: files_with_clones.len(),
164        total_lines: report.stats.total_lines,
165        duplicated_lines,
166        total_tokens: report.stats.total_tokens,
167        duplicated_tokens: duplicated_tokens.min(report.stats.total_tokens),
168        clone_groups: report.clone_groups.len(),
169        clone_families: report.clone_families.len(),
170        clone_instances,
171        duplication_percentage: if report.stats.total_lines > 0 {
172            (duplicated_lines as f64 / report.stats.total_lines as f64) * 100.0
173        } else {
174            0.0
175        },
176        clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
177        clone_groups_ignored: report.stats.clone_groups_ignored,
178        near_candidates_skipped: report.stats.near_candidates_skipped,
179    }
180}
181
182/// Compare two JS/TS sources by duplicate-token kind sequence.
183///
184/// This keeps CLI audit's non-behavioral change check from depending on the
185/// tokenizer module shape.
186#[must_use]
187pub fn source_token_kinds_equivalent(
188    path: &Path,
189    current: &str,
190    base: &str,
191    cross_language: bool,
192) -> bool {
193    let current_tokens = detector::tokenize::tokenize_file(path, current, cross_language);
194    let base_tokens = detector::tokenize::tokenize_file(path, base, cross_language);
195    current_tokens
196        .tokens
197        .iter()
198        .map(|token| &token.kind)
199        .eq(base_tokens.tokens.iter().map(|token| &token.kind))
200}
201
202/// Run duplication detection on a discovered file set.
203#[must_use]
204pub fn find_duplicates(
205    root: &Path,
206    files: &[DiscoveredFile],
207    config: &DuplicatesConfig,
208) -> DuplicationReport {
209    detector::find_duplicates(root, files, config)
210}
211
212/// Run duplication detection and include metadata about built-in ignored files.
213#[must_use]
214pub fn find_duplicates_with_defaults(
215    root: &Path,
216    files: &[DiscoveredFile],
217    config: &DuplicatesConfig,
218    cache_dir: Option<&Path>,
219) -> DuplicationAnalysis {
220    detector::detect_duplicates(root, files, config, None, cache_dir)
221}
222
223/// Run focused duplication detection and include metadata about built-in ignored files.
224#[must_use]
225pub fn find_duplicates_touching_files_with_defaults(
226    root: &Path,
227    files: &[DiscoveredFile],
228    config: &DuplicatesConfig,
229    changed_files: &[PathBuf],
230    cache_dir: Option<&Path>,
231) -> DuplicationAnalysis {
232    let changed_files = changed_files.iter().cloned().collect::<FxHashSet<_>>();
233    detector::detect_duplicates(root, files, config, Some(&changed_files), cache_dir)
234}
235
236#[cfg(test)]
237mod tests {
238    use std::path::PathBuf;
239
240    use super::*;
241
242    fn instance(file: &str, start_line: usize, end_line: usize) -> CloneInstance {
243        CloneInstance {
244            file: PathBuf::from(file),
245            start_line,
246            end_line,
247            start_col: 0,
248            end_col: 0,
249            fragment: String::new(),
250        }
251    }
252
253    fn report(clone_groups: Vec<CloneGroup>) -> DuplicationReport {
254        DuplicationReport {
255            clone_groups,
256            clone_families: Vec::new(),
257            mirrored_directories: Vec::new(),
258            stats: DuplicationStats {
259                total_files: 3,
260                total_lines: 100,
261                total_tokens: 1_000,
262                clone_groups_below_min_occurrences: 4,
263                ..DuplicationStats::default()
264            },
265        }
266    }
267
268    #[test]
269    fn recompute_stats_deduplicates_overlapping_lines_per_file() {
270        let report = report(vec![
271            CloneGroup {
272                instances: vec![instance("src/a.ts", 1, 10), instance("src/b.ts", 20, 24)],
273                token_count: 30,
274                line_count: 10,
275                similarity: None,
276            },
277            CloneGroup {
278                instances: vec![instance("src/a.ts", 5, 12), instance("src/c.ts", 40, 44)],
279                token_count: 20,
280                line_count: 8,
281                similarity: None,
282            },
283        ]);
284
285        let stats = recompute_stats(&report);
286
287        assert_eq!(stats.total_files, 3);
288        assert_eq!(stats.files_with_clones, 3);
289        assert_eq!(stats.total_lines, 100);
290        assert_eq!(stats.duplicated_lines, 22);
291        assert_eq!(stats.total_tokens, 1_000);
292        assert_eq!(stats.duplicated_tokens, 50);
293        assert_eq!(stats.clone_groups, 2);
294        assert_eq!(stats.clone_instances, 4);
295        assert!((stats.duplication_percentage - 22.0).abs() < f64::EPSILON);
296        assert_eq!(stats.clone_groups_below_min_occurrences, 4);
297    }
298
299    #[test]
300    fn recompute_stats_handles_zero_total_lines() {
301        let mut report = report(vec![CloneGroup {
302            instances: vec![instance("src/a.ts", 1, 1)],
303            token_count: 5,
304            line_count: 1,
305            similarity: None,
306        }]);
307        report.stats.total_lines = 0;
308
309        let stats = recompute_stats(&report);
310
311        assert_eq!(stats.duplicated_lines, 1);
312        assert!(stats.duplication_percentage.abs() < f64::EPSILON);
313    }
314
315    #[test]
316    fn clone_fingerprint_set_delegates_without_leaking_core_type() {
317        let groups = vec![CloneGroup {
318            instances: vec![
319                CloneInstance {
320                    fragment: "const value = 1;".to_string(),
321                    ..instance("src/a.ts", 1, 1)
322                },
323                CloneInstance {
324                    fragment: "const value = 1;".to_string(),
325                    ..instance("src/b.ts", 2, 2)
326                },
327            ],
328            token_count: 5,
329            line_count: 1,
330            similarity: None,
331        }];
332        let fingerprints = CloneFingerprintSet::from_groups(&groups);
333        let fingerprint = fingerprints.fingerprint_for_group(&groups[0]);
334
335        assert!(fingerprint.starts_with(FINGERPRINT_PREFIX));
336        assert!(fingerprints.find_group(&groups, &fingerprint).is_some());
337    }
338}