Skip to main content

sokf_core/include/
graph.rs

1//! This module builds the include graph from the source markers, never from
2//! materialised content (`SOKF_FORMAT_91`).
3
4use std::collections::{BTreeSet, HashMap, HashSet};
5
6use crate::{Model, RepoPath, markdown::IncludeTarget};
7
8/// `Graph` is the include graph. Each document and each additional file is a
9/// node, and each open marker that includes a document's body is an edge. A
10/// marker with a named fragment is not an edge, and neither is a marker that
11/// includes an asset by its sidecar's id with no fragment, because the asset
12/// is a file.
13#[derive(Debug, Clone, Default, PartialEq, Eq)]
14pub(super) struct Graph {
15    /// The path of each node.
16    pub nodes: Vec<RepoPath>,
17    /// The edges, each from the including node to the included node.
18    pub edges: Vec<(usize, usize)>,
19}
20
21/// `Order` is the order of a graph. It holds two things: the nodes that aren't
22/// on a cycle, in topological order with the leaves first, and the cycles.
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24pub(super) struct Order {
25    /// The indices of the nodes that aren't on a cycle, each after every node
26    /// it includes.
27    pub sorted: Vec<usize>,
28    /// Every cycle, as the sorted paths of its nodes.
29    pub cycles: Vec<Vec<RepoPath>>,
30}
31
32/// `knowledge_of_additional` returns the knowledge in which the includes of an
33/// additional file resolve: the knowledge of its schema, or else the knowledge
34/// that holds the file.
35pub fn knowledge_of_additional(
36    model: &Model,
37    file: &crate::model::AdditionalFile,
38) -> Option<usize> {
39    file.schema
40        .map(|s| s.knowledge)
41        .or_else(|| model.knowledge_of(&file.path))
42}
43
44/// `graph_for` builds the include graph of every document, schema, and
45/// additional file, with every node. With `only`, it adds the edges from a
46/// set of nodes: the paths in `only` and every node they include, directly
47/// or indirectly. It stops when no new node joins that set, and returns the
48/// set too. With `None`, it adds every edge. A run that loads a document but
49/// doesn't expand it resolves none of that document's includes, as the cache
50/// contract requires.
51// sokf-implements: SOKF_FORMAT_91
52pub(super) fn graph_for(
53    model: &Model,
54    only: Option<&BTreeSet<RepoPath>>,
55) -> (Graph, Option<HashSet<usize>>) {
56    let mut g = Graph::default();
57    let mut index: HashMap<RepoPath, usize> = HashMap::new();
58    let mut sources: Vec<(usize, Option<usize>, Vec<IncludedId>)> = Vec::new();
59    let documents = model
60        .documents_and_schemas()
61        .map(|(k, doc)| (&doc.path, Some(k), &doc.segments));
62    let additional = model
63        .additional
64        .iter()
65        .map(|f| (&f.path, knowledge_of_additional(model, f), &f.segments));
66    for (path, knowledge, segments) in documents.chain(additional) {
67        let i = g.nodes.len();
68        index.insert(path.clone(), i);
69        g.nodes.push(path.clone());
70        sources.push((i, knowledge, included_ids(segments)));
71    }
72    let mut wanted: Option<HashSet<usize>> = only.map(|o| {
73        o.iter()
74            .filter_map(|p| index.get(p).copied())
75            .collect::<HashSet<usize>>()
76    });
77    let mut done: HashSet<usize> = HashSet::new();
78    loop {
79        let mut grew = false;
80        for (from, knowledge, ids) in &sources {
81            if done.contains(from) || wanted.as_ref().is_some_and(|w| !w.contains(from)) {
82                continue;
83            }
84            done.insert(*from);
85            let Some(k) = knowledge else { continue };
86            for (store, id, fragment) in ids {
87                if let Some((_, target)) = model.document_in(*k, store.as_deref(), id)
88                    && includes_body(model, &target.path, fragment.as_deref())
89                    && let Some(&to) = index.get(&target.path)
90                {
91                    g.edges.push((*from, to));
92                    if let Some(w) = wanted.as_mut()
93                        && w.insert(to)
94                    {
95                        grew = true;
96                    }
97                }
98            }
99        }
100        if !grew {
101            break;
102        }
103    }
104    (g, wanted)
105}
106
107/// `includes_body` says whether an id-form include of `target` with
108/// `fragment` materialises the document's body (`SOKF_FORMAT_85`,
109/// FORMAT-2_AC-5). An include with an empty fragment includes the body of any
110/// document, an include with no fragment includes the body of a document that
111/// isn't an asset's sidecar, and an include with a named fragment never
112/// includes the body.
113// sokf-implements: FORMAT-2_AC-5
114pub fn includes_body(model: &Model, target: &RepoPath, fragment: Option<&str>) -> bool {
115    match fragment {
116        Some("") => true,
117        Some(_) => false,
118        None => model.asset_of(target).is_none(),
119    }
120}
121
122/// An `IncludedId` holds the store, id, and fragment of an include by id.
123type IncludedId = (Option<String>, String, Option<String>);
124
125fn included_ids(segments: &crate::Segments) -> Vec<IncludedId> {
126    segments
127        .regions
128        .iter()
129        .filter_map(|i| match &IncludeTarget::parse(&i.target) {
130            IncludeTarget::Document {
131                store,
132                id,
133                fragment,
134            } => Some((store.clone(), id.clone(), fragment.clone())),
135            IncludeTarget::File { .. } => None,
136        })
137        .collect()
138}
139
140/// `order` orders the graph with Tarjan's algorithm for strongly connected
141/// components. The algorithm emits the components in reverse topological
142/// order, so every node follows the nodes it includes.
143pub(super) fn order(graph: &Graph) -> Order {
144    let n = graph.nodes.len();
145    let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); n];
146    for &(from, to) in &graph.edges {
147        adjacency[from].push(to);
148    }
149    let mut state = Tarjan {
150        adjacency: &adjacency,
151        index: vec![None; n],
152        low: vec![0; n],
153        on_stack: vec![false; n],
154        stack: Vec::new(),
155        next: 0,
156        components: Vec::new(),
157    };
158    for v in 0..n {
159        if state.index[v].is_none() {
160            state.visit(v);
161        }
162    }
163    let mut out = Order::default();
164    for component in state.components {
165        let self_loop = component.len() == 1 && adjacency[component[0]].contains(&component[0]);
166        if component.len() > 1 || self_loop {
167            let mut paths: Vec<RepoPath> =
168                component.iter().map(|&i| graph.nodes[i].clone()).collect();
169            paths.sort();
170            out.cycles.push(paths);
171        } else {
172            out.sorted.push(component[0]);
173        }
174    }
175    out.cycles.sort();
176    out
177}
178
179struct Tarjan<'a> {
180    adjacency: &'a [Vec<usize>],
181    index: Vec<Option<usize>>,
182    low: Vec<usize>,
183    on_stack: Vec<bool>,
184    stack: Vec<usize>,
185    next: usize,
186    components: Vec<Vec<usize>>,
187}
188
189impl Tarjan<'_> {
190    fn visit(&mut self, v: usize) {
191        self.index[v] = Some(self.next);
192        self.low[v] = self.next;
193        self.next += 1;
194        self.stack.push(v);
195        self.on_stack[v] = true;
196        for &w in &self.adjacency[v] {
197            match self.index[w] {
198                None => {
199                    self.visit(w);
200                    self.low[v] = self.low[v].min(self.low[w]);
201                }
202                Some(i) if self.on_stack[w] => self.low[v] = self.low[v].min(i),
203                Some(_) => {}
204            }
205        }
206        if self.low[v] == self.index[v].expect("set earlier") {
207            let mut component = Vec::new();
208            loop {
209                let w = self.stack.pop().expect("v is on the stack");
210                self.on_stack[w] = false;
211                component.push(w);
212                if w == v {
213                    break;
214                }
215            }
216            component.sort_unstable();
217            self.components.push(component);
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    fn p(s: &str) -> RepoPath {
227        RepoPath::parse(s).unwrap()
228    }
229
230    fn g(nodes: &[&str], edges: &[(usize, usize)]) -> Graph {
231        Graph {
232            nodes: nodes.iter().map(|n| p(n)).collect(),
233            edges: edges.to_vec(),
234        }
235    }
236
237    #[test]
238    fn orders_leaves_first_and_finds_cycles() {
239        let graph = g(
240            &["/a", "/b", "/c", "/d", "/e", "/f"],
241            &[(0, 1), (1, 2), (3, 4), (4, 3), (5, 5)],
242        );
243        let o = order(&graph);
244        let pos = |i: usize| o.sorted.iter().position(|&x| x == i).unwrap();
245        assert!(pos(2) < pos(1) && pos(1) < pos(0));
246        assert_eq!(o.sorted.len(), 3);
247        assert_eq!(o.cycles, vec![vec![p("/d"), p("/e")], vec![p("/f")]]);
248        let empty = order(&Graph::default());
249        assert!(empty.sorted.is_empty() && empty.cycles.is_empty());
250    }
251}