xur-std 0.1.10

The standard library of the Xur language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! `std::json`: JSON parsing and serialisation.

mod de;
mod ser;

use std::sync::Arc;

use xur_runtime::registry::RawSig;
use xur_runtime::{Context, Record, Registry, RunResult, RuntimeError, Value, lock};
use xur_span::Symbol;

/// A newtype so `serde::Deserialize` and `serde::Serialize` can be
/// implemented for xur values without orphan issues.
pub(crate) struct JsonValue(pub Value);

impl JsonValue {
    /// JSON null, as xur's `None`.
    fn null() -> Self {
        // Constructed with a placeholder DefId; the real None ctor is set
        // by the `parse` function which has access to Context.
        Self(Value::Unit)
    }
}

pub(crate) fn register(registry: &Registry) {
    registry
        .module("std::json")
        .raw_function_sig(
            "parse",
            RawSig::new()
                .param("text", "str")
                .returns("Result<any, str>"),
            parse,
        )
        .raw_function_sig(
            "stringify",
            RawSig::new()
                .param("value", "any")
                .returns("Result<str, str>"),
            stringify,
        );
}

/// Parses JSON text into a xur value, as `std::json::parse` does: objects
/// become records, arrays lists, and `null` becomes `None`. For hosts and
/// other modules (`std::http`) that read JSON.
pub fn parse_str(cx: &dyn Context, text: &str) -> RunResult<Value> {
    match serde_json::from_str::<JsonValue>(text) {
        Ok(JsonValue(value)) => Ok(fixup_nulls(cx, &value)),
        Err(e) => Err(RuntimeError::new(crate::error_text(e))),
    }
}

/// A xur value as JSON text, as `std::json::stringify` does: structs and
/// records become objects, maps objects with their keys as strings, lists
/// and tuples arrays, `None` null. Functions, modules and other non-data
/// values are an error. For hosts and other modules (`std::http`) that write
/// JSON.
pub fn stringify_value(cx: &mut dyn Context, value: &Value) -> RunResult<String> {
    let prepared = prepare_for_json(cx, value)?;
    serde_json::to_string(&JsonValue(prepared)).map_err(|e| RuntimeError::new(crate::error_text(e)))
}

/// [`stringify_value`] as a `serde_json::Value`, for hosts that pass JSON on
/// rather than text.
pub fn to_json(cx: &mut dyn Context, value: &Value) -> RunResult<serde_json::Value> {
    let prepared = prepare_for_json(cx, value)?;
    serde_json::to_value(JsonValue(prepared)).map_err(|e| RuntimeError::new(crate::error_text(e)))
}

/// `std::json::parse(text) -> Result<value, str>`
fn parse(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [Value::Str(text)] = args else {
        return Err(RuntimeError::new("`json::parse` takes a single string"));
    };
    let res = match serde_json::from_str::<JsonValue>(text) {
        Ok(JsonValue(value)) => Ok(fixup_nulls(cx, &value)),
        Err(e) => Err(crate::error_text(e)),
    };
    Ok(crate::result(cx, res))
}

/// `std::json::stringify(value) -> Result<str, str>`
fn stringify(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
    let [value] = args else {
        return Err(RuntimeError::new("`json::stringify` takes a single value"));
    };
    let prepared = prepare_for_json(cx, value)?;
    let res = serde_json::to_string(&JsonValue(prepared)).map_err(crate::error_text);
    Ok(crate::result(cx, res.map(|s| Value::str(&s))))
}

/// Converts Adt values to Records with named fields so the serializer
/// can emit JSON objects with keys instead of arrays.
fn prepare_for_json(cx: &mut dyn Context, value: &Value) -> RunResult<Value> {
    match value {
        Value::Adt(adt) => {
            if let Some(info) = cx.adt_info(adt.ctor) {
                let mut fields = Vec::with_capacity(info.fields.len());
                for (i, fi) in info.fields.iter().enumerate() {
                    let name = fi.name.unwrap_or_else(|| Symbol::intern(&i.to_string()));
                    let val = adt.fields.get(i).cloned().unwrap_or(Value::Unit);
                    fields.push((name, prepare_for_json(cx, &val)?));
                }
                Ok(Value::Record(Arc::new(Record::new(fields))))
            } else {
                // No field info (e.g. None, Ok, Err) — keep as Adt.
                Ok(value.clone())
            }
        }
        Value::List(items) => {
            let items = lock(items);
            let prepared: RunResult<Vec<_>> =
                items.iter().map(|v| prepare_for_json(cx, v)).collect();
            Ok(Value::list(prepared?))
        }
        Value::Record(record) => {
            let mut fields = Vec::with_capacity(record.fields.len());
            for (name, v) in &record.fields {
                fields.push((*name, prepare_for_json(cx, v)?));
            }
            Ok(Value::Record(Arc::new(Record {
                ty: record.ty,
                variant: record.variant,
                fields,
            })))
        }
        Value::Tuple(items) => {
            let prepared: RunResult<Vec<_>> =
                items.iter().map(|v| prepare_for_json(cx, v)).collect();
            Ok(Value::tuple(prepared?))
        }
        // A map becomes an object: its keys as strings, sorted so the output
        // doesn't depend on hashing.
        Value::Map(map) => {
            let mut entries = Vec::with_capacity(map.len());
            for entry in map.iter() {
                let key = map_key_name(cx, &entry.key().0);
                entries.push((key, entry.value().clone()));
            }
            entries.sort_by(|a, b| a.0.cmp(&b.0));
            let mut fields = Vec::with_capacity(entries.len());
            for (key, v) in entries {
                fields.push((Symbol::intern(&key), prepare_for_json(cx, &v)?));
            }
            Ok(Value::Record(Arc::new(Record::new(fields))))
        }
        _ => Ok(value.clone()),
    }
}

