Skip to main content

sokf_core/graph/
build.rs

1//! This module builds the graph: `build`, `build_from`, and
2//! `Graph::add_edges` add the nodes of the model and its declared edges,
3//! with their inverses (CLI-7).
4
5use std::collections::{BTreeMap, BTreeSet, HashSet};
6
7use serde_json::{Map, Value};
8
9use super::{Edge, EdgeKind, Graph, Hydrator, Node, NodeKey, NodeKind, model::ancestors};
10use crate::{
11    Document, FileKind, Model, RepoPath, Segments, Yaml,
12    markdown::{Body, IncludeTarget},
13    model::{frontmatter::Resource, keys::Label},
14    yaml::Spanned,
15};
16
17/// A `Target` is what the `to` of a `links` entry resolves to.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Target {
20    /// A document, of this store or another.
21    Document {
22        /// The path of the document.
23        path: RepoPath,
24        /// The id of the document.
25        id: String,
26        /// The index of the document's knowledge.
27        knowledge: usize,
28    },
29    /// A repository file, by path.
30    File(RepoPath),
31}
32
33/// `resolve_to` resolves `to`, written in a document of `knowledge`. Text
34/// that starts with `/` is a path, and any other text is an id. A store can
35/// prefix an id. A path that identifies a document in any store
36/// resolves to that document (`SOKF_FORMAT_54`). The lookup searches both the
37/// documents that the run holds and the rows of the store, so the target
38/// does not need to be in the run (CACHE-1_AC-22).
39// sokf-implements: SOKF_FORMAT_54
40// sokf-implements: CONF-2_AC-3
41// sokf-implements: FORMAT-2_AC-1
42pub fn resolve_to(model: &Model, knowledge: usize, to: &str) -> Option<Target> {
43    if !to.starts_with('/') {
44        let (store, id) = crate::model::split_store(to);
45        let (k, path) = path_in(model, knowledge, store, id)?;
46        return Some(Target::Document {
47            path,
48            id: id.to_string(),
49            knowledge: k,
50        });
51    }
52    let path = RepoPath::parse(to)?;
53    if let Some((k, id)) = model.id_of(&path) {
54        return Some(Target::Document {
55            path,
56            id,
57            knowledge: k,
58        });
59    }
60    model.exists(&path).then_some(Target::File(path))
61}
62
63/// `path_in` returns the knowledge and the path of the document that `id`
64/// identifies in `store`. A document of the knowledge `citing` cites the
65/// id. When no store is written, `path_in` looks in `citing` itself.
66fn path_in(
67    model: &Model,
68    citing: usize,
69    store: Option<&str>,
70    id: &str,
71) -> Option<(usize, RepoPath)> {
72    let k = match store {
73        None => citing,
74        Some(s) => model.store(citing, s)?.knowledge,
75    };
76    model.path_of_id(k, id).map(|p| (k, p))
77}
78
79/// `inverse_rel` returns the inverse of the relation `rel`. It covers each
80/// core relation and the relations of `resource`, `sources`, and `includes`
81/// edges, and it returns `relates-to` for a custom value.
82// sokf-implements: SOKF_FORMAT_59
83// sokf-implements: SOKF_FORMAT_55
84// sokf-implements: SOKF_FORMAT_57
85// sokf-implements: SOKF_FORMAT_115
86// sokf-implements: SOKF_FORMAT_116
87#[expect(
88    clippy::match_same_arms,
89    reason = "the arm for `relates-to` repeats the wildcard's value, so that the list names every inverse that SOKF_FORMAT_116 gives"
90)]
91pub fn inverse_rel(rel: &str) -> &'static str {
92    match rel {
93        "relates-to" => "relates-to",
94        "part-of" => "has-part",
95        "has-part" => "part-of",
96        "depends-on" => "depended-on-by",
97        "depended-on-by" => "depends-on",
98        "references" => "referenced-by",
99        "referenced-by" => "references",
100        "supersedes" => "superseded-by",
101        "superseded-by" => "supersedes",
102        "implements" => "implemented-by",
103        "implemented-by" => "implements",
104        "tests" => "tested-by",
105        "tested-by" => "tests",
106        "contradicts" => "contradicts",
107        "describes" => "described-by",
108        "described-by" => "describes",
109        "derives-from" => "derived-by",
110        "derived-by" => "derives-from",
111        "includes" => "included-by",
112        "included-by" => "includes",
113        _ => "relates-to",
114    }
115}
116
117/// `frontmatter_json` returns the fields of a document node: the
118/// frontmatter as written, without `links` and the keys that the tool sets,
119/// then `status`, and then `broken` and `reason` when the document is
120/// broken.
121// sokf-implements: CLI-7_AC-41
122// sokf-implements: CLI-7_AC-42
123pub fn frontmatter_json(doc: &Document) -> Map<String, Value> {
124    let mut fields = Map::new();
125    if let Some(entries) = doc.frontmatter.as_ref().and_then(Spanned::as_map) {
126        for (key, value) in entries {
127            if matches!(
128                key.value.as_str(),
129                "links" | "kind" | "path" | "broken" | "reason"
130            ) {
131                continue;
132            }
133            fields.insert(key.value.clone(), yaml_json(value));
134        }
135    }
136    // sokf-implements: CLI-7_AC-53
137    if !fields.contains_key("status") {
138        fields.insert("status".into(), Value::from("stable"));
139    }
140    // sokf-implements: CLI-7_AC-54
141    let reason = if doc.frontmatter.is_none() && doc.frontmatter_found {
142        Some("frontmatter does not parse")
143    } else if doc.id().is_none() {
144        Some("no id")
145    } else {
146        None
147    };
148    if let Some(reason) = reason {
149        fields.insert("broken".into(), Value::Bool(true));
150        fields.insert("reason".into(), Value::from(reason));
151    }
152    fields
153}
154
155/// `yaml_json` returns the YAML value `value` as JSON, with each map's keys in
156/// the order that it writes them.
157pub(crate) fn yaml_json(value: &Spanned) -> Value {
158    match &value.value {
159        Yaml::Null => Value::Null,
160        Yaml::Bool(b) => Value::Bool(*b),
161        Yaml::Int(i) => Value::from(*i),
162        Yaml::Float(f) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
163        Yaml::Str(s) => Value::from(s.as_str()),
164        Yaml::Seq(items) => Value::Array(items.iter().map(yaml_json).collect()),
165        Yaml::Map(entries) => Value::Object(
166            entries
167                .iter()
168                .map(|(k, v)| (k.value.clone(), yaml_json(v)))
169                .collect(),
170        ),
171    }
172}
173
174/// A `RawEdge` is one edge as its source declares it, before the nodes at
175/// its two ends exist in the graph. The cache keeps a document's edges in
176/// this form. A `RawEdge` stores the target as a path when the target
177/// resolves, and as the text written in the source when it doesn't
178/// (CACHE-1_AC-22).
179#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
180pub struct RawEdge {
181    /// The path of the source.
182    pub from: RepoPath,
183    /// The kind of the edge.
184    pub kind: EdgeKind,
185    /// The target as the source wrote it: a `to`, a label's id, a
186    /// resource, or an include's target.
187    pub written: String,
188    /// The node key that the target resolved to.
189    pub to: NodeKey,
190    /// The relation, such as `implements`.
191    pub rel: String,
192    /// The region of an include, or the slug of the fragment that a code
193    /// marker cites, if any.
194    pub region: Option<String>,
195    /// The line of a code marker in its file.
196    pub line: Option<usize>,
197    /// The `note` of a `links` entry.
198    pub note: Option<String>,
199}
200
201/// `edges_of` returns the edges that the file at `path` declares. For a
202/// document or a schema, these are its links, body links, resources,
203/// sources, and includes, and for an additional file, its body links and
204/// includes. It returns no edge for a path that the run doesn't hold.
205// sokf-implements: SOKF_FORMAT_57
206// sokf-implements: SOKF_FORMAT_115
207// sokf-implements: SOKF_FORMAT_116
208// sokf-implements: SOKF_FORMAT_117
209// sokf-implements: SOKF_FORMAT_118
210// sokf-implements: CACHE-1_AC-22
211pub fn edges_of(model: &Model, path: &RepoPath) -> Vec<RawEdge> {
212    let mut b = Builder::new(model);
213    if let Some((k, doc)) = model.loaded_document(path) {
214        b.document_edges(k, doc);
215        b.include_edges(&doc.path, Some(k), &doc.segments);
216        return b.raw;
217    }
218    if let Some(crate::Located::Additional(file)) = model.by_path(path) {
219        b.body_links(&file.path, None, &file.body, &BTreeSet::new());
220        b.include_edges(&file.path, file.schema.map(|s| s.knowledge), &file.segments);
221    }
222    b.raw
223}
224
225/// `build` builds the graph of `model` from the declared edges of every
226/// document, schema, and additional file that the run holds.
227pub fn build(model: &Model) -> Graph {
228    build_from(model, declared_edges(model), None)
229}
230
231/// `declared_edges` returns the declared edges of every document, schema,
232/// and additional file that the run holds, in that order.
233pub(super) fn declared_edges(model: &Model) -> Vec<RawEdge> {
234    model
235        .documents_and_schemas()
236        .map(|(_, d)| &d.path)
237        .chain(model.additional.iter().map(|a| &a.path))
238        .flat_map(|p| edges_of(model, p))
239        .collect()
240}
241
242/// `build_from` builds the graph from the files that the walk lists and
243/// from `edges`. When `build` calls it, `edges` holds every declared edge.
244/// A caller can instead pass no edges. That caller then calls
245/// `Graph::add_edges` later to add the edges near the start nodes. With a `hydrator`, the
246/// graph loads the fields of a document node that the run doesn't hold
247/// when a query first prints the node or reads its fields (CACHE-1_AC-22).
248// sokf-implements: CLI-7_AC-25
249// sokf-implements: CLI-7_AC-83
250// sokf-implements: CACHE-1_AC-22
251// sokf-implements: CLI-7_AC-57
252pub fn build_from(model: &Model, edges: Vec<RawEdge>, hydrator: Option<Hydrator>) -> Graph {
253    let mut b = Builder::new(model);
254    let mut built: HashSet<NodeKey> = HashSet::new();
255    // sokf-implements: CLI-7_AC-51
256    // sokf-implements: CLI-7_AC-52
257    for knowledge in &model.knowledges {
258        let mut fields = Map::new();
259        if let Some(m) = &knowledge.manifest {
260            for (key, value) in [
261                ("name", &m.name),
262                ("scope", &m.scope),
263                ("description", &m.description),
264            ] {
265                if let Some(value) = value {
266                    fields.insert(key.into(), Value::from(value.as_str()));
267                }
268            }
269        }
270        b.insert(knowledge.root.clone(), NodeKind::Root, fields);
271    }
272    // Every document and schema that the walk lists becomes a node, and
273    // those that the run holds carry their fields.
274    // sokf-implements: CLI-7_AC-61
275    // sokf-implements: CLI-7_AC-88
276    for file in &model.tree.files {
277        if !matches!(file.kind, FileKind::Document | FileKind::Schema) {
278            continue;
279        }
280        let Some(k) = file.root else { continue };
281        let fields = match model.loaded_document(&file.path) {
282            Some((_, doc)) => {
283                built.insert(NodeKey::Path(file.path.clone()));
284                frontmatter_json(doc)
285            }
286            None => Map::new(),
287        };
288        b.insert(file.path.clone(), NodeKind::Document, fields);
289        b.directories(&file.path, &model.knowledges[k].root);
290    }
291    // sokf-implements: CLI-7_AC-55
292    for (path, schema) in &model.dispatch {
293        let mut fields = Map::new();
294        if let Some(r) = schema {
295            fields.insert("schema".into(), Value::from(model.schema(*r).id()));
296        }
297        b.insert(path.clone(), NodeKind::Additional, fields);
298        if let Some(k) = model.knowledge_of(path) {
299            b.directories(path, &model.knowledges[k].root);
300        }
301    }
302    // Add the asset nodes before any edge, so that an edge whose target is an
303    // asset's path finds the asset's node instead of creating a `file` node
304    // (CLI-7_AC-25).
305    for knowledge in &model.knowledges {
306        for asset in &knowledge.assets {
307            let mut fields = Map::new();
308            let sidecar = asset.sidecar_path();
309            let id = match asset.sidecar {
310                Some(i) => knowledge.documents[i].id().map(str::to_string),
311                None if asset.has_sidecar => model
312                    .fallback
313                    .as_ref()
314                    .and_then(|f| f.fields(&sidecar))
315                    .and_then(|f| f.id),
316                None => None,
317            };
318            if let Some(id) = id {
319                fields.insert("sidecar".into(), Value::from(id));
320            }
321            b.insert(asset.path.clone(), NodeKind::Asset, fields);
322            b.directories(&asset.path, &knowledge.root);
323        }
324    }
325    // `finish` adds a node for the target of each edge.
326    b.raw.extend(edges);
327    let graph = b.finish();
328    match hydrator {
329        Some(h) => graph.with_hydrator(h, built),
330        None => graph,
331    }
332}
333
334struct Builder<'a> {
335    model: &'a Model,
336    nodes: BTreeMap<NodeKey, Node>,
337    /// The edges declared so far, which don't have their nodes yet.
338    raw: Vec<RawEdge>,
339}
340
341impl<'a> Builder<'a> {
342    fn new(model: &'a Model) -> Self {
343        Builder {
344            model,
345            nodes: BTreeMap::new(),
346            raw: Vec::new(),
347        }
348    }
349
350    fn insert(&mut self, path: RepoPath, kind: NodeKind, fields: Map<String, Value>) {
351        let key = NodeKey::Path(path);
352        self.nodes.insert(key.clone(), Node { key, kind, fields });
353    }
354
355    /// `directories` adds a node for each directory between `root` and
356    /// `path`, excluding both.
357    fn directories(&mut self, path: &RepoPath, root: &RepoPath) {
358        for d in ancestors(path).take_while(|d| d != root && d.starts_with(root)) {
359            let key = NodeKey::Path(d);
360            self.nodes.entry(key.clone()).or_insert_with(|| Node {
361                key,
362                kind: NodeKind::Directory,
363                fields: Map::new(),
364            });
365        }
366    }
367
368    #[allow(clippy::too_many_arguments)]
369    fn edge(
370        &mut self,
371        from: &RepoPath,
372        kind: EdgeKind,
373        written: &str,
374        to: NodeKey,
375        rel: &str,
376        region: Option<String>,
377        note: Option<String>,
378    ) {
379        self.raw.push(RawEdge {
380            from: from.clone(),
381            kind,
382            written: written.to_string(),
383            to,
384            rel: rel.to_string(),
385            region,
386            line: None,
387            note,
388        });
389    }
390
391    /// `path_target` returns the node key of a path target: the path when
392    /// the file exists, and a missing key otherwise.
393    fn path_target(&self, written: &str) -> NodeKey {
394        match RepoPath::parse(written) {
395            Some(p) if self.model.exists(&p) => NodeKey::Path(p),
396            _ => NodeKey::Missing(written.to_string()),
397        }
398    }
399
400    fn document_edges(&mut self, k: usize, doc: &Document) {
401        let mut reached = BTreeSet::new();
402        for entry in &doc.core.links {
403            let to = match resolve_to(self.model, k, &entry.to) {
404                Some(Target::Document { path: p, .. } | Target::File(p)) => NodeKey::Path(p),
405                None => NodeKey::Missing(entry.to.clone()),
406            };
407            reached.insert(to.clone());
408            self.edge(
409                &doc.path,
410                EdgeKind::Links,
411                &entry.to,
412                to,
413                &entry.rel,
414                None,
415                entry.note.clone(),
416            );
417        }
418        self.body_links(&doc.path, Some(k), &doc.body, &reached);
419        let resources = doc.core.resource.iter().flat_map(Resource::entries);
420        let paths = resources
421            .map(|r| (EdgeKind::Resource, r.as_str(), "describes"))
422            .chain(
423                doc.core
424                    .sources
425                    .iter()
426                    .map(|e| (EdgeKind::Sources, e.resource.as_str(), "derives-from")),
427            );
428        for (kind, written, rel) in paths {
429            if RepoPath::parse(written).is_some() {
430                let to = self.path_target(written);
431                self.edge(&doc.path, kind, written, to, rel, None, None);
432            }
433        }
434    }
435
436    /// `body_links` adds a `relates-to` edge for each body link
437    /// `sokf:<id>`, once per target, when no `links` entry reaches that
438    /// target.
439    fn body_links(
440        &mut self,
441        from: &RepoPath,
442        knowledge: Option<usize>,
443        body: &Body,
444        reached: &BTreeSet<NodeKey>,
445    ) {
446        let mut seen = reached.clone();
447        for link in &body.links {
448            let Some(Label {
449                store,
450                id: Some(id),
451                ..
452            }) = Label::of(&link.target)
453            else {
454                continue;
455            };
456            let written = match store {
457                Some(s) => format!("{s}:{id}"),
458                None => id.to_string(),
459            };
460            let to = match knowledge.and_then(|k| path_in(self.model, k, store, id)) {
461                Some((_, path)) => NodeKey::Path(path),
462                None => NodeKey::Missing(written.clone()),
463            };
464            if seen.insert(to.clone()) {
465                self.edge(
466                    from,
467                    EdgeKind::Links,
468                    &written,
469                    to,
470                    "relates-to",
471                    None,
472                    None,
473                );
474            }
475        }
476    }
477
478    fn include_edges(&mut self, from: &RepoPath, knowledge: Option<usize>, segments: &Segments) {
479        for block in &segments.regions {
480            let (to, region) = match &IncludeTarget::parse(&block.target) {
481                // The id of a sidecar resolves to its asset, or to the
482                // sidecar itself when the fragment is empty. A fragment
483                // with a name identifies the region that the include takes
484                // (FORMAT-2_AC-5).
485                IncludeTarget::Document {
486                    store,
487                    id,
488                    fragment,
489                } => {
490                    let to = match knowledge
491                        .and_then(|k| path_in(self.model, k, store.as_deref(), id))
492                    {
493                        Some((_, path)) => {
494                            match (fragment.as_deref(), self.model.asset_of(&path)) {
495                                (Some(""), _) | (_, None) => NodeKey::Path(path),
496                                (_, Some((_, asset))) => NodeKey::Path(asset.path.clone()),
497                            }
498                        }
499                        None => NodeKey::Missing(block.target.clone()),
500                    };
501                    (to, fragment.clone().filter(|f| !f.is_empty()))
502                }
503                IncludeTarget::File { path, region } => (self.path_target(path), region.clone()),
504            };
505            self.edge(
506                from,
507                EdgeKind::Includes,
508                &block.target,
509                to,
510                "includes",
511                region,
512                None,
513            );
514        }
515    }
516
517    /// `finish` returns the graph of the nodes and the declared edges, with
518    /// their inverses, sorted and without duplicates.
519    fn finish(mut self) -> Graph {
520        let raw = std::mem::take(&mut self.raw);
521        let edges = link(&mut self.nodes, raw);
522        Graph::new(self.nodes, edges)
523    }
524}
525
526impl Graph {
527    /// `add_edges` adds the declared edges `raw`, with their nodes and
528    /// inverses, to a graph that was built with no declared edge. `raw`
529    /// holds the edges near the start nodes of the graph, read from the store
530    /// (CACHE-1_AC-38).
531    pub fn add_edges(&mut self, raw: Vec<RawEdge>) {
532        let edges = link(&mut self.nodes, raw);
533        self.extend_edges(edges);
534    }
535}
536
537/// `target` returns the key of the node that an edge ends at. A path that
538/// isn't a node yet becomes a `file` node, and an unresolved target becomes
539/// a `missing` node.
540// sokf-implements: CLI-7_AC-18
541fn target(nodes: &mut BTreeMap<NodeKey, Node>, key: NodeKey) -> NodeKey {
542    let kind = match &key {
543        NodeKey::Path(_) => NodeKind::File,
544        NodeKey::Key(_) => NodeKind::Key,
545        NodeKey::Missing(_) => NodeKind::Missing,
546    };
547    nodes.entry(key.clone()).or_insert_with(|| Node {
548        key: key.clone(),
549        kind,
550        fields: Map::new(),
551    });
552    key
553}
554
555/// `link` gives each declared edge its nodes, and adds the inverse of each
556/// edge unless that inverse is declared too.
557// sokf-implements: CLI-7_AC-5
558fn link(nodes: &mut BTreeMap<NodeKey, Node>, raw: Vec<RawEdge>) -> Vec<Edge> {
559    type Ends<'e> = (
560        &'e NodeKey,
561        EdgeKind,
562        &'e NodeKey,
563        &'e str,
564        Option<&'e str>,
565        Option<usize>,
566    );
567    fn ends(e: &Edge) -> Ends<'_> {
568        (&e.from, e.kind, &e.to, &e.rel, e.region.as_deref(), e.line)
569    }
570    let mut edges: Vec<Edge> = Vec::with_capacity(raw.len());
571    for e in raw {
572        let to = target(nodes, e.to);
573        // A marker's file is outside every knowledge root, so it is a node
574        // only once an edge reaches it.
575        let from = target(nodes, NodeKey::Path(e.from));
576        edges.push(Edge {
577            from,
578            kind: e.kind,
579            to,
580            rel: e.rel,
581            region: e.region,
582            line: e.line,
583            synthesised: false,
584            note: e.note,
585        });
586    }
587    let declared: BTreeSet<Ends> = edges.iter().map(ends).collect();
588    let inverses: Vec<Edge> = edges
589        .iter()
590        .map(|e| Edge {
591            from: e.to.clone(),
592            kind: e.kind,
593            to: e.from.clone(),
594            rel: inverse_rel(&e.rel).to_string(),
595            region: e.region.clone(),
596            line: e.line,
597            synthesised: true,
598            note: None,
599        })
600        .filter(|inv| !declared.contains(&ends(inv)))
601        .collect();
602    edges.extend(inverses);
603    edges
604}
605
606#[cfg(test)]
607mod tests;