Skip to main content

_diffctx/edges/structural/
containment.rs

1use std::path::Path;
2
3use rustc_hash::FxHashMap;
4
5use crate::config::weights::EDGE_WEIGHTS;
6use crate::types::Fragment;
7
8use super::super::EdgeDict;
9use super::super::base::{EdgeBuilder, add_edge};
10
11pub struct ContainmentEdgeBuilder;
12
13impl EdgeBuilder for ContainmentEdgeBuilder {
14    fn build(&self, fragments: &[Fragment], _repo_root: Option<&Path>) -> EdgeDict {
15        let weight = EDGE_WEIGHTS["containment"].forward;
16        let reverse_factor = EDGE_WEIGHTS["containment"].reverse_factor;
17
18        let mut by_path: FxHashMap<&str, Vec<&Fragment>> = FxHashMap::default();
19        for f in fragments {
20            by_path.entry(f.path()).or_default().push(f);
21        }
22
23        let mut edges: EdgeDict = FxHashMap::default();
24
25        for (_path, frags) in &by_path {
26            if frags.len() < 2 {
27                continue;
28            }
29            let mut sorted = frags.clone();
30            sorted.sort_by(|a, b| {
31                a.start_line()
32                    .cmp(&b.start_line())
33                    .then(b.end_line().cmp(&a.end_line()))
34            });
35
36            let mut stack: Vec<&Fragment> = Vec::new();
37
38            for f in &sorted {
39                while let Some(top) = stack.last() {
40                    if f.start_line() > top.end_line() {
41                        stack.pop();
42                    } else {
43                        break;
44                    }
45                }
46
47                if let Some(parent) = stack.last() {
48                    if parent.start_line() <= f.start_line()
49                        && f.end_line() <= parent.end_line()
50                        && parent.id != f.id
51                    {
52                        add_edge(&mut edges, &f.id, &parent.id, weight, reverse_factor);
53                    }
54                }
55
56                stack.push(f);
57            }
58        }
59
60        edges
61    }
62}