Skip to main content

dive_value/
json.rs

1//! TLC's JSON form of values, as written by `-dumpTrace json` and `JsonSerialize`.
2//!
3//! Port of `tlc2.module.Json.getNode` (tlaplus `94d0c50`) with Gson's compact
4//! serialization (`JsonElement.toString`, no HTML escaping):
5//! - records are objects, in field order;
6//! - tuples and sequences (functions with domain `1..n`) are arrays;
7//! - other functions are objects keyed by the domain element's TLC string form
8//!   (a string domain element without quotes);
9//! - finite sets are arrays in normalized order (intervals and other lazy sets are
10//!   enumerated);
11//! - strings and model values are JSON strings, integers numbers, booleans booleans.
12
13use 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
20/// The JSON text TLC writes for a value.
21///
22/// ```
23/// use dive_value::{Ctx, Interner, Value, json::to_tlc_json};
24/// let ctx = Ctx::tlc();
25/// let names = Interner::new();
26/// let r = Value::record(vec![(names.intern("x"), Value::interval(1.into(), 3.into(), ctx))], ctx)?;
27/// assert_eq!(to_tlc_json(&r, ctx)?, r#"{"x":[1,2,3]}"#);
28/// # Ok::<(), dive_value::ValueError>(())
29/// ```
30///
31/// # Errors
32/// [`ErrorKind::Json`] for infinite sets (TLC: `Cannot convert value: unsupported
33/// value type tlc2.value.impl.UserValue`), and enumeration errors.
34pub 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/// Gson's string escaping (`JsonWriter.string` without HTML-safe mode).
41#[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}