Skip to main content

xur_std/json/
mod.rs

1//! `std::json`: JSON parsing and serialisation.
2
3mod de;
4mod ser;
5
6use std::sync::Arc;
7
8use xur_runtime::registry::RawSig;
9use xur_runtime::{Context, Record, Registry, RunResult, RuntimeError, Value, lock};
10use xur_span::Symbol;
11
12/// A newtype so `serde::Deserialize` and `serde::Serialize` can be
13/// implemented for xur values without orphan issues.
14pub(crate) struct JsonValue(pub Value);
15
16impl JsonValue {
17    /// JSON null, as xur's `None`.
18    fn null() -> Self {
19        // Constructed with a placeholder DefId; the real None ctor is set
20        // by the `parse` function which has access to Context.
21        Self(Value::Unit)
22    }
23}
24
25pub(crate) fn register(registry: &Registry) {
26    registry
27        .module("std::json")
28        .raw_function_sig(
29            "parse",
30            RawSig::new()
31                .param("text", "str")
32                .returns("Result<any, str>"),
33            parse,
34        )
35        .raw_function_sig(
36            "stringify",
37            RawSig::new()
38                .param("value", "any")
39                .returns("Result<str, str>"),
40            stringify,
41        );
42}
43
44/// Parses JSON text into a xur value, as `std::json::parse` does: objects
45/// become records, arrays lists, and `null` becomes `None`. For hosts and
46/// other modules (`std::http`) that read JSON.
47pub fn parse_str(cx: &dyn Context, text: &str) -> RunResult<Value> {
48    match serde_json::from_str::<JsonValue>(text) {
49        Ok(JsonValue(value)) => Ok(fixup_nulls(cx, &value)),
50        Err(e) => Err(RuntimeError::new(crate::error_text(e))),
51    }
52}
53
54/// A xur value as JSON text, as `std::json::stringify` does: structs and
55/// records become objects, maps objects with their keys as strings, lists
56/// and tuples arrays, `None` null. Functions, modules and other non-data
57/// values are an error. For hosts and other modules (`std::http`) that write
58/// JSON.
59pub fn stringify_value(cx: &mut dyn Context, value: &Value) -> RunResult<String> {
60    let prepared = prepare_for_json(cx, value)?;
61    serde_json::to_string(&JsonValue(prepared)).map_err(|e| RuntimeError::new(crate::error_text(e)))
62}
63
64/// [`stringify_value`] as a `serde_json::Value`, for hosts that pass JSON on
65/// rather than text.
66pub fn to_json(cx: &mut dyn Context, value: &Value) -> RunResult<serde_json::Value> {
67    let prepared = prepare_for_json(cx, value)?;
68    serde_json::to_value(JsonValue(prepared)).map_err(|e| RuntimeError::new(crate::error_text(e)))
69}
70
71/// `std::json::parse(text) -> Result<value, str>`
72fn parse(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
73    let [Value::Str(text)] = args else {
74        return Err(RuntimeError::new("`json::parse` takes a single string"));
75    };
76    let res = match serde_json::from_str::<JsonValue>(text) {
77        Ok(JsonValue(value)) => Ok(fixup_nulls(cx, &value)),
78        Err(e) => Err(crate::error_text(e)),
79    };
80    Ok(crate::result(cx, res))
81}
82
83/// `std::json::stringify(value) -> Result<str, str>`
84fn stringify(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
85    let [value] = args else {
86        return Err(RuntimeError::new("`json::stringify` takes a single value"));
87    };
88    let prepared = prepare_for_json(cx, value)?;
89    let res = serde_json::to_string(&JsonValue(prepared)).map_err(crate::error_text);
90    Ok(crate::result(cx, res.map(|s| Value::str(&s))))
91}
92
93/// Converts Adt values to Records with named fields so the serializer
94/// can emit JSON objects with keys instead of arrays.
95fn prepare_for_json(cx: &mut dyn Context, value: &Value) -> RunResult<Value> {
96    match value {
97        Value::Adt(adt) => {
98            if let Some(info) = cx.adt_info(adt.ctor) {
99                let mut fields = Vec::with_capacity(info.fields.len());
100                for (i, fi) in info.fields.iter().enumerate() {
101                    let name = fi.name.unwrap_or_else(|| Symbol::intern(&i.to_string()));
102                    let val = adt.fields.get(i).cloned().unwrap_or(Value::Unit);
103                    fields.push((name, prepare_for_json(cx, &val)?));
104                }
105                Ok(Value::Record(Arc::new(Record::new(fields))))
106            } else {
107                // No field info (e.g. None, Ok, Err) — keep as Adt.
108                Ok(value.clone())
109            }
110        }
111        Value::List(items) => {
112            let items = lock(items);
113            let prepared: RunResult<Vec<_>> =
114                items.iter().map(|v| prepare_for_json(cx, v)).collect();
115            Ok(Value::list(prepared?))
116        }
117        Value::Record(record) => {
118            let mut fields = Vec::with_capacity(record.fields.len());
119            for (name, v) in &record.fields {
120                fields.push((*name, prepare_for_json(cx, v)?));
121            }
122            Ok(Value::Record(Arc::new(Record {
123                ty: record.ty,
124                variant: record.variant,
125                fields,
126            })))
127        }
128        Value::Tuple(items) => {
129            let prepared: RunResult<Vec<_>> =
130                items.iter().map(|v| prepare_for_json(cx, v)).collect();
131            Ok(Value::tuple(prepared?))
132        }
133        // A map becomes an object: its keys as strings, sorted so the output
134        // doesn't depend on hashing.
135        Value::Map(map) => {
136            let mut entries = Vec::with_capacity(map.len());
137            for entry in map.iter() {
138                let key = map_key_name(cx, &entry.key().0);
139                entries.push((key, entry.value().clone()));
140            }
141            entries.sort_by(|a, b| a.0.cmp(&b.0));
142            let mut fields = Vec::with_capacity(entries.len());
143            for (key, v) in entries {
144                fields.push((Symbol::intern(&key), prepare_for_json(cx, &v)?));
145            }
146            Ok(Value::Record(Arc::new(Record::new(fields))))
147        }
148        _ => Ok(value.clone()),
149    }
150}
151
152/// A map key as a JSON object key: strings as they are, numbers and bools
153/// as written, a unit enum variant by its name.
154fn map_key_name(cx: &mut dyn Context, key: &Value) -> String {
155    match key {
156        Value::Str(s) => s.to_string(),
157        Value::Unit => "()".to_owned(),
158        Value::Int(i) => i.to_i128().to_string(),
159        Value::Bool(b) => b.to_string(),
160        // A unit variant, by its last path segment (`Color::Red` -> "Red").
161        Value::Adt(adt) => cx
162            .adt_info(adt.ctor)
163            .map(|info| {
164                info.name
165                    .rsplit("::")
166                    .next()
167                    .unwrap_or(&info.name)
168                    .to_owned()
169            })
170            .unwrap_or_else(|| "?".to_owned()),
171        other => other.kind().to_owned(),
172    }
173}
174
175/// The deserializer cannot build `None` ADTs (it doesn't have a Context),
176/// so they are left as `Unit` and fixed up here.
177fn fixup_nulls(cx: &dyn Context, value: &Value) -> Value {
178    match value {
179        Value::Unit => crate::option(cx, None),
180        Value::List(items) => {
181            let items = lock(items);
182            Value::list(items.iter().map(|v| fixup_nulls(cx, v)).collect())
183        }
184        Value::Record(record) => {
185            let fields = record
186                .fields
187                .iter()
188                .map(|(name, v)| (*name, fixup_nulls(cx, v)))
189                .collect();
190            Value::Record(
191                Record {
192                    ty: record.ty,
193                    variant: record.variant,
194                    fields,
195                }
196                .into(),
197            )
198        }
199        other => other.clone(),
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use xur_runtime::testing::{TestCx, fn_id};
206    use xur_runtime::{Record, lock};
207    use xur_span::Symbol;
208
209    use super::*;
210
211    fn registry() -> Registry {
212        let registry = Registry::new();
213        register(&registry);
214        registry
215    }
216
217    fn call_parse(cx: &mut TestCx<'_>, json: &str) -> Value {
218        let id = fn_id(cx.registry, "std::json::parse");
219        cx.call(id, &[Value::str(json)]).unwrap()
220    }
221
222    fn call_stringify(cx: &mut TestCx<'_>, value: Value) -> Value {
223        let id = fn_id(cx.registry, "std::json::stringify");
224        cx.call(id, &[value]).unwrap()
225    }
226
227    /// Unwraps an Ok(value) from a xur Result ADT.
228    fn unwrap_ok(cx: &TestCx<'_>, result: &Value) -> Value {
229        let Value::Adt(adt) = result else {
230            panic!("expected a Result ADT, got {result:?}");
231        };
232        assert_eq!(adt.ctor, cx.lang.ok, "expected Ok, got Err");
233        adt.fields[0].clone()
234    }
235
236    /// Unwraps an Err(message) from a xur Result ADT.
237    fn unwrap_err(cx: &TestCx<'_>, result: &Value) -> String {
238        let Value::Adt(adt) = result else {
239            panic!("expected a Result ADT, got {result:?}");
240        };
241        assert_eq!(adt.ctor, cx.lang.err, "expected Err, got Ok");
242        match &adt.fields[0] {
243            Value::Str(s) => s.to_string(),
244            other => panic!("expected string error, got {other:?}"),
245        }
246    }
247
248    fn field(record: &Value, name: &str) -> Value {
249        let Value::Record(r) = record else {
250            panic!("expected Record, got {record:?}");
251        };
252        r.field(Symbol::intern(name))
253            .unwrap_or_else(|| panic!("no field `{name}`"))
254            .clone()
255    }
256
257    #[test]
258    fn parse_object() {
259        let reg = registry();
260        let mut cx = TestCx::new(&reg, crate::PRELUDE);
261        let result = call_parse(&mut cx, r#"{"name": "Alice", "age": 30}"#);
262        let value = unwrap_ok(&cx, &result);
263
264        assert_eq!(field(&value, "name"), Value::str("Alice"));
265        assert_eq!(field(&value, "age"), Value::int(30));
266    }
267
268    #[test]
269    fn parse_nested_object() {
270        let reg = registry();
271        let mut cx = TestCx::new(&reg, crate::PRELUDE);
272        let result = call_parse(&mut cx, r#"{"user": {"name": "Bob"}, "scores": [10, 20]}"#);
273        let value = unwrap_ok(&cx, &result);
274
275        assert_eq!(field(&field(&value, "user"), "name"), Value::str("Bob"));
276        let Value::List(scores) = field(&value, "scores") else {
277            panic!("expected list");
278        };
279        let scores = lock(&scores);
280        assert_eq!(*scores, vec![Value::int(10), Value::int(20)]);
281    }
282
283    #[test]
284    fn parse_null_becomes_none() {
285        let reg = registry();
286        let mut cx = TestCx::new(&reg, crate::PRELUDE);
287        let result = call_parse(&mut cx, r#"{"x": null}"#);
288        let value = unwrap_ok(&cx, &result);
289        let x = field(&value, "x");
290        let Value::Adt(adt) = &x else {
291            panic!("expected None ADT for null, got {x:?}");
292        };
293        assert_eq!(adt.ctor, cx.lang.none);
294    }
295
296    #[test]
297    fn parse_array() {
298        let reg = registry();
299        let mut cx = TestCx::new(&reg, crate::PRELUDE);
300        let result = call_parse(&mut cx, r#"[1, "two", true]"#);
301        let value = unwrap_ok(&cx, &result);
302        let Value::List(items) = &value else {
303            panic!("expected list, got {value:?}");
304        };
305        let items = lock(items);
306        assert_eq!(items[0], Value::int(1));
307        assert_eq!(items[1], Value::str("two"));
308        assert_eq!(items[2], Value::Bool(true));
309    }
310
311    #[test]
312    fn parse_scalars() {
313        let reg = registry();
314        let mut cx = TestCx::new(&reg, crate::PRELUDE);
315
316        let r = call_parse(&mut cx, "42");
317        assert_eq!(unwrap_ok(&cx, &r), Value::int(42));
318
319        let r = call_parse(&mut cx, "2.75");
320        assert_eq!(unwrap_ok(&cx, &r), Value::float(2.75));
321
322        let r = call_parse(&mut cx, "true");
323        assert_eq!(unwrap_ok(&cx, &r), Value::Bool(true));
324
325        let r = call_parse(&mut cx, r#""hello""#);
326        assert_eq!(unwrap_ok(&cx, &r), Value::str("hello"));
327    }
328
329    #[test]
330    fn parse_invalid_json_returns_err() {
331        let reg = registry();
332        let mut cx = TestCx::new(&reg, crate::PRELUDE);
333        let result = call_parse(&mut cx, "not json");
334        let msg = unwrap_err(&cx, &result);
335        assert!(msg.contains("expected"), "error was: {msg}");
336    }
337
338    #[test]
339    fn stringify_object() {
340        let reg = registry();
341        let mut cx = TestCx::new(&reg, crate::PRELUDE);
342        let record = Value::Record(
343            Record::new(vec![
344                (Symbol::intern("a"), Value::int(1)),
345                (Symbol::intern("b"), Value::str("two")),
346            ])
347            .into(),
348        );
349        let result = call_stringify(&mut cx, record);
350        let json = unwrap_ok(&cx, &result);
351        let Value::Str(s) = &json else {
352            panic!("expected string");
353        };
354        let parsed: serde_json::Value = serde_json::from_str(s).unwrap();
355        assert_eq!(parsed["a"], 1);
356        assert_eq!(parsed["b"], "two");
357    }
358
359    #[test]
360    fn stringify_map_as_object() {
361        let reg = registry();
362        let mut cx = TestCx::new(&reg, crate::PRELUDE);
363        let map = Value::map(vec![
364            (Value::str("b"), Value::int(2)),
365            (Value::str("a"), Value::list(vec![Value::int(1)])),
366            (Value::int(7), Value::Bool(true)),
367        ])
368        .unwrap();
369        let result = call_stringify(&mut cx, map);
370        let json = unwrap_ok(&cx, &result);
371        assert_eq!(json, Value::str(r#"{"7":true,"a":[1],"b":2}"#));
372    }
373
374    #[test]
375    fn stringify_nested_map() {
376        let reg = registry();
377        let mut cx = TestCx::new(&reg, crate::PRELUDE);
378        let inner = Value::map(vec![(Value::str("x"), Value::int(1))]).unwrap();
379        let record = Value::Record(Arc::new(Record::new(vec![(Symbol::intern("m"), inner)])));
380        let result = call_stringify(&mut cx, record);
381        assert_eq!(unwrap_ok(&cx, &result), Value::str(r#"{"m":{"x":1}}"#));
382    }
383
384    #[test]
385    fn to_json_is_a_serde_value() {
386        let reg = registry();
387        let mut cx = TestCx::new(&reg, crate::PRELUDE);
388        let map = Value::map(vec![(Value::str("k"), Value::str("v"))]).unwrap();
389        assert_eq!(
390            to_json(&mut cx, &map).unwrap(),
391            serde_json::json!({"k": "v"})
392        );
393    }
394
395    #[test]
396    fn stringify_list() {
397        let reg = registry();
398        let mut cx = TestCx::new(&reg, crate::PRELUDE);
399        let list = Value::list(vec![Value::int(1), Value::Bool(false)]);
400        let result = call_stringify(&mut cx, list);
401        let json = unwrap_ok(&cx, &result);
402        assert_eq!(json, Value::str("[1,false]"));
403    }
404
405    #[test]
406    fn roundtrip() {
407        let reg = registry();
408        let mut cx = TestCx::new(&reg, crate::PRELUDE);
409        let input = r#"{"name":"Alice","tags":["a","b"],"score":99}"#;
410        let r = call_parse(&mut cx, input);
411        let parsed = unwrap_ok(&cx, &r);
412        let r = call_stringify(&mut cx, parsed);
413        let stringified = unwrap_ok(&cx, &r);
414        let Value::Str(s) = &stringified else {
415            panic!("expected string");
416        };
417        let a: serde_json::Value = serde_json::from_str(input).unwrap();
418        let b: serde_json::Value = serde_json::from_str(s).unwrap();
419        assert_eq!(a, b);
420    }
421}