cbcl-parser 0.3.0

CBCL pure parser and pipeline
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Reading dialects and acts for a host, so no host re-encodes CBCL's grammar
//! to look inside one (SPEC-013 REQ-018, SPEC-010 REQ-002). Three reads, each
//! the parser's and the installed structures' view, returned as JSON:
//!
//! ```text
//! define_text(<define | (meta (define …)) | (meta (teach (define …)))>) → canonical "(define …)"
//! describe_dialect(<dialect text>)  → {name, author, opener, verbs, roles, state, domains, bounds, text}
//! read_act(<message text>)          → {dialect, address, verb, recipients, fields, thread, from, causedBy}
//! ```

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use cbcl_core::dialect::Dialect;
use cbcl_core::message::{CausedBy, Message};
use cbcl_core::protocol::NodeRef;
use cbcl_core::role::RoleCardinality;
use cbcl_core::serializer::serialize;
use cbcl_core::sexpr::{Atom, SExpr};
use cbcl_core::shape::ShapeRule;
use cbcl_core::state::{Act, Entry, Rule, RESERVED_REPLACES};
use serde_json::{json, Map, Value as Json};

fn symbol(s: &SExpr) -> Option<&str> {
    match s {
        SExpr::Atom(Atom::Symbol(x)) => Some(x),
        _ => None,
    }
}

/// The `(define …)` form of a dialect text, a `(meta (define …))`, or a
/// `(meta (teach (define …)))` teach frame, in canonical serialisation.
pub fn define_form(input: &str) -> Result<SExpr, String> {
    let form = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
    let mut current = &form;
    loop {
        let SExpr::List(items) = current else {
            return Err(String::from(
                "expected a (define …), (meta (define …)) or (meta (teach (define …))) form",
            ));
        };
        match items.first().and_then(symbol) {
            Some("define") => return Ok(current.clone()),
            Some("meta") | Some("teach") if items.len() >= 2 => current = &items[1],
            _ => {
                return Err(String::from(
                    "expected a (define …), (meta (define …)) or (meta (teach (define …))) form",
                ))
            }
        }
    }
}

/// `define_text`: the canonical text of the `(define …)` a frame carries.
pub fn define_text_str(input: &str) -> Result<String, String> {
    Ok(serialize(&define_form(input)?))
}

fn json_of_sexpr(s: &SExpr) -> Json {
    match s {
        SExpr::List(items) => Json::Array(items.iter().map(json_of_sexpr).collect()),
        SExpr::Atom(Atom::Str(x)) | SExpr::Atom(Atom::Symbol(x)) => Json::String(x.clone()),
        SExpr::Atom(Atom::Keyword(k)) => Json::String(alloc::format!(":{k}")),
        SExpr::Atom(Atom::Float(n)) => json!(n.get()),
        SExpr::Atom(Atom::Decimal(n)) => json!({"decimal": n.as_str()}),
        SExpr::Atom(Atom::Num(n)) => json!(n),
        SExpr::Atom(Atom::Bool(b)) => Json::Bool(*b),
    }
}

fn shape_description(rule: &ShapeRule) -> Json {
    let (keyword, constraint, children, required, default) = match rule {
        ShapeRule::Require {
            keyword,
            type_constraint,
            children,
        } => (keyword, type_constraint, children, true, None),
        ShapeRule::Optional {
            keyword,
            type_constraint,
            children,
            default,
        } => (
            keyword,
            type_constraint,
            children,
            false,
            default.as_ref().map(serialize),
        ),
        ShapeRule::MaxDepth(limit) => return json!({"maxDepth":limit}),
    };
    json!({
        "keyword":keyword, "required":required, "default":default,
        "source":constraint.as_ref().map(|t| serialize(&t.source())).unwrap_or_default(),
        "representations":constraint.as_ref().map(cbcl_core::contracts::representation_names).unwrap_or_default(),
        "children":children.iter().map(shape_description).collect::<Vec<_>>(),
    })
}

