1use alloc::string::{String, ToString};
12use alloc::vec::Vec;
13use cbcl_core::dialect::Dialect;
14use cbcl_core::message::{CausedBy, Message};
15use cbcl_core::protocol::NodeRef;
16use cbcl_core::role::RoleCardinality;
17use cbcl_core::serializer::serialize;
18use cbcl_core::sexpr::{Atom, SExpr};
19use cbcl_core::shape::ShapeRule;
20use cbcl_core::state::{Act, Entry, Rule, RESERVED_REPLACES};
21use serde_json::{json, Map, Value as Json};
22
23fn symbol(s: &SExpr) -> Option<&str> {
24 match s {
25 SExpr::Atom(Atom::Symbol(x)) => Some(x),
26 _ => None,
27 }
28}
29
30pub fn define_form(input: &str) -> Result<SExpr, String> {
33 let form = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
34 let mut current = &form;
35 loop {
36 let SExpr::List(items) = current else {
37 return Err(String::from(
38 "expected a (define …), (meta (define …)) or (meta (teach (define …))) form",
39 ));
40 };
41 match items.first().and_then(symbol) {
42 Some("define") => return Ok(current.clone()),
43 Some("meta") | Some("teach") if items.len() >= 2 => current = &items[1],
44 _ => {
45 return Err(String::from(
46 "expected a (define …), (meta (define …)) or (meta (teach (define …))) form",
47 ))
48 }
49 }
50 }
51}
52
53pub fn define_text_str(input: &str) -> Result<String, String> {
55 Ok(serialize(&define_form(input)?))
56}
57
58fn json_of_sexpr(s: &SExpr) -> Json {
59 match s {
60 SExpr::List(items) => Json::Array(items.iter().map(json_of_sexpr).collect()),
61 SExpr::Atom(Atom::Str(x)) | SExpr::Atom(Atom::Symbol(x)) => Json::String(x.clone()),
62 SExpr::Atom(Atom::Keyword(k)) => Json::String(alloc::format!(":{k}")),
63 SExpr::Atom(Atom::Float(n)) => json!(n.get()),
64 SExpr::Atom(Atom::Decimal(n)) => json!({"decimal": n.as_str()}),
65 SExpr::Atom(Atom::Num(n)) => json!(n),
66 SExpr::Atom(Atom::Bool(b)) => Json::Bool(*b),
67 }
68}
69
70fn shape_description(rule: &ShapeRule) -> Json {
71 let (keyword, constraint, children, required, default) = match rule {
72 ShapeRule::Require {
73 keyword,
74 type_constraint,
75 children,
76 } => (keyword, type_constraint, children, true, None),
77 ShapeRule::Optional {
78 keyword,
79 type_constraint,
80 children,
81 default,
82 } => (
83 keyword,
84 type_constraint,
85 children,
86 false,
87 default.as_ref().map(serialize),
88 ),
89 ShapeRule::MaxDepth(limit) => return json!({"maxDepth":limit}),
90 };
91 json!({
92 "keyword":keyword, "required":required, "default":default,
93 "source":constraint.as_ref().map(|t| serialize(&t.source())).unwrap_or_default(),
94 "representations":constraint.as_ref().map(cbcl_core::contracts::representation_names).unwrap_or_default(),
95 "children":children.iter().map(shape_description).collect::<Vec<_>>(),
96 })
97}
98
99fn rule_json(rule: &Rule) -> Json {
101 if let Rule::Lift(lift) = rule {
102 let mut args = alloc::vec![SExpr::Atom(Atom::Symbol("lift".into()))];
103 args.extend(lift.arguments());
104 return json_of_sexpr(&SExpr::List(args));
105 }
106 if let Rule::BoundedCounter(c) = rule {
107 return json!([
108 "boundedCounter",
109 c.canonical_options()
110 .iter()
111 .map(json_of_sexpr)
112 .collect::<Vec<_>>()
113 ]);
114 }
115 let (op, args): (&str, Vec<&str>) = match rule {
116 Rule::BoundedCounter(_) | Rule::Lift(_) => unreachable!("handled above"),
117 Rule::LwwRegister { verb, key, clock } => ("lwwRegister", alloc::vec![verb, key, clock]),
118 Rule::LwwPerSigner { verb, key, clock } => ("lwwPerSigner", alloc::vec![verb, key, clock]),
119 Rule::LwwMap {
120 verb,
121 key,
122 value,
123 clock,
124 delete,
125 } => {
126 let mut args = alloc::vec![verb.as_str(), key, value, clock];
127 if let Some(d) = delete {
128 args.push(d);
129 }
130 ("lwwMap", args)
131 }
132 Rule::Context { path, .. } => ("context", path.iter().map(String::as_str).collect()),
133 Rule::Initial { verb, key } => ("initial", alloc::vec![verb, key]),
134
135 Rule::Exists { verb } => ("exists", alloc::vec![verb]),
136 Rule::Count { verb } => ("count", alloc::vec![verb]),
137 Rule::Progress { verb } => ("progress", alloc::vec![verb]),
138 Rule::Events { verb, key } => ("events", alloc::vec![verb, key]),
139 Rule::SetUnion { verb, key } => ("setUnion", alloc::vec![verb, key]),
140 Rule::Values { verb, key } => ("values", alloc::vec![verb, key]),
141 Rule::ValuesPerKey {
142 verb,
143 key,
144 value,
145 delete,
146 } => {
147 let mut v = alloc::vec![verb.as_str(), key, value];
148 if let Some(d) = delete {
149 v.push(d);
150 }
151 ("valuesPerKey", v)
152 }
153
154 Rule::ObservedSet { add, remove, key } => ("observedSet", alloc::vec![add, remove, key]),
155 Rule::Counter { inc, dec, key } => ("counter", alloc::vec![inc, dec, key]),
156 Rule::Histogram { field } => ("histogram", alloc::vec![field]),
157 Rule::Sum { field } => ("sum", alloc::vec![field]),
158 };
159 let mut out = alloc::vec![Json::String(op.to_string())];
160 out.extend(args.into_iter().map(|a| Json::String(a.to_string())));
161 Json::Array(out)
162}
163
164pub fn describe(d: &Dialect, text: &str) -> Json {
166 let mut verbs = Map::new();
167 for p in &d.performatives {
168 let params: Vec<Json> = p.params.iter().map(json_of_sexpr).collect();
169 let mut shape_rules = Vec::new();
170 let mut fields = Map::new();
171 let mut contracts = Map::new();
172 for shape in d.shapes.iter().filter(|s| s.performative == p.name) {
173 for rule in &shape.rules {
174 let description = shape_description(rule);
175 if let ShapeRule::Require {
176 keyword,
177 type_constraint,
178 ..
179 }
180 | ShapeRule::Optional {
181 keyword,
182 type_constraint,
183 ..
184 } = rule
185 {
186 if keyword == RESERVED_REPLACES {
187 continue;
188 }
189 let ty = type_constraint
190 .as_ref()
191 .map(|t| t.to_string())
192 .unwrap_or_default();
193 fields.insert(keyword.clone(), Json::String(ty));
194 contracts.insert(keyword.clone(), description.clone());
195 }
196 shape_rules.push(description);
197 }
198 }
199 let after: Vec<Json> = d
200 .causal_protocol
201 .as_ref()
202 .and_then(|proto| proto.steps.get(&p.name))
203 .map(|step| {
204 step.predecessors
205 .iter()
206 .flat_map(|n| match n {
207 NodeRef::Single(s) => alloc::vec![s.clone()],
208 NodeRef::Any(set) | NodeRef::All(set) => set.iter().cloned().collect(),
209 })
210 .map(Json::String)
211 .collect()
212 })
213 .unwrap_or_default();
214 let mut entry = json!({ "params": params, "fields": fields, "contracts":contracts, "shapeRules":shape_rules, "after": after });
215 if let Some(ann) = &p.role {
216 entry["from"] = Json::String(ann.from.clone());
217 entry["to"] = Json::Array(ann.to.iter().cloned().map(Json::String).collect());
218 }
219 verbs.insert(p.name.clone(), entry);
220 }
221 let opener = d
222 .causal_protocol
223 .as_ref()
224 .and_then(cbcl_core::state::opener_verb)
225 .map(|v| Json::String(v.to_string()))
226 .unwrap_or(Json::Null);
227 let mut roles = Map::new();
228 for r in &d.roles {
229 let kind = match r.cardinality {
230 RoleCardinality::Singleton => "singleton",
231 RoleCardinality::Indexed => "indexed",
232 };
233 roles.insert(r.name.clone(), Json::String(kind.to_string()));
234 }
235 let mut state = Map::new();
236 let mut domains = Vec::new();
237 let mut thresholds = Vec::new();
238 let mut freezes = Vec::new();
239 let mut lattices = Vec::new();
240 if let Some(clause) = &d.state {
241 for entry in &clause.entries {
242 match entry {
243 Entry::Lattice(definition) => lattices.push(json_of_sexpr(&definition.to_sexpr())),
244 Entry::Freeze {
245 field,
246 verb,
247 policy,
248 } => {
249 freezes.push(json!({"field":field,"verb":verb,"policy":policy.as_str()}));
250 }
251 Entry::Field { name, rule } => {
252 state.insert(name.clone(), rule_json(rule));
253 }
254 Entry::Domain { verb, key, field } => {
255 domains.push(json!({ "verb": verb, "key": key, "field": field }));
256 }
257 Entry::Condition { name, condition } => {
258 let condition: Json =
259 serde_json::from_str(&condition.schema().render()).unwrap();
260 thresholds.push(json!({"name":name,"condition":condition}));
261 }
262 Entry::Threshold {
263 name,
264 field,
265 elements,
266 } => {
267 let elements: Vec<Json> = elements
268 .iter()
269 .map(|e| serde_json::from_str(&e.render().render()).unwrap_or(Json::Null))
270 .collect();
271 thresholds.push(json!({ "name": name, "field": field, "elements": elements }));
272 }
273 }
274 }
275 }
276 let bounds = match &d.state_bounds {
277 Some(b) => {
278 json!({ "max-string": b.max_string, "max-list": b.max_list, "max-number": b.max_number, "max-fields": b.max_fields })
279 }
280 None => json!({}),
281 };
282 let mut types = Map::new();
283 match cbcl_core::contracts::type_schema(d) {
284 Ok(entries) => {
285 for (name, expression, representations) in entries {
286 types.insert(
287 name,
288 json!({"source":serialize(&expression), "representations":representations}),
289 );
290 }
291 }
292 Err(error) => return json!({"error":error}),
293 }
294 json!({
295 "typeProfile": cbcl_core::contracts::PROFILE,
296 "types": types,
297 "name": d.name,
298 "author": d.author,
299 "opener": opener,
300 "verbs": verbs,
301 "roles": roles,
302 "state": state,
303 "domains": domains,
304 "thresholds": thresholds,
305 "freezes": freezes,
306 "lattices": lattices,
307 "bounds": bounds,
308 "text": text,
309 })
310}
311
312pub fn describe_dialect_str(input: &str) -> Result<String, String> {
314 let form = define_form(input)?;
315 let d = crate::parse_dialect(&form).map_err(|e| alloc::format!("dialect parse error: {e}"))?;
316 Ok(describe(&d, &serialize(&form)).to_string())
317}
318
319fn dialect_of(m: &Message) -> Option<&str> {
320 match m {
321 Message::Dialect { dialect_name, .. } => Some(dialect_name),
322 Message::Wrapped { content, .. } => dialect_of(content),
323 _ => None,
324 }
325}
326
327pub fn read_act_str(input: &str) -> Result<String, String> {
330 read_act_with(input, json_of_sexpr)
331}
332
333pub fn read_act_exact_str(input: &str) -> Result<String, String> {
335 read_act_with(input, exact_field)
336}
337
338fn exact_field(value: &SExpr) -> Json {
339 match value {
340 SExpr::List(values) => Json::Array(values.iter().map(exact_field).collect()),
341 SExpr::Atom(Atom::Keyword(s)) => json!({"keyword": s}),
342 SExpr::Atom(Atom::Symbol(s)) => json!({"symbol": s}),
343 SExpr::Atom(Atom::Float(n)) => json!({"float": n.get()}),
344 SExpr::Atom(Atom::Num(n)) if n.unsigned_abs() > (1_u64 << 53) - 1 => {
345 json!({"integer": n.to_string()})
346 }
347 _ => json_of_sexpr(value),
348 }
349}
350
351fn read_act_with(input: &str, field_value: fn(&SExpr) -> Json) -> Result<String, String> {
352 let form = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
353 let message =
354 crate::parse_message(&form).map_err(|e| alloc::format!("message parse error: {e}"))?;
355 let dialect = dialect_of(&message).map(|s| s.to_string());
356 let act = Act::from_message(message, "")?;
357 let simple = act.simple();
358 let from = match simple {
359 Message::Simple { params, .. } => {
360 let mut found = None;
361 let mut i = 0;
362 while i + 1 < params.len() {
363 if matches!(¶ms[i], SExpr::Atom(Atom::Keyword(k)) if k == "from") {
364 found = symbol(¶ms[i + 1])
365 .map(|s| s.to_string())
366 .or_else(|| match ¶ms[i + 1] {
367 SExpr::Atom(Atom::Str(s)) => Some(s.clone()),
368 _ => None,
369 });
370 }
371 i += 2;
372 }
373 found
374 }
375 _ => None,
376 };
377 let caused_by = match simple.caused_by() {
378 None | Some(CausedBy::Begin) => Json::String("begin".into()),
379 Some(CausedBy::Single(h)) => Json::String(h.clone()),
380 Some(CausedBy::Multiple(hs)) => Json::Array(hs.iter().cloned().map(Json::String).collect()),
381 };
382 let mut fields = Map::new();
383 for (k, v) in &act.fields {
384 fields.insert(k.clone(), field_value(v));
385 }
386 Ok(json!({
387 "dialect": dialect,
388 "address": act.address,
389 "verb": act.verb,
390 "recipients": act.recipients.iter().cloned().collect::<Vec<_>>(),
391 "fields": fields,
392 "thread": simple.thread(),
393 "from": from,
394 "causedBy": caused_by,
395 })
396 .to_string())
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 const D: &str = "(define d (cbcl) @a (extend open (to title) (tell to :title title)) (extend vote (to choice) (tell to :choice choice)) (shape open (require :title string)) (shape vote (require :choice string) (require :clock hlc)) (protocol (then begin open) (then open vote)) (state (title (initial open :title)) (ballots (lww-per-signer vote :choice :clock))))";
404
405 #[test]
406 fn define_text_unwraps_meta_and_teach() {
407 let bare = define_text_str(D).unwrap();
408 assert!(bare.starts_with("(define d (cbcl) @a"));
409 assert_eq!(
410 define_text_str(&alloc::format!("; c\n(meta {D})")).unwrap(),
411 bare
412 );
413 assert_eq!(
414 define_text_str(&alloc::format!("(meta (teach {D}))")).unwrap(),
415 bare
416 );
417 assert!(define_text_str("(tell @a \"x\")").is_err());
418 }
419
420 #[test]
421 fn describe_reads_the_installed_structures() {
422 let v: Json = serde_json::from_str(&describe_dialect_str(D).unwrap()).unwrap();
423 assert_eq!(v["opener"], "open");
424 assert_eq!(v["verbs"]["vote"]["fields"]["choice"], "string");
425 assert_eq!(v["verbs"]["vote"]["after"], json!(["open"]));
426 assert_eq!(
427 v["state"]["ballots"],
428 json!(["lwwPerSigner", "vote", "choice", "clock"])
429 );
430 assert_eq!(v["roles"], json!({}));
431 }
432
433 #[test]
434 fn read_act_gives_routing_and_fields() {
435 let v: Json = serde_json::from_str(&read_act_str("(lang d (vote (@a @b) :choice \"x\" :n 3 :ok #t :caused-by begin :thread \"t\" :from @b))").unwrap()).unwrap();
436 assert_eq!(v["dialect"], "d");
437 assert_eq!(v["verb"], "vote");
438 assert_eq!(v["recipients"], json!(["@a", "@b"]));
439 assert_eq!(v["fields"], json!({"choice": "x", "n": 3, "ok": true}));
440 assert_eq!(v["thread"], "t");
441 assert_eq!(v["from"], "@b");
442 assert_eq!(v["causedBy"], "begin");
443 assert!(v["address"].as_str().unwrap().starts_with("f1220"));
444 }
445}