Skip to main content

sokf_core/graph/
model.rs

1//! This module defines the types that model the graph of `sokf graph`
2//! (CLI-7): `NodeKey`, `Node`, `Edge`, and `Graph`.
3
4use std::{
5    collections::{BTreeMap, HashMap, HashSet},
6    rc::Rc,
7};
8
9use serde_json::{Map, Value};
10
11use crate::RepoPath;
12
13/// `Fields` holds the fields of a document node.
14pub type Fields = Map<String, Value>;
15
16/// `Hydrate` is a function that reads the fields of a document node from
17/// the node's file.
18pub type Hydrate = dyn Fn(&RepoPath) -> Option<Fields>;
19
20/// `Hydrator` reads the fields of a document node from its file when the
21/// graph first needs them. A graph built from the store holds no fields for
22/// a node until the node is visited (CACHE-1_AC-22).
23#[derive(Clone)]
24pub struct Hydrator(pub Rc<Hydrate>);
25
26impl std::fmt::Debug for Hydrator {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        f.write_str("Hydrator")
29    }
30}
31
32/// `NodeKey` identifies a node in one of three ways: by a path, by a key
33/// written as its document's path and its slug, or by the target text of a
34/// link or entry whose target is missing. Paths sort before keys, and keys
35/// sort before missing targets, which is the node order of CLI-7_AC-13.
36// sokf-implements: CLI-7_AC-13
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub enum NodeKey {
39    /// A node at a path.
40    Path(RepoPath),
41    /// A key, as `<path>#<slug>`.
42    Key(String),
43    /// An unresolved target. The variant holds the target text through which
44    /// a link or an entry refers to it.
45    Missing(String),
46}
47
48impl NodeKey {
49    /// `as_str` returns the path, the key, or the target text.
50    pub fn as_str(&self) -> &str {
51        match self {
52            NodeKey::Path(p) => p.as_str(),
53            NodeKey::Key(t) | NodeKey::Missing(t) => t,
54        }
55    }
56
57    /// `path` returns the node's path, or `None` for a key or a missing
58    /// target.
59    pub fn path(&self) -> Option<&RepoPath> {
60        match self {
61            NodeKey::Path(p) => Some(p),
62            NodeKey::Key(_) | NodeKey::Missing(_) => None,
63        }
64    }
65}
66
67/// `NodeKind` lists the kinds of node in `sokf graph`.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum NodeKind {
70    /// A knowledge root.
71    Root,
72    /// A directory in a root, or a directory given as a `START` of
73    /// `sokf graph`.
74    Directory,
75    /// A document or a schema.
76    Document,
77    /// An additional file.
78    Additional,
79    /// An asset (CLI-7_AC-25).
80    Asset,
81    /// A repository file that an edge points at, or a file given as a
82    /// `START` of `sokf graph`.
83    File,
84    /// A key given as a `START` of `sokf graph` (CLI-7_AC-75).
85    Key,
86    /// An unresolved target.
87    Missing,
88}
89
90impl NodeKind {
91    /// `shows_via` says whether the row of a node of this kind shows the
92    /// `via` edges: the edges to the documents that describe or include the
93    /// node's file or one of the directories above it.
94    pub(super) fn shows_via(self) -> bool {
95        matches!(
96            self,
97            NodeKind::File | NodeKind::Additional | NodeKind::Asset | NodeKind::Directory
98        )
99    }
100
101    /// `name` returns the node's `kind` value in the JSON output.
102    pub fn name(self) -> &'static str {
103        match self {
104            NodeKind::Root => "root",
105            NodeKind::Directory => "directory",
106            NodeKind::Document => "document",
107            NodeKind::Additional => "additional",
108            NodeKind::Asset => "asset",
109            NodeKind::File => "file",
110            NodeKind::Key => "key",
111            NodeKind::Missing => "missing",
112        }
113    }
114}
115
116/// `Node` is one node of the graph: its key, its kind, and the fields that
117/// it carries, ready for the JSON output.
118#[derive(Debug, Clone, PartialEq)]
119pub struct Node {
120    /// The key that identifies the node.
121    pub key: NodeKey,
122    /// The node's kind.
123    pub kind: NodeKind,
124    /// The fields other than `kind` and the key, in output order.
125    pub fields: Map<String, Value>,
126}
127
128/// `EdgeKind` lists the kinds of edge in `sokf graph`, in alphabetical
129/// order.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
131pub enum EdgeKind {
132    /// An include marker.
133    Includes,
134    /// An edge from a key to its document, or a body link to the key
135    /// (CLI-7_AC-75).
136    Keys,
137    /// A `links` entry or a body link.
138    Links,
139    /// A marker in a file outside the knowledge roots (CLI-7_AC-83).
140    Marker,
141    /// A `resource` path.
142    Resource,
143    /// A `sources[].resource` path.
144    Sources,
145}
146
147impl EdgeKind {
148    /// `name` returns the edge's `kind` value in the JSON output.
149    pub fn name(self) -> &'static str {
150        match self {
151            EdgeKind::Includes => "includes",
152            EdgeKind::Keys => "keys",
153            EdgeKind::Links => "links",
154            EdgeKind::Marker => "marker",
155            EdgeKind::Resource => "resource",
156            EdgeKind::Sources => "sources",
157        }
158    }
159}
160
161/// `Edge` is one edge of the graph. All of its fields together identify it,
162/// and the order of the fields makes the derived `Ord` sort edges in the
163/// order of CLI-7_AC-14.
164#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
165pub struct Edge {
166    /// The source node.
167    pub from: NodeKey,
168    /// The edge's kind.
169    pub kind: EdgeKind,
170    /// The target node.
171    pub to: NodeKey,
172    /// The relationship.
173    pub rel: String,
174    /// The include region, when the marker specifies one, or the slug of
175    /// the fragment that a code marker cites.
176    pub region: Option<String>,
177    /// The line of a code marker in its file.
178    pub line: Option<usize>,
179    /// Whether the edge is a synthesised inverse.
180    pub synthesised: bool,
181    /// The `note` of a `links` entry.
182    pub note: Option<String>,
183}
184
185/// `inverse` returns the inverse `rel` of an edge. For a `keys` edge, it
186/// uses the pairs of `rel` values that key edges carry, such as
187/// `defined-in` and `defines`. It does so because key edges come from the
188/// graph and never from a `links` entry. For every other edge, it uses the inverse
189/// that the SOKF format defines for the `rel`.
190fn inverse(kind: EdgeKind, rel: &str) -> &'static str {
191    match (kind, rel) {
192        (EdgeKind::Keys, "defined-in") => "defines",
193        (EdgeKind::Keys, "defines") => "defined-in",
194        (EdgeKind::Keys, "cites") => "cited-by",
195        (EdgeKind::Keys, _) => "cites",
196        _ => super::inverse_rel(rel),
197    }
198}
199
200/// `Graph` holds every node and every edge, with the edges indexed by
201/// their endpoints.
202#[derive(Debug, Clone, Default)]
203pub struct Graph {
204    /// The nodes, by key.
205    pub nodes: BTreeMap<NodeKey, Node>,
206    /// The edges, sorted, without duplicates.
207    pub edges: Vec<Edge>,
208    out: HashMap<NodeKey, Vec<usize>>,
209    inbound: HashMap<NodeKey, Vec<usize>>,
210    /// The hydrator that reads a document node's fields on the first visit,
211    /// or `None` when every node was built with its fields.
212    hydrator: Option<Hydrator>,
213    /// The document nodes whose fields were read.
214    hydrated: HashSet<NodeKey>,
215    /// The archived documents (CLI-7_AC-67).
216    archived: HashSet<NodeKey>,
217}
218
219impl Graph {
220    /// `new` builds a graph from nodes and edges, and sorts the edges and
221    /// removes duplicates.
222    // sokf-implements: SOKF_FORMAT_114
223    // sokf-implements: CLI-7_AC-14
224    pub fn new(nodes: BTreeMap<NodeKey, Node>, mut edges: Vec<Edge>) -> Graph {
225        edges.sort();
226        edges.dedup();
227        let mut out: HashMap<NodeKey, Vec<usize>> = HashMap::new();
228        let mut inbound: HashMap<NodeKey, Vec<usize>> = HashMap::new();
229        for (i, e) in edges.iter().enumerate() {
230            out.entry(e.from.clone()).or_default().push(i);
231            inbound.entry(e.to.clone()).or_default().push(i);
232        }
233        Graph {
234            nodes,
235            edges,
236            out,
237            inbound,
238            hydrator: None,
239            hydrated: HashSet::new(),
240            archived: HashSet::new(),
241        }
242    }
243
244    /// `set_archived` marks the documents at `paths` as archived
245    /// (CLI-7_AC-67). The call replaces the archived documents from any
246    /// earlier call.
247    pub fn set_archived(&mut self, paths: impl IntoIterator<Item = RepoPath>) {
248        self.archived = paths.into_iter().map(NodeKey::Path).collect();
249    }
250
251    /// `is_archived` returns whether the node at `key` is an archived
252    /// document.
253    pub fn is_archived(&self, key: &NodeKey) -> bool {
254        self.archived.contains(key)
255    }
256
257    /// `add_key` adds a key node with a `defined-in` edge to its document
258    /// and a `cites` edge from each document in `citing`, and gives each
259    /// edge its inverse (CLI-7_AC-74, CLI-7_AC-75).
260    // sokf-implements: CLI-7_AC-75
261    pub fn add_key(
262        &mut self,
263        path: &RepoPath,
264        slug: &str,
265        key: &str,
266        line: usize,
267        citing: &[RepoPath],
268    ) {
269        let node = NodeKey::Key(format!("{path}#{slug}"));
270        let mut fields = Map::new();
271        fields.insert("key".into(), Value::from(key));
272        fields.insert("line".into(), Value::from(line));
273        self.nodes.insert(
274            node.clone(),
275            Node {
276                key: node.clone(),
277                kind: NodeKind::Key,
278                fields,
279            },
280        );
281        let doc = NodeKey::Path(path.clone());
282        let pair = |from: &NodeKey, to: &NodeKey, rel: &str| {
283            [false, true].map(|synthesised| {
284                let (from, to, rel) = if synthesised {
285                    (to, from, inverse(EdgeKind::Keys, rel))
286                } else {
287                    (from, to, rel)
288                };
289                Edge {
290                    from: from.clone(),
291                    kind: EdgeKind::Keys,
292                    to: to.clone(),
293                    rel: rel.to_string(),
294                    region: None,
295                    line: None,
296                    synthesised,
297                    note: None,
298                }
299            })
300        };
301        let mut edges: Vec<Edge> = pair(&node, &doc, "defined-in").into();
302        for source in citing {
303            edges.extend(pair(&NodeKey::Path(source.clone()), &node, "cites"));
304        }
305        self.extend_edges(edges);
306    }
307
308    /// `extend_edges` adds `edges` to the graph's edges, sorts them again,
309    /// and removes duplicates. Each node keeps its kind, its fields, and
310    /// whether it is hydrated.
311    pub(super) fn extend_edges(&mut self, edges: Vec<Edge>) {
312        let mut all = std::mem::take(&mut self.edges);
313        all.extend(edges);
314        let rebuilt = Graph::new(BTreeMap::new(), all);
315        self.edges = rebuilt.edges;
316        self.out = rebuilt.out;
317        self.inbound = rebuilt.inbound;
318    }
319
320    /// `with_hydrator` gives the graph a hydrator. The document nodes in
321    /// `built` already carry their fields. The hydrator reads the file of
322    /// every other document node when the node is first visited
323    /// (CACHE-1_AC-22).
324    #[must_use]
325    pub fn with_hydrator(mut self, hydrator: Hydrator, built: HashSet<NodeKey>) -> Graph {
326        self.hydrator = Some(hydrator);
327        self.hydrated = built;
328        self
329    }
330
331    /// `hydrate` reads the fields of the document node at `key`, and does
332    /// nothing when it has read them before or the graph has no hydrator.
333    // sokf-implements: CACHE-1_AC-22
334    pub fn hydrate(&mut self, key: &NodeKey) {
335        let Some(hydrator) = &self.hydrator else {
336            return;
337        };
338        if self.hydrated.contains(key) {
339            return;
340        }
341        let Some(node) = self.nodes.get_mut(key) else {
342            return;
343        };
344        if node.kind != NodeKind::Document {
345            return;
346        }
347        if let Some(path) = key.path()
348            && let Some(fields) = (hydrator.0)(path)
349        {
350            node.fields = fields;
351        }
352        self.hydrated.insert(key.clone());
353    }
354
355    /// `node` returns the node at `key`.
356    pub fn node(&self, key: &NodeKey) -> Option<&Node> {
357        self.nodes.get(key)
358    }
359
360    /// `kind` returns the kind of the node at `key`.
361    pub fn kind(&self, key: &NodeKey) -> Option<NodeKind> {
362        self.nodes.get(key).map(|n| n.kind)
363    }
364
365    /// `edges_from` returns the edges from `key`, in graph order.
366    pub fn edges_from(&self, key: &NodeKey) -> impl Iterator<Item = &Edge> {
367        self.edge_indices_from(key).iter().map(|&i| &self.edges[i])
368    }
369
370    /// `edge_indices_from` returns the indices of the edges from `key`, in
371    /// graph order.
372    pub fn edge_indices_from(&self, key: &NodeKey) -> &[usize] {
373        self.out.get(key).map(Vec::as_slice).unwrap_or_default()
374    }
375
376    /// `inverse_indices` returns the indices of the inverses of `edge`,
377    /// declared or synthesised, in graph order. An inverse is an edge with
378    /// the endpoints swapped, the same kind, region, and line, and a `rel`
379    /// that is the inverse of `edge`'s `rel`. `inverse_indices` checks the
380    /// match in both directions: the inverse of `edge`'s `rel` is the other
381    /// edge's `rel`, or the inverse of the other edge's `rel` is `edge`'s
382    /// `rel`. A custom `rel` is one that the SOKF format does not define,
383    /// and its inverse is `relates-to`. So a declared `relates-to` edge is
384    /// the inverse of every edge with a custom `rel` that runs in the
385    /// opposite direction between the same endpoints. An edge can have
386    /// several inverses.
387    pub fn inverse_indices(&self, edge: &Edge) -> impl Iterator<Item = usize> {
388        self.inbound
389            .get(&edge.from)
390            .into_iter()
391            .flatten()
392            .copied()
393            .filter(move |&i| {
394                let other = &self.edges[i];
395                other.from == edge.to
396                    && other.kind == edge.kind
397                    && other.region == edge.region
398                    && other.line == edge.line
399                    && (other.rel == inverse(edge.kind, &edge.rel)
400                        || inverse(other.kind, &other.rel) == edge.rel)
401            })
402    }
403
404    /// `parent` returns the directory that contains a path node, or `None`
405    /// for the repository root and for a node without a path.
406    pub fn parent(key: &NodeKey) -> Option<NodeKey> {
407        key.path()?.parent().map(NodeKey::Path)
408    }
409
410    /// `ensure` gives the node at `path` the kind `kind`. The code that
411    /// resolves each `START` of `sokf graph` calls it when the `START` is a
412    /// directory or a repository file (CLI-7_AC-35, CLI-7_AC-37). If the
413    /// node exists, it takes the new kind and keeps its fields. If the node
414    /// doesn't exist, `ensure` adds it with no fields.
415    pub fn ensure(&mut self, path: RepoPath, kind: NodeKind) {
416        let key = NodeKey::Path(path);
417        self.nodes
418            .entry(key.clone())
419            .and_modify(|n| n.kind = kind)
420            .or_insert_with(|| Node {
421                key,
422                kind,
423                fields: Map::new(),
424            });
425    }
426}
427
428/// `ancestors` returns each directory that holds `path`, nearest first.
429pub(super) fn ancestors(path: &RepoPath) -> impl Iterator<Item = RepoPath> {
430    std::iter::successors(path.parent(), RepoPath::parent)
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436
437    fn p(s: &str) -> NodeKey {
438        NodeKey::Path(RepoPath::parse(s).unwrap())
439    }
440
441    fn edge(from: &NodeKey, kind: EdgeKind, to: &NodeKey, rel: &str, synthesised: bool) -> Edge {
442        Edge {
443            from: from.clone(),
444            kind,
445            to: to.clone(),
446            rel: rel.into(),
447            region: None,
448            line: None,
449            synthesised,
450            note: None,
451        }
452    }
453
454    // sokf-tests: CLI-7_AC-13
455    #[test]
456    fn keys_order_paths_before_missing_targets() {
457        let mut keys = vec![
458            NodeKey::Missing("a".into()),
459            p("/z.md"),
460            p("/a.md"),
461            NodeKey::Missing("b".into()),
462        ];
463        keys.sort();
464        assert_eq!(
465            keys,
466            vec![
467                p("/a.md"),
468                p("/z.md"),
469                NodeKey::Missing("a".into()),
470                NodeKey::Missing("b".into())
471            ]
472        );
473        assert_eq!(p("/a.md").as_str(), "/a.md");
474        assert_eq!(NodeKey::Missing("x".into()).as_str(), "x");
475        assert!(NodeKey::Missing("x".into()).path().is_none());
476        assert_eq!(Graph::parent(&p("/k/a.md")), Some(p("/k")));
477        assert_eq!(Graph::parent(&p("/")), None);
478        assert_eq!(Graph::parent(&NodeKey::Missing("x".into())), None);
479    }
480
481    // sokf-tests: SOKF_FORMAT_114
482    // sokf-tests: CLI-7_AC-14
483    #[test]
484    fn edges_sort_by_from_kind_to_rel_region_note_and_dedup() {
485        let a = p("/a.md");
486        let b = p("/b.md");
487        let m = NodeKey::Missing("m".into());
488        let mut edges = vec![
489            edge(&b, EdgeKind::Links, &a, "depends-on", false),
490            edge(&a, EdgeKind::Resource, &b, "describes", false),
491            edge(&a, EdgeKind::Links, &m, "references", false),
492            edge(&a, EdgeKind::Links, &b, "references", false),
493            edge(&a, EdgeKind::Includes, &b, "includes", false),
494            edge(&a, EdgeKind::Links, &b, "depends-on", false),
495            edge(&a, EdgeKind::Links, &b, "depends-on", false),
496        ];
497        let g = Graph::new(BTreeMap::new(), std::mem::take(&mut edges));
498        let shown: Vec<String> = g
499            .edges
500            .iter()
501            .map(|e| {
502                format!(
503                    "{} {} {} {}",
504                    e.from.as_str(),
505                    e.kind.name(),
506                    e.to.as_str(),
507                    e.rel
508                )
509            })
510            .collect();
511        assert_eq!(
512            shown,
513            vec![
514                "/a.md includes /b.md includes",
515                "/a.md links /b.md depends-on",
516                "/a.md links /b.md references",
517                "/a.md links m references",
518                "/a.md resource /b.md describes",
519                "/b.md links /a.md depends-on",
520            ]
521        );
522        assert_eq!(g.edges_from(&a).count(), 5);
523        assert_eq!(g.edge_indices_from(&b), &[5]);
524        assert_eq!(g.edge_indices_from(&m), [] as [usize; 0]);
525        assert_eq!(EdgeKind::Sources.name(), "sources");
526    }
527
528    #[test]
529    fn inverses_find_the_declared_or_synthesised_side_and_every_custom_rel() {
530        let a = p("/a.md");
531        let b = p("/b.md");
532        let c = p("/c.md");
533        let g = Graph::new(
534            BTreeMap::new(),
535            vec![
536                edge(&a, EdgeKind::Links, &b, "depends-on", false),
537                edge(&b, EdgeKind::Links, &a, "depended-on-by", true),
538                edge(&a, EdgeKind::Links, &c, "likes", false),
539                edge(&a, EdgeKind::Links, &c, "hates", false),
540                edge(&c, EdgeKind::Links, &a, "relates-to", false),
541                edge(&b, EdgeKind::Resource, &c, "describes", false),
542            ],
543        );
544        let rels = |e: &Edge| {
545            g.inverse_indices(e)
546                .map(|i| g.edges[i].rel.clone())
547                .collect::<Vec<_>>()
548        };
549        let declared = &g.edges[g.edge_indices_from(&a)[0]];
550        assert_eq!(declared.rel, "depends-on");
551        assert_eq!(rels(declared), vec!["depended-on-by"]);
552        let relates = g.edges.iter().find(|e| e.rel == "relates-to").unwrap();
553        assert_eq!(rels(relates), vec!["hates", "likes"]);
554        let custom = g.edges.iter().find(|e| e.rel == "likes").unwrap();
555        assert_eq!(rels(custom), vec!["relates-to"]);
556        let lone = g.edges.iter().find(|e| e.rel == "describes").unwrap();
557        assert_eq!(rels(lone), Vec::<String>::new());
558    }
559
560    #[test]
561    fn ensure_adds_or_rekinds_a_node() {
562        let mut g = Graph::default();
563        let path = RepoPath::parse("/src").unwrap();
564        g.ensure(path.clone(), NodeKind::File);
565        assert_eq!(g.kind(&p("/src")), Some(NodeKind::File));
566        g.ensure(path, NodeKind::Directory);
567        assert_eq!(g.kind(&p("/src")), Some(NodeKind::Directory));
568        assert_eq!(g.nodes.len(), 1);
569        assert!(g.node(&p("/nope")).is_none());
570        assert_eq!(NodeKind::Additional.name(), "additional");
571    }
572}