Skip to main content

cbcl_parser/
read.rs

1//! `read`: the parser's tree for a host that must look inside a frame
2//! without recognising it again (SPEC-010 REQ-002: one parser). A client
3//! dispatches on a performative, reads `:thread`, or lifts a `(define …)`
4//! out of a teach frame; each of those is a read, not a judgement, and
5//! every host makes it through this export rather than a reader of its own,
6//! so no two readers of one frame can disagree (SPEC-013 REQ-018).
7//!
8//! The tree is JSON in the shape the web client's reader always produced:
9//! a list is an array; a quoted string is `{"str": …}`; a symbol, keyword
10//! (with its colon), number, or boolean is its source text.
11
12use alloc::string::String;
13use cbcl_core::sexpr::{Atom, SExpr};
14use cbcl_core::state::Value;
15
16fn json(expr: &SExpr, out: &mut String) {
17    match expr {
18        SExpr::List(items) => {
19            out.push('[');
20            for (i, item) in items.iter().enumerate() {
21                if i > 0 {
22                    out.push(',');
23                }
24                json(item, out);
25            }
26            out.push(']');
27        }
28        SExpr::Atom(Atom::Str(s)) => {
29            out.push_str("{\"str\":");
30            out.push_str(&Value::Str(s.clone()).render());
31            out.push('}');
32        }
33        SExpr::Atom(Atom::Symbol(s)) => out.push_str(&Value::Str(s.clone()).render()),
34        SExpr::Atom(Atom::Keyword(k)) => {
35            let mut text = String::from(":");
36            text.push_str(k);
37            out.push_str(&Value::Str(text).render());
38        }
39        SExpr::Atom(Atom::Float(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
40        SExpr::Atom(Atom::Decimal(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
41        SExpr::Atom(Atom::Num(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
42        SExpr::Atom(Atom::Bool(b)) => out.push_str(if *b { "\"#t\"" } else { "\"#f\"" }),
43    }
44}
45
46/// Parse one S-expression (comments included) and return its tree as JSON.
47pub fn read_str(input: &str) -> Result<String, String> {
48    let expr = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
49    let mut out = String::new();
50    json(&expr, &mut out);
51    Ok(out)
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn tree_shape_matches_the_client_reader() {
60        let text = "; a comment\n(lang d (check (@a @b) :item \"a)b\\\"\" :done #t :n -3 :caused-by begin))";
61        assert_eq!(
62            read_str(text).unwrap(),
63            "[\"lang\",\"d\",[\"check\",[\"@a\",\"@b\"],\":item\",{\"str\":\"a)b\\\"\"},\":done\",\"#t\",\":n\",\"-3\",\":caused-by\",\"begin\"]]"
64        );
65        assert!(read_str("(tell").unwrap_err().starts_with("parse error"));
66    }
67}