1use std::fmt::Write as _;
14
15use crate::ctx::Ctx;
16use crate::error::{ErrorKind, Result, ValueError};
17use crate::print::to_tlc_string;
18use crate::value::{FcnRepr, SetRepr, Value};
19
20pub fn to_tlc_json(v: &Value, ctx: Ctx) -> Result<String> {
35 let mut out = String::new();
36 write_json(v, ctx, &mut out)?;
37 Ok(out)
38}
39
40#[must_use]
42pub fn json_string(s: &str) -> String {
43 let mut out = String::with_capacity(s.len() + 2);
44 out.push('"');
45 for c in s.chars() {
46 match c {
47 '"' => out.push_str("\\\""),
48 '\\' => out.push_str("\\\\"),
49 '\t' => out.push_str("\\t"),
50 '\u{0008}' => out.push_str("\\b"),
51 '\n' => out.push_str("\\n"),
52 '\r' => out.push_str("\\r"),
53 '\u{000C}' => out.push_str("\\f"),
54 '\u{2028}' => out.push_str("\\u2028"),
55 '\u{2029}' => out.push_str("\\u2029"),
56 c if u32::from(c) < 0x20 => {
57 let _ = write!(out, "\\u{:04x}", u32::from(c));
58 }
59 c => out.push(c),
60 }
61 }
62 out.push('"');
63 out
64}
65
66fn write_json(v: &Value, ctx: Ctx, out: &mut String) -> Result<()> {
67 let _guard = crate::depth::Guard::enter()?;
68 match v {
69 Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
70 Value::Int(i) => {
71 let _ = write!(out, "{i}");
72 }
73 Value::BigInt(b) => {
74 let _ = write!(out, "{b}");
75 }
76 Value::Str(a) | Value::Model(a) => out.push_str(&json_string(a.as_str())),
77 Value::Fcn(f) => {
78 if let FcnRepr::Tuple(e) = &f.0.repr {
79 out.push('[');
80 for (i, x) in e.iter().enumerate() {
81 if i > 0 {
82 out.push(',');
83 }
84 write_json(x, ctx, out)?;
85 }
86 out.push(']');
87 } else {
88 out.push('{');
89 let mut pairs: Vec<(Value, Value)> =
90 f.iter().map(|(d, x)| (d, x.clone())).collect();
91 if f.order() != ctx.order {
92 pairs.sort_by(|a, b| a.0.cmp_with(&b.0, ctx.order));
93 }
94 for (i, (d, x)) in pairs.iter().enumerate() {
95 if i > 0 {
96 out.push(',');
97 }
98 let key = match &d {
99 Value::Str(a) => a.as_str().to_owned(),
100 _ => to_tlc_string(d, ctx)?,
101 };
102 out.push_str(&json_string(&key));
103 out.push(':');
104 write_json(x, ctx, out)?;
105 }
106 out.push('}');
107 }
108 }
109 Value::Set(s) => {
110 if matches!(
111 s.repr(),
112 SetRepr::Nat | SetRepr::Int | SetRepr::Strings | SetRepr::Seq(_)
113 ) {
114 return Err(ValueError::new(
115 ErrorKind::Json,
116 "Cannot convert value: unsupported value type tlc2.value.impl.UserValue",
117 ));
118 }
119 out.push('[');
120 for (i, x) in crate::stream::elems_in(s, ctx, true)?.iter().enumerate() {
121 if i > 0 {
122 out.push(',');
123 }
124 write_json(x, ctx, out)?;
125 }
126 out.push(']');
127 }
128 }
129 Ok(())
130}