use std::fmt::Write as _;
use crate::ctx::Ctx;
use crate::error::{ErrorKind, Result, ValueError};
use crate::print::to_tlc_string;
use crate::value::{FcnRepr, SetRepr, Value};
pub fn to_tlc_json(v: &Value, ctx: Ctx) -> Result<String> {
let mut out = String::new();
write_json(v, ctx, &mut out)?;
Ok(out)
}
#[must_use]
pub fn json_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\t' => out.push_str("\\t"),
'\u{0008}' => out.push_str("\\b"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\u{000C}' => out.push_str("\\f"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
c if u32::from(c) < 0x20 => {
let _ = write!(out, "\\u{:04x}", u32::from(c));
}
c => out.push(c),
}
}
out.push('"');
out
}
fn write_json(v: &Value, ctx: Ctx, out: &mut String) -> Result<()> {
let _guard = crate::depth::Guard::enter()?;
match v {
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Value::Int(i) => {
let _ = write!(out, "{i}");
}
Value::BigInt(b) => {
let _ = write!(out, "{b}");
}
Value::Str(a) | Value::Model(a) => out.push_str(&json_string(a.as_str())),
Value::Fcn(f) => {
if let FcnRepr::Tuple(e) = &f.0.repr {
out.push('[');
for (i, x) in e.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_json(x, ctx, out)?;
}
out.push(']');
} else {
out.push('{');
let mut pairs: Vec<(Value, Value)> =
f.iter().map(|(d, x)| (d, x.clone())).collect();
if f.order() != ctx.order {
pairs.sort_by(|a, b| a.0.cmp_with(&b.0, ctx.order));
}
for (i, (d, x)) in pairs.iter().enumerate() {
if i > 0 {
out.push(',');
}
let key = match &d {
Value::Str(a) => a.as_str().to_owned(),
_ => to_tlc_string(d, ctx)?,
};
out.push_str(&json_string(&key));
out.push(':');
write_json(x, ctx, out)?;
}
out.push('}');
}
}
Value::Set(s) => {
if matches!(
s.repr(),
SetRepr::Nat | SetRepr::Int | SetRepr::Strings | SetRepr::Seq(_)
) {
return Err(ValueError::new(
ErrorKind::Json,
"Cannot convert value: unsupported value type tlc2.value.impl.UserValue",
));
}
out.push('[');
for (i, x) in crate::stream::elems_in(s, ctx, true)?.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_json(x, ctx, out)?;
}
out.push(']');
}
}
Ok(())
}