Skip to main content

dive_trace/
value_json.rs

1//! dive's JSON values (trace format version 1).
2//!
3//! TLC's `-dumpTrace json` form ([`dive_value::json`]) cannot be read back
4//! exactly: a set and a sequence are both arrays, a string and a model value
5//! are both strings. This form distinguishes them. It is a value
6//! transport, not a stored-representation transport: it does not record how
7//! TLC happened to store a value (a tuple or a function with domain `1..n`,
8//! for instance). Scalars remain plain JSON:
9//!
10//! | Value | JSON |
11//! |---|---|
12//! | `TRUE`, `FALSE` | `true`, `false` |
13//! | an integer in `i64` range | a number: `3`, `-7` |
14//! | any other integer | `{"int": "123456789012345678901234567890"}` |
15//! | a string `"a"` | `"a"` |
16//! | a model value `m1` | `{"model": "m1"}` |
17//! | a set `{1, 2}` | `{"set": [1, 2]}` |
18//! | a tuple or sequence `<<1, "a">>` | `{"seq": [1, "a"]}` |
19//! | a record `[a \|-> 1]` | `{"record": {"a": 1}}` |
20//! | any other function `(1 :> "a" @@ 3 :> "b")` | `{"fcn": [[1, "a"], [3, "b"]]}` |
21//!
22//! A function whose domain is `1..n` is a `seq`; one whose domain is a
23//! non-empty set of strings is a `record`. Reading normalizes, so a `fcn`
24//! with domain `{1, 2}` reads as the sequence it equals. Sets are written
25//! in the run's normalized order. Reading reconstructs mathematical sets, so
26//! mixed structured values round-trip independently of input order. Literal/function and Raw/normalized
27//! representation flags are not preserved. Infinite sets (`Nat`) have no form.
28
29use dive_value::{Ctx, Int, Interner, Value};
30use serde_json::{Map, Value as J, json};
31
32/// Writes `v` in dive's JSON form.
33///
34/// # Errors
35/// For an infinite set, or a lazy set that cannot be enumerated.
36pub fn to_json(v: &Value, ctx: Ctx) -> Result<J, String> {
37    Ok(match v {
38        Value::Bool(b) => J::Bool(*b),
39        Value::Int(i) => J::from(*i),
40        Value::BigInt(b) => json!({ "int": b.to_string() }),
41        Value::Str(a) => J::String(a.as_str().to_owned()),
42        Value::Model(a) => json!({ "model": a.as_str() }),
43        Value::Set(s) => {
44            if s.is_infinite() {
45                return Err("an infinite set has no JSON form".to_owned());
46            }
47            let elems = s.elements(ctx).map_err(|e| e.message().to_owned())?;
48            let items = elems
49                .iter()
50                .map(|e| to_json(e, ctx))
51                .collect::<Result<Vec<_>, _>>()?;
52            json!({ "set": items })
53        }
54        Value::Fcn(f) => {
55            if let Some(t) = f.as_tuple() {
56                let items = t
57                    .iter()
58                    .map(|e| to_json(e, ctx))
59                    .collect::<Result<Vec<_>, _>>()?;
60                json!({ "seq": items })
61            } else if let Some(r) = f.as_record() {
62                let mut m = Map::new();
63                for (k, x) in r {
64                    m.insert(k.as_str().to_owned(), to_json(x, ctx)?);
65                }
66                json!({ "record": m })
67            } else {
68                let items = f
69                    .iter()
70                    .map(|(d, x)| Ok(J::Array(vec![to_json(&d, ctx)?, to_json(x, ctx)?])))
71                    .collect::<Result<Vec<_>, String>>()?;
72                json!({ "fcn": items })
73            }
74        }
75    })
76}
77
78/// Reads a value in dive's JSON form, interning names in `names`.
79///
80/// # Errors
81/// A message naming what is malformed.
82pub fn from_json(j: &J, names: &Interner, ctx: Ctx) -> Result<Value, String> {
83    match j {
84        J::Bool(b) => Ok(Value::Bool(*b)),
85        J::Number(n) => n.as_i64().map(Value::Int).ok_or_else(|| {
86            format!("`{n}` is not an integer in i64 range (write {{\"int\": \"...\"}})")
87        }),
88        J::String(s) => Ok(Value::string(names, s)),
89        J::Null => Err("null is not a value".to_owned()),
90        J::Array(_) => {
91            Err("a bare array is ambiguous: write {\"set\": [...]} or {\"seq\": [...]}".to_owned())
92        }
93        J::Object(m) => {
94            let mut it = m.iter();
95            let (Some((tag, body)), None) = (it.next(), it.next()) else {
96                return Err(format!(
97                    "a value object has exactly one key (set, seq, record, fcn, model or int), got {}",
98                    m.len()
99                ));
100            };
101            match (tag.as_str(), body) {
102                ("model", J::String(s)) => Ok(Value::model(names, s)),
103                ("int", J::String(s)) => parse_int(s, ctx),
104                ("set", J::Array(a)) => {
105                    let elems = a
106                        .iter()
107                        .map(|e| from_json(e, names, ctx))
108                        .collect::<Result<Vec<_>, _>>()?;
109                    Value::set_canonical(elems, ctx).map_err(|error| error.message().to_owned())
110                }
111                ("seq", J::Array(a)) => Ok(Value::tuple(
112                    a.iter()
113                        .map(|e| from_json(e, names, ctx))
114                        .collect::<Result<Vec<_>, _>>()?,
115                )),
116                ("record", J::Object(fields)) => {
117                    let fields = fields
118                        .iter()
119                        .map(|(k, x)| Ok((names.intern(k), from_json(x, names, ctx)?)))
120                        .collect::<Result<Vec<_>, String>>()?;
121                    Value::record(fields, ctx).map_err(|e| e.message().to_owned())
122                }
123                ("fcn", J::Array(pairs)) => {
124                    let pairs = pairs
125                        .iter()
126                        .map(|p| match p.as_array().map(Vec::as_slice) {
127                            Some([d, x]) => {
128                                Ok((from_json(d, names, ctx)?, from_json(x, names, ctx)?))
129                            }
130                            _ => Err("a fcn entry is a [argument, value] pair".to_owned()),
131                        })
132                        .collect::<Result<Vec<_>, String>>()?;
133                    Value::fcn(pairs, ctx).map_err(|e| e.message().to_owned())
134                }
135                (tag, _) => Err(format!(
136                    "`{tag}` is not a value tag, or its body has the wrong type"
137                )),
138            }
139        }
140    }
141}
142
143/// An integer written as a decimal string, in the run's integer mode.
144pub(crate) fn parse_int(s: &str, ctx: Ctx) -> Result<Value, String> {
145    let (neg, digits) = match s.strip_prefix('-') {
146        Some(d) => (true, d),
147        None => (false, s),
148    };
149    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
150        return Err(format!("`{s}` is not a decimal integer"));
151    }
152    let i = Int::from_literal(digits, ctx.int_mode).map_err(|e| e.message().to_owned())?;
153    let i = if neg {
154        i.neg(ctx.int_mode).map_err(|e| e.message().to_owned())?
155    } else {
156        i
157    };
158    Ok(Value::int(i))
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn round_trips_every_kind() -> Result<(), String> {
167        let ctx = Ctx::dive();
168        let names = Interner::new();
169        let text = r#"{"record":{"a":{"set":[1,2]},"b":{"seq":["x",{"model":"m1"}]},
170            "c":{"fcn":[[{"model":"m1"},true],[{"model":"m2"},false]]},
171            "d":{"int":"123456789012345678901234567890"},"e":{"seq":[]}}}"#;
172        let j: J = serde_json::from_str(text).map_err(|e| e.to_string())?;
173        let v = from_json(&j, &names, ctx)?;
174        let back = to_json(&v, ctx)?;
175        assert_eq!(back, j);
176        assert_eq!(from_json(&back, &names, ctx)?, v);
177        Ok(())
178    }
179
180    #[test]
181    fn rejects_ambiguous_and_malformed_input() {
182        let ctx = Ctx::dive();
183        let names = Interner::new();
184        for bad in [
185            "[1, 2]",
186            "null",
187            "1.5",
188            r#"{"set": [1], "seq": []}"#,
189            r#"{"bag": []}"#,
190            r#"{"int": "12x"}"#,
191        ] {
192            let j: J = serde_json::from_str(bad).unwrap_or(J::Null);
193            assert!(from_json(&j, &names, ctx).is_err(), "{bad}");
194        }
195    }
196
197    #[test]
198    fn a_fcn_over_one_to_n_reads_as_the_sequence() -> Result<(), String> {
199        let ctx = Ctx::tlc();
200        let names = Interner::new();
201        let j: J =
202            serde_json::from_str(r#"{"fcn": [[2, "b"], [1, "a"]]}"#).map_err(|e| e.to_string())?;
203        let v = from_json(&j, &names, ctx)?;
204        assert_eq!(
205            v,
206            Value::tuple(vec![Value::string(&names, "a"), Value::string(&names, "b")])
207        );
208        Ok(())
209    }
210}