Skip to main content

fallow_api/diff_risk/
clones.rs

1//! `diverged-clone-sibling`: the change edited one copy of a base clone group,
2//! that copy no longer matches, and no sibling changed.
3
4use rustc_hash::{FxHashMap, FxHashSet};
5
6/// One clone instance location, root-relative with forward slashes.
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub struct CloneSpan {
9    /// Root-relative path.
10    pub path: String,
11    /// 1-based first line.
12    pub start_line: u32,
13    /// 1-based last line, inclusive.
14    pub end_line: u32,
15}
16
17/// The instances of one base clone group. The paths are base paths: the
18/// rename remap of the audit does not move them.
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct BaseCloneGroup {
21    /// Instance locations in the base tree.
22    pub instances: Vec<CloneSpan>,
23}
24
25/// A base clone group that a `duplicates.ignoredClones` entry hid. The paths
26/// are base paths.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28pub struct AcceptedCloneGroup {
29    /// The `ignoredClones` entry that matched the group.
30    pub key: String,
31    /// Instance locations in the base tree.
32    pub instances: Vec<CloneSpan>,
33}
34
35/// One edited clone copy whose siblings did not change.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct DivergedClone {
38    /// Head path of the edited copy.
39    pub path: String,
40    /// 1-based head line where the edited copy starts, when a line of it
41    /// survives.
42    pub line: Option<u32>,
43    /// The unchanged siblings, at their head paths.
44    pub siblings: Vec<CloneSpan>,
45}
46
47/// Text access for the detector. `base` takes a base path, `head` a head path.
48pub struct CloneTexts<'a> {
49    /// Base text of a file, `None` when it cannot be read.
50    pub base: &'a mut dyn FnMut(&str) -> Option<String>,
51    /// Head text of a file, `None` when the file is gone or unreadable.
52    pub head: &'a mut dyn FnMut(&str) -> Option<String>,
53}
54
55/// Find the base clone groups where exactly one copy was edited, the edit
56/// broke the clone, and every sibling kept its text.
57///
58/// `changed` holds the head paths of the changed files. `renames` maps a base
59/// path to its head path. `head_groups` holds the instances of every head
60/// clone group, at head paths.
61#[must_use]
62#[expect(
63    clippy::implicit_hasher,
64    reason = "fallow standardizes on FxHashSet across the workspace"
65)]
66pub fn diverged_clone_siblings(
67    base_groups: &[BaseCloneGroup],
68    head_groups: &[Vec<CloneSpan>],
69    changed: &FxHashSet<String>,
70    renames: &FxHashMap<String, String>,
71    texts: &mut CloneTexts<'_>,
72) -> Vec<DivergedClone> {
73    let mut base_cache: FxHashMap<String, Option<String>> = FxHashMap::default();
74    let mut head_cache: FxHashMap<String, Option<String>> = FxHashMap::default();
75    let mut found = Vec::new();
76    for group in base_groups {
77        if group.instances.len() < 2 {
78            continue;
79        }
80        let mut edited: Vec<(CloneSpan, Option<u32>)> = Vec::new();
81        let mut siblings: Vec<CloneSpan> = Vec::new();
82        let mut skip_group = false;
83        for instance in &group.instances {
84            let head_path = renames
85                .get(&instance.path)
86                .cloned()
87                .unwrap_or_else(|| instance.path.clone());
88            let head_span = CloneSpan {
89                path: head_path.clone(),
90                ..instance.clone()
91            };
92            if !changed.contains(&head_path) {
93                siblings.push(head_span);
94                continue;
95            }
96            let base_text = base_cache
97                .entry(instance.path.clone())
98                .or_insert_with(|| (texts.base)(&instance.path));
99            let Some(fragment) = base_text
100                .as_deref()
101                .map(|text| fragment_lines(text, instance))
102            else {
103                skip_group = true;
104                break;
105            };
106            let head_text = head_cache
107                .entry(head_path.clone())
108                .or_insert_with(|| (texts.head)(&head_path));
109            let Some(head_text) = head_text.as_deref() else {
110                // A deleted copy is a removal, not a divergence.
111                skip_group = true;
112                break;
113            };
114            match classify_copy(&fragment, head_text) {
115                CopyState::Unchanged(lines) => siblings.push(match lines {
116                    Some((start_line, end_line)) => CloneSpan {
117                        start_line,
118                        end_line,
119                        ..head_span
120                    },
121                    None => head_span,
122                }),
123                CopyState::Edited(line) => edited.push((head_span, line)),
124                CopyState::Removed => {
125                    skip_group = true;
126                    break;
127                }
128            }
129        }
130        if skip_group || edited.len() != 1 || siblings.is_empty() {
131            continue;
132        }
133        let (copy, line) = edited.remove(0);
134        if still_clones(head_groups, &copy.path, &siblings) {
135            continue;
136        }
137        found.push(DivergedClone {
138            path: copy.path,
139            line,
140            siblings,
141        });
142    }
143    merge_same_copy(found)
144}
145
146/// One finding for each edited copy: two base groups that share the copy
147/// (nested or overlapping clones) merge, and their siblings join.
148fn merge_same_copy(found: Vec<DivergedClone>) -> Vec<DivergedClone> {
149    let mut merged: Vec<DivergedClone> = Vec::new();
150    for diverged in found {
151        if let Some(existing) = merged
152            .iter_mut()
153            .find(|existing| existing.path == diverged.path && existing.line == diverged.line)
154        {
155            existing.siblings.extend(diverged.siblings);
156        } else {
157            merged.push(diverged);
158        }
159    }
160    for diverged in &mut merged {
161        diverged
162            .siblings
163            .sort_by(|a, b| a.path.cmp(&b.path).then(a.start_line.cmp(&b.start_line)));
164        diverged
165            .siblings
166            .dedup_by(|a, b| a.path == b.path && a.start_line == b.start_line);
167    }
168    merged.sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
169    merged
170}
171
172enum CopyState {
173    /// The fragment is still in the head file, word for word. Carries the
174    /// 1-based head lines of its first and last non-blank line, so a copy
175    /// that moved inside its file keeps its head location.
176    Unchanged(Option<(u32, u32)>),
177    /// The fragment changed, and most of its lines survive. Carries the head
178    /// line of the first surviving line.
179    Edited(Option<u32>),
180    /// Most of the fragment is gone: a removal or a rewrite, not an edit.
181    Removed,
182}
183
184/// The trimmed, non-blank lines of a clone instance in its file.
185fn fragment_lines(text: &str, span: &CloneSpan) -> Vec<String> {
186    let start = usize::try_from(span.start_line.saturating_sub(1)).unwrap_or(usize::MAX);
187    let count = usize::try_from(span.end_line.saturating_sub(span.start_line) + 1).unwrap_or(0);
188    text.lines()
189        .skip(start)
190        .take(count)
191        .map(str::trim)
192        .filter(|line| !line.is_empty())
193        .map(str::to_owned)
194        .collect()
195}
196
197fn classify_copy(fragment: &[String], head_text: &str) -> CopyState {
198    if fragment.is_empty() {
199        return CopyState::Unchanged(None);
200    }
201    // Each non-blank head line with its 1-based line number.
202    let numbered: Vec<(u32, &str)> = head_text
203        .lines()
204        .enumerate()
205        .map(|(index, line)| (index, line.trim()))
206        .filter(|(_, line)| !line.is_empty())
207        .filter_map(|(index, line)| u32::try_from(index + 1).ok().map(|number| (number, line)))
208        .collect();
209    let head_lines: Vec<&str> = numbered.iter().map(|(_, line)| *line).collect();
210    let verbatim = head_lines.windows(fragment.len()).position(|window| {
211        window
212            .iter()
213            .zip(fragment)
214            .all(|(head, base)| *head == base)
215    });
216    if let Some(start) = verbatim {
217        let first = numbered[start].0;
218        let last = numbered[start + fragment.len() - 1].0;
219        return CopyState::Unchanged(Some((first, last)));
220    }
221    let head_set: FxHashSet<&str> = head_lines.iter().copied().collect();
222    let surviving = fragment
223        .iter()
224        .filter(|line| head_set.contains(line.as_str()))
225        .count();
226    if surviving * 2 < fragment.len() {
227        return CopyState::Removed;
228    }
229    let first_line = fragment
230        .iter()
231        .find(|line| head_set.contains(line.as_str()))
232        .and_then(|line| {
233            head_text
234                .lines()
235                .position(|head| head.trim() == line)
236                .and_then(|index| u32::try_from(index + 1).ok())
237        });
238    CopyState::Edited(first_line)
239}
240
241/// Whether a head clone group still joins the edited copy with the whole of
242/// a sibling. A group that covers only part of the sibling means the clone
243/// shrank: the edit broke the match from that point on.
244fn still_clones(head_groups: &[Vec<CloneSpan>], copy_path: &str, siblings: &[CloneSpan]) -> bool {
245    head_groups.iter().any(|group| {
246        group.iter().any(|instance| instance.path == copy_path)
247            && group.iter().any(|instance| {
248                siblings.iter().any(|sibling| {
249                    sibling.path == instance.path
250                        && instance.start_line <= sibling.start_line
251                        && sibling.end_line <= instance.end_line
252                })
253            })
254    })
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    const COPY: &str = "export function total(items) {\n  let sum = 0;\n  for (const item of items) {\n    sum += item.price * item.quantity;\n  }\n  return sum;\n}\n";
262    const EDITED: &str = "export function total(items) {\n  let sum = 0;\n  for (const item of items) {\n    sum += item.price * item.quantity * (1 - item.discount);\n  }\n  return sum;\n}\n";
263
264    fn span(path: &str) -> CloneSpan {
265        CloneSpan {
266            path: path.to_owned(),
267            start_line: 1,
268            end_line: 7,
269        }
270    }
271
272    fn group() -> Vec<BaseCloneGroup> {
273        vec![BaseCloneGroup {
274            instances: vec![span("src/a.ts"), span("src/b.ts")],
275        }]
276    }
277
278    fn run(
279        changed: &[&str],
280        head_a: Option<&str>,
281        head_b: &str,
282        head_groups: &[Vec<CloneSpan>],
283    ) -> Vec<DivergedClone> {
284        let changed: FxHashSet<String> = changed.iter().map(|path| (*path).to_owned()).collect();
285        let head_a = head_a.map(str::to_owned);
286        let head_b = head_b.to_owned();
287        let mut base = |_: &str| Some(COPY.to_owned());
288        let mut head = move |path: &str| match path {
289            "src/a.ts" => head_a.clone(),
290            _ => Some(head_b.clone()),
291        };
292        diverged_clone_siblings(
293            &group(),
294            head_groups,
295            &changed,
296            &FxHashMap::default(),
297            &mut CloneTexts {
298                base: &mut base,
299                head: &mut head,
300            },
301        )
302    }
303
304    #[test]
305    fn edited_copy_with_unchanged_sibling_is_reported() {
306        let found = run(&["src/a.ts"], Some(EDITED), COPY, &[]);
307        assert_eq!(found.len(), 1);
308        assert_eq!(found[0].path, "src/a.ts");
309        assert_eq!(found[0].line, Some(1));
310        assert_eq!(found[0].siblings, vec![span("src/b.ts")]);
311    }
312
313    #[test]
314    fn both_copies_edited_is_not_reported() {
315        assert!(run(&["src/a.ts", "src/b.ts"], Some(EDITED), EDITED, &[]).is_empty());
316    }
317
318    #[test]
319    fn edit_that_keeps_the_clone_is_not_reported() {
320        let head_groups = vec![vec![span("src/a.ts"), span("src/b.ts")]];
321        assert!(run(&["src/a.ts"], Some(EDITED), COPY, &head_groups).is_empty());
322    }
323
324    #[test]
325    fn edit_that_shrinks_the_clone_to_a_prefix_is_reported() {
326        let prefix = |path: &str| CloneSpan {
327            path: path.to_owned(),
328            start_line: 1,
329            end_line: 3,
330        };
331        let head_groups = vec![vec![prefix("src/a.ts"), prefix("src/b.ts")]];
332        assert_eq!(
333            run(&["src/a.ts"], Some(EDITED), COPY, &head_groups).len(),
334            1
335        );
336    }
337
338    #[test]
339    fn two_groups_on_one_edited_copy_report_once_with_every_sibling() {
340        let short = |path: &str| CloneSpan {
341            path: path.to_owned(),
342            start_line: 1,
343            end_line: 6,
344        };
345        let groups = vec![
346            BaseCloneGroup {
347                instances: vec![span("src/a.ts"), span("src/b.ts")],
348            },
349            BaseCloneGroup {
350                instances: vec![short("src/a.ts"), short("src/c.ts")],
351            },
352        ];
353        let changed: FxHashSet<String> = std::iter::once("src/a.ts".to_owned()).collect();
354        let mut base = |_: &str| Some(COPY.to_owned());
355        let mut head = |path: &str| Some(if path == "src/a.ts" { EDITED } else { COPY }.to_owned());
356        let found = diverged_clone_siblings(
357            &groups,
358            &[],
359            &changed,
360            &FxHashMap::default(),
361            &mut CloneTexts {
362                base: &mut base,
363                head: &mut head,
364            },
365        );
366        assert_eq!(found.len(), 1);
367        let paths: Vec<&str> = found[0].siblings.iter().map(|s| s.path.as_str()).collect();
368        assert_eq!(paths, vec!["src/b.ts", "src/c.ts"]);
369    }
370
371    const SHIFTED: &str = "import { round } from './round';\n";
372
373    fn shifted(path: &str) -> CloneSpan {
374        CloneSpan {
375            path: path.to_owned(),
376            start_line: 2,
377            end_line: 8,
378        }
379    }
380
381    #[test]
382    fn sibling_shifted_in_a_changed_file_that_still_clones_is_not_reported() {
383        let head_b = format!("{SHIFTED}{COPY}");
384        let head_groups = vec![vec![span("src/a.ts"), shifted("src/b.ts")]];
385        assert!(
386            run(
387                &["src/a.ts", "src/b.ts"],
388                Some(EDITED),
389                &head_b,
390                &head_groups
391            )
392            .is_empty()
393        );
394    }
395
396    #[test]
397    fn sibling_shifted_in_a_changed_file_reports_its_head_lines() {
398        let head_b = format!("{SHIFTED}{COPY}");
399        let found = run(&["src/a.ts", "src/b.ts"], Some(EDITED), &head_b, &[]);
400        assert_eq!(found.len(), 1);
401        assert_eq!(found[0].siblings, vec![shifted("src/b.ts")]);
402    }
403
404    #[test]
405    fn change_elsewhere_in_the_file_is_not_reported() {
406        let head = format!("{COPY}export const other = 1;\n");
407        assert!(run(&["src/a.ts"], Some(&head), COPY, &[]).is_empty());
408    }
409
410    #[test]
411    fn removed_or_deleted_copy_is_not_reported() {
412        assert!(run(&["src/a.ts"], Some("export const x = 1;\n"), COPY, &[]).is_empty());
413        assert!(run(&["src/a.ts"], None, COPY, &[]).is_empty());
414    }
415}