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