system2 0.1.0

An (unofficial) idiomatic Rust SDK for TypeSafe's System One model, Jev.
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
use serde::ser::Error;
use serde::{Serialize, Serializer};
use serde_json::Value;
use serde_json::value::{RawValue, to_raw_value};
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;

// the instructions or a criterion, after a macro or a constructor validates it: text, an
// object, or an array, and never empty
#[doc(hidden)]
#[derive(Clone)]
pub enum Json {
    // the value of a json string, such as `Is it "spam"?`, which goes out as `"Is it \"spam\"?"`
    String(Cow<'static, str>),
    // json text, such as `{"policy":"No secrets."}`, which goes out with no change
    Raw(Cow<'static, str>),
}

impl From<Box<RawValue>> for Json {
    fn from(json: Box<RawValue>) -> Self {
        Json::Raw(Cow::Owned(Box::<str>::from(json).into_string()))
    }
}

// shows the json that goes out, so text from a macro and from a constructor look the same
impl fmt::Debug for Json {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Json::String(text) => fmt::Display::fmt(&Value::from(text.as_ref()), formatter),
            Json::Raw(json) => formatter.write_str(json),
        }
    }
}

impl Serialize for Json {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Json::String(text) => serializer.serialize_str(text),
            Json::Raw(json) => serde_json::from_str::<&RawValue>(json)
                .map_err(S::Error::custom)?
                .serialize(serializer),
        }
    }
}

#[doc(hidden)]
#[diagnostic::on_unimplemented(
    message = "`{Self}` can fail to serialize, so a macro cannot prove the question valid",
    label = "can fail to serialize",
    note = "use a constructor such as `Noul::new(json!({{ … }}))?`, or put the value in the state"
)]
pub trait AlwaysSerialize: Serialize {}

impl AlwaysSerialize for str {}
impl AlwaysSerialize for String {}
impl AlwaysSerialize for char {}
impl AlwaysSerialize for bool {}
impl AlwaysSerialize for () {}
impl AlwaysSerialize for serde_json::Value {}
impl AlwaysSerialize for serde_json::Map<String, serde_json::Value> {}
impl<T: AlwaysSerialize + ?Sized> AlwaysSerialize for &T {}
impl<T: AlwaysSerialize + ?Sized> AlwaysSerialize for Box<T> {}
impl<T: AlwaysSerialize + ToOwned + ?Sized> AlwaysSerialize for Cow<'_, T> {}
impl<T: AlwaysSerialize> AlwaysSerialize for Option<T> {}
impl<T: AlwaysSerialize> AlwaysSerialize for [T] {}
impl<T: AlwaysSerialize> AlwaysSerialize for Vec<T> {}
impl<T: AlwaysSerialize> AlwaysSerialize for VecDeque<T> {}
impl<T: AlwaysSerialize> AlwaysSerialize for BTreeSet<T> {}
impl<T: AlwaysSerialize, S> AlwaysSerialize for HashSet<T, S> {}

// serde serializes an array of up to 32 items, and an `Rc` or an `Arc` only with its `rc` feature
impl<T: AlwaysSerialize, const N: usize> AlwaysSerialize for [T; N] where [T; N]: Serialize {}
impl<T: AlwaysSerialize + ?Sized> AlwaysSerialize for Rc<T> where Rc<T>: Serialize {}
impl<T: AlwaysSerialize + ?Sized> AlwaysSerialize for Arc<T> where Arc<T>: Serialize {}

// a json key is always text
impl<T: AlwaysSerialize> AlwaysSerialize for BTreeMap<String, T> {}
impl<T: AlwaysSerialize> AlwaysSerialize for BTreeMap<&str, T> {}
impl<T: AlwaysSerialize, S> AlwaysSerialize for HashMap<String, T, S> {}
impl<T: AlwaysSerialize, S> AlwaysSerialize for HashMap<&str, T, S> {}

macro_rules! tuple {
    ($($item:ident),+) => { impl<$($item: AlwaysSerialize),+> AlwaysSerialize for ($($item,)+) {} };
}

tuple!(A);
tuple!(A, B);
tuple!(A, B, C);
tuple!(A, B, C, D);
tuple!(A, B, C, D, E);
tuple!(A, B, C, D, E, F);
tuple!(A, B, C, D, E, F, G);
tuple!(A, B, C, D, E, F, G, H);
tuple!(A, B, C, D, E, F, G, H, I);
tuple!(A, B, C, D, E, F, G, H, I, J);
tuple!(A, B, C, D, E, F, G, H, I, J, K);
tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

macro_rules! numbers {
    ($($number:ty),*) => { $(impl AlwaysSerialize for $number {})* };
}

numbers!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

#[doc(hidden)]
#[expect(clippy::expect_used, reason = "the value always serializes")]
#[must_use]
pub fn to_json(value: &impl AlwaysSerialize) -> String {
    serde_json::to_string(value).expect("the value always serializes")
}

// a literal with no placeholder, such as "a {{b}}", gives "a {b}", also in a const
#[doc(hidden)]
#[expect(
    clippy::expect_used,
    reason = "the macro gives only a literal with no placeholder"
)]
#[must_use]
pub const fn unescaped(arguments: fmt::Arguments<'_>) -> &'static str {
    arguments.as_str().expect("a literal with no placeholder")
}

// `str::trim` is not const, so this matches the utf-8 bytes of each whitespace char: tab to
// carriage return, space, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F,
// U+205F, and U+3000
#[doc(hidden)]
#[must_use]
pub const fn is_blank(text: &str) -> bool {
    let mut bytes = text.as_bytes();
    loop {
        bytes = match bytes {
            [] => return true,
            [b'\t'..=b'\r' | b' ', rest @ ..]
            | [0xC2, 0x85 | 0xA0, rest @ ..]
            | [0xE1, 0x9A, 0x80, rest @ ..]
            | [0xE2, 0x80, 0x80..=0x8A | 0xA8 | 0xA9 | 0xAF, rest @ ..]
            | [0xE2, 0x81, 0x9F, rest @ ..]
            | [0xE3, 0x80, 0x80, rest @ ..] => rest,
            _ => return false,
        };
    }
}

/// A value that is not valid JSON for the API, as a part of another error.
///
/// The instructions, each criterion, each description, each level, and the state follow its
/// rules. Each message completes the message of its error, as in "the instructions must not be
/// empty".
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InvalidJson {
    /// The value does not serialize to JSON.
    #[error("must serialize to JSON: {0}")]
    Serialize(serde_json::Error),
    /// The value is a bare number or `bool`.
    #[error("must be text, an object, or an array")]
    Shape,
    /// The value is only whitespace, `[]`, `{}`, or `null`.
    #[error("must not be empty")]
    Empty,
}

// raw json keeps the order that serde writes, which a `Value` sorts
pub(crate) fn validate(value: impl Serialize) -> Result<Box<RawValue>, InvalidJson> {
    let json = to_raw_value(&value).map_err(InvalidJson::Serialize)?;

    // the text is valid json, so its first character gives its type
    let text = json.get().trim();
    let empty = match text.chars().next() {
        Some('"') => serde_json::from_str::<String>(text).is_ok_and(|text| is_blank(&text)),
        Some('{' | '[') => text[1..text.len() - 1].trim().is_empty(),
        Some('n') => true,
        _ => return Err(InvalidJson::Shape),
    };
    if empty {
        return Err(InvalidJson::Empty);
    }
    Ok(json)
}

pub(crate) fn validate_optional(
    value: impl Serialize,
) -> Result<Option<Box<RawValue>>, InvalidJson> {
    let json = to_raw_value(&value).map_err(InvalidJson::Serialize)?;
    if json.get().trim() == "null" {
        return Ok(None);
    }
    validate(json).map(Some)
}

#[cfg(test)]
mod tests {
    use super::{Json, is_blank, to_json, unescaped, validate, validate_optional};
    use crate::InvalidJson;
    use serde::Serialize;
    use serde_json::value::RawValue;
    use serde_json::{Map, json};
    use std::borrow::Cow;
    use std::collections::BTreeMap;

    #[test]
    fn fmt_shows_the_json_that_goes_out() {
        let cases = [
            (
                Json::String(Cow::Borrowed(r#"Is it "spam"?"#)),
                r#""Is it \"spam\"?""#,
            ),
            (
                Json::String(Cow::Borrowed("Is it \u{1}?")),
                r#""Is it \u0001?""#,
            ),
            (
                Json::Raw(Cow::Borrowed(r#""Is it spam?""#)),
                r#""Is it spam?""#,
            ),
            (
                Json::Raw(Cow::Borrowed(r#"{"policy":"No secrets."}"#)),
                r#"{"policy":"No secrets."}"#,
            ),
        ];

        for (json, shown) in cases {
            assert_eq!(format!("{json:?}"), shown);
        }
    }

    #[test]
    fn serialize_quotes_only_a_string() {
        let cases = [
            (
                Json::String(Cow::Borrowed(r#"Is {"a": 1} JSON?"#)),
                r#""Is {\"a\": 1} JSON?""#,
            ),
            (Json::Raw(Cow::Borrowed(r#"{"a":1}"#)), r#"{"a":1}"#),
            (
                Json::from(RawValue::from_string(r#"["a"]"#.to_owned()).unwrap()),
                r#"["a"]"#,
            ),
        ];
        for (json, text) in cases {
            assert_eq!(serde_json::to_string(&json).unwrap(), text, "{json:?}");
        }
    }

    #[test]
    fn to_json_gives_the_json_of_a_value() {
        let value = (
            vec![Some("a"), None],
            Box::new('b'),
            Cow::Borrowed("c"),
            BTreeMap::from([("d", 1)]),
            (),
            [1.5],
            Map::from_iter([(String::from("e"), json!(true))]),
        );
        assert_eq!(
            to_json(&value),
            r#"[["a",null],"b","c",{"d":1},null,[1.5],{"e":true}]"#
        );
    }

    #[test]
    fn unescaped_gives_each_brace_one_time() {
        assert_eq!(
            unescaped(format_args!("Is `{{}}` a block?")),
            "Is `{}` a block?"
        );
    }

    #[test]
    fn is_blank_takes_only_whitespace_as_blank() {
        let cases = [
            ("", true),
            (" ", true),
            (" \t\n\r", true),
            ("\u{a0}", true),
            ("\u{2003}\u{3000}", true),
            (" a ", false),
            ("é", false),
            ("日本", false),
            ("🦀", false),
            ("\u{3000}a", false),
            // these look empty, but unicode has no whitespace property for them
            ("\u{200b}", false),
            ("\u{feff}", false),
        ];
        for (text, blank) in cases {
            assert_eq!(is_blank(text), blank, "{text:?}");
        }
    }

    #[test]
    fn is_blank_agrees_with_is_whitespace_for_each_char() {
        for character in char::MIN..=char::MAX {
            let text = character.to_string();
            assert_eq!(is_blank(&text), character.is_whitespace(), "{character:?}");
        }
    }

    #[test]
    fn validate_refuses_text_of_unicode_whitespace() {
        let error = validate(json!("\u{a0}\u{2003}")).unwrap_err();

        assert!(matches!(error, InvalidJson::Empty));
    }

    // one type for each test of `validate`, so coverage sees all its rules together
    fn raw(text: &str) -> Box<RawValue> {
        RawValue::from_string(text.to_owned()).unwrap()
    }

    #[test]
    fn validate_takes_text_an_object_or_an_array() {
        let cases = [
            r#""Is it spam?""#,
            r#"{"question":"Is it spam?"}"#,
            r#"["Is it spam?"]"#,
        ];
        for text in cases {
            assert_eq!(validate(raw(text)).unwrap().get(), text);
        }
    }

    #[test]
    fn validate_keeps_the_order_of_the_fields() {
        #[derive(Serialize)]
        struct Change {
            diff: &'static str,
            description: &'static str,
        }
        let change = Change {
            diff: "+ fn main() {}",
            description: "Add main.",
        };

        assert_eq!(
            validate(change).unwrap().get(),
            r#"{"diff":"+ fn main() {}","description":"Add main."}"#
        );
    }

    #[test]
    fn validate_refuses_an_empty_value() {
        let cases = [r#""""#, r#"" \n\t""#, "{}", "[ ]", " { \n } ", "null"];
        for text in cases {
            let error = validate(raw(text)).unwrap_err();
            assert!(matches!(error, InvalidJson::Empty), "{text}");
            assert_eq!(error.to_string(), "must not be empty");
        }
    }

    #[test]
    fn validate_refuses_a_number_or_a_bool() {
        for text in ["42", "-1", "true", "false"] {
            let error = validate(raw(text)).unwrap_err();
            assert!(matches!(error, InvalidJson::Shape), "{text}");
            assert_eq!(error.to_string(), "must be text, an object, or an array");
        }
    }

    #[test]
    fn validate_refuses_a_value_that_does_not_serialize() {
        let pairs = BTreeMap::from([((1, 2), "a pair as a key")]);

        let error = validate(pairs).unwrap_err();

        assert!(matches!(error, InvalidJson::Serialize(_)));
        assert_eq!(
            error.to_string(),
            "must serialize to JSON: key must be a string"
        );
    }

    #[test]
    fn validate_optional_takes_null_as_no_value() {
        assert!(validate_optional(()).unwrap().is_none());
        assert!(validate_optional(None::<&str>).unwrap().is_none());
        assert_eq!(
            validate_optional("Ask for a fix.").unwrap().unwrap().get(),
            r#""Ask for a fix.""#
        );
    }

    #[test]
    fn validate_optional_refuses_what_validate_refuses() {
        let cases = [
            (validate_optional("").unwrap_err(), "must not be empty"),
            (
                validate_optional(1).unwrap_err(),
                "must be text, an object, or an array",
            ),
            (
                validate_optional(BTreeMap::from([((1, 2), "")])).unwrap_err(),
                "must serialize to JSON: key must be a string",
            ),
        ];
        for (error, message) in cases {
            assert_eq!(error.to_string(), message);
        }
    }
}