Skip to main content

specfold_core/corpus/graph/
build.rs

1//! Builds the graph: indexes ids, paths and aliases, then resolves relations and links into edges.
2
3use super::types::{DOC_RELATIONS, Edge, Graph, MENTIONS, Resolution};
4use crate::corpus::Corpus;
5use crate::model::RefText;
6
7impl Graph {
8    pub fn build(c: &Corpus) -> Self {
9        let mut g = Graph {
10            owners: c.docs.iter().map(|d| d.id.owner.clone()).collect(),
11            anchors: vec![Default::default(); c.docs.len()],
12            outgoing: vec![vec![]; c.docs.len()],
13            incoming: vec![vec![]; c.docs.len()],
14            ..Default::default()
15        };
16        for (i, d) in c.docs.iter().enumerate() {
17            g.by_id.insert(d.id.to_string(), i);
18            g.by_path.insert(d.path.clone(), i);
19            if let Some(dir) = &d.dir {
20                g.by_path.insert(dir.clone(), i);
21            }
22            if let Some(s) = d.slug_id() {
23                g.by_slug.entry(s).or_default().push(i);
24            }
25            for a in d.list_field("aliases") {
26                g.by_alias.entry(a).or_default().push(i);
27            }
28            g.anchors[i] = d.anchors.iter().map(|a| a.item.clone()).collect();
29        }
30        for (old, news) in &c.aliases.map {
31            for n in news {
32                if let Some(&i) = g.by_id.get(n) {
33                    let list = g.by_alias.entry(old.clone()).or_default();
34                    if !list.contains(&i) {
35                        list.push(i);
36                    }
37                }
38            }
39        }
40        for (i, d) in c.docs.iter().enumerate() {
41            for (kind, targets) in d.rel() {
42                if !DOC_RELATIONS.contains(&kind.as_str()) {
43                    continue;
44                }
45                for t in targets {
46                    g.link(i, &t, &kind);
47                }
48            }
49            for l in &d.links {
50                g.link(i, &l.item, MENTIONS);
51            }
52        }
53        g
54    }
55
56    fn link(&mut self, from: usize, text: &str, kind: &str) {
57        let owner = self.owners[from].clone();
58        if let Resolution::Doc { idx, anchor, .. } = self.resolve_from(&owner, text) {
59            if idx == from {
60                return;
61            }
62            let e = self.edges.len();
63            self.edges.push(Edge { from, to: idx, kind: kind.to_string(), anchor });
64            self.outgoing[from].push(e);
65            self.incoming[idx].push(e);
66        }
67    }
68
69    /// Resolves an id, an alias, or a path to a document, checking the anchor if there is one.
70    pub fn resolve(&self, text: &str) -> Resolution {
71        self.resolve_within(None, text)
72    }
73
74    /// Resolves as written by `owner`: an alias or slug several owners declare names that owner's
75    /// document when exactly one of the candidates is its own.
76    pub fn resolve_from(&self, owner: &str, text: &str) -> Resolution {
77        self.resolve_within(Some(owner), text)
78    }
79
80    fn resolve_within(&self, owner: Option<&str>, text: &str) -> Resolution {
81        let r = RefText::parse(text);
82        // A path written relative to the citing file (`../../.spec/…`) names the same document;
83        // ids never start with a dot, so stripping these prefixes cannot change an id.
84        let mut target = r.target.trim_end_matches('/');
85        while let Some(rest) = target.strip_prefix("../").or_else(|| target.strip_prefix("./")) {
86            target = rest;
87        }
88        let (candidates, via_alias) = if let Some(&i) = self.by_id.get(target).or_else(|| self.by_path.get(target)) {
89            (vec![i], false)
90        } else if let Some(list) = self.by_alias.get(target) {
91            (list.clone(), true)
92        } else if let Some(list) = self.by_slug.get(target) {
93            (list.clone(), true)
94        } else {
95            (vec![], false)
96        };
97        let candidates = match owner {
98            Some(o) if candidates.len() > 1 => {
99                let own: Vec<usize> = candidates.iter().copied().filter(|&i| self.owners[i] == o).collect();
100                if own.len() == 1 { own } else { candidates }
101            }
102            _ => candidates,
103        };
104        match candidates.as_slice() {
105            [] => Resolution::Missing,
106            [idx] => match r.anchor {
107                Some(a) if !self.anchors[*idx].contains(&a) => Resolution::MissingAnchor { idx: *idx, anchor: a },
108                anchor => Resolution::Doc { idx: *idx, anchor, via_alias },
109            },
110            many => Resolution::Ambiguous(many.to_vec()),
111        }
112    }
113
114    pub fn edges_from(&self, idx: usize) -> impl Iterator<Item = &Edge> {
115        self.outgoing[idx].iter().map(|&e| &self.edges[e])
116    }
117
118    pub fn edges_to(&self, idx: usize) -> impl Iterator<Item = &Edge> {
119        self.incoming[idx].iter().map(|&e| &self.edges[e])
120    }
121}