#![forbid(unsafe_code)]
use crate::sexpr::{Atom, SExpr};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TypeConstraint {
String,
Hlc,
Integer,
Number,
Contract(crate::contracts::Contract),
Float,
Decimal,
Nonnegative,
Bool,
Symbol,
Keyword,
List,
}
impl TypeConstraint {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<TypeConstraint> {
match s {
"string" => Some(TypeConstraint::String),
"hlc" => Some(TypeConstraint::Hlc),
"float" => Some(TypeConstraint::Float),
"decimal" => Some(TypeConstraint::Decimal),
"integer" => Some(TypeConstraint::Integer),
"number" => Some(TypeConstraint::Number),
"nonnegative" => Some(TypeConstraint::Nonnegative),
"bool" => Some(TypeConstraint::Bool),
"symbol" => Some(TypeConstraint::Symbol),
"keyword" => Some(TypeConstraint::Keyword),
"list" => Some(TypeConstraint::List),
_ => None,
}
}
pub fn check(&self, value: &SExpr, work: u64) -> Result<(), crate::contracts::CheckError> {
if work == 0 || !crate::contracts::input_fits(value) {
return Err(crate::contracts::CheckError::ResourceLimit);
}
if let Self::Contract(c) = self {
return c.check(value, work);
}
if self.matches_builtin(value) {
Ok(())
} else {
Err(crate::contracts::CheckError::Violation(alloc::format!(
"expected {self}; found {}",
describe_type(value)
)))
}
}
pub(crate) fn resource_detail(&self, value: &SExpr, available: u64) -> String {
let required = match self {
Self::Contract(c) => c.required_work().unwrap_or(1),
_ => 1,
};
if available < required {
return alloc::format!(
"resource-limit: work requires {required} units; available {available}"
);
}
match crate::contracts::check_input(value) {
Err(reason) => alloc::format!("resource-limit: {reason}"),
Ok(()) => String::from("resource-limit"),
}
}
pub fn representation(&self) -> Option<Self> {
if let Self::Contract(c) = self {
c.representation().or_else(|| Some(self.clone()))
} else {
Some(self.clone())
}
}
pub fn source(&self) -> SExpr {
if let Self::Contract(c) = self {
c.source().clone()
} else {
SExpr::Atom(Atom::Symbol(self.to_string()))
}
}
pub(crate) fn matches_builtin(&self, sexpr: &SExpr) -> bool {
if *self == TypeConstraint::Hlc {
return matches!(sexpr, SExpr::Atom(Atom::Str(text)) if crate::hlc::Hlc::parse(text).is_some());
}
if *self == TypeConstraint::Nonnegative {
return matches!(sexpr, SExpr::Atom(Atom::Num(n)) if *n >= 0);
}
matches!(
(self, sexpr),
(TypeConstraint::String, SExpr::Atom(Atom::Str(_)))
| (
TypeConstraint::Integer | TypeConstraint::Number,
SExpr::Atom(Atom::Num(_))
)
| (
TypeConstraint::Number,
SExpr::Atom(Atom::Float(_) | Atom::Decimal(_))
)
| (TypeConstraint::Float, SExpr::Atom(Atom::Float(_)))
| (TypeConstraint::Decimal, SExpr::Atom(Atom::Decimal(_)))
| (TypeConstraint::Bool, SExpr::Atom(Atom::Bool(_)))
| (TypeConstraint::Symbol, SExpr::Atom(Atom::Symbol(_)))
| (TypeConstraint::Keyword, SExpr::Atom(Atom::Keyword(_)))
| (TypeConstraint::List, SExpr::List(_))
)
}
}
#[cfg(test)]
mod nonnegative_tests {
use super::*;
#[test]
fn nonnegative_recognizes_only_unsigned_integer_values() {
let ty = TypeConstraint::from_str("nonnegative").unwrap();
for value in [0, 1, i64::MAX] {
assert!(ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
}
for value in [i64::MIN, -1] {
assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Num(value))));
}
assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
assert!(!ty.matches_builtin(&SExpr::Atom(Atom::Str("0".into()))));
assert!(!ty.matches_builtin(&SExpr::List(Vec::new())));
assert_eq!(ty.to_string(), "nonnegative");
}
}
impl fmt::Display for TypeConstraint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
TypeConstraint::String => "string",
TypeConstraint::Hlc => "hlc",
TypeConstraint::Float => "float",
TypeConstraint::Decimal => "decimal",
TypeConstraint::Integer => "integer",
TypeConstraint::Contract(c) => return write!(f, "{}", c.source()),
TypeConstraint::Number => "number",
TypeConstraint::Nonnegative => "nonnegative",
TypeConstraint::Bool => "bool",
TypeConstraint::Symbol => "symbol",
TypeConstraint::Keyword => "keyword",
TypeConstraint::List => "list",
};
f.write_str(s)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ShapeRule {
Require {
keyword: String,
type_constraint: Option<TypeConstraint>,
children: Vec<ShapeRule>,
},
Optional {
keyword: String,
type_constraint: Option<TypeConstraint>,
default: Option<SExpr>,
children: Vec<ShapeRule>,
},
MaxDepth(u32),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShapeConstraint {
pub performative: String,
pub rules: Vec<ShapeRule>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShapeViolation {
pub rule: String,
pub field: Option<String>,
pub expected: Option<String>,
pub found: Option<String>,
pub detail: String,
}
impl fmt::Display for ShapeViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "shape violation: {}", self.detail)
}
}
impl ShapeConstraint {
pub fn check(&self, sexpr: &SExpr) -> Result<(), ShapeViolation> {
self.check_with_work(sexpr, crate::contracts::DEFAULT_WORK)
}
pub fn check_with_work(&self, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
for rule in &self.rules {
check_rule(rule, sexpr, work)?;
}
Ok(())
}
pub fn no_duplicate_keywords(&self) -> Result<(), String> {
check_duplicate_keywords(&self.rules)
}
pub fn max_depth(&self) -> Option<u32> {
self.max_depths().next()
}
pub fn max_depths(&self) -> impl Iterator<Item = u32> {
let mut out = Vec::new();
collect_max_depths(&self.rules, &mut out);
out.into_iter()
}
}
fn collect_max_depths(rules: &[ShapeRule], out: &mut Vec<u32>) {
for rule in rules {
match rule {
ShapeRule::MaxDepth(d) => out.push(*d),
ShapeRule::Require { children, .. } | ShapeRule::Optional { children, .. } => {
collect_max_depths(children, out);
}
}
}
}
pub(crate) fn check_rule(rule: &ShapeRule, sexpr: &SExpr, work: u64) -> Result<(), ShapeViolation> {
match rule {
ShapeRule::Require {
keyword,
type_constraint,
children,
} => {
let value = find_keyword_value(sexpr, keyword).ok_or_else(|| ShapeViolation {
rule: alloc::format!("require :{keyword}"),
field: Some(alloc::format!(":{keyword}")),
expected: Some(String::from("present")),
found: Some(String::from("missing")),
detail: alloc::format!("required parameter :{keyword} is missing"),
})?;
if let Some(tc) = type_constraint {
if let Err(check_error) = tc.check(value, work) {
let diagnostic =
if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
tc.resource_detail(value, work)
} else {
check_error.to_string()
};
return Err(ShapeViolation {
rule: if matches!(check_error, crate::contracts::CheckError::ResourceLimit)
{
"resource-limit".into()
} else {
alloc::format!("require :{keyword} {tc}")
},
field: Some(alloc::format!(":{keyword}")),
expected: Some(alloc::format!("{tc}")),
found: Some(describe_type(value)),
detail: if matches!(
check_error,
crate::contracts::CheckError::ResourceLimit
) {
alloc::format!(
"parameter :{keyword}: {diagnostic}; found {}",
describe_type(value)
)
} else {
alloc::format!(
"parameter :{keyword} failed {tc}: {diagnostic}; found {}",
describe_type(value)
)
},
});
}
}
for child in children {
check_rule(child, value, work).map_err(|mut err| {
err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
err
})?;
}
Ok(())
}
ShapeRule::Optional {
keyword,
type_constraint,
children,
..
} => {
if let Some(value) = find_keyword_value(sexpr, keyword) {
if let Some(tc) = type_constraint {
if let Err(check_error) = tc.check(value, work) {
let diagnostic =
if matches!(check_error, crate::contracts::CheckError::ResourceLimit) {
tc.resource_detail(value, work)
} else {
check_error.to_string()
};
return Err(ShapeViolation {
rule: if matches!(
check_error,
crate::contracts::CheckError::ResourceLimit
) {
"resource-limit".into()
} else {
alloc::format!("optional :{keyword} {tc}")
},
field: Some(alloc::format!(":{keyword}")),
expected: Some(alloc::format!("{tc}")),
found: Some(describe_type(value)),
detail: if matches!(
check_error,
crate::contracts::CheckError::ResourceLimit
) {
alloc::format!(
"parameter :{keyword}: {diagnostic}; found {}",
describe_type(value)
)
} else {
alloc::format!(
"parameter :{keyword} failed {tc}: {diagnostic}; found {}",
describe_type(value)
)
},
});
}
}
for child in children {
check_rule(child, value, work).map_err(|mut err| {
err.field = err.field.map(|field| alloc::format!(":{keyword}/{field}"));
err
})?;
}
}
Ok(())
}
ShapeRule::MaxDepth(max) => {
let depth = sexpr.depth() as u32;
if depth > *max {
Err(ShapeViolation {
rule: alloc::format!("max-depth {max}"),
field: None,
expected: Some(alloc::format!("<= {max}")),
found: Some(alloc::format!("{depth}")),
detail: alloc::format!("message depth {depth} exceeds max-depth {max}"),
})
} else {
Ok(())
}
}
}
}
fn find_keyword_value<'a>(sexpr: &'a SExpr, keyword: &str) -> Option<&'a SExpr> {
let items = match sexpr {
SExpr::List(items) => items,
_ => return None,
};
let mut i = 0;
while i < items.len() {
if let SExpr::Atom(Atom::Keyword(k)) = &items[i] {
if k == keyword {
return items.get(i + 1);
}
}
i += 1;
}
None
}
pub(crate) fn describe_type(sexpr: &SExpr) -> String {
match sexpr {
SExpr::Atom(Atom::Str(_)) => String::from("string"),
SExpr::Atom(Atom::Float(_)) => String::from("float"),
SExpr::Atom(Atom::Decimal(_)) => String::from("decimal"),
SExpr::Atom(Atom::Num(_)) => String::from("integer"),
SExpr::Atom(Atom::Bool(_)) => String::from("bool"),
SExpr::Atom(Atom::Symbol(_)) => String::from("symbol"),
SExpr::Atom(Atom::Keyword(_)) => String::from("keyword"),
SExpr::List(_) => String::from("list"),
}
}
fn check_duplicate_keywords(rules: &[ShapeRule]) -> Result<(), String> {
walk_keywords(rules, 0)
}
fn walk_keywords(rules: &[ShapeRule], depth: usize) -> Result<(), String> {
let mut seen: alloc::collections::BTreeSet<String> = alloc::collections::BTreeSet::new();
for rule in rules {
let (keyword, children) = match rule {
ShapeRule::Require {
keyword, children, ..
}
| ShapeRule::Optional {
keyword, children, ..
} => (keyword, children),
ShapeRule::MaxDepth(_) => continue,
};
if !seen.insert(keyword.clone()) {
return Err(alloc::format!(
"duplicate keyword :{keyword} at depth {depth}"
));
}
walk_keywords(children, depth + 1)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use alloc::vec;
fn sym(s: &str) -> SExpr {
SExpr::Atom(Atom::Symbol(String::from(s)))
}
fn kw(s: &str) -> SExpr {
SExpr::Atom(Atom::Keyword(String::from(s)))
}
fn str_expr(s: &str) -> SExpr {
SExpr::Atom(Atom::Str(String::from(s)))
}
fn num(n: i64) -> SExpr {
SExpr::Atom(Atom::Num(n))
}
fn list(items: Vec<SExpr>) -> SExpr {
SExpr::List(items)
}
#[test]
fn type_constraint_from_str() {
assert_eq!(
TypeConstraint::from_str("string"),
Some(TypeConstraint::String)
);
assert_eq!(
TypeConstraint::from_str("number"),
Some(TypeConstraint::Number)
);
assert_eq!(TypeConstraint::from_str("bool"), Some(TypeConstraint::Bool));
assert_eq!(
TypeConstraint::from_str("symbol"),
Some(TypeConstraint::Symbol)
);
assert_eq!(
TypeConstraint::from_str("keyword"),
Some(TypeConstraint::Keyword)
);
assert_eq!(TypeConstraint::from_str("list"), Some(TypeConstraint::List));
assert_eq!(TypeConstraint::from_str("unknown"), None);
}
#[test]
fn type_constraint_matches() {
assert!(TypeConstraint::String.matches_builtin(&str_expr("hello")));
assert!(!TypeConstraint::String.matches_builtin(&num(42)));
assert!(TypeConstraint::Number.matches_builtin(&num(42)));
assert!(TypeConstraint::Bool.matches_builtin(&SExpr::Atom(Atom::Bool(true))));
assert!(TypeConstraint::Symbol.matches_builtin(&sym("x")));
assert!(TypeConstraint::Keyword.matches_builtin(&kw("key")));
assert!(TypeConstraint::List.matches_builtin(&list(vec![sym("a")])));
assert!(!TypeConstraint::List.matches_builtin(&sym("a")));
}
#[test]
fn type_constraint_display() {
assert_eq!(TypeConstraint::String.to_string(), "string");
assert_eq!(TypeConstraint::Number.to_string(), "number");
assert_eq!(TypeConstraint::List.to_string(), "list");
}
#[test]
fn check_require_present() {
let shape = ShapeConstraint {
performative: String::from("track-shipment"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let msg = list(vec![
sym("track-shipment"),
kw("package"),
str_expr("box-1"),
]);
assert!(shape.check(&msg).is_ok());
}
#[test]
fn check_require_missing() {
let shape = ShapeConstraint {
performative: String::from("track-shipment"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let msg = list(vec![sym("track-shipment"), kw("route"), str_expr("A-B")]);
let err = shape.check(&msg).unwrap_err();
assert_eq!(err.field, Some(String::from(":package")));
assert!(err.detail.contains("missing"));
}
#[test]
fn check_require_wrong_type() {
let shape = ShapeConstraint {
performative: String::from("track-shipment"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let msg = list(vec![sym("track-shipment"), kw("package"), num(42)]);
let err = shape.check(&msg).unwrap_err();
assert_eq!(err.expected, Some(String::from("string")));
assert_eq!(err.found, Some(String::from("integer")));
}
#[test]
fn check_optional_absent_ok() {
let shape = ShapeConstraint {
performative: String::from("track-shipment"),
rules: vec![ShapeRule::Optional {
keyword: String::from("priority"),
type_constraint: Some(TypeConstraint::String),
default: Some(str_expr("normal")),
children: vec![],
}],
};
let msg = list(vec![sym("track-shipment")]);
assert!(shape.check(&msg).is_ok());
}
#[test]
fn check_optional_present_wrong_type() {
let shape = ShapeConstraint {
performative: String::from("track-shipment"),
rules: vec![ShapeRule::Optional {
keyword: String::from("priority"),
type_constraint: Some(TypeConstraint::String),
default: None,
children: vec![],
}],
};
let msg = list(vec![sym("track-shipment"), kw("priority"), num(1)]);
let err = shape.check(&msg).unwrap_err();
assert_eq!(err.expected, Some(String::from("string")));
}
#[test]
fn check_max_depth_ok() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![ShapeRule::MaxDepth(4)],
};
let msg = list(vec![sym("test"), kw("a"), str_expr("b")]);
assert!(shape.check(&msg).is_ok());
}
#[test]
fn check_max_depth_exceeded() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![ShapeRule::MaxDepth(1)],
};
let msg = list(vec![
sym("test"),
list(vec![sym("nested"), list(vec![sym("deep")])]),
]);
let err = shape.check(&msg).unwrap_err();
assert!(err.detail.contains("exceeds"));
}
#[test]
fn check_nested_children() {
let shape = ShapeConstraint {
performative: String::from("propose-step"),
rules: vec![ShapeRule::Require {
keyword: String::from("params"),
type_constraint: Some(TypeConstraint::List),
children: vec![ShapeRule::Require {
keyword: String::from("target"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
}],
};
let msg = list(vec![
sym("propose-step"),
kw("params"),
list(vec![kw("target"), str_expr("server-1")]),
]);
assert!(shape.check(&msg).is_ok());
}
#[test]
fn check_nested_children_missing_inner() {
let shape = ShapeConstraint {
performative: String::from("propose-step"),
rules: vec![ShapeRule::Require {
keyword: String::from("params"),
type_constraint: Some(TypeConstraint::List),
children: vec![ShapeRule::Require {
keyword: String::from("target"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
}],
};
let msg = list(vec![
sym("propose-step"),
kw("params"),
list(vec![kw("other"), str_expr("x")]),
]);
let err = shape.check(&msg).unwrap_err();
assert!(err.detail.contains(":target"));
}
#[test]
fn no_duplicate_keywords_ok() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![
ShapeRule::Require {
keyword: String::from("a"),
type_constraint: None,
children: vec![],
},
ShapeRule::Optional {
keyword: String::from("b"),
type_constraint: None,
default: None,
children: vec![],
},
],
};
assert!(shape.no_duplicate_keywords().is_ok());
}
#[test]
fn no_duplicate_keywords_allows_shared_child_under_different_parents() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![
ShapeRule::Require {
keyword: String::from("a"),
type_constraint: Some(TypeConstraint::List),
children: vec![ShapeRule::Require {
keyword: String::from("x"),
type_constraint: None,
children: vec![],
}],
},
ShapeRule::Require {
keyword: String::from("b"),
type_constraint: Some(TypeConstraint::List),
children: vec![ShapeRule::Require {
keyword: String::from("x"),
type_constraint: None,
children: vec![],
}],
},
],
};
assert!(shape.no_duplicate_keywords().is_ok());
}
#[test]
fn no_duplicate_keywords_detects_duplicate_within_same_parent() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![ShapeRule::Require {
keyword: String::from("a"),
type_constraint: Some(TypeConstraint::List),
children: vec![
ShapeRule::Require {
keyword: String::from("x"),
type_constraint: None,
children: vec![],
},
ShapeRule::Optional {
keyword: String::from("x"),
type_constraint: None,
default: None,
children: vec![],
},
],
}],
};
let err = shape.no_duplicate_keywords().unwrap_err();
assert!(err.contains(":x"), "expected :x to be flagged: {err}");
assert!(err.contains("depth 1"), "expected depth in error: {err}");
}
#[test]
fn no_duplicate_keywords_detects_duplicate() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![
ShapeRule::Require {
keyword: String::from("a"),
type_constraint: None,
children: vec![],
},
ShapeRule::Optional {
keyword: String::from("a"),
type_constraint: None,
default: None,
children: vec![],
},
],
};
let err = shape.no_duplicate_keywords().unwrap_err();
assert!(err.contains(":a"));
}
#[test]
fn max_depth_accessor() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![
ShapeRule::Require {
keyword: String::from("a"),
type_constraint: None,
children: vec![],
},
ShapeRule::MaxDepth(6),
],
};
assert_eq!(shape.max_depth(), Some(6));
}
#[test]
fn max_depth_none() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![],
};
assert_eq!(shape.max_depth(), None);
}
#[test]
fn multiple_shapes_compose_via_conjunction() {
let shape1 = ShapeConstraint {
performative: String::from("track"),
rules: vec![ShapeRule::Require {
keyword: String::from("package"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let shape2 = ShapeConstraint {
performative: String::from("track"),
rules: vec![ShapeRule::Require {
keyword: String::from("route"),
type_constraint: Some(TypeConstraint::String),
children: vec![],
}],
};
let msg = list(vec![
sym("track"),
kw("package"),
str_expr("box-1"),
kw("route"),
str_expr("A-B"),
]);
assert!(shape1.check(&msg).is_ok());
assert!(shape2.check(&msg).is_ok());
let partial = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
assert!(shape1.check(&partial).is_ok());
assert!(shape2.check(&partial).is_err());
}
#[test]
fn shape_violation_display() {
let v = ShapeViolation {
rule: String::from("require :package string"),
field: Some(String::from(":package")),
expected: Some(String::from("string")),
found: Some(String::from("number")),
detail: String::from("parameter :package expected type string, found number"),
};
let s = v.to_string();
assert!(s.contains("shape violation"));
assert!(s.contains(":package"));
}
#[test]
fn check_on_atom_fails_for_require() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![ShapeRule::Require {
keyword: String::from("a"),
type_constraint: None,
children: vec![],
}],
};
assert!(shape.check(&sym("not-a-list")).is_err());
}
#[test]
fn require_without_type_constraint() {
let shape = ShapeConstraint {
performative: String::from("test"),
rules: vec![ShapeRule::Require {
keyword: String::from("data"),
type_constraint: None,
children: vec![],
}],
};
let msg = list(vec![sym("test"), kw("data"), num(42)]);
assert!(shape.check(&msg).is_ok());
}
}