/// A map key as a JSON object key: strings as they are, numbers and bools
/// as written, a unit enum variant by its name.
fn map_key_name(cx: &mut dyn Context, key: &Value) -> String {
    match key {
        Value::Str(s) => s.to_string(),
        Value::Unit => "()".to_owned(),
        Value::Int(i) => i.to_i128().to_string(),
        Value::Bool(b) => b.to_string(),
        // A unit variant, by its last path segment (`Color::Red` -> "Red").
        Value::Adt(adt) => cx
            .adt_info(adt.ctor)
            .map(|info| {
                info.name
                    .rsplit("::")
                    .next()
                    .unwrap_or(&info.name)
                    .to_owned()
            })
            .unwrap_or_else(|| "?".to_owned()),
        other => other.kind().to_owned(),
    }
}

/// The deserializer cannot build `None` ADTs (it doesn't have a Context),
/// so they are left as `Unit` and fixed up here.
fn fixup_nulls(cx: &dyn Context, value: &Value) -> Value {
    match value {
        Value::Unit => crate::option(cx, None),
        Value::List(items) => {
            let items = lock(items);
            Value::list(items.iter().map(|v| fixup_nulls(cx, v)).collect())
        }
        Value::Record(record) => {
            let fields = record
                .fields
                .iter()
                .map(|(name, v)| (*name, fixup_nulls(cx, v)))
                .collect();
            Value::Record(
                Record {
                    ty: record.ty,
                    variant: record.variant,
                    fields,
                }
                .into(),
            )
        }
        other => other.clone(),
    }
}

#[cfg(test)]
mod tests {
    use xur_runtime::testing::{TestCx, fn_id};
    use xur_runtime::{Record, lock};
    use xur_span::Symbol;

    use super::*;

    fn registry() -> Registry {
        let registry = Registry::new();
        register(&registry);
        registry
    }

    fn call_parse(cx: &mut TestCx<'_>, json: &str) -> Value {
        let id = fn_id(cx.registry, "std::json::parse");
        cx.call(id, &[Value::str(json)]).unwrap()
    }

    fn call_stringify(cx: &mut TestCx<'_>, value: Value) -> Value {
        let id = fn_id(cx.registry, "std::json::stringify");
        cx.call(id, &[value]).unwrap()
    }

    /// Unwraps an Ok(value) from a xur Result ADT.
    fn unwrap_ok(cx: &TestCx<'_>, result: &Value) -> Value {
        let Value::Adt(adt) = result else {
            panic!("expected a Result ADT, got {result:?}");
        };
        assert_eq!(adt.ctor, cx.lang.ok, "expected Ok, got Err");
        adt.fields[0].clone()
    }

    /// Unwraps an Err(message) from a xur Result ADT.
    fn unwrap_err(cx: &TestCx<'_>, result: &Value) -> String {
        let Value::Adt(adt) = result else {
            panic!("expected a Result ADT, got {result:?}");
        };
        assert_eq!(adt.ctor, cx.lang.err, "expected Err, got Ok");
        match &adt.fields[0] {
            Value::Str(s) => s.to_string(),
            other => panic!("expected string error, got {other:?}"),
        }
    }

    fn field(record: &Value, name: &str) -> Value {
        let Value::Record(r) = record else {
            panic!("expected Record, got {record:?}");
        };
        r.field(Symbol::intern(name))
            .unwrap_or_else(|| panic!("no field `{name}`"))
            .clone()
    }

    #[test]
    fn parse_object() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let result = call_parse(&mut cx, r#"{"name": "Alice", "age": 30}"#);
        let value = unwrap_ok(&cx, &result);

        assert_eq!(field(&value, "name"), Value::str("Alice"));
        assert_eq!(field(&value, "age"), Value::int(30));
    }

