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