Skip to main content

cbcl_core/
shape.rs

1//! Structural shape constraints for dialect messages (REQ-220, REQ-223, REQ-224).
2//!
3//! Shape constraints declare the required structure of expanded messages:
4//! which keyword parameters must or may be present, their expected atom types,
5//! and maximum nesting depth.
6//!
7//! Shape checking is monotonic — it is a positive assertion about the structure
8//! of an immutable S-expression. VPL ⊂ DCFL (Alur & Madhusudan 2004).
9
10#![forbid(unsafe_code)]
11
12use crate::sexpr::{Atom, SExpr};
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15use core::fmt;
16
17/// Recognised type constraints for shape rules (REQ-221, SPEC-038 CON-3801).
18#[derive(Debug, Clone, PartialEq, Eq, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum TypeConstraint {
21    String,
22    /// Canonical host-supplied hybrid logical clock evidence, encoded as a string.
23    Hlc,
24    Integer,
25    Number,
26    Contract(crate::contracts::Contract),
27    Float,
28    Decimal,
29    /// Integer >= 0, recognized before admission (SPEC-038 ADR-3805).
30    Nonnegative,
31    Bool,
32    Symbol,
33    Keyword,
34    List,
35}
36
37impl TypeConstraint {
38    /// Parse a type constraint from a symbol name.
39    #[allow(clippy::should_implement_trait)]
40    pub fn from_str(s: &str) -> Option<TypeConstraint> {
41        match s {
42            "string" => Some(TypeConstraint::String),
43            "hlc" => Some(TypeConstraint::Hlc),
44            "float" => Some(TypeConstraint::Float),
45            "decimal" => Some(TypeConstraint::Decimal),
46            "integer" => Some(TypeConstraint::Integer),
47            "number" => Some(TypeConstraint::Number),
48            "nonnegative" => Some(TypeConstraint::Nonnegative),
49            "bool" => Some(TypeConstraint::Bool),
50            "symbol" => Some(TypeConstraint::Symbol),
51            "keyword" => Some(TypeConstraint::Keyword),
52            "list" => Some(TypeConstraint::List),
53            _ => None,
54        }
55    }
56
57    pub fn check(&self, value: &SExpr, work: u64) -> Result<(), crate::contracts::CheckError> {
58        if work == 0 || !crate::contracts::input_fits(value) {
59            return Err(crate::contracts::CheckError::ResourceLimit);
60        }
61        if let Self::Contract(c) = self {
62            return c.check(value, work);
63        }
64        if self.matches_builtin(value) {
65            Ok(())
66        } else {
67            Err(crate::contracts::CheckError::Violation(alloc::format!(
68                "expected {self}; found {}",
69                describe_type(value)
70            )))
71        }
72    }
73    pub(crate) fn resource_detail(&self, value: &SExpr, available: u64) -> String {
74        let required = match self {
75            Self::Contract(c) => c.required_work().unwrap_or(1),
76            _ => 1,
77        };
78        if available < required {
79            return alloc::format!(
80                "resource-limit: work requires {required} units; available {available}"
81            );
82        }
83        match crate::contracts::check_input(value) {
84            Err(reason) => alloc::format!("resource-limit: {reason}"),
85            Ok(()) => String::from("resource-limit"),
86        }
87    }
88    pub fn representation(&self) -> Option<Self> {
89        if let Self::Contract(c) = self {
90            c.representation().or_else(|| Some(self.clone()))
91        } else {
92            Some(self.clone())
93        }
94    }
95    pub fn source(&self) -> SExpr {
96        if let Self::Contract(c) = self {
97            c.source().clone()
98        } else {
99            SExpr::Atom(Atom::Symbol(self.to_string()))
100        }
101    }
102
103    /// Check whether an S-expression satisfies this type constraint.
104    pub(crate) fn matches_builtin(&self, sexpr: &SExpr) -> bool {
105        if *self == TypeConstraint::Hlc {
106            return matches!(sexpr, SExpr::Atom(Atom::Str(text)) if crate::hlc::Hlc::parse(text).is_some());
107        }
108        if *self == TypeConstraint::Nonnegative {
109            return matches!(sexpr, SExpr::Atom(Atom::Num(n)) if *n >= 0);
110        }
111        matches!(
112            (self, sexpr),
113            (TypeConstraint::String, SExpr::Atom(Atom::Str(_)))
114                | (
115                    TypeConstraint::Integer | TypeConstraint::Number,
116                    SExpr::Atom(Atom::Num(_))
117                )
118                | (
119                    TypeConstraint::Number,
120                    SExpr::Atom(Atom::Float(_) | Atom::Decimal(_))
121                )
122                | (TypeConstraint::Float, SExpr::Atom(Atom::Float(_)))
123                | (TypeConstraint::Decimal, SExpr::Atom(Atom::Decimal(_)))
124                | (TypeConstraint::Bool, SExpr::Atom(Atom::Bool(_)))
125                | (TypeConstraint::Symbol, SExpr::Atom(Atom::Symbol(_)))
126                | (TypeConstraint::Keyword, SExpr::Atom(Atom::Keyword(_)))
127                | (TypeConstraint::List, SExpr::List(_))
128        )
129    }
130}
131
132#[cfg(test)]
133mod nonnegative_tests {
134    use super::*;
135
136    #[test]
137    fn nonnegative_recognizes_only_unsigned_integer_values() {
138        let ty = TypeConstraint::from_str("nonnegative").unwrap();
139        for value in [0, 1, i64::MAX] {
140            assert!(ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
141        }
142        for value in [i64::MIN, -1] {
143            assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
144        }
145        assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
146        assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Str("0".into()))));
147        assert!(!ty.matches_builtin(&SExpr::List(Vec::new())));
148        assert_eq!(ty.to_string(), "nonnegative");
149    }
150}
151
152impl fmt::Display for TypeConstraint {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        let s = match self {
155            TypeConstraint::String => "string",
156            TypeConstraint::Hlc => "hlc",
157            TypeConstraint::Float => "float",
158            TypeConstraint::Decimal => "decimal",
159            TypeConstraint::Integer => "integer",
160            TypeConstraint::Contract(c) => return write!(f, "{}", c.source()),
161            TypeConstraint::Number => "number",
162            TypeConstraint::Nonnegative => "nonnegative",
163            TypeConstraint::Bool => "bool",
164            TypeConstraint::Symbol => "symbol",
165            TypeConstraint::Keyword => "keyword",
166            TypeConstraint::List => "list",
167        };
168        f.write_str(s)
169    }
170}
171
172/// A single shape rule within a shape constraint (REQ-221).
173#[derive(Debug, Clone, PartialEq, Eq)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
175pub enum ShapeRule {
176    /// A required keyword parameter.
177    Require {
178        keyword: String,
179        type_constraint: Option<TypeConstraint>,
180        children: Vec<ShapeRule>,
181    },
182    /// An optional keyword parameter with an optional default value.
183    Optional {
184        keyword: String,
185        type_constraint: Option<TypeConstraint>,
186        default: Option<SExpr>,
187        children: Vec<ShapeRule>,
188    },
189    /// Maximum nesting depth for the message.
190    MaxDepth(u32),
191}
192
193/// A shape constraint for a performative (REQ-220).
194///
195/// Declares the required structure of expanded messages for a specific
196/// performative. Multiple shape constraints on the same performative
197/// compose via conjunction (REQ-224).
198#[derive(Debug, Clone, PartialEq, Eq)]
199#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
200pub struct ShapeConstraint {
201    /// The performative this shape constrains.
202    pub performative: String,
203    /// The rules that expanded messages must satisfy.
204    pub rules: Vec<ShapeRule>,
205}
206
207/// A violation found during shape checking (REQ-223).
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct ShapeViolation {
210    pub rule: String,
211    pub field: Option<String>,
212    pub expected: Option<String>,
213    pub found: Option<String>,
214    pub detail: String,
215}
216
217impl fmt::Display for ShapeViolation {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        write!(f, "shape violation: {}", self.detail)
220    }
221}
222
223impl ShapeConstraint {
224    /// Check an expanded S-expression against this shape constraint (REQ-223).
225    ///
226    /// The `sexpr` should be the fully expanded message (after template expansion).
227    /// Returns `Ok(())` if all rules are satisfied, or `Err` with the first violation.
228    pub fn check(&self, sexpr: &SExpr) -> Result<(), ShapeViolation> {
229        self.check_with_work(sexpr, crate::contracts::DEFAULT_WORK)
230    }
231
232    pub fn check_with_work(&self, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
233        for rule in &self.rules {
234            check_rule(rule, sexpr, work)?;
235        }
236        Ok(())
237    }
238
239    /// Check whether this constraint has any duplicate require/optional keywords
240    /// at the same depth (REQ-222 §5).
241    pub fn no_duplicate_keywords(&self) -> Result<(), String> {
242        check_duplicate_keywords(&self.rules)
243    }
244
245    /// Return the first declared max-depth bound, if any.
246    ///
247    /// Prefer [`max_depths`](Self::max_depths) when validating every declared
248    /// bound (e.g. the R5 install-time check); this accessor is retained for
249    /// callers that only want a single representative bound.
250    pub fn max_depth(&self) -> Option<u32> {
251        self.max_depths().next()
252    }
253
254    /// Iterate over every `(max-depth …)` bound declared on this shape,
255    /// including bounds nested inside `require`/`optional` rules.
256    ///
257    /// A shape may declare more than one `MaxDepth` rule, and the parser
258    /// allows `(max-depth N)` to appear among a parent rule's children
259    /// (e.g. `(require :payload list (max-depth N))`). Install-time R5
260    /// (REQ-222 §4) must check every declared bound against the dialect's
261    /// R2 limit — a top-level-only walk would silently accept oversized
262    /// nested bounds, since at runtime any subtree's depth is bounded by
263    /// the whole message's depth, so `N > R2` is unreachable but still a
264    /// malformed declaration.
265    pub fn max_depths(&self) -> impl Iterator<Item = u32> {
266        let mut out = Vec::new();
267        collect_max_depths(&self.rules, &mut out);
268        out.into_iter()
269    }
270}
271
272/// Pre-order walk over a rule tree, pushing every `MaxDepth` value found.
273fn collect_max_depths(rules: &[ShapeRule], out: &mut Vec<u32>) {
274    for rule in rules {
275        match rule {
276            ShapeRule::MaxDepth(d) => out.push(*d),
277            ShapeRule::Require { children, .. } | ShapeRule::Optional { children, .. } => {
278                collect_max_depths(children, out);
279            }
280        }
281    }
282}
283
284/// Check a single rule against an S-expression.
285pub(crate) fn check_rule(rule: &ShapeRule, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
286    match rule {
287        ShapeRule::Require {
288            keyword,
289            type_constraint,
290            children,
291        } => {
292            let value = find_keyword_value(sexpr, keyword).ok_or_else(|| ShapeViolation {
293                rule: alloc::format!("require :{keyword}"),
294                field: Some(alloc::format!(":{keyword}")),
295                expected: Some(String::from("present")),
296                found: Some(String::from("missing")),
297                detail: alloc::format!("required parameter :{keyword} is missing"),
298            })?;
299            if let Some(tc) = type_constraint {
300                if let Err(check_error) = tc.check(value, work) {
301                    let diagnostic =
302                        if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
303                            tc.resource_detail(value, work)
304                        } else {
305                            check_error.to_string()
306                        };
307                    return Err(ShapeViolation {
308                        rule: if matches!(check_error, crate::contracts::CheckError::ResourceLimit)
309                        {
310                            "resource-limit".into()
311                        } else {
312                            alloc::format!("require :{keyword} {tc}")
313                        },
314                        field: Some(alloc::format!(":{keyword}")),
315                        expected: Some(alloc::format!("{tc}")),
316                        found: Some(describe_type(value)),
317                        detail: if matches!(
318                            check_error,
319                            crate::contracts::CheckError::ResourceLimit
320                        ) {
321                            alloc::format!(
322                                "parameter :{keyword}: {diagnostic}; found {}",
323                                describe_type(value)
324                            )
325                        } else {
326                            alloc::format!(
327                                "parameter :{keyword} failed {tc}: {diagnostic}; found {}",
328                                describe_type(value)
329                            )
330                        },
331                    });
332                }
333            }
334            for child in children {
335                check_rule(child, value, work).map_err(|mut err| {
336                    err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
337                    err
338                })?;
339            }
340            Ok(())
341        }
342        ShapeRule::Optional {
343            keyword,
344            type_constraint,
345            children,
346            ..
347        } => {
348            if let Some(value) = find_keyword_value(sexpr, keyword) {
349                if let Some(tc) = type_constraint {
350                    if let Err(check_error) = tc.check(value, work) {
351                        let diagnostic =
352                            if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
353                                tc.resource_detail(value, work)
354                            } else {
355                                check_error.to_string()
356                            };
357                        return Err(ShapeViolation {
358                            rule: if matches!(
359                                check_error,
360                                crate::contracts::CheckError::ResourceLimit
361                            ) {
362                                "resource-limit".into()
363                            } else {
364                                alloc::format!("optional :{keyword} {tc}")
365                            },
366                            field: Some(alloc::format!(":{keyword}")),
367                            expected: Some(alloc::format!("{tc}")),
368                            found: Some(describe_type(value)),
369                            detail: if matches!(
370                                check_error,
371                                crate::contracts::CheckError::ResourceLimit
372                            ) {
373                                alloc::format!(
374                                    "parameter :{keyword}: {diagnostic}; found {}",
375                                    describe_type(value)
376                                )
377                            } else {
378                                alloc::format!(
379                                    "parameter :{keyword} failed {tc}: {diagnostic}; found {}",
380                                    describe_type(value)
381                                )
382                            },
383                        });
384                    }
385                }
386                for child in children {
387                    check_rule(child, value, work).map_err(|mut err| {
388                        err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
389                        err
390                    })?;
391                }
392            }
393            Ok(())
394        }
395        ShapeRule::MaxDepth(max) => {
396            let depth = sexpr.depth() as u32;
397            if depth > *max {
398                Err(ShapeViolation {
399                    rule: alloc::format!("max-depth {max}"),
400                    field: None,
401                    expected: Some(alloc::format!("<= {max}")),
402                    found: Some(alloc::format!("{depth}")),
403                    detail: alloc::format!("message depth {depth} exceeds max-depth {max}"),
404                })
405            } else {
406                Ok(())
407            }
408        }
409    }
410}
411
412/// Find the value following a keyword in an S-expression list.
413///
414/// Scans `(performative ... :keyword value ...)` and returns `value`.
415fn find_keyword_value<'a>(sexpr: &'a SExpr, keyword: &str) -> Option<&'a SExpr> {
416    let items = match sexpr {
417        SExpr::List(items) => items,
418        _ => return None,
419    };
420    let mut i = 0;
421    while i < items.len() {
422        if let SExpr::Atom(Atom::Keyword(k)) = &items[i] {
423            if k == keyword {
424                return items.get(i + 1);
425            }
426        }
427        i += 1;
428    }
429    None
430}
431
432/// Describe the type of an S-expression value for error messages.
433pub(crate) fn describe_type(sexpr: &SExpr) -> String {
434    match sexpr {
435        SExpr::Atom(Atom::Str(_)) => String::from("string"),
436        SExpr::Atom(Atom::Float(_)) => String::from("float"),
437        SExpr::Atom(Atom::Decimal(_)) => String::from("decimal"),
438        SExpr::Atom(Atom::Num(_)) => String::from("integer"),
439        SExpr::Atom(Atom::Bool(_)) => String::from("bool"),
440        SExpr::Atom(Atom::Symbol(_)) => String::from("symbol"),
441        SExpr::Atom(Atom::Keyword(_)) => String::from("keyword"),
442        SExpr::List(_) => String::from("list"),
443    }
444}
445
446/// Check for duplicate require/optional keywords within the same parent
447/// scope (REQ-222 §5).
448///
449/// Each `(...)` list in an expanded message has its own keyword namespace
450/// (see `find_keyword_value` and the `Require` arm of `check_rule`, which
451/// recurses children against the matched parent's value). The static check
452/// mirrors that scoping: duplicates are sibling rules under the same
453/// parent, not arbitrary co-depth rules across independent subtrees.
454fn check_duplicate_keywords(rules: &[ShapeRule]) -> Result<(), String> {
455    walk_keywords(rules, 0)
456}
457
458fn walk_keywords(rules: &[ShapeRule], depth: usize) -> Result<(), String> {
459    let mut seen: alloc::collections::BTreeSet<String> = alloc::collections::BTreeSet::new();
460    for rule in rules {
461        let (keyword, children) = match rule {
462            ShapeRule::Require {
463                keyword, children, ..
464            }
465            | ShapeRule::Optional {
466                keyword, children, ..
467            } => (keyword, children),
468            ShapeRule::MaxDepth(_) => continue,
469        };
470        if !seen.insert(keyword.clone()) {
471            return Err(alloc::format!(
472                "duplicate keyword :{keyword} at depth {depth}"
473            ));
474        }
475        walk_keywords(children, depth + 1)?;
476    }
477    Ok(())
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use alloc::string::ToString;
484    use alloc::vec;
485
486    fn sym(s: &str) -> SExpr {
487        SExpr::Atom(Atom::Symbol(String::from(s)))
488    }
489
490    fn kw(s: &str) -> SExpr {
491        SExpr::Atom(Atom::Keyword(String::from(s)))
492    }
493
494    fn str_expr(s: &str) -> SExpr {
495        SExpr::Atom(Atom::Str(String::from(s)))
496    }
497
498    fn num(n: i64) -> SExpr {
499        SExpr::Atom(Atom::Num(n))
500    }
501
502    fn list(items: Vec<SExpr>) -> SExpr {
503        SExpr::List(items)
504    }
505
506    // -- TypeConstraint tests --
507
508    #[test]
509    fn type_constraint_from_str() {
510        assert_eq!(
511            TypeConstraint::from_str("string"),
512            Some(TypeConstraint::String)
513        );
514        assert_eq!(
515            TypeConstraint::from_str("number"),
516            Some(TypeConstraint::Number)
517        );
518        assert_eq!(TypeConstraint::from_str("bool"), Some(TypeConstraint::Bool));
519        assert_eq!(
520            TypeConstraint::from_str("symbol"),
521            Some(TypeConstraint::Symbol)
522        );
523        assert_eq!(
524            TypeConstraint::from_str("keyword"),
525            Some(TypeConstraint::Keyword)
526        );
527        assert_eq!(TypeConstraint::from_str("list"), Some(TypeConstraint::List));
528        assert_eq!(TypeConstraint::from_str("unknown"), None);
529    }
530
531    #[test]
532    fn type_constraint_matches() {
533        assert!(TypeConstraint::String.matches_builtin(&str_expr("hello")));
534        assert!(!TypeConstraint::String.matches_builtin(&num(42)));
535        assert!(TypeConstraint::Number.matches_builtin(&num(42)));
536        assert!(TypeConstraint::Bool.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
537        assert!(TypeConstraint::Symbol.matches_builtin(&sym("x")));
538        assert!(TypeConstraint::Keyword.matches_builtin(&kw("key")));
539        assert!(TypeConstraint::List.matches_builtin(&list(vec![sym("a")])));
540        assert!(!TypeConstraint::List.matches_builtin(&sym("a")));
541    }
542
543    #[test]
544    fn type_constraint_display() {
545        assert_eq!(TypeConstraint::String.to_string(), "string");
546        assert_eq!(TypeConstraint::Number.to_string(), "number");
547        assert_eq!(TypeConstraint::List.to_string(), "list");
548    }
549
550    // -- ShapeConstraint::check tests --
551
552    #[test]
553    fn check_require_present() {
554        let shape = ShapeConstraint {
555            performative: String::from("track-shipment"),
556            rules: vec![ShapeRule::Require {
557                keyword: String::from("package"),
558                type_constraint: Some(TypeConstraint::String),
559                children: vec![],
560            }],
561        };
562        let msg = list(vec![
563            sym("track-shipment"),
564            kw("package"),
565            str_expr("box-1"),
566        ]);
567        assert!(shape.check(&msg).is_ok());
568    }
569
570    #[test]
571    fn check_require_missing() {
572        let shape = ShapeConstraint {
573            performative: String::from("track-shipment"),
574            rules: vec![ShapeRule::Require {
575                keyword: String::from("package"),
576                type_constraint: Some(TypeConstraint::String),
577                children: vec![],
578            }],
579        };
580        let msg = list(vec![sym("track-shipment"), kw("route"), str_expr("A-B")]);
581        let err = shape.check(&msg).unwrap_err();
582        assert_eq!(err.field, Some(String::from(":package")));
583        assert!(err.detail.contains("missing"));
584    }
585
586    #[test]
587    fn check_require_wrong_type() {
588        let shape = ShapeConstraint {
589            performative: String::from("track-shipment"),
590            rules: vec![ShapeRule::Require {
591                keyword: String::from("package"),
592                type_constraint: Some(TypeConstraint::String),
593                children: vec![],
594            }],
595        };
596        let msg = list(vec![sym("track-shipment"), kw("package"), num(42)]);
597        let err = shape.check(&msg).unwrap_err();
598        assert_eq!(err.expected, Some(String::from("string")));
599        assert_eq!(err.found, Some(String::from("integer")));
600    }
601
602    #[test]
603    fn check_optional_absent_ok() {
604        let shape = ShapeConstraint {
605            performative: String::from("track-shipment"),
606            rules: vec![ShapeRule::Optional {
607                keyword: String::from("priority"),
608                type_constraint: Some(TypeConstraint::String),
609                default: Some(str_expr("normal")),
610                children: vec![],
611            }],
612        };
613        let msg = list(vec![sym("track-shipment")]);
614        assert!(shape.check(&msg).is_ok());
615    }
616
617    #[test]
618    fn check_optional_present_wrong_type() {
619        let shape = ShapeConstraint {
620            performative: String::from("track-shipment"),
621            rules: vec![ShapeRule::Optional {
622                keyword: String::from("priority"),
623                type_constraint: Some(TypeConstraint::String),
624                default: None,
625                children: vec![],
626            }],
627        };
628        let msg = list(vec![sym("track-shipment"), kw("priority"), num(1)]);
629        let err = shape.check(&msg).unwrap_err();
630        assert_eq!(err.expected, Some(String::from("string")));
631    }
632
633    #[test]
634    fn check_max_depth_ok() {
635        let shape = ShapeConstraint {
636            performative: String::from("test"),
637            rules: vec![ShapeRule::MaxDepth(4)],
638        };
639        // depth 1: (test :a "b")
640        let msg = list(vec![sym("test"), kw("a"), str_expr("b")]);
641        assert!(shape.check(&msg).is_ok());
642    }
643
644    #[test]
645    fn check_max_depth_exceeded() {
646        let shape = ShapeConstraint {
647            performative: String::from("test"),
648            rules: vec![ShapeRule::MaxDepth(1)],
649        };
650        // depth 2: (test (nested (deep)))
651        let msg = list(vec![
652            sym("test"),
653            list(vec![sym("nested"), list(vec![sym("deep")])]),
654        ]);
655        let err = shape.check(&msg).unwrap_err();
656        assert!(err.detail.contains("exceeds"));
657    }
658
659    #[test]
660    fn check_nested_children() {
661        // (shape propose-step
662        //   (require :params list
663        //     (require :target string)))
664        let shape = ShapeConstraint {
665            performative: String::from("propose-step"),
666            rules: vec![ShapeRule::Require {
667                keyword: String::from("params"),
668                type_constraint: Some(TypeConstraint::List),
669                children: vec![ShapeRule::Require {
670                    keyword: String::from("target"),
671                    type_constraint: Some(TypeConstraint::String),
672                    children: vec![],
673                }],
674            }],
675        };
676        let msg = list(vec![
677            sym("propose-step"),
678            kw("params"),
679            list(vec![kw("target"), str_expr("server-1")]),
680        ]);
681        assert!(shape.check(&msg).is_ok());
682    }
683
684    #[test]
685    fn check_nested_children_missing_inner() {
686        let shape = ShapeConstraint {
687            performative: String::from("propose-step"),
688            rules: vec![ShapeRule::Require {
689                keyword: String::from("params"),
690                type_constraint: Some(TypeConstraint::List),
691                children: vec![ShapeRule::Require {
692                    keyword: String::from("target"),
693                    type_constraint: Some(TypeConstraint::String),
694                    children: vec![],
695                }],
696            }],
697        };
698        let msg = list(vec![
699            sym("propose-step"),
700            kw("params"),
701            list(vec![kw("other"), str_expr("x")]),
702        ]);
703        let err = shape.check(&msg).unwrap_err();
704        assert!(err.detail.contains(":target"));
705    }
706
707    // -- no_duplicate_keywords tests --
708
709    #[test]
710    fn no_duplicate_keywords_ok() {
711        let shape = ShapeConstraint {
712            performative: String::from("test"),
713            rules: vec![
714                ShapeRule::Require {
715                    keyword: String::from("a"),
716                    type_constraint: None,
717                    children: vec![],
718                },
719                ShapeRule::Optional {
720                    keyword: String::from("b"),
721                    type_constraint: None,
722                    default: None,
723                    children: vec![],
724                },
725            ],
726        };
727        assert!(shape.no_duplicate_keywords().is_ok());
728    }
729
730    #[test]
731    fn no_duplicate_keywords_allows_shared_child_under_different_parents() {
732        // Children rules are scoped to the matched parent list at runtime
733        // (see `check_rule` Require branch), so `:x` under `:a` and `:x`
734        // under `:b` live in independent keyword namespaces and must not
735        // be reported as duplicates. Mirrors the pickup/dropoff :id pattern
736        // that motivated this regression.
737        let shape = ShapeConstraint {
738            performative: String::from("test"),
739            rules: vec![
740                ShapeRule::Require {
741                    keyword: String::from("a"),
742                    type_constraint: Some(TypeConstraint::List),
743                    children: vec![ShapeRule::Require {
744                        keyword: String::from("x"),
745                        type_constraint: None,
746                        children: vec![],
747                    }],
748                },
749                ShapeRule::Require {
750                    keyword: String::from("b"),
751                    type_constraint: Some(TypeConstraint::List),
752                    children: vec![ShapeRule::Require {
753                        keyword: String::from("x"),
754                        type_constraint: None,
755                        children: vec![],
756                    }],
757                },
758            ],
759        };
760        assert!(shape.no_duplicate_keywords().is_ok());
761    }
762
763    #[test]
764    fn no_duplicate_keywords_detects_duplicate_within_same_parent() {
765        // Two child rules with the same keyword under the same parent
766        // collide at runtime (they target the same value slot of `:a`),
767        // so R5 must reject this even though the duplicates are nested.
768        let shape = ShapeConstraint {
769            performative: String::from("test"),
770            rules: vec![ShapeRule::Require {
771                keyword: String::from("a"),
772                type_constraint: Some(TypeConstraint::List),
773                children: vec![
774                    ShapeRule::Require {
775                        keyword: String::from("x"),
776                        type_constraint: None,
777                        children: vec![],
778                    },
779                    ShapeRule::Optional {
780                        keyword: String::from("x"),
781                        type_constraint: None,
782                        default: None,
783                        children: vec![],
784                    },
785                ],
786            }],
787        };
788        let err = shape.no_duplicate_keywords().unwrap_err();
789        assert!(err.contains(":x"), "expected :x to be flagged: {err}");
790        assert!(err.contains("depth 1"), "expected depth in error: {err}");
791    }
792
793    #[test]
794    fn no_duplicate_keywords_detects_duplicate() {
795        let shape = ShapeConstraint {
796            performative: String::from("test"),
797            rules: vec![
798                ShapeRule::Require {
799                    keyword: String::from("a"),
800                    type_constraint: None,
801                    children: vec![],
802                },
803                ShapeRule::Optional {
804                    keyword: String::from("a"),
805                    type_constraint: None,
806                    default: None,
807                    children: vec![],
808                },
809            ],
810        };
811        let err = shape.no_duplicate_keywords().unwrap_err();
812        assert!(err.contains(":a"));
813    }
814
815    // -- max_depth accessor --
816
817    #[test]
818    fn max_depth_accessor() {
819        let shape = ShapeConstraint {
820            performative: String::from("test"),
821            rules: vec![
822                ShapeRule::Require {
823                    keyword: String::from("a"),
824                    type_constraint: None,
825                    children: vec![],
826                },
827                ShapeRule::MaxDepth(6),
828            ],
829        };
830        assert_eq!(shape.max_depth(), Some(6));
831    }
832
833    #[test]
834    fn max_depth_none() {
835        let shape = ShapeConstraint {
836            performative: String::from("test"),
837            rules: vec![],
838        };
839        assert_eq!(shape.max_depth(), None);
840    }
841
842    // -- Composition via conjunction (REQ-224) --
843
844    #[test]
845    fn multiple_shapes_compose_via_conjunction() {
846        let shape1 = ShapeConstraint {
847            performative: String::from("track"),
848            rules: vec![ShapeRule::Require {
849                keyword: String::from("package"),
850                type_constraint: Some(TypeConstraint::String),
851                children: vec![],
852            }],
853        };
854        let shape2 = ShapeConstraint {
855            performative: String::from("track"),
856            rules: vec![ShapeRule::Require {
857                keyword: String::from("route"),
858                type_constraint: Some(TypeConstraint::String),
859                children: vec![],
860            }],
861        };
862        // Must satisfy both
863        let msg = list(vec![
864            sym("track"),
865            kw("package"),
866            str_expr("box-1"),
867            kw("route"),
868            str_expr("A-B"),
869        ]);
870        assert!(shape1.check(&msg).is_ok());
871        assert!(shape2.check(&msg).is_ok());
872
873        // Missing route fails shape2
874        let partial = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
875        assert!(shape1.check(&partial).is_ok());
876        assert!(shape2.check(&partial).is_err());
877    }
878
879    // -- ShapeViolation display --
880
881    #[test]
882    fn shape_violation_display() {
883        let v = ShapeViolation {
884            rule: String::from("require :package string"),
885            field: Some(String::from(":package")),
886            expected: Some(String::from("string")),
887            found: Some(String::from("number")),
888            detail: String::from("parameter :package expected type string, found number"),
889        };
890        let s = v.to_string();
891        assert!(s.contains("shape violation"));
892        assert!(s.contains(":package"));
893    }
894
895    // -- find_keyword_value on non-list --
896
897    #[test]
898    fn check_on_atom_fails_for_require() {
899        let shape = ShapeConstraint {
900            performative: String::from("test"),
901            rules: vec![ShapeRule::Require {
902                keyword: String::from("a"),
903                type_constraint: None,
904                children: vec![],
905            }],
906        };
907        assert!(shape.check(&sym("not-a-list")).is_err());
908    }
909
910    // -- Require without type constraint --
911
912    #[test]
913    fn require_without_type_constraint() {
914        let shape = ShapeConstraint {
915            performative: String::from("test"),
916            rules: vec![ShapeRule::Require {
917                keyword: String::from("data"),
918                type_constraint: None,
919                children: vec![],
920            }],
921        };
922        // Any type of value is accepted
923        let msg = list(vec![sym("test"), kw("data"), num(42)]);
924        assert!(shape.check(&msg).is_ok());
925    }
926}