cbcl_parser/
shape_exports.rs1#![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
22pub 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 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 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}