Skip to main content

cbcl_parser/
shape_exports.rs

1//! `verify_message_shape`: a message against a dialect's `(shape …)` clauses,
2//! as one implementation every binding wraps (SPEC-010 REQ-002). A host that
3//! admits frames judges their shape here, never with predicates of its own:
4//! the hub and the browser must agree on what a well-shaped frame is
5//! (cbcl-rs issue #14).
6//!
7//! ```text
8//! (verify-shape <dialect-or-chain> <performative> <message>)   → "ok" | blame S-expression
9//! ```
10
11#![forbid(unsafe_code)]
12
13use alloc::format;
14use alloc::string::String;
15use cbcl_core::blame::ViolationError;
16use cbcl_core::serializer::serialize;
17use cbcl_core::sexpr::{Atom, SExpr};
18
19use crate::parser;
20use crate::state_exports::parse_and_install_dialect;
21
22/// Verify a runtime message against a dialect's shape constraints.
23pub fn verify_message_shape_str(input: &str) -> Result<String, String> {
24    let frame = parser::parse(input).map_err(|e| format!("parse error: {e}"))?;
25    let items = match &frame {
26        SExpr::List(items) => items,
27        _ => {
28            return Err(String::from(
29                "expected (verify-shape <dialect-or-chain> <performative> <message>)",
30            ))
31        }
32    };
33    if items.len() != 4 || !matches!(&items[0], SExpr::Atom(Atom::Symbol(s)) if s == "verify-shape")
34    {
35        return Err(String::from(
36            "expected (verify-shape <dialect-or-chain> <performative> <message>)",
37        ));
38    }
39    let performative = match &items[2] {
40        SExpr::Atom(Atom::Symbol(s)) => s.clone(),
41        _ => return Err(String::from("performative must be a symbol")),
42    };
43    let dialect_sexpr = &items[1];
44    let message_sexpr = &items[3];
45
46    let registry = parse_and_install_dialect(dialect_sexpr)?;
47
48    // Composition by conjunction (REQ-224): every matching shape across the
49    // whole installed registry must pass. Iterating all installed dialects
50    // (not just the leaf) matches the full pipeline's behaviour, so a shape
51    // declared on a parent dialect supplied via the `(dialects ...)` chain
52    // form still fires for messages that target the parent's performative.
53    // Blame attribution follows the dialect that owns the failing shape.
54    for d in registry.iter() {
55        for shape in &d.shapes {
56            if shape.performative != performative {
57                continue;
58            }
59            if let Err(violation) = shape.check(message_sexpr) {
60                let blame = ViolationError::from_shape_violation(&violation, None, None, None)
61                    .with_dialect_context(
62                        &d.name,
63                        d.author.as_deref(),
64                        d.hash.as_deref(),
65                        Some(&performative),
66                    );
67                return Err(serialize(&blame.to_sexpr()));
68            }
69        }
70    }
71    Ok(String::from("ok"))
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    const D: &str = "(define d (cbcl) @a (extend vote (to choice) (tell to :choice choice)) (shape vote (require :choice string)))";
79
80    #[test]
81    fn shape_verdicts() {
82        assert_eq!(
83            verify_message_shape_str(&format!("(verify-shape {D} vote (vote @r :choice \"x\"))"))
84                .unwrap(),
85            "ok"
86        );
87        let blame =
88            verify_message_shape_str(&format!("(verify-shape {D} vote (vote @r :choice 1))"))
89                .unwrap_err();
90        assert!(blame.contains("choice"), "{blame}");
91        assert!(verify_message_shape_str(&format!("(verify-shape {D} vote (vote @r))")).is_err());
92        // No shape targets the performative: nothing to violate.
93        assert_eq!(
94            verify_message_shape_str(&format!("(verify-shape {D} other (other @r))")).unwrap(),
95            "ok"
96        );
97        assert!(verify_message_shape_str("(verify-shape")
98            .unwrap_err()
99            .starts_with("parse error"));
100    }
101}