/// A rule of the state clause as JSON's spelling: `[op, arg…]`, keys without their colon.
fn rule_json(rule: &Rule) -> Json {
    if let Rule::Lift(lift) = rule {
        let mut args = alloc::vec![SExpr::Atom(Atom::Symbol("lift".into()))];
        args.extend(lift.arguments());
        return json_of_sexpr(&SExpr::List(args));
    }
    if let Rule::BoundedCounter(c) = rule {
        return json!([
            "boundedCounter",
            c.canonical_options()
                .iter()
                .map(json_of_sexpr)
                .collect::<Vec<_>>()
        ]);
    }
    let (op, args): (&str, Vec<&str>) = match rule {
        Rule::BoundedCounter(_) | Rule::Lift(_) => unreachable!("handled above"),
        Rule::LwwRegister { verb, key, clock } => ("lwwRegister", alloc::vec![verb, key, clock]),
        Rule::LwwPerSigner { verb, key, clock } => ("lwwPerSigner", alloc::vec![verb, key, clock]),
        Rule::LwwMap {
            verb,
            key,
            value,
            clock,
            delete,
        } => {
            let mut args = alloc::vec![verb.as_str(), key, value, clock];
            if let Some(d) = delete {
                args.push(d);
            }
            ("lwwMap", args)
        }
        Rule::Context { path, .. } => ("context", path.iter().map(String::as_str).collect()),
        Rule::Initial { verb, key } => ("initial", alloc::vec![verb, key]),

        Rule::Exists { verb } => ("exists", alloc::vec![verb]),
        Rule::Count { verb } => ("count", alloc::vec![verb]),
        Rule::Progress { verb } => ("progress", alloc::vec![verb]),
        Rule::Events { verb, key } => ("events", alloc::vec![verb, key]),
        Rule::SetUnion { verb, key } => ("setUnion", alloc::vec![verb, key]),
        Rule::Values { verb, key } => ("values", alloc::vec![verb, key]),
        Rule::ValuesPerKey {
            verb,
            key,
            value,
            delete,
        } => {
            let mut v = alloc::vec![verb.as_str(), key, value];
            if let Some(d) = delete {
                v.push(d);
            }
            ("valuesPerKey", v)
        }

        Rule::ObservedSet { add, remove, key } => ("observedSet", alloc::vec![add, remove, key]),
        Rule::Counter { inc, dec, key } => ("counter", alloc::vec![inc, dec, key]),
        Rule::Histogram { field } => ("histogram", alloc::vec![field]),
        Rule::Sum { field } => ("sum", alloc::vec![field]),
    };
    let mut out = alloc::vec![Json::String(op.to_string())];
    out.extend(args.into_iter().map(|a| Json::String(a.to_string())));
    Json::Array(out)
}

