Skip to main content

trumly_core/
structure.rs

1//! Structural checks: is the graph well-formed, before any rules run?
2//! Mirrors `structure` in reference/core.py and section 4 of spec/FORMAT.md.
3
4use std::collections::BTreeSet;
5
6use crate::model::Graph;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9/// One problem found in the structure of the graph.
10pub struct Finding {
11    /// Id of the node the finding is about.
12    pub node: String,
13    /// The finding's name as used in `check --json`, for example `missing_parent`.
14    pub kind: &'static str,
15    /// The related id, for example a parent that does not exist.
16    pub reference: Option<String>, // the related id, e.g. the parent that does not exist
17}
18
19#[derive(Debug, Default)]
20/// The findings of a structure check.
21pub struct Structure {
22    /// Problems that make the model invalid.
23    pub errors: Vec<Finding>,
24    /// Problems worth fixing that do not make the model invalid.
25    pub warnings: Vec<Finding>,
26}
27
28/// Walk up the parent chain from `id`. True if we ever come back to a node we have already seen.
29/// A chain that ends at a missing node simply stops; that is `missing_parent`, reported elsewhere.
30fn reaches_cycle(graph: &Graph, id: &str) -> bool {
31    let mut seen = BTreeSet::new();
32    let mut cur = Some(id);
33    while let Some(c) = cur {
34        let Some(node) = graph.get(c) else { return false };
35        if !seen.insert(c) {
36            return true; // insert returns false when the value was already there
37        }
38        cur = node.parent.as_deref();
39    }
40    false
41}
42
43/// The namespace a pack's nodes use: its manifest's `namespace`, else its name.
44fn pack_namespace(graph: &Graph, name: &str) -> String {
45    graph
46        .nodes()
47        .filter(|n| n.kind.as_deref() == Some("pack") && n.fields.get("name").and_then(|v| v.as_str()) == Some(name))
48        .map(|n| n.fields.get("namespace").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).unwrap_or(name).to_string())
49        .next()
50        .unwrap_or_else(|| name.to_string())
51}
52
53/// A `type` or `link-type` whose `fields.name` another node of the same kind also has: the name would mean two things.
54fn duplicate_definition(graph: &Graph, n: &crate::model::Node) -> Option<String> {
55    let kind = n.kind.as_deref().filter(|k| *k == "type" || *k == "link-type")?;
56    let name = n.fields.get("name").and_then(|v| v.as_str())?;
57    let twin = graph.nodes().any(|m| m.id != n.id && m.kind.as_deref() == Some(kind) && m.fields.get("name").and_then(|v| v.as_str()) == Some(name));
58    twin.then(|| name.to_string())
59}
60
61/// Fields the node's type definition marks `required: true` that it leaves unset (absent, null or "").
62fn missing_required(graph: &Graph, n: &crate::model::Node) -> Vec<String> {
63    const RESERVED: [&str; 6] = ["plane", "rule", "group", "type", "link-type", "pack"];
64    let Some(kind) = n.kind.as_deref() else { return Vec::new() };
65    if RESERVED.contains(&kind) || graph.scratch_of(n).is_some() {
66        return Vec::new();
67    }
68    let mut need = BTreeSet::new();
69    for m in graph.nodes().filter(|m| m.kind.as_deref() == Some("type") && m.fields.get("name").and_then(|v| v.as_str()) == Some(kind)) {
70        if let Some(list) = m.fields.get("fields").and_then(|v| v.as_array()) {
71            for d in list {
72                if d.get("required").and_then(|v| v.as_bool()) == Some(true) {
73                    if let Some(name) = d.get("name").and_then(|v| v.as_str()) {
74                        need.insert(name.to_string());
75                    }
76                }
77            }
78        }
79    }
80    need.into_iter().filter(|f| match n.fields.get(f) { None => true, Some(v) => v.is_null() || v.as_str() == Some("") }).collect()
81}
82
83/// `type->to` for each link whose link-type definition lists `from` / `to` node types that the link's ends are not among.
84fn endpoint_mismatches(graph: &Graph, n: &crate::model::Node) -> Vec<String> {
85    const RESERVED: [&str; 6] = ["plane", "rule", "group", "type", "link-type", "pack"];
86    let Some(kind) = n.kind.as_deref() else { return Vec::new() };
87    if RESERVED.contains(&kind) || graph.scratch_of(n).is_some() {
88        return Vec::new();
89    }
90    let mut out = BTreeSet::new();
91    for l in &n.links {
92        let Some(t) = graph.get(&l.to) else { continue };
93        let (mut from, mut to) = (BTreeSet::new(), BTreeSet::new());
94        for m in graph.nodes().filter(|m| m.kind.as_deref() == Some("link-type") && m.fields.get("name").and_then(|v| v.as_str()) == Some(l.kind.as_str())) {
95            for (key, acc) in [("from", &mut from), ("to", &mut to)] {
96                if let Some(list) = m.fields.get(key).and_then(|v| v.as_array()) {
97                    acc.extend(list.iter().filter_map(|x| x.as_str().map(str::to_string)));
98                }
99            }
100        }
101        let bad_from = !from.is_empty() && !from.contains(kind);
102        let bad_to = !to.is_empty() && !to.contains(t.kind.as_deref().unwrap_or(""));
103        if bad_from || bad_to {
104            out.insert(format!("{}->{}", l.kind, l.to));
105        }
106    }
107    out.into_iter().collect()
108}
109
110/// Ids with `--` belong to packs. A node must say the same thing twice: its id prefix and its `fields.pack`.
111fn namespace_mismatch(graph: &Graph, n: &crate::model::Node) -> bool {
112    let ns = n.id.split_once("--").map(|(a, _)| a);
113    let tag = n.fields.get("pack").and_then(|v| v.as_str());
114    if n.kind.as_deref() == Some("pack") {
115        return match n.fields.get("name").and_then(|v| v.as_str()) {
116            Some(name) => ns != Some(pack_namespace(graph, name).as_str()),
117            None => false,
118        };
119    }
120    match (ns, tag) {
121        (None, None) => false,
122        (Some(ns), Some(tag)) => ns != pack_namespace(graph, tag.split('@').next().unwrap_or("")),
123        _ => true,
124    }
125}
126
127/// Check the structure of a graph: parents, links, planes, types and namespaces.
128pub fn check(graph: &Graph) -> Structure {
129    let planes: BTreeSet<&str> = graph.nodes().filter(|n| n.kind.as_deref() == Some("plane")).map(|n| n.id.as_str()).collect();
130    let mut out = Structure::default();
131
132    for n in graph.nodes() {
133        let mut err = |kind: &'static str, reference: Option<String>| {
134            out.errors.push(Finding { node: n.id.clone(), kind, reference });
135        };
136
137        if n.kind.as_deref().unwrap_or("").is_empty() {
138            err("missing_type", None);
139        }
140        match n.parent.as_deref() {
141            Some(p) if graph.get(p).is_none() => err("missing_parent", Some(p.to_string())),
142            _ if reaches_cycle(graph, &n.id) => err("parent_cycle", None),
143            _ => {}
144        }
145        let mut seen = BTreeSet::new();
146        for l in &n.links {
147            if graph.get(&l.to).is_none() {
148                err("missing_link_target", Some(format!("{}->{}", l.kind, l.to)));
149            }
150            let key = l.key.as_deref().unwrap_or("");
151            if !seen.insert((l.kind.as_str(), l.to.as_str(), key)) {
152                let suffix = if key.is_empty() { String::new() } else { format!("#{key}") };
153                err("duplicate_link", Some(format!("{}->{}{}", l.kind, l.to, suffix)));
154            }
155        }
156        // a scratch is a sandbox: links and parents may not cross its edge, in either direction
157        let here = graph.scratch_of(n);
158        if let Some(p) = n.parent.as_deref().and_then(|p| graph.get(p)) {
159            if graph.scratch_of(p) != here {
160                err("scratch_boundary", Some(format!("parent->{}", p.id)));
161            }
162        }
163        for l in &n.links {
164            if let Some(t) = graph.get(&l.to) {
165                if graph.scratch_of(t) != here {
166                    err("scratch_boundary", Some(format!("{}->{}", l.kind, l.to)));
167                }
168            }
169        }
170        if namespace_mismatch(graph, n) {
171            out.warnings.push(Finding { node: n.id.clone(), kind: "namespace_mismatch", reference: None });
172        }
173        if let Some(name) = duplicate_definition(graph, n) {
174            out.warnings.push(Finding { node: n.id.clone(), kind: "duplicate_definition", reference: Some(name) });
175        }
176        for r in endpoint_mismatches(graph, n) {
177            out.warnings.push(Finding { node: n.id.clone(), kind: "link_endpoint_mismatch", reference: Some(r) });
178        }
179        for f in missing_required(graph, n) {
180            out.warnings.push(Finding { node: n.id.clone(), kind: "missing_required_field", reference: Some(f) });
181        }
182        if let Some(p) = n.plane.as_deref() {
183            if !planes.contains(p) {
184                out.warnings.push(Finding { node: n.id.clone(), kind: "undeclared_plane", reference: Some(p.to_string()) });
185            }
186        }
187    }
188
189    // Same ordering as the spec: (node, kind, ref).
190    let order = |f: &Finding| (f.node.clone(), f.kind, f.reference.clone().unwrap_or_default());
191    out.errors.sort_by_key(order);
192    out.warnings.sort_by_key(order);
193    out
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::load::load;
200
201    fn graph(files: &[(&str, &str)]) -> Graph {
202        let v = files.iter().map(|(p, t)| (p.to_string(), format!("---\n{t}\n---\n"))).collect();
203        load(v).0
204    }
205
206    fn kinds(s: &[Finding]) -> Vec<(&str, &'static str)> {
207        s.iter().map(|f| (f.node.as_str(), f.kind)).collect()
208    }
209
210    #[test]
211    fn clean_graph_has_no_findings() {
212        let s = check(&graph(&[("a.md", "id: a\ntype: t")]));
213        assert!(s.errors.is_empty() && s.warnings.is_empty());
214    }
215
216    #[test]
217    fn cycle_is_reported_on_every_node_that_reaches_it() {
218        let g = graph(&[("a.md", "id: a\ntype: t\nparent: b"), ("b.md", "id: b\ntype: t\nparent: a"), ("c.md", "id: c\ntype: t\nparent: a")]);
219        assert_eq!(kinds(&check(&g).errors), [("a", "parent_cycle"), ("b", "parent_cycle"), ("c", "parent_cycle")]);
220    }
221
222    #[test]
223    fn missing_parent_is_only_on_the_node_that_names_it() {
224        let g = graph(&[("a.md", "id: a\ntype: t\nparent: b"), ("b.md", "id: b\ntype: t\nparent: gone")]);
225        assert_eq!(kinds(&check(&g).errors), [("b", "missing_parent")]);
226    }
227}