Skip to main content

trumly_core/
rules.rs

1//! Runs the rules: which rule applies to which node, and does the node pass?
2//! Mirrors `matches`, `run_check` and `evaluate` in reference/core.py and section 5 of the spec.
3
4
5use serde_json::Value;
6
7use crate::model::{Graph, Link, Node};
8
9/// Node types that rules never apply to.
10const RESERVED: [&str; 6] = ["plane", "rule", "group", "type", "link-type", "pack"];
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13/// The outcome of one rule on one node.
14pub enum Status {
15    /// The rule holds.
16    Pass,
17    /// The rule is broken.
18    Fail,
19    /// The rule is broken, but its severity only advises.
20    Advisory,
21    /// The rule's check uses something this implementation does not understand. Never a silent pass.
22    Unsupported,
23}
24
25impl Status {
26    /// The name used in `check --json`.
27    pub fn as_str(self) -> &'static str {
28        match self {
29            Status::Pass => "pass",
30            Status::Fail => "fail",
31            Status::Advisory => "advisory",
32            Status::Unsupported => "unsupported",
33        }
34    }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38/// One rule applied to one node.
39pub struct RuleResult {
40    /// Id of the node that was checked.
41    pub node: String,
42    /// Id of the rule.
43    pub rule: String,
44    /// The rule's severity, as the rule states it.
45    pub severity: String,
46    /// The outcome.
47    pub status: Status,
48}
49
50/// A node that a failed `require_link` says should exist: "a link of this type to something of
51/// this type, in this plane". The editor draws these as ghosts.
52#[derive(Debug, Clone, PartialEq)]
53pub struct Ghost {
54    /// Id of the node the missing link starts from.
55    pub node: String,
56    /// Id of the rule that asks for it.
57    pub rule: String,
58    /// The wanted link type.
59    pub link: Value,    // the wanted link type (Null if the rule gave none)
60    /// The wanted node type.
61    pub to_type: Value, // Null if unspecified
62    /// The plane the missing node belongs in.
63    pub plane: Value,   // `to_plane` if given, otherwise the node's own plane
64}
65
66#[derive(Debug, Default)]
67/// Everything the rules found in a graph.
68pub struct Evaluation {
69    /// One result per rule and node it applies to.
70    pub results: Vec<RuleResult>,
71    /// Nodes that failed `require_link` rules say should exist.
72    pub ghosts: Vec<Ghost>,
73}
74
75/// JSON equality, the way the spec defines it: `true` is never `1`, but `1` equals `1.0`,
76/// and this holds inside lists and maps. serde_json's own `==` would say `1 != 1.0`.
77pub fn json_eq(a: &Value, b: &Value) -> bool {
78    match (a, b) {
79        (Value::Number(x), Value::Number(y)) => {
80            let int = |n: &serde_json::Number| n.is_i64() || n.is_u64();
81            if int(x) && int(y) {
82                x == y // two integers: compare exactly, no float rounding
83            } else {
84                x.as_f64() == y.as_f64()
85            }
86        }
87        (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| json_eq(p, q)),
88        (Value::Object(x), Value::Object(y)) => {
89            x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| json_eq(v, w)))
90        }
91        // Everything else (null, bool, string, or mismatched kinds) is plain equality.
92        _ => a == b,
93    }
94}
95
96/// "Truthy" in the reference's sense, used for `to_plane or node.plane`.
97fn truthy(v: &Value) -> bool {
98    match v {
99        Value::Null => false,
100        Value::Bool(b) => *b,
101        Value::Number(n) => n.as_f64() != Some(0.0),
102        Value::String(s) => !s.is_empty(),
103        Value::Array(a) => !a.is_empty(),
104        Value::Object(o) => !o.is_empty(),
105    }
106}
107
108fn opt_value(s: &Option<String>) -> Value {
109    s.as_ref().map_or(Value::Null, |s| Value::String(s.clone()))
110}
111
112/// The node itself, then its parents. Stops at a missing parent or a repeat.
113fn ancestors<'a>(graph: &'a Graph, id: &'a str) -> Vec<&'a str> {
114    let mut chain: Vec<&str> = Vec::new();
115    let mut cur = Some(id);
116    while let Some(c) = cur {
117        let Some(node) = graph.get(c) else { break };
118        if chain.contains(&c) {
119            break;
120        }
121        chain.push(c);
122        cur = node.parent.as_deref();
123    }
124    chain
125}
126
127/// Does `node` match an `applies_to` filter? Every key must match.
128fn matches(graph: &Graph, node: &Node, filter: &serde_json::Map<String, Value>) -> bool {
129    filter.iter().all(|(key, want)| match key.as_str() {
130        "type" => json_eq(&opt_value(&node.kind), want),
131        "plane" => json_eq(&opt_value(&node.plane), want),
132        // Strict ancestor: the node itself does not count (`skip(1)`).
133        "under" => want.as_str().is_some_and(|w| ancestors(graph, &node.id).iter().skip(1).any(|a| *a == w)),
134        // One id, or a list of ids; anything that is not a string never matches.
135        "id" => match want {
136            Value::Array(list) => list.iter().any(|x| x.as_str() == Some(node.id.as_str())),
137            other => other.as_str() == Some(node.id.as_str()),
138        },
139        // Any other key is a field. A missing field never matches, even against null.
140        _ => node.fields.get(key).is_some_and(|have| json_eq(have, want)),
141    })
142}
143
144// ---------- checks ----------
145// Each check returns Pass, Fail, or Bad (the check is malformed or not understood). Bad inside one check
146// always wins over Fail inside that same check, exactly as in the reference.
147
148#[derive(Clone, Copy, PartialEq, Eq)]
149enum Outcome {
150    Pass,
151    Fail,
152    Bad,
153}
154
155type Obj = serde_json::Map<String, Value>;
156
157/// A check value may be one item or a list of items.
158fn items(v: &Value) -> Vec<&Value> {
159    match v {
160        Value::Array(a) => a.iter().collect(),
161        other => vec![other],
162    }
163}
164
165/// Present means: there, and neither null nor the empty string.
166fn present(v: Option<&Value>) -> bool {
167    v.is_some_and(|v| !v.is_null() && v != &Value::String(String::new()))
168}
169
170fn is_number(v: &Value) -> bool {
171    v.is_number()
172}
173
174fn cmp_numbers(a: &serde_json::Number, b: &serde_json::Number) -> Option<std::cmp::Ordering> {
175    if let (Some(x), Some(y)) = (a.as_i64(), b.as_i64()) {
176        return Some(x.cmp(&y)); // two integers: exact
177    }
178    a.as_f64()?.partial_cmp(&b.as_f64()?)
179}
180
181fn non_neg_int(v: &Value) -> Option<u64> {
182    v.as_u64() // floats such as 1.0 are not integers here
183}
184
185fn type_is(v: &Value, name: &str) -> Option<bool> {
186    Some(match name {
187        "string" => v.is_string(),
188        "number" => v.is_number(),
189        "integer" => v.is_i64() || v.is_u64(),
190        "boolean" => v.is_boolean(),
191        "list" => v.is_array(),
192        "map" => v.is_object(),
193        "null" => v.is_null(),
194        _ => return None,
195    })
196}
197
198fn check_require_fields(node: &Node, names: &Value) -> Outcome {
199    let Some(names) = names.as_array() else { return Outcome::Bad };
200    let mut all = true;
201    for n in names {
202        let Some(n) = n.as_str() else { return Outcome::Bad };
203        all &= present(node.fields.get(n));
204    }
205    if all { Outcome::Pass } else { Outcome::Fail }
206}
207
208fn check_field_is(node: &Node, specs: &Value) -> Outcome {
209    let Some(specs) = specs.as_object() else { return Outcome::Bad };
210    let mut outcome = Outcome::Pass;
211    for (name, spec) in specs {
212        let Some(spec) = spec.as_object() else { return Outcome::Bad };
213        if spec.keys().any(|k| !["in", "min", "max", "type", "optional"].contains(&k.as_str())) {
214            return Outcome::Bad;
215        }
216        if spec.get("in").is_some_and(|v| !v.is_array()) {
217            return Outcome::Bad;
218        }
219        if ["min", "max"].iter().any(|k| spec.get(*k).is_some_and(|v| !is_number(v))) {
220            return Outcome::Bad;
221        }
222        if spec.get("type").is_some_and(|t| t.as_str().and_then(|t| type_is(&Value::Null, t)).is_none()) {
223            return Outcome::Bad;
224        }
225        let Some(v) = node.fields.get(name) else {
226            if spec.get("optional") != Some(&Value::Bool(true)) {
227                outcome = Outcome::Fail;
228            }
229            continue;
230        };
231        let num = v.as_number();
232        let bound = |k: &str, want: std::cmp::Ordering| -> bool {
233            // `min` needs v >= min, `max` needs v <= max
234            match (num, spec[k].as_number()) {
235                (Some(x), Some(y)) => cmp_numbers(x, y).is_some_and(|o| o == want || o == std::cmp::Ordering::Equal),
236                _ => false,
237            }
238        };
239        if spec.get("in").and_then(Value::as_array).is_some_and(|list| !list.iter().any(|x| json_eq(v, x))) {
240            outcome = Outcome::Fail;
241        }
242        if spec.contains_key("min") && !bound("min", std::cmp::Ordering::Greater) {
243            outcome = Outcome::Fail;
244        }
245        if spec.contains_key("max") && !bound("max", std::cmp::Ordering::Less) {
246            outcome = Outcome::Fail;
247        }
248        if let Some(t) = spec.get("type").and_then(Value::as_str) {
249            if type_is(v, t) != Some(true) {
250                outcome = Outcome::Fail;
251            }
252        }
253    }
254    outcome
255}
256
257fn check_compare_fields(node: &Node, list: &Value) -> Outcome {
258    let mut outcome = Outcome::Pass;
259    for it in items(list) {
260        let Some(it) = it.as_object() else { return Outcome::Bad };
261        if it.keys().any(|k| !["left", "op", "right", "value"].contains(&k.as_str())) {
262            return Outcome::Bad;
263        }
264        let (Some(left), Some(op)) = (it.get("left").and_then(Value::as_str), it.get("op").and_then(Value::as_str)) else {
265            return Outcome::Bad;
266        };
267        if !["==", "!=", "<", "<=", ">", ">="].contains(&op) || it.contains_key("right") == it.contains_key("value") {
268            return Outcome::Bad;
269        }
270        let right_name = match it.get("right") {
271            Some(r) => match r.as_str() {
272                Some(r) => Some(r),
273                None => return Outcome::Bad,
274            },
275            None => None,
276        };
277        let l = node.fields.get(left);
278        let r = match right_name {
279            Some(name) => node.fields.get(name),
280            None => it.get("value"),
281        };
282        let (Some(l), Some(r)) = (l, r) else {
283            outcome = Outcome::Fail; // a missing field never compares
284            continue;
285        };
286        use std::cmp::Ordering::*;
287        let ordering = match (l, r) {
288            (Value::Number(a), Value::Number(b)) => cmp_numbers(a, b),
289            (Value::String(a), Value::String(b)) => Some(a.as_str().cmp(b.as_str())),
290            _ => None,
291        };
292        let ok = match op {
293            "==" => json_eq(l, r),
294            "!=" => !json_eq(l, r),
295            "<" => ordering == Some(Less),
296            "<=" => matches!(ordering, Some(Less | Equal)),
297            ">" => ordering == Some(Greater),
298            _ => matches!(ordering, Some(Greater | Equal)),
299        };
300        if !ok {
301            outcome = Outcome::Fail;
302        }
303    }
304    outcome
305}
306
307/// For every node, the links that point at it: (the node they come from, the link).
308type Inbound<'a> = std::collections::BTreeMap<&'a str, Vec<(&'a Node, &'a Link)>>;
309
310fn build_inbound(graph: &Graph) -> Inbound<'_> {
311    let mut m: Inbound = Inbound::new();
312    for n in graph.nodes() {
313        for l in &n.links {
314            m.entry(l.to.as_str()).or_default().push((n, l));
315        }
316    }
317    m
318}
319
320const LINK_KEYS: [&str; 13] = ["type", "dir", "node_type", "node_plane", "to_type", "to_plane", "node_fields", "same_fields", "ancestor_type", "scope", "with_fields", "min", "max"];
321
322fn non_empty_str(v: Option<&Value>) -> Option<&str> {
323    v.and_then(Value::as_str).filter(|s| !s.is_empty())
324}
325
326fn dir_of(it: &Obj) -> Option<&str> {
327    match it.get("dir") {
328        None => Some("out"),
329        Some(Value::String(d)) if d == "out" || d == "in" => Some(d.as_str()),
330        _ => None,
331    }
332}
333
334fn link_item_valid(it: &Obj) -> bool {
335    if it.keys().any(|k| !LINK_KEYS.contains(&k.as_str())) || non_empty_str(it.get("type")).is_none() || dir_of(it).is_none() {
336        return false;
337    }
338    if it.contains_key("ancestor_type") != it.contains_key("scope") {
339        return false;
340    }
341    if it.get("scope").is_some_and(|s| s != "same" && s != "other") {
342        return false;
343    }
344    if it.contains_key("ancestor_type") && non_empty_str(it.get("ancestor_type")).is_none() {
345        return false;
346    }
347    if it.get("node_fields").is_some_and(|m| !m.as_object().is_some()) {
348        return false;
349    }
350    if let Some(w) = it.get("same_fields") {
351        if !w.as_array().is_some_and(|a| a.iter().all(Value::is_string)) {
352            return false;
353        }
354    }
355    if let Some(w) = it.get("with_fields") {
356        if !w.as_array().is_some_and(|a| a.iter().all(Value::is_string)) {
357            return false;
358        }
359    }
360    ["min", "max"].iter().all(|k| it.get(*k).is_none_or(|v| non_neg_int(v).is_some()))
361}
362
363fn link_bounds(it: &Obj) -> (u64, Option<u64>) {
364    let max = it.get("max").and_then(non_neg_int);
365    (it.get("min").and_then(non_neg_int).unwrap_or(if max.is_some() { 0 } else { 1 }), max)
366}
367
368fn nearest_ancestor<'a>(graph: &'a Graph, id: &'a str, kind: &str) -> Option<&'a str> {
369    ancestors(graph, id).into_iter().skip(1).find(|a| graph.get(a).is_some_and(|n| n.kind.as_deref() == Some(kind)))
370}
371
372/// How many links of this node (out) or to this node (in) satisfy every filter in `it`.
373fn count_links(graph: &Graph, inbound: &Inbound, node: &Node, it: &Obj) -> u64 {
374    let kind = it["type"].as_str().unwrap_or("");
375    let pairs: Vec<(&Link, Option<&Node>)> = if dir_of(it) == Some("out") {
376        node.links.iter().filter(|l| l.kind == kind).map(|l| (l, graph.get(&l.to))).collect()
377    } else {
378        inbound.get(node.id.as_str()).map_or_else(Vec::new, |v| v.iter().filter(|(_, l)| l.kind == kind).map(|(src, l)| (*l, Some(*src))).collect())
379    };
380    let want_type = it.get("node_type").or_else(|| it.get("to_type"));
381    let want_plane = it.get("node_plane").or_else(|| it.get("to_plane"));
382    let mut n = 0;
383    for (l, other) in pairs {
384        let Some(other) = other else { continue }; // a link to nothing never counts
385        if want_type.is_some_and(|w| !json_eq(&opt_value(&other.kind), w)) || want_plane.is_some_and(|w| !json_eq(&opt_value(&other.plane), w)) {
386            continue;
387        }
388        if let Some(want) = it.get("node_fields").and_then(Value::as_object) {
389            if !want.iter().all(|(k, v)| other.fields.get(k).is_some_and(|have| json_eq(have, v))) {
390                continue;
391            }
392        }
393        if let Some(names) = it.get("same_fields").and_then(Value::as_array) {
394            if !names.iter().filter_map(Value::as_str).all(|f| match (node.fields.get(f), other.fields.get(f)) {
395                (Some(a), Some(b)) => json_eq(a, b),
396                _ => false,
397            }) {
398                continue;
399            }
400        }
401        if let (Some(t), Some(scope)) = (it.get("ancestor_type").and_then(Value::as_str), it.get("scope").and_then(Value::as_str)) {
402            let (a, b) = (nearest_ancestor(graph, &node.id, t), nearest_ancestor(graph, &other.id, t));
403            let ok = match scope {
404                "same" => a.is_some() && a == b,
405                _ => a.is_some() && b.is_some() && a != b,
406            };
407            if !ok {
408                continue;
409            }
410        }
411        if let Some(names) = it.get("with_fields").and_then(Value::as_array) {
412            if !names.iter().all(|f| present(f.as_str().and_then(|f| l.fields.get(f)))) {
413                continue;
414            }
415        }
416        n += 1;
417    }
418    n
419}
420
421fn check_require_link(graph: &Graph, inbound: &Inbound, node: &Node, list: &Value) -> Outcome {
422    let mut outcome = Outcome::Pass;
423    for it in items(list) {
424        let Some(it) = it.as_object().filter(|it| link_item_valid(it)) else { return Outcome::Bad };
425        let (lo, hi) = link_bounds(it);
426        let n = count_links(graph, inbound, node, it);
427        if n < lo || hi.is_some_and(|h| n > h) {
428            outcome = Outcome::Fail;
429        }
430    }
431    outcome
432}
433
434/// Sugar for `max: 0`: the same filters as `require_link`, but `min` and `max` are not accepted.
435fn check_forbid_link(graph: &Graph, inbound: &Inbound, node: &Node, list: &Value) -> Outcome {
436    let mut outcome = Outcome::Pass;
437    for it in items(list) {
438        let Some(it) = it.as_object().filter(|it| link_item_valid(it) && !it.contains_key("min") && !it.contains_key("max")) else { return Outcome::Bad };
439        if count_links(graph, inbound, node, it) > 0 {
440            outcome = Outcome::Fail;
441        }
442    }
443    outcome
444}
445
446const STEP_KEYS: [&str; 5] = ["type", "dir", "node_type", "node_plane", "node_fields"];
447
448fn step_valid(it: &Obj) -> bool {
449    !it.keys().any(|k| !STEP_KEYS.contains(&k.as_str()))
450        && non_empty_str(it.get("type")).is_some()
451        && dir_of(it).is_some()
452        && it.get("node_fields").is_none_or(Value::is_object)
453}
454
455/// Ids at the other end of `id`'s links of this step's type that exist and match the step's filters.
456fn step_targets<'a>(graph: &'a Graph, inbound: &Inbound<'a>, id: &str, step: &Obj) -> Vec<&'a str> {
457    let kind = step["type"].as_str().unwrap_or("");
458    let ends: Vec<&'a Node> = if dir_of(step) == Some("out") {
459        graph.get(id).map_or_else(Vec::new, |n| n.links.iter().filter(|l| l.kind == kind).filter_map(|l| graph.get(&l.to)).collect())
460    } else {
461        inbound.get(id).map_or_else(Vec::new, |v| v.iter().filter(|(_, l)| l.kind == kind).map(|(src, _)| *src).collect())
462    };
463    ends.into_iter()
464        .filter(|o| step.get("node_type").is_none_or(|w| json_eq(&opt_value(&o.kind), w)))
465        .filter(|o| step.get("node_plane").is_none_or(|w| json_eq(&opt_value(&o.plane), w)))
466        .filter(|o| {
467            step.get("node_fields").and_then(Value::as_object).is_none_or(|want| want.iter().all(|(k, v)| o.fields.get(k).is_some_and(|h| json_eq(h, v))))
468        })
469        .map(|o| o.id.as_str())
470        .collect()
471}
472
473/// A chain of link steps must exist from this node; each step is followed from every node the last one reached.
474fn check_path(graph: &Graph, inbound: &Inbound, node: &Node, steps: &Value) -> Outcome {
475    let Some(steps) = steps.as_array().filter(|a| !a.is_empty()) else { return Outcome::Bad };
476    let mut parsed: Vec<&Obj> = Vec::new();
477    for s in steps {
478        match s.as_object().filter(|o| step_valid(o)) {
479            Some(o) => parsed.push(o),
480            None => return Outcome::Bad,
481        }
482    }
483    let mut frontier: std::collections::BTreeSet<&str> = std::collections::BTreeSet::from([node.id.as_str()]);
484    for step in parsed {
485        frontier = frontier.iter().flat_map(|f| step_targets(graph, inbound, f, step)).collect();
486        if frontier.is_empty() {
487            return Outcome::Fail;
488        }
489    }
490    Outcome::Pass
491}
492
493/// Fails if this node can reach itself by following links of the given type(s).
494fn check_acyclic(graph: &Graph, node: &Node, types: &Value) -> Outcome {
495    let list = items(types);
496    let kinds: Vec<&str> = list.iter().filter_map(|v| non_empty_str(Some(*v))).collect();
497    if list.is_empty() || kinds.len() != list.len() {
498        return Outcome::Bad;
499    }
500    for kind in kinds {
501        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
502        let mut stack: Vec<&str> = node.links.iter().filter(|l| l.kind == kind).map(|l| l.to.as_str()).collect();
503        while let Some(cur) = stack.pop() {
504            if cur == node.id {
505                return Outcome::Fail;
506            }
507            let Some(n) = graph.get(cur) else { continue };
508            if seen.insert(cur) {
509                stack.extend(n.links.iter().filter(|l| l.kind == kind).map(|l| l.to.as_str()));
510            }
511        }
512    }
513    Outcome::Pass
514}
515
516fn check_require_link_fields(inbound: &Inbound, node: &Node, list: &Value) -> Outcome {
517    let mut outcome = Outcome::Pass;
518    for it in items(list) {
519        let Some(it) = it.as_object() else { return Outcome::Bad };
520        let fields_ok = it.get("fields").and_then(Value::as_array).is_some_and(|a| a.iter().all(Value::is_string));
521        if it.keys().any(|k| !["type", "dir", "fields"].contains(&k.as_str())) || non_empty_str(it.get("type")).is_none() || dir_of(it).is_none() || !fields_ok {
522            return Outcome::Bad;
523        }
524        let kind = it["type"].as_str().unwrap_or("");
525        let names: Vec<&str> = it["fields"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
526        let links: Vec<&Link> = if dir_of(it) == Some("out") {
527            node.links.iter().filter(|l| l.kind == kind).collect()
528        } else {
529            inbound.get(node.id.as_str()).map_or_else(Vec::new, |v| v.iter().filter(|(_, l)| l.kind == kind).map(|(_, l)| *l).collect())
530        };
531        if !links.iter().all(|l| names.iter().all(|f| present(l.fields.get(*f)))) {
532            outcome = Outcome::Fail;
533        }
534    }
535    outcome
536}
537
538/// Pass only if every part passes and every part is understood; a failure outranks "not understood".
539fn run_check(graph: &Graph, inbound: &Inbound, node: &Node, check: &Obj) -> Status {
540    let mut any_fail = false;
541    let mut any_bad = false;
542    for (key, val) in check {
543        let o = match key.as_str() {
544            "require_fields" => check_require_fields(node, val),
545            "field_is" => check_field_is(node, val),
546            "compare_fields" => check_compare_fields(node, val),
547            "require_link" => check_require_link(graph, inbound, node, val),
548            "forbid_link" => check_forbid_link(graph, inbound, node, val),
549            "require_link_fields" => check_require_link_fields(inbound, node, val),
550            "path" => check_path(graph, inbound, node, val),
551            "acyclic" => check_acyclic(graph, node, val),
552            _ => Outcome::Bad,
553        };
554        any_fail |= o == Outcome::Fail;
555        any_bad |= o == Outcome::Bad;
556    }
557    if any_fail {
558        Status::Fail
559    } else if any_bad {
560        Status::Unsupported
561    } else {
562        Status::Pass
563    }
564}
565
566/// One ghost per outgoing `require_link` that has fewer links than its minimum (which must be at least one).
567fn ghosts_for(graph: &Graph, inbound: &Inbound, node: &Node, rule: &str, check: &Obj) -> Vec<Ghost> {
568    let Some(list) = check.get("require_link") else { return vec![] };
569    let mut out = Vec::new();
570    for it in items(list) {
571        let Some(it) = it.as_object().filter(|it| link_item_valid(it) && dir_of(it) == Some("out")) else { continue };
572        let (lo, _) = link_bounds(it);
573        if lo >= 1 && count_links(graph, inbound, node, it) < lo {
574            let get = |a: &str, b: &str| it.get(a).or_else(|| it.get(b)).cloned().unwrap_or(Value::Null);
575            let plane = get("node_plane", "to_plane");
576            out.push(Ghost {
577                node: node.id.clone(),
578                rule: rule.to_string(),
579                link: it["type"].clone(),
580                to_type: get("node_type", "to_type"),
581                plane: if truthy(&plane) { plane } else { opt_value(&node.plane) },
582            });
583        }
584    }
585    out
586}
587
588/// Run every rule over the graph.
589pub fn evaluate(graph: &Graph) -> Evaluation {
590    let rules: Vec<&Node> = graph.nodes().filter(|n| n.kind.as_deref() == Some("rule")).collect();
591    let inbound = build_inbound(graph);
592    let mut out = Evaluation::default();
593    let empty = Obj::new();
594
595    for node in graph.nodes() {
596        if node.kind.as_deref().is_some_and(|k| RESERVED.contains(&k)) || graph.scratch_of(node).is_some() {
597            continue;
598        }
599        for rule in &rules {
600            // A rule with `enabled: false` is switched off: no results, no ghosts.
601            if rule.fields.get("enabled") == Some(&Value::Bool(false)) {
602                continue;
603            }
604            // `applies_to` that is missing or not a map matches every node.
605            let filter = rule.fields.get("applies_to").and_then(Value::as_object).unwrap_or(&empty);
606            if !matches(graph, node, filter) {
607                continue;
608            }
609            let severity = match rule.fields.get("severity").and_then(Value::as_str) {
610                Some(s @ ("error" | "warn" | "info")) => s.to_string(),
611                _ => "warn".to_string(),
612            };
613            let check = rule.fields.get("check").and_then(Value::as_object).filter(|c| !c.is_empty());
614            let status = match check {
615                None => Status::Advisory,
616                Some(c) => run_check(graph, &inbound, node, c),
617            };
618            out.results.push(RuleResult { node: node.id.clone(), rule: rule.id.clone(), severity, status });
619            if let (Status::Fail, Some(c)) = (status, check) {
620                out.ghosts.extend(ghosts_for(graph, &inbound, node, &rule.id, c));
621            }
622        }
623    }
624    // Nodes and rules both come out in id order, so results and ghosts are already sorted by (node, rule).
625    debug_assert!(out.results.windows(2).all(|w| (&w[0].node, &w[0].rule) <= (&w[1].node, &w[1].rule)));
626    out
627}
628
629/// Enabled rules that name specific nodes with `id` but match none of them: a typo looks exactly like success.
630pub fn unmatched_rules(graph: &Graph) -> Vec<String> {
631    let mut out = Vec::new();
632    for r in graph.nodes().filter(|n| n.kind.as_deref() == Some("rule")) {
633        if r.fields.get("enabled") == Some(&Value::Bool(false)) {
634            continue;
635        }
636        let Some(filter) = r.fields.get("applies_to").and_then(Value::as_object).filter(|f| f.contains_key("id")) else { continue };
637        let hit = graph.nodes().any(|n| !n.kind.as_deref().is_some_and(|k| RESERVED.contains(&k)) && graph.scratch_of(n).is_none() && matches(graph, n, filter));
638        if !hit {
639            out.push(r.id.clone());
640        }
641    }
642    out
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648    use serde_json::json;
649
650    #[test]
651    fn equality_is_json_equality() {
652        assert!(json_eq(&json!(1), &json!(1.0)));
653        assert!(!json_eq(&json!(true), &json!(1)));
654        assert!(!json_eq(&json!([1, true]), &json!([true, 1])));
655        assert!(json_eq(&json!({"a": [1, 2.0]}), &json!({"a": [1.0, 2]})));
656        assert!(!json_eq(&json!(null), &json!(0)));
657        assert!(!json_eq(&json!("1"), &json!(1)));
658        assert!(!json_eq(&json!(9007199254740993i64), &json!(9007199254740992i64)));
659    }
660
661    #[test]
662    fn truthiness() {
663        assert!(!truthy(&json!("")) && !truthy(&json!(null)) && !truthy(&json!(0)));
664        assert!(truthy(&json!("p")) && truthy(&json!([0])));
665    }
666}