/// What a host or a view needs to know about a dialect, from the installed structures.
pub fn describe(d: &Dialect, text: &str) -> Json {
    let mut verbs = Map::new();
    for p in &d.performatives {
        let params: Vec<Json> = p.params.iter().map(json_of_sexpr).collect();
        let mut shape_rules = Vec::new();
        let mut fields = Map::new();
        let mut contracts = Map::new();
        for shape in d.shapes.iter().filter(|s| s.performative == p.name) {
            for rule in &shape.rules {
                let description = shape_description(rule);
                if let ShapeRule::Require {
                    keyword,
                    type_constraint,
                    ..
                }
                | ShapeRule::Optional {
                    keyword,
                    type_constraint,
                    ..
                } = rule
                {
                    if keyword == RESERVED_REPLACES {
                        continue;
                    }
                    let ty = type_constraint
                        .as_ref()
                        .map(|t| t.to_string())
                        .unwrap_or_default();
                    fields.insert(keyword.clone(), Json::String(ty));
                    contracts.insert(keyword.clone(), description.clone());
                }
                shape_rules.push(description);
            }
        }
        let after: Vec<Json> = d
            .causal_protocol
            .as_ref()
            .and_then(|proto| proto.steps.get(&p.name))
            .map(|step| {
                step.predecessors
                    .iter()
                    .flat_map(|n| match n {
                        NodeRef::Single(s) => alloc::vec![s.clone()],
                        NodeRef::Any(set) | NodeRef::All(set) => set.iter().cloned().collect(),
                    })
                    .map(Json::String)
                    .collect()
            })
            .unwrap_or_default();
        let mut entry = json!({ "params": params, "fields": fields, "contracts":contracts, "shapeRules":shape_rules, "after": after });
        if let Some(ann) = &p.role {
            entry["from"] = Json::String(ann.from.clone());
            entry["to"] = Json::Array(ann.to.iter().cloned().map(Json::String).collect());
        }
        verbs.insert(p.name.clone(), entry);
    }
    let opener = d
        .causal_protocol
        .as_ref()
        .and_then(cbcl_core::state::opener_verb)
        .map(|v| Json::String(v.to_string()))
        .unwrap_or(Json::Null);
    let mut roles = Map::new();
    for r in &d.roles {
        let kind = match r.cardinality {
            RoleCardinality::Singleton => "singleton",
            RoleCardinality::Indexed => "indexed",
        };
        roles.insert(r.name.clone(), Json::String(kind.to_string()));
    }
    let mut state = Map::new();
    let mut domains = Vec::new();
    let mut thresholds = Vec::new();
    let mut freezes = Vec::new();
    let mut lattices = Vec::new();
    if let Some(clause) = &d.state {
        for entry in &clause.entries {
            match entry {
                Entry::Lattice(definition) => lattices.push(json_of_sexpr(&definition.to_sexpr())),
                Entry::Freeze {
                    field,
                    verb,
                    policy,
                } => {
                    freezes.push(json!({"field":field,"verb":verb,"policy":policy.as_str()}));
                }
                Entry::Field { name, rule } => {
                    state.insert(name.clone(), rule_json(rule));
                }
                Entry::Domain { verb, key, field } => {
                    domains.push(json!({ "verb": verb, "key": key, "field": field }));
                }
                Entry::Condition { name, condition } => {
                    let condition: Json =
                        serde_json::from_str(&condition.schema().render()).unwrap();
                    thresholds.push(json!({"name":name,"condition":condition}));
                }
                Entry::Threshold {
                    name,
                    field,
                    elements,
                } => {
                    let elements: Vec<Json> = elements
                        .iter()
                        .map(|e| serde_json::from_str(&e.render().render()).unwrap_or(Json::Null))
                        .collect();
                    thresholds.push(json!({ "name": name, "field": field, "elements": elements }));
                }
            }
        }
    }
    let bounds = match &d.state_bounds {
        Some(b) => {
            json!({ "max-string": b.max_string, "max-list": b.max_list, "max-number": b.max_number, "max-fields": b.max_fields })
        }
        None => json!({}),
    };
    let mut types = Map::new();
    match cbcl_core::contracts::type_schema(d) {
        Ok(entries) => {
            for (name, expression, representations) in entries {
                types.insert(
                    name,
                    json!({"source":serialize(&expression), "representations":representations}),
                );
            }
        }
        Err(error) => return json!({"error":error}),
    }
    json!({
        "typeProfile": cbcl_core::contracts::PROFILE,
        "types": types,
        "name": d.name,
        "author": d.author,
        "opener": opener,
        "verbs": verbs,
        "roles": roles,
        "state": state,
        "domains": domains,
        "thresholds": thresholds,
        "freezes": freezes,
        "lattices": lattices,
        "bounds": bounds,
        "text": text,
    })
}

/// `describe_dialect`: a dialect text (or teach frame) → its description as JSON.
pub fn describe_dialect_str(input: &str) -> Result<String, String> {
    let form = define_form(input)?;
    let d = crate::parse_dialect(&form).map_err(|e| alloc::format!("dialect parse error: {e}"))?;
    Ok(describe(&d, &serialize(&form)).to_string())
}

fn dialect_of(m: &Message) -> Option<&str> {
    match m {
        Message::Dialect { dialect_name, .. } => Some(dialect_name),
        Message::Wrapped { content, .. } => dialect_of(content),
        _ => None,
    }
}

/// `read_act`: an act's wire text → its dialect, address, verb, recipients,
/// data fields (routing excluded), and routing, as JSON.
pub fn read_act_str(input: &str) -> Result<String, String> {
    read_act_with(input, json_of_sexpr)
}

/// Read fields with explicit atom kinds where ordinary JSON would lose information.
pub fn read_act_exact_str(input: &str) -> Result<String, String> {
    read_act_with(input, exact_field)
}

fn exact_field(value: &SExpr) -> Json {
    match value {
        SExpr::List(values) => Json::Array(values.iter().map(exact_field).collect()),
        SExpr::Atom(Atom::Keyword(s)) => json!({"keyword": s}),
        SExpr::Atom(Atom::Symbol(s)) => json!({"symbol": s}),
        SExpr::Atom(Atom::Float(n)) => json!({"float": n.get()}),
        SExpr::Atom(Atom::Num(n)) if n.unsigned_abs() > (1_u64 << 53) - 1 => {
            json!({"integer": n.to_string()})
        }
        _ => json_of_sexpr(value),
    }
}

fn read_act_with(input: &str, field_value: fn(&SExpr) -> Json) -> Result<String, String> {
    let form = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
    let message =
        crate::parse_message(&form).map_err(|e| alloc::format!("message parse error: {e}"))?;
    let dialect = dialect_of(&message).map(|s| s.to_string());
    let act = Act::from_message(message, "")?;
    let simple = act.simple();
    let from = match simple {
        Message::Simple { params, .. } => {
            let mut found = None;
            let mut i = 0;
            while i + 1 < params.len() {
                if matches!(&params[i], SExpr::Atom(Atom::Keyword(k)) if k == "from") {
                    found = symbol(&params[i + 1])
                        .map(|s| s.to_string())
                        .or_else(|| match &params[i + 1] {
                            SExpr::Atom(Atom::Str(s)) => Some(s.clone()),
                            _ => None,
                        });
                }
                i += 2;
            }
            found
        }
        _ => None,
    };
    let caused_by = match simple.caused_by() {
        None | Some(CausedBy::Begin) => Json::String("begin".into()),
        Some(CausedBy::Single(h)) => Json::String(h.clone()),
        Some(CausedBy::Multiple(hs)) => Json::Array(hs.iter().cloned().map(Json::String).collect()),
    };
    let mut fields = Map::new();
    for (k, v) in &act.fields {
        fields.insert(k.clone(), field_value(v));
    }
    Ok(json!({
        "dialect": dialect,
        "address": act.address,
        "verb": act.verb,
        "recipients": act.recipients.iter().cloned().collect::<Vec<_>>(),
        "fields": fields,
        "thread": simple.thread(),
        "from": from,
        "causedBy": caused_by,
    })
    .to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    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))))";

    #[test]
    fn define_text_unwraps_meta_and_teach() {
        let bare = define_text_str(D).unwrap();
        assert!(bare.starts_with("(define d (cbcl) @a"));
        assert_eq!(
            define_text_str(&alloc::format!("; c\n(meta {D})")).unwrap(),
            bare
        );
        assert_eq!(
            define_text_str(&alloc::format!("(meta (teach {D}))")).unwrap(),
            bare
        );
        assert!(define_text_str("(tell @a \"x\")").is_err());
    }

    #[test]
    fn describe_reads_the_installed_structures() {
        let v: Json = serde_json::from_str(&describe_dialect_str(D).unwrap()).unwrap();
        assert_eq!(v["opener"], "open");
        assert_eq!(v["verbs"]["vote"]["fields"]["choice"], "string");
        assert_eq!(v["verbs"]["vote"]["after"], json!(["open"]));
        assert_eq!(
            v["state"]["ballots"],
            json!(["lwwPerSigner", "vote", "choice", "clock"])
        );
        assert_eq!(v["roles"], json!({}));
    }

    #[test]
    fn read_act_gives_routing_and_fields() {
        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();
        assert_eq!(v["dialect"], "d");
        assert_eq!(v["verb"], "vote");
        assert_eq!(v["recipients"], json!(["@a", "@b"]));
        assert_eq!(v["fields"], json!({"choice": "x", "n": 3, "ok": true}));
        assert_eq!(v["thread"], "t");
        assert_eq!(v["from"], "@b");
        assert_eq!(v["causedBy"], "begin");
        assert!(v["address"].as_str().unwrap().starts_with("f1220"));
    }
}