    #[test]
    fn parse_nested_object() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let result = call_parse(&mut cx, r#"{"user": {"name": "Bob"}, "scores": [10, 20]}"#);
        let value = unwrap_ok(&cx, &result);

        assert_eq!(field(&field(&value, "user"), "name"), Value::str("Bob"));
        let Value::List(scores) = field(&value, "scores") else {
            panic!("expected list");
        };
        let scores = lock(&scores);
        assert_eq!(*scores, vec![Value::int(10), Value::int(20)]);
    }

    #[test]
    fn parse_null_becomes_none() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let result = call_parse(&mut cx, r#"{"x": null}"#);
        let value = unwrap_ok(&cx, &result);
        let x = field(&value, "x");
        let Value::Adt(adt) = &x else {
            panic!("expected None ADT for null, got {x:?}");
        };
        assert_eq!(adt.ctor, cx.lang.none);
    }

    #[test]
    fn parse_array() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let result = call_parse(&mut cx, r#"[1, "two", true]"#);
        let value = unwrap_ok(&cx, &result);
        let Value::List(items) = &value else {
            panic!("expected list, got {value:?}");
        };
        let items = lock(items);
        assert_eq!(items[0], Value::int(1));
        assert_eq!(items[1], Value::str("two"));
        assert_eq!(items[2], Value::Bool(true));
    }

    #[test]
    fn parse_scalars() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);

        let r = call_parse(&mut cx, "42");
        assert_eq!(unwrap_ok(&cx, &r), Value::int(42));

        let r = call_parse(&mut cx, "2.75");
        assert_eq!(unwrap_ok(&cx, &r), Value::float(2.75));

        let r = call_parse(&mut cx, "true");
        assert_eq!(unwrap_ok(&cx, &r), Value::Bool(true));

        let r = call_parse(&mut cx, r#""hello""#);
        assert_eq!(unwrap_ok(&cx, &r), Value::str("hello"));
    }

    #[test]
    fn parse_invalid_json_returns_err() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let result = call_parse(&mut cx, "not json");
        let msg = unwrap_err(&cx, &result);
        assert!(msg.contains("expected"), "error was: {msg}");
    }

    #[test]
    fn stringify_object() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let record = Value::Record(
            Record::new(vec![
                (Symbol::intern("a"), Value::int(1)),
                (Symbol::intern("b"), Value::str("two")),
            ])
            .into(),
        );
        let result = call_stringify(&mut cx, record);
        let json = unwrap_ok(&cx, &result);
        let Value::Str(s) = &json else {
            panic!("expected string");
        };
        let parsed: serde_json::Value = serde_json::from_str(s).unwrap();
        assert_eq!(parsed["a"], 1);
        assert_eq!(parsed["b"], "two");
    }

    #[test]
    fn stringify_map_as_object() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let map = Value::map(vec![
            (Value::str("b"), Value::int(2)),
            (Value::str("a"), Value::list(vec![Value::int(1)])),
            (Value::int(7), Value::Bool(true)),
        ])
        .unwrap();
        let result = call_stringify(&mut cx, map);
        let json = unwrap_ok(&cx, &result);
        assert_eq!(json, Value::str(r#"{"7":true,"a":[1],"b":2}"#));
    }

    #[test]
    fn stringify_nested_map() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let inner = Value::map(vec![(Value::str("x"), Value::int(1))]).unwrap();
        let record = Value::Record(Arc::new(Record::new(vec![(Symbol::intern("m"), inner)])));
        let result = call_stringify(&mut cx, record);
        assert_eq!(unwrap_ok(&cx, &result), Value::str(r#"{"m":{"x":1}}"#));
    }

    #[test]
    fn to_json_is_a_serde_value() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let map = Value::map(vec![(Value::str("k"), Value::str("v"))]).unwrap();
        assert_eq!(
            to_json(&mut cx, &map).unwrap(),
            serde_json::json!({"k": "v"})
        );
    }

    #[test]
    fn stringify_list() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let list = Value::list(vec![Value::int(1), Value::Bool(false)]);
        let result = call_stringify(&mut cx, list);
        let json = unwrap_ok(&cx, &result);
        assert_eq!(json, Value::str("[1,false]"));
    }

    #[test]
    fn roundtrip() {
        let reg = registry();
        let mut cx = TestCx::new(&reg, crate::PRELUDE);
        let input = r#"{"name":"Alice","tags":["a","b"],"score":99}"#;
        let r = call_parse(&mut cx, input);
        let parsed = unwrap_ok(&cx, &r);
        let r = call_stringify(&mut cx, parsed);
        let stringified = unwrap_ok(&cx, &r);
        let Value::Str(s) = &stringified else {
            panic!("expected string");
        };
        let a: serde_json::Value = serde_json::from_str(input).unwrap();
        let b: serde_json::Value = serde_json::from_str(s).unwrap();
        assert_eq!(a, b);
    }
}