use alloc::string::String;
use cbcl_core::sexpr::{Atom, SExpr};
use cbcl_core::state::Value;
fn json(expr: &SExpr, out: &mut String) {
match expr {
SExpr::List(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
json(item, out);
}
out.push(']');
}
SExpr::Atom(Atom::Str(s)) => {
out.push_str("{\"str\":");
out.push_str(&Value::Str(s.clone()).render());
out.push('}');
}
SExpr::Atom(Atom::Symbol(s)) => out.push_str(&Value::Str(s.clone()).render()),
SExpr::Atom(Atom::Keyword(k)) => {
let mut text = String::from(":");
text.push_str(k);
out.push_str(&Value::Str(text).render());
}
SExpr::Atom(Atom::Float(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
SExpr::Atom(Atom::Decimal(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
SExpr::Atom(Atom::Num(n)) => out.push_str(&Value::Str(alloc::format!("{n}")).render()),
SExpr::Atom(Atom::Bool(b)) => out.push_str(if *b { "\"#t\"" } else { "\"#f\"" }),
}
}
pub fn read_str(input: &str) -> Result<String, String> {
let expr = crate::parser::parse(input).map_err(|e| alloc::format!("parse error: {e}"))?;
let mut out = String::new();
json(&expr, &mut out);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tree_shape_matches_the_client_reader() {
let text = "; a comment\n(lang d (check (@a @b) :item \"a)b\\\"\" :done #t :n -3 :caused-by begin))";
assert_eq!(
read_str(text).unwrap(),
"[\"lang\",\"d\",[\"check\",[\"@a\",\"@b\"],\":item\",{\"str\":\"a)b\\\"\"},\":done\",\"#t\",\":n\",\"-3\",\":caused-by\",\"begin\"]]"
);
assert!(read_str("(tell").unwrap_err().starts_with("parse error"));
}
}