Skip to main content

fallow_api/audit_run/
clone_regions.rs

1//! Clone-region attribution of the audit.
2//!
3//! The detector keeps each maximal repeat. So one paste can give a long
4//! group with fewer copies and a short group with more copies, and the two
5//! groups cover the same lines. The audit collapses the groups whose
6//! instances overlap into one region, maps each instance through the diff to
7//! the base, and grades the region:
8//!
9//! - `introduced`: a member group has a copy that the base does not have, or
10//!   the change made two old pieces of code equal.
11//! - `inherited`: each member group is a base group, or the change wrote no
12//!   line of it.
13//! - `inherited-edited`: each member group lies inside a base group, and the
14//!   change edited one or more of its copies. Each copy grows by fewer lines
15//!   than `duplicates.minLines`. The rule reads the line count only, so a
16//!   rewrite that keeps the size of every copy is an edit, also when it
17//!   writes many new identical lines.
18//!
19//! The `introduced-clone-group` gate counts regions, and only an
20//! `introduced` region fails it.
21//!
22//! An `ignoredClones` entry follows an accepted clone through the audit
23//! match. The engine key of the entry does not change.
24
25use std::path::Path;
26
27use fallow_engine::changed_files::RenamedFile;
28use fallow_engine::duplicates::{CloneFingerprintSet, IgnoredCloneGroup};
29use fallow_engine::module_graph::relative_key_path;
30use fallow_output::DiffIndex;
31use fallow_types::duplicates::{CloneGroup, CloneInstance};
32use rustc_hash::{FxHashMap, FxHashSet};
33
34use crate::audit_keys::{ChangedPaths, dupe_group_key};
35use crate::audit_moved::moved_dupe_group_keys;
36use crate::diff_risk::clones::{AcceptedCloneGroup, BaseCloneGroup, CloneSpan};
37use crate::{
38    CloneDemotionReason, CloneRegionFinding, CloneRegionGrade, CloneRegionSpan, DupesReportPayload,
39};
40
41/// The head side of the region match.
42pub struct CloneRegionHead<'a> {
43    /// Head clone groups in output order.
44    pub groups: &'a [&'a CloneGroup],
45    /// Head clone groups that `duplicates.ignoredClones` hid.
46    pub ignored: &'a [IgnoredCloneGroup],
47    /// Root that key paths are relative to.
48    pub root: &'a Path,
49    /// The `duplicates.minLines` of the run: the fewest lines of a clone.
50    pub min_lines: usize,
51}
52
53/// The base side of the region match.
54pub struct CloneRegionBase<'a> {
55    /// Attribution keys of the base clone groups, at head paths.
56    pub keys: &'a FxHashSet<String>,
57    /// Instance locations of the base clone groups, at base paths.
58    pub groups: &'a [BaseCloneGroup],
59    /// Base clone groups that `duplicates.ignoredClones` hid, at base paths.
60    pub accepted: &'a [AcceptedCloneGroup],
61    /// The renamed files of the change.
62    pub renames: &'a [RenamedFile],
63    /// The changed files of the change, as key paths.
64    pub changed: &'a ChangedPaths,
65}
66
67/// The graded regions of one audit run.
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub struct CloneRegions {
70    regions: Vec<CloneRegion>,
71    /// Region index of each head group, in output order.
72    group_region: Vec<usize>,
73    /// Whether each head group adds duplication that no `ignoredClones`
74    /// entry accepts, in output order.
75    group_introduced: Vec<bool>,
76    /// Whether the change wrote no line of each head group with a new key,
77    /// in output order (issue #2164).
78    group_demoted: Vec<bool>,
79}
80
81/// One region: the head clone groups whose instances overlap.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct CloneRegion {
84    /// Grade of the region.
85    pub grade: CloneRegionGrade,
86    /// Whether the region fails the `introduced-clone-group` gate under
87    /// `new-only`: the grade is `introduced`, and no `ignoredClones` entry
88    /// accepts the new copies.
89    pub gates: bool,
90    /// Indices of the member groups, in output order.
91    pub groups: Vec<usize>,
92    /// The union of the member instance lines in each file, at head paths.
93    pub spans: Vec<CloneSpan>,
94    /// The `ignoredClones` entries that accept the region.
95    pub accepted_by: Vec<String>,
96    /// The `ignoredClones` keys of the member groups, when the region follows
97    /// an accepted base clone that the change edited. The config needs these
98    /// keys so that `fallow dupes` hides the edited clone too.
99    pub ignore_hint: Vec<String>,
100    /// Member groups that the change wrote no line of, although their key is
101    /// not in the base (issue #2164).
102    pub demoted: Vec<usize>,
103    /// The member groups of an `inherited-edited` region that lie inside a
104    /// base clone that an `ignoredClones` entry accepted.
105    edited_accepted: Vec<usize>,
106}
107
108impl CloneRegion {
109    /// Whether the region is `inherited-edited` and follows an accepted base
110    /// clone.
111    #[must_use]
112    pub fn follows_edited_accept(&self) -> bool {
113        !self.edited_accepted.is_empty()
114    }
115}
116
117impl CloneRegions {
118    /// The graded regions.
119    #[must_use]
120    pub fn regions(&self) -> &[CloneRegion] {
121        &self.regions
122    }
123
124    /// Number of regions that fail the gate.
125    #[must_use]
126    pub fn introduced_count(&self) -> usize {
127        self.regions.iter().filter(|region| region.gates).count()
128    }
129
130    /// Number of regions that do not fail the gate.
131    #[must_use]
132    pub fn inherited_count(&self) -> usize {
133        self.regions.len() - self.introduced_count()
134    }
135
136    /// Number of regions whose member groups the change did not write.
137    #[must_use]
138    pub fn demoted_count(&self) -> usize {
139        self.regions
140            .iter()
141            .filter(|region| !region.gates && !region.demoted.is_empty())
142            .count()
143    }
144
145    /// Region index of each head group, in output order.
146    #[must_use]
147    pub fn group_regions(&self) -> &[usize] {
148        &self.group_region
149    }
150
151    /// Whether the head group at `index` adds duplication that no
152    /// `ignoredClones` entry accepts. Its region then fails the gate. An old
153    /// group that overlaps a new group stays not introduced.
154    #[must_use]
155    pub fn group_introduced(&self, index: usize) -> bool {
156        self.group_introduced.get(index).copied().unwrap_or(false)
157    }
158
159    /// Whether the change wrote no line of the head group at `index`,
160    /// although its key is new (issue #2164).
161    #[must_use]
162    pub fn group_demoted(&self, index: usize) -> bool {
163        self.group_demoted.get(index).copied().unwrap_or(false)
164    }
165
166    /// Set the `region` index of each clone group and the `clone_regions`
167    /// list of a typed duplication payload whose groups are the graded head
168    /// groups, in the same order.
169    pub fn annotate_payload(&self, payload: &mut DupesReportPayload) {
170        if self.regions.is_empty() {
171            return;
172        }
173        for (finding, region) in payload.clone_groups.iter_mut().zip(&self.group_region) {
174            finding.region = Some(*region);
175        }
176        payload.clone_regions = self.findings();
177    }
178
179    /// Insert the `region` index of each clone group and the `clone_regions`
180    /// list into serialized duplication JSON whose `clone_groups` are the
181    /// graded head groups, in the same order.
182    pub fn annotate_json(&self, json: &mut serde_json::Value) {
183        if self.regions.is_empty() {
184            return;
185        }
186        if let Some(items) = json
187            .get_mut("clone_groups")
188            .and_then(serde_json::Value::as_array_mut)
189        {
190            for (item, region) in items.iter_mut().zip(&self.group_region) {
191                if let serde_json::Value::Object(map) = item {
192                    map.insert("region".to_owned(), serde_json::json!(region));
193                }
194            }
195        }
196        if let (serde_json::Value::Object(map), Ok(regions)) =
197            (json, serde_json::to_value(self.findings()))
198        {
199            map.insert("clone_regions".to_owned(), regions);
200        }
201    }
202
203    /// The wire form of the regions.
204    #[must_use]
205    pub fn findings(&self) -> Vec<CloneRegionFinding> {
206        self.regions
207            .iter()
208            .map(|region| CloneRegionFinding {
209                grade: region.grade,
210                introduced: region.gates,
211                groups: region.groups.clone(),
212                instances: region
213                    .spans
214                    .iter()
215                    .map(|span| CloneRegionSpan {
216                        file: span.path.clone(),
217                        start_line: span.start_line,
218                        end_line: span.end_line,
219                    })
220                    .collect(),
221                accepted_by: region.accepted_by.clone(),
222                ignore_hint: region.ignore_hint.clone(),
223                demotion_reason: (!region.gates && !region.demoted.is_empty())
224                    .then_some(CloneDemotionReason::NoAddedLines),
225            })
226            .collect()
227    }
228}
229
230/// How the change relates to one head clone group.
231#[derive(Debug, Clone, PartialEq, Eq)]
232enum Member {
233    /// The base has the group, under the same key or moved to other files.
234    Unchanged,
235    /// The key is new, but the change wrote no line of the group.
236    Demoted,
237    /// Each instance lies inside a different instance of one base group, and
238    /// the change edited one or more instances. `accepted` holds the
239    /// `ignoredClones` key of the base group when the base hid it.
240    Edited { accepted: Option<String> },
241    /// The change made duplication that the base did not have. `accepted`
242    /// holds the `ignoredClones` keys of the head groups that hid each new
243    /// copy, or is empty.
244    New { accepted: Vec<String> },
245}
246
247/// A base group that a set of spans fits in.
248enum Fit<'a> {
249    Visible,
250    Accepted(&'a str),
251}
252
253/// Maps a head instance to its base path and base lines.
254struct BaseMapper<'a> {
255    root: &'a Path,
256    diff: &'a DiffIndex,
257    head_to_base: FxHashMap<String, String>,
258}
259
260impl<'a> BaseMapper<'a> {
261    fn new(root: &'a Path, diff: &'a DiffIndex, renames: &[RenamedFile]) -> Self {
262        let head_to_base = renames
263            .iter()
264            .map(|rename| {
265                (
266                    relative_key_path(&rename.to, root),
267                    relative_key_path(&rename.from, root),
268                )
269            })
270            .collect();
271        Self {
272            root,
273            diff,
274            head_to_base,
275        }
276    }
277
278    /// The base span of a head span. `None` when the span has no base
279    /// lines, for example a copy in a new file.
280    fn base_span(&self, head: &CloneSpan) -> Option<CloneSpan> {
281        let rel = &head.path;
282        let key = self.diff.key_for(&self.root.join(rel), self.root)?;
283        let (base_start, base_end) = self.diff.base_line_range(
284            &key,
285            u64::from(head.start_line),
286            u64::from(head.end_line),
287        )?;
288        let path = self.head_to_base.get(rel).cloned().unwrap_or_else(|| {
289            self.diff
290                .old_path_for_root_relative(rel)
291                .map_or_else(|| rel.clone(), |old| old.into_owned())
292        });
293        Some(CloneSpan {
294            path,
295            start_line: u32::try_from(base_start).ok()?,
296            end_line: u32::try_from(base_end).ok()?,
297        })
298    }
299
300    /// Whether the change added a line inside `instance`. An instance whose
301    /// path does not map into the diff counts as touched, so its group keeps
302    /// its gate.
303    fn touched(&self, instance: &CloneInstance) -> bool {
304        let Some(key) = self.diff.key_for(&instance.file, self.root) else {
305            return true;
306        };
307        let start = u64::try_from(instance.start_line).unwrap_or(u64::MAX);
308        let end = u64::try_from(instance.end_line).unwrap_or(u64::MAX);
309        self.diff.range_overlaps_added(&key, start, end)
310    }
311}
312
313/// Grade the head clone groups as regions.
314///
315/// With `diff` absent, a group whose key is not in the base and that the
316/// change did not move is `introduced`.
317#[must_use]
318pub fn grade_clone_regions(
319    head: &CloneRegionHead<'_>,
320    base: &CloneRegionBase<'_>,
321    diff: Option<&DiffIndex>,
322) -> CloneRegions {
323    let keys: Vec<String> = head
324        .groups
325        .iter()
326        .map(|group| dupe_group_key(group, head.root))
327        .collect();
328    let moved = moved_dupe_group_keys(
329        keys.iter()
330            .map(String::as_str)
331            .filter(|key| !base.keys.contains(*key)),
332        &keys.iter().map(String::as_str).collect(),
333        base.keys,
334        base.changed,
335    );
336    let mapper = diff.map(|diff| BaseMapper::new(head.root, diff, base.renames));
337    let members: Vec<Member> = head
338        .groups
339        .iter()
340        .zip(&keys)
341        .map(|(group, key)| {
342            if base.keys.contains(key) || moved.contains(key) {
343                Member::Unchanged
344            } else if let Some(mapper) = mapper.as_ref() {
345                member_against_base(group, mapper, head, base)
346            } else {
347                Member::New {
348                    accepted: Vec::new(),
349                }
350            }
351        })
352        .collect();
353    collect_regions(head, &members)
354}
355
356fn member_against_base(
357    group: &CloneGroup,
358    mapper: &BaseMapper<'_>,
359    head: &CloneRegionHead<'_>,
360    base: &CloneRegionBase<'_>,
361) -> Member {
362    let touched: Vec<bool> = group
363        .instances
364        .iter()
365        .map(|instance| mapper.touched(instance))
366        .collect();
367    if !touched.contains(&true) {
368        return Member::Demoted;
369    }
370    let spans = head_spans(group, head.root);
371    let mapped: Vec<Option<CloneSpan>> = spans.iter().map(|span| mapper.base_span(span)).collect();
372    match edited_fit(&spans, &mapped, base.groups, base.accepted, head.min_lines) {
373        Some(Fit::Visible) => return Member::Edited { accepted: None },
374        Some(Fit::Accepted(key)) => {
375            return Member::Edited {
376                accepted: Some(key.to_owned()),
377            };
378        }
379        None => {}
380    }
381    Member::New {
382        accepted: accepting_ignored_groups(group, &mapped, &touched, head),
383    }
384}
385
386/// The head spans of a clone group, root-relative.
387fn head_spans(group: &CloneGroup, root: &Path) -> Vec<CloneSpan> {
388    group
389        .instances
390        .iter()
391        .map(|instance| CloneSpan {
392            path: relative_key_path(&instance.file, root),
393            start_line: u32::try_from(instance.start_line).unwrap_or(u32::MAX),
394            end_line: u32::try_from(instance.end_line).unwrap_or(u32::MAX),
395        })
396        .collect()
397}
398
399/// The number of lines of a span.
400fn span_lines(span: &CloneSpan) -> u32 {
401    span.end_line.saturating_sub(span.start_line) + 1
402}
403
404/// The base group that a head group edits: each head span maps to base
405/// lines, and the mapped spans fit in one base group. A base group that
406/// `ignoredClones` did not hide wins.
407///
408/// The growth of a copy is its head line count minus the line count of its
409/// mapped base span. Each copy must grow by fewer than `min_lines` lines. A
410/// rewrite that keeps the line count does not grow the copy, so it is an
411/// edit, also when it rewrites the whole copy. `mapped` holds the base span
412/// of each head span, `None` for a span with no base lines.
413fn edited_fit<'a>(
414    head: &[CloneSpan],
415    mapped: &[Option<CloneSpan>],
416    visible: &[BaseCloneGroup],
417    accepted: &'a [AcceptedCloneGroup],
418    min_lines: usize,
419) -> Option<Fit<'a>> {
420    let spans: Vec<CloneSpan> = mapped.iter().cloned().collect::<Option<_>>()?;
421    let growth = head
422        .iter()
423        .zip(&spans)
424        .map(|(head, base)| span_lines(head).saturating_sub(span_lines(base)))
425        .max()
426        .unwrap_or(0);
427    if usize::try_from(growth).unwrap_or(usize::MAX) >= min_lines {
428        return None;
429    }
430    if visible
431        .iter()
432        .any(|group| spans_fit_in_group(&spans, &group.instances, growth))
433    {
434        return Some(Fit::Visible);
435    }
436    accepted
437        .iter()
438        .find(|group| spans_fit_in_group(&spans, &group.instances, growth))
439        .map(|group| Fit::Accepted(group.key.as_str()))
440}
441
442/// The change that a head clone group compares with: the diff of the run and
443/// its renamed files.
444pub struct CloneChange<'a> {
445    /// Root that the head paths are relative to.
446    pub root: &'a Path,
447    /// The diff of the run.
448    pub diff: &'a DiffIndex,
449    /// The renamed files of the change.
450    pub renames: &'a [RenamedFile],
451}
452
453/// Whether the head clone group with the root-relative spans `head` is an
454/// edit of one of `base_groups`, by the rule that grades a clone region
455/// `inherited-edited`: each copy maps through the diff into a different copy
456/// of one base group, at the same relative place, and grows by fewer than
457/// `min_lines` lines. The base group may have more copies.
458#[must_use]
459pub fn edits_base_clone(
460    head: &[CloneSpan],
461    change: &CloneChange<'_>,
462    base_groups: &[BaseCloneGroup],
463    min_lines: usize,
464) -> bool {
465    let mapper = BaseMapper::new(change.root, change.diff, change.renames);
466    let mapped: Vec<Option<CloneSpan>> = head.iter().map(|span| mapper.base_span(span)).collect();
467    // No accepted groups: an accepted base group changes only which entry
468    // accepts the region, not whether the group is an edit.
469    edited_fit(head, &mapped, base_groups, &[], min_lines).is_some()
470}
471
472/// Whether each span lies inside a different instance of `base`, at the
473/// same place in each instance.
474///
475/// The copies of one clone hold equal text, so a part of the clone starts at
476/// the same relative place in each copy. Two base copies can differ in line
477/// count when their formatting differs, so the check scales the offset of
478/// the first span to the length of each other copy. The scaled offset may
479/// differ by the growth of the copies plus one line for a rewritten first
480/// line. Without
481/// this check, one new block that replaces lines at two different places of
482/// a base clone would map inside the base clone.
483fn spans_fit_in_group(spans: &[CloneSpan], base: &[CloneSpan], growth: u32) -> bool {
484    let mut used = vec![false; base.len()];
485    let mut offsets: Vec<(u32, u32)> = Vec::with_capacity(spans.len());
486    let all_inside = spans.iter().all(|span| {
487        let slot = base.iter().enumerate().position(|(index, outer)| {
488            !used[index]
489                && outer.path == span.path
490                && outer.start_line <= span.start_line
491                && span.end_line <= outer.end_line
492        });
493        slot.is_some_and(|index| {
494            used[index] = true;
495            let outer = &base[index];
496            offsets.push((
497                span.start_line - outer.start_line,
498                outer.end_line - outer.start_line + 1,
499            ));
500            true
501        })
502    });
503    if !all_inside {
504        return false;
505    }
506    let Some(&(first_offset, first_length)) = offsets.first() else {
507        return true;
508    };
509    let tolerance = u64::from(growth).saturating_add(1);
510    offsets.iter().all(|&(offset, length)| {
511        // `offset / length` against `first_offset / first_length`, in lines
512        // of the first copy.
513        let scaled = u64::from(offset) * u64::from(first_length);
514        let expected = u64::from(first_offset) * u64::from(length);
515        scaled.abs_diff(expected) <= tolerance.saturating_mul(u64::from(first_length))
516    })
517}
518
519/// The `ignoredClones` keys of the hidden head groups that accept the new
520/// copies of `group`, or an empty list.
521///
522/// The new copies are the instances with no base lines. Each one must lie
523/// inside an instance of a hidden head group. The other instances must be
524/// old duplication: they hold no added line. Equal text that the change did
525/// not edit was equal at the base too, so the base had that clone. The base
526/// snapshot cannot show it, because the base pass reports only the groups in
527/// the changed files. So when a paste gives a long group and a short group
528/// inside it, and the config accepts the long group, the short group only
529/// adds a copy that the base already had (issue #4967).
530fn accepting_ignored_groups(
531    group: &CloneGroup,
532    mapped: &[Option<CloneSpan>],
533    touched: &[bool],
534    head: &CloneRegionHead<'_>,
535) -> Vec<String> {
536    let mut keys: Vec<String> = Vec::new();
537    for (instance, span) in group.instances.iter().zip(mapped) {
538        if span.is_some() {
539            continue;
540        }
541        let Some(ignored) = head.ignored.iter().find(|ignored| {
542            ignored.group.instances.iter().any(|outer| {
543                outer.file == instance.file
544                    && outer.start_line <= instance.start_line
545                    && instance.end_line <= outer.end_line
546            })
547        }) else {
548            return Vec::new();
549        };
550        if !keys.contains(&ignored.key) {
551            keys.push(ignored.key.clone());
552        }
553    }
554    let edited_old_copy = mapped
555        .iter()
556        .zip(touched)
557        .any(|(span, touched)| span.is_some() && *touched);
558    if edited_old_copy {
559        return Vec::new();
560    }
561    keys
562}
563
564/// Collapse the groups whose instances overlap, and grade each region.
565fn collect_regions(head: &CloneRegionHead<'_>, members: &[Member]) -> CloneRegions {
566    let component = overlap_components(head.groups);
567    let mut region_of_component: FxHashMap<usize, usize> = FxHashMap::default();
568    let mut grouped: Vec<Vec<usize>> = Vec::new();
569    let mut group_region = Vec::with_capacity(head.groups.len());
570    for (index, root) in component.iter().enumerate() {
571        let region = *region_of_component.entry(*root).or_insert_with(|| {
572            grouped.push(Vec::new());
573            grouped.len() - 1
574        });
575        grouped[region].push(index);
576        group_region.push(region);
577    }
578    let mut regions: Vec<CloneRegion> = grouped
579        .into_iter()
580        .map(|groups| grade_region(head, members, groups))
581        .collect();
582    if regions.iter().any(CloneRegion::follows_edited_accept) {
583        let fingerprints = CloneFingerprintSet::from_group_refs(head.groups);
584        for region in &mut regions {
585            region.ignore_hint = region
586                .edited_accepted
587                .iter()
588                .map(|group| fingerprints.ignored_clone_key_for_group(head.groups[*group]))
589                .collect();
590        }
591    }
592    CloneRegions {
593        regions,
594        group_region,
595        group_introduced: members
596            .iter()
597            .map(|member| matches!(member, Member::New { accepted } if accepted.is_empty()))
598            .collect(),
599        group_demoted: members
600            .iter()
601            .map(|member| matches!(member, Member::Demoted))
602            .collect(),
603    }
604}
605
606fn grade_region(head: &CloneRegionHead<'_>, members: &[Member], groups: Vec<usize>) -> CloneRegion {
607    let mut grade = CloneRegionGrade::Inherited;
608    let mut gates = false;
609    let mut accepted_by: Vec<String> = Vec::new();
610    let mut edited_accepted = Vec::new();
611    let mut demoted = Vec::new();
612    let add_key = |accepted_by: &mut Vec<String>, key: &str| {
613        if !accepted_by.iter().any(|known| known == key) {
614            accepted_by.push(key.to_owned());
615        }
616    };
617    for index in &groups {
618        match &members[*index] {
619            Member::Unchanged => {}
620            Member::Demoted => demoted.push(*index),
621            Member::Edited { accepted } => {
622                if grade == CloneRegionGrade::Inherited {
623                    grade = CloneRegionGrade::InheritedEdited;
624                }
625                if let Some(key) = accepted {
626                    edited_accepted.push(*index);
627                    add_key(&mut accepted_by, key);
628                }
629            }
630            Member::New { accepted } => {
631                grade = CloneRegionGrade::Introduced;
632                if accepted.is_empty() {
633                    gates = true;
634                }
635                for key in accepted {
636                    add_key(&mut accepted_by, key);
637                }
638            }
639        }
640    }
641    // An entry does not accept a region that fails the gate, and a new copy
642    // makes the entry of an edited member irrelevant.
643    if gates {
644        accepted_by.clear();
645    }
646    if grade != CloneRegionGrade::InheritedEdited {
647        edited_accepted.clear();
648    }
649    CloneRegion {
650        grade,
651        gates,
652        spans: region_spans(head, &groups),
653        ignore_hint: Vec::new(),
654        edited_accepted,
655        accepted_by,
656        groups,
657        demoted,
658    }
659}
660
661/// The union of the member instance lines in each file, sorted by path and
662/// line.
663fn region_spans(head: &CloneRegionHead<'_>, groups: &[usize]) -> Vec<CloneSpan> {
664    let mut lines: Vec<(String, u32, u32)> = groups
665        .iter()
666        .flat_map(|index| &head.groups[*index].instances)
667        .map(|instance| {
668            (
669                relative_key_path(&instance.file, head.root),
670                u32::try_from(instance.start_line).unwrap_or(u32::MAX),
671                u32::try_from(instance.end_line).unwrap_or(u32::MAX),
672            )
673        })
674        .collect();
675    lines.sort_unstable();
676    let mut spans: Vec<CloneSpan> = Vec::new();
677    for (path, start_line, end_line) in lines {
678        match spans.last_mut() {
679            Some(last) if last.path == path && start_line <= last.end_line => {
680                last.end_line = last.end_line.max(end_line);
681            }
682            _ => spans.push(CloneSpan {
683                path,
684                start_line,
685                end_line,
686            }),
687        }
688    }
689    spans
690}
691
692/// The component root of each group: two groups share a component when an
693/// instance of one overlaps an instance of the other in the same file.
694fn overlap_components(groups: &[&CloneGroup]) -> Vec<usize> {
695    let mut parent: Vec<usize> = (0..groups.len()).collect();
696    let mut by_file: FxHashMap<&Path, Vec<(usize, usize, usize)>> = FxHashMap::default();
697    for (index, group) in groups.iter().enumerate() {
698        for instance in &group.instances {
699            by_file.entry(instance.file.as_path()).or_default().push((
700                instance.start_line,
701                instance.end_line,
702                index,
703            ));
704        }
705    }
706    let mut files: Vec<_> = by_file.into_values().collect();
707    for instances in &mut files {
708        instances.sort_unstable();
709        let mut reach: Option<(usize, usize)> = None;
710        for &(start, end, index) in instances.iter() {
711            match reach {
712                Some((reach_end, owner)) if start <= reach_end => {
713                    union(&mut parent, owner, index);
714                    reach = Some((reach_end.max(end), owner));
715                }
716                _ => reach = Some((end, index)),
717            }
718        }
719    }
720    (0..groups.len())
721        .map(|index| find(&mut parent, index))
722        .collect()
723}
724
725fn find(parent: &mut [usize], mut index: usize) -> usize {
726    while parent[index] != index {
727        parent[index] = parent[parent[index]];
728        index = parent[index];
729    }
730    index
731}
732
733fn union(parent: &mut [usize], left: usize, right: usize) {
734    let left = find(parent, left);
735    let right = find(parent, right);
736    if left != right {
737        let (low, high) = if left < right {
738            (left, right)
739        } else {
740            (right, left)
741        };
742        parent[high] = low;
743    }
744}
745
746/// Whether a head group has a key that the base does not hold. Without such
747/// a group, the grade needs no diff.
748#[must_use]
749pub fn has_unmatched_group(head: &CloneRegionHead<'_>, base_keys: &FxHashSet<String>) -> bool {
750    head.groups
751        .iter()
752        .any(|group| !base_keys.contains(&dupe_group_key(group, head.root)))
753}
754
755#[cfg(test)]
756#[path = "clone_regions_tests.rs"]
757mod tests;