1use 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
46pub 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}