Skip to main content

jsonx_lib/
macros.rs

1//! The `json!` and `json_struct!` macros.
2
3/// Builds a [`Value`](crate::Value) from JSON-like syntax.
4///
5/// `null`, `true`, `false`, arrays `[...]`, and objects `{...}` are written as
6/// in JSON, nested to any depth. Anything else is a Rust expression converted
7/// with [`Value::from`](crate::Value), so variables, numbers, strings, `Option`s,
8/// `Vec`s, and other values drop straight in. An object key is a string
9/// literal, or any expression in parentheses that converts into
10/// `Cow<str>` (a `&str` or a `String`).
11///
12/// Members are appended in the order written, as [`Object::push`](crate::Object::push)
13/// does; a key written twice appears twice. An expression containing a
14/// top-level comma (a generic with two parameters, say) must be wrapped in
15/// parentheses.
16///
17/// **Size.** The macro takes items that are a single token (`1`, `"s"`,
18/// `x`, `null`, a nested `[...]` or `{...}`) up to thirty-two at a time, and
19/// members with a string-literal key and a single-token value up to sixteen
20/// at a time, so literals of thousands of such items expand within the
21/// default `recursion_limit` (the tests check 2,000 array items and 1,000
22/// members). Two-token array items (a negative number) go eight at a time.
23/// Anything longer (`a + b`, `x.len()`, a member with a computed key or a
24/// longer value) costs one level of recursion per token, so a literal holds
25/// a few dozen of those at the default limit; build larger values in code.
26///
27/// # Examples
28///
29/// ```
30/// use jsonx_lib::json;
31///
32/// let id = 7;
33/// let method = String::from("textDocument/hover");
34/// let field = "line";
35/// let msg = json!({
36///     "jsonrpc": "2.0",
37///     "id": id,
38///     "method": method,
39///     "params": { "position": { (field): 3, "character": 1 + 1 } },
40///     "flags": [true, null, -1.5],
41/// });
42/// assert_eq!(
43///     msg.to_string(),
44///     r#"{"jsonrpc":"2.0","id":7,"method":"textDocument/hover","params":{"position":{"line":3,"character":2}},"flags":[true,null,-1.5]}"#
45/// );
46/// ```
47#[macro_export]
48macro_rules! json {
49    ($($tt:tt)+) => {
50        $crate::__json_value!($($tt)+)
51    };
52}
53
54/// Implementation detail of [`json!`].
55#[doc(hidden)]
56#[macro_export]
57macro_rules! __json_value {
58    (null) => {
59        $crate::Value::Null
60    };
61    (true) => {
62        $crate::Value::Bool(true)
63    };
64    (false) => {
65        $crate::Value::Bool(false)
66    };
67    ([]) => {
68        $crate::Value::Array($crate::Array::new())
69    };
70    ([ $($tt:tt)+ ]) => {
71        $crate::Value::Array($crate::Array::from(
72            $crate::__json_array!([] [] $($tt)+)
73        ))
74    };
75    ({}) => {
76        $crate::Value::Object($crate::Object::new())
77    };
78    ({ $($tt:tt)+ }) => {
79        $crate::Value::Object($crate::Object::from(
80            $crate::__json_object!([] $($tt)+)
81        ))
82    };
83    ($other:expr) => {
84        $crate::Value::from($other)
85    };
86}
87
88/// Implementation detail of [`json!`]: munches array items, splitting at
89/// top-level commas. State: `[done items] [tokens of the current item] rest`.
90#[doc(hidden)]
91#[macro_export]
92macro_rules! __json_array {
93    // The end, after a trailing comma or with nothing pending.
94    ([$($done:expr,)*] []) => {
95        $crate::__private::vec![$($done,)*]
96    };
97    // Thirty-two single-token items at once, when nothing is pending.
98    ([$($done:expr,)*] [] $a0:tt , $a1:tt , $a2:tt , $a3:tt , $a4:tt , $a5:tt , $a6:tt , $a7:tt , $a8:tt , $a9:tt , $a10:tt , $a11:tt , $a12:tt , $a13:tt , $a14:tt , $a15:tt , $a16:tt , $a17:tt , $a18:tt , $a19:tt , $a20:tt , $a21:tt , $a22:tt , $a23:tt , $a24:tt , $a25:tt , $a26:tt , $a27:tt , $a28:tt , $a29:tt , $a30:tt , $a31:tt , $($rest:tt)*) => {
99        $crate::__json_array!([$($done,)*
100            $crate::__json_value!($a0),
101            $crate::__json_value!($a1),
102            $crate::__json_value!($a2),
103            $crate::__json_value!($a3),
104            $crate::__json_value!($a4),
105            $crate::__json_value!($a5),
106            $crate::__json_value!($a6),
107            $crate::__json_value!($a7),
108            $crate::__json_value!($a8),
109            $crate::__json_value!($a9),
110            $crate::__json_value!($a10),
111            $crate::__json_value!($a11),
112            $crate::__json_value!($a12),
113            $crate::__json_value!($a13),
114            $crate::__json_value!($a14),
115            $crate::__json_value!($a15),
116            $crate::__json_value!($a16),
117            $crate::__json_value!($a17),
118            $crate::__json_value!($a18),
119            $crate::__json_value!($a19),
120            $crate::__json_value!($a20),
121            $crate::__json_value!($a21),
122            $crate::__json_value!($a22),
123            $crate::__json_value!($a23),
124            $crate::__json_value!($a24),
125            $crate::__json_value!($a25),
126            $crate::__json_value!($a26),
127            $crate::__json_value!($a27),
128            $crate::__json_value!($a28),
129            $crate::__json_value!($a29),
130            $crate::__json_value!($a30),
131            $crate::__json_value!($a31),
132        ] [] $($rest)*)
133    };
134    // Eight single-token items at once, when nothing is pending.
135    ([$($done:expr,)*] [] $a:tt , $b:tt , $c:tt , $d:tt , $e:tt , $f:tt , $g:tt , $h:tt , $($rest:tt)*) => {
136        $crate::__json_array!([$($done,)*
137            $crate::__json_value!($a), $crate::__json_value!($b),
138            $crate::__json_value!($c), $crate::__json_value!($d),
139            $crate::__json_value!($e), $crate::__json_value!($f),
140            $crate::__json_value!($g), $crate::__json_value!($h),
141        ] [] $($rest)*)
142    };
143    // One single-token item, when nothing is pending.
144    ([$($done:expr,)*] [] $a:tt , $($rest:tt)*) => {
145        $crate::__json_array!([$($done,)* $crate::__json_value!($a),] [] $($rest)*)
146    };
147    // The end, with the last item pending.
148    ([$($done:expr,)*] [$($item:tt)+]) => {
149        $crate::__private::vec![$($done,)* $crate::__json_value!($($item)+)]
150    };
151    // Eight two-token items (negative numbers) at once.
152    ([$($done:expr,)*] [] $a0:tt $b0:tt , $a1:tt $b1:tt , $a2:tt $b2:tt , $a3:tt $b3:tt , $a4:tt $b4:tt , $a5:tt $b5:tt , $a6:tt $b6:tt , $a7:tt $b7:tt , $($rest:tt)*) => {
153        $crate::__json_array!([$($done,)*
154            $crate::__json_value!($a0 $b0),
155            $crate::__json_value!($a1 $b1),
156            $crate::__json_value!($a2 $b2),
157            $crate::__json_value!($a3 $b3),
158            $crate::__json_value!($a4 $b4),
159            $crate::__json_value!($a5 $b5),
160            $crate::__json_value!($a6 $b6),
161            $crate::__json_value!($a7 $b7),
162        ] [] $($rest)*)
163    };
164    // One two-token item.
165    ([$($done:expr,)*] [] $a:tt $b:tt , $($rest:tt)*) => {
166        $crate::__json_array!([$($done,)* $crate::__json_value!($a $b),] [] $($rest)*)
167    };
168    // A comma ends the pending item.
169    ([$($done:expr,)*] [$($item:tt)+] , $($rest:tt)*) => {
170        $crate::__json_array!([$($done,)* $crate::__json_value!($($item)+),] [] $($rest)*)
171    };
172    // Any other token joins the pending item.
173    ([$($done:expr,)*] [$($item:tt)*] $next:tt $($rest:tt)*) => {
174        $crate::__json_array!([$($done,)*] [$($item)* $next] $($rest)*)
175    };
176}
177
178/// Implementation detail of [`json!`]: munches object members. A key is a
179/// literal or a parenthesized expression, then `:`, then the value's tokens up
180/// to a top-level comma.
181#[doc(hidden)]
182#[macro_export]
183macro_rules! __json_object {
184    // The end.
185    ([$($done:expr,)*]) => {
186        $crate::__private::vec![$($done,)*]
187    };
188    // Sixteen members with literal keys and single-token values at once.
189    ([$($done:expr,)*] $k0:literal : $v0:tt , $k1:literal : $v1:tt , $k2:literal : $v2:tt , $k3:literal : $v3:tt , $k4:literal : $v4:tt , $k5:literal : $v5:tt , $k6:literal : $v6:tt , $k7:literal : $v7:tt , $k8:literal : $v8:tt , $k9:literal : $v9:tt , $k10:literal : $v10:tt , $k11:literal : $v11:tt , $k12:literal : $v12:tt , $k13:literal : $v13:tt , $k14:literal : $v14:tt , $k15:literal : $v15:tt , $($rest:tt)*) => {
190        $crate::__json_object!([$($done,)*
191            $crate::__private::member($k0, $crate::__json_value!($v0)),
192            $crate::__private::member($k1, $crate::__json_value!($v1)),
193            $crate::__private::member($k2, $crate::__json_value!($v2)),
194            $crate::__private::member($k3, $crate::__json_value!($v3)),
195            $crate::__private::member($k4, $crate::__json_value!($v4)),
196            $crate::__private::member($k5, $crate::__json_value!($v5)),
197            $crate::__private::member($k6, $crate::__json_value!($v6)),
198            $crate::__private::member($k7, $crate::__json_value!($v7)),
199            $crate::__private::member($k8, $crate::__json_value!($v8)),
200            $crate::__private::member($k9, $crate::__json_value!($v9)),
201            $crate::__private::member($k10, $crate::__json_value!($v10)),
202            $crate::__private::member($k11, $crate::__json_value!($v11)),
203            $crate::__private::member($k12, $crate::__json_value!($v12)),
204            $crate::__private::member($k13, $crate::__json_value!($v13)),
205            $crate::__private::member($k14, $crate::__json_value!($v14)),
206            $crate::__private::member($k15, $crate::__json_value!($v15)),
207        ] $($rest)*)
208    };
209    // Four members with literal keys and single-token values at once.
210    ([$($done:expr,)*] $k1:literal : $v1:tt , $k2:literal : $v2:tt , $k3:literal : $v3:tt , $k4:literal : $v4:tt , $($rest:tt)*) => {
211        $crate::__json_object!([$($done,)*
212            $crate::__private::member($k1, $crate::__json_value!($v1)),
213            $crate::__private::member($k2, $crate::__json_value!($v2)),
214            $crate::__private::member($k3, $crate::__json_value!($v3)),
215            $crate::__private::member($k4, $crate::__json_value!($v4)),
216        ] $($rest)*)
217    };
218    // One such member.
219    ([$($done:expr,)*] $k:literal : $v:tt , $($rest:tt)*) => {
220        $crate::__json_object!([$($done,)* $crate::__private::member($k, $crate::__json_value!($v)),] $($rest)*)
221    };
222    // The last such member, without a trailing comma.
223    ([$($done:expr,)*] $k:literal : $v:tt) => {
224        $crate::__json_object!([$($done,)* $crate::__private::member($k, $crate::__json_value!($v)),])
225    };
226    // A key; start collecting its value.
227    ([$($done:expr,)*] $key:literal : $($rest:tt)+) => {
228        $crate::__json_member!([$($done,)*] ($key) [] $($rest)+)
229    };
230    ([$($done:expr,)*] ($key:expr) : $($rest:tt)+) => {
231        $crate::__json_member!([$($done,)*] ($key) [] $($rest)+)
232    };
233}
234
235/// Implementation detail of [`json!`]: collects one member's value.
236#[doc(hidden)]
237#[macro_export]
238macro_rules! __json_member {
239    // The last member, without a trailing comma.
240    ([$($done:expr,)*] ($key:expr) [$($value:tt)+]) => {
241        $crate::__json_object!([$($done,)* $crate::__private::member($key, $crate::__json_value!($($value)+)),])
242    };
243    // A comma ends the value.
244    ([$($done:expr,)*] ($key:expr) [$($value:tt)+] , $($rest:tt)*) => {
245        $crate::__json_object!([$($done,)* $crate::__private::member($key, $crate::__json_value!($($value)+)),] $($rest)*)
246    };
247    // Any other token joins the value.
248    ([$($done:expr,)*] ($key:expr) [$($value:tt)*] $next:tt $($rest:tt)*) => {
249        $crate::__json_member!([$($done,)*] ($key) [$($value)* $next] $($rest)*)
250    };
251}
252
253/// Implements [`ToJson`](crate::ToJson) and [`FromJson`](crate::FromJson)
254/// for a struct whose fields map one to one onto object members.
255///
256/// The macro writes exactly the hand implementation the
257/// [`FromJson`](crate::FromJson) docs show, nothing more: each field listed
258/// is a member, keyed by the field's name or by the string given after a
259/// colon (`new_text: "newText"`). It is a `macro_rules!` macro over the list
260/// you write, not a derive: no attribute, no reflection, and every key is in
261/// your source.
262///
263/// - **Reading:** members in any order; unknown members skipped (and
264///   validated); a repeated field refused
265///   ([`DecodeErrorKind::DuplicateField`](crate::DecodeErrorKind::DuplicateField));
266///   a missing field refused
267///   ([`DecodeErrorKind::MissingField`](crate::DecodeErrorKind::MissingField))
268///   unless its type allows absence: an `Option<T>` field reads as `None`,
269///   a [`Nullable<T>`](crate::Nullable) as `Absent`.
270/// - **Writing:** members in the order listed; an `Option<T>` field that is
271///   `None` (or a `Nullable` that is `Absent`) is left out, which is
272///   TypeScript's `key?: T` as LSP and MCP use it.
273///
274/// For a struct with a lifetime (to borrow strings from the input), name it:
275/// `json_struct!(Name<'a> { ... })`. For anything else (renamed variants,
276/// defaults, validation, enums), write the impls by hand.
277///
278/// # Examples
279///
280/// ```
281/// use std::borrow::Cow;
282/// use jsonx_lib::json_struct;
283///
284/// #[derive(Debug, PartialEq)]
285/// struct Position { line: u32, character: u32 }
286/// json_struct!(Position { line, character });
287///
288/// #[derive(Debug, PartialEq)]
289/// struct TextEdit<'a> { range: [Position; 2], new_text: Cow<'a, str>, label: Option<String> }
290/// json_struct!(TextEdit<'a> { range, new_text: "newText", label });
291///
292/// let text = r#"{"newText": "x", "range": [{"line": 1, "character": 0}, {"line": 1, "character": 3}]}"#;
293/// let edit: TextEdit = jsonx_lib::from_str(text)?;
294/// assert_eq!(edit.new_text, "x");
295/// assert_eq!(edit.label, None);
296/// assert_eq!(
297///     jsonx_lib::to_string(&edit),
298///     r#"{"range":[{"line":1,"character":0},{"line":1,"character":3}],"newText":"x"}"#
299/// );
300/// # Ok::<(), jsonx_lib::DecodeError>(())
301/// ```
302#[macro_export]
303macro_rules! json_struct {
304    ($name:ident { $($field:ident $(: $key:literal)?),* $(,)? }) => {
305        impl $crate::ToJson for $name {
306            $crate::__json_struct_to_json!($($field $(: $key)?),*);
307        }
308        impl<'de> $crate::FromJson<'de> for $name {
309            $crate::__json_struct_from_json!('de; $($field $(: $key)?),*);
310        }
311    };
312    ($name:ident < $lt:lifetime > { $($field:ident $(: $key:literal)?),* $(,)? }) => {
313        impl<$lt> $crate::ToJson for $name<$lt> {
314            $crate::__json_struct_to_json!($($field $(: $key)?),*);
315        }
316        impl<$lt> $crate::FromJson<$lt> for $name<$lt> {
317            $crate::__json_struct_from_json!($lt; $($field $(: $key)?),*);
318        }
319    };
320}
321
322/// Implementation detail of [`json_struct!`]: a field's key.
323#[doc(hidden)]
324#[macro_export]
325macro_rules! __json_struct_key {
326    ($field:ident) => {
327        ::core::stringify!($field)
328    };
329    ($field:ident : $key:literal) => {
330        $key
331    };
332}
333
334/// Implementation detail of [`json_struct!`]: `ToJson::to_json`.
335#[doc(hidden)]
336#[macro_export]
337macro_rules! __json_struct_to_json {
338    ($($field:ident $(: $key:literal)?),*) => {
339        fn to_json(&self, out: $crate::ValueWriter<'_>) -> $crate::Written {
340            out.object(|object| {
341                $(object.optional($crate::__json_struct_key!($field $(: $key)?), &self.$field);)*
342            })
343        }
344    };
345}
346
347/// Implementation detail of [`json_struct!`]: `FromJson::from_json`.
348#[doc(hidden)]
349#[macro_export]
350macro_rules! __json_struct_from_json {
351    ($lt:lifetime; $($field:ident $(: $key:literal)?),*) => {
352        fn from_json(
353            reader: &mut $crate::Reader<$lt>,
354        ) -> ::core::result::Result<Self, $crate::DecodeError> {
355            $(let mut $field = ::core::option::Option::None;)*
356            let mut object = reader.read_object()?;
357            while let ::core::option::Option::Some(key) = object.next_key()? {
358                match &*key {
359                    $($crate::__json_struct_key!($field $(: $key)?) => object.field(&mut $field)?,)*
360                    _ => {}
361                }
362            }
363            ::core::result::Result::Ok(Self {
364                $($field: object.required($field, $crate::__json_struct_key!($field $(: $key)?))?,)*
365            })
366        }
367    };
368}
369
370#[cfg(test)]
371mod tests {
372    use alloc::string::{String, ToString};
373
374    use crate::Value;
375
376    #[test]
377    fn test_json_macro_mixes_fast_and_slow_items() {
378        let n = 4;
379        let v = json!([1, 2, 3, 4, 5, 6, 7, 8, -9, n, n + 1, "s", null, [true, false], { "a": -1 }, 10]);
380        assert_eq!(
381            v.to_string(),
382            r#"[1,2,3,4,5,6,7,8,-9,4,5,"s",null,[true,false],{"a":-1},10]"#
383        );
384        let key = "k";
385        let o = json!({ "a": 1, "b": [2], "c": { "d": null }, "e": n, (key): -n, "f": n * 2, "g": "x" });
386        assert_eq!(
387            o.to_string(),
388            r#"{"a":1,"b":[2],"c":{"d":null},"e":4,"k":-4,"f":8,"g":"x"}"#
389        );
390    }
391
392    #[test]
393    fn test_json_macro_shapes() {
394        assert_eq!(json!(null), Value::Null);
395        assert_eq!(json!([]).to_string(), "[]");
396        assert_eq!(json!({}).to_string(), "{}");
397        assert_eq!(json!([1, [2, [3]], {}]).to_string(), "[1,[2,[3]],{}]");
398        assert_eq!(json!([1,]).to_string(), "[1]");
399        assert_eq!(json!({ "a": 1, }).to_string(), r#"{"a":1}"#);
400        assert_eq!(json!(-5).to_string(), "-5");
401        assert_eq!(json!([-5, -6]).to_string(), "[-5,-6]");
402        let key = String::from("k");
403        assert_eq!(
404            json!({ (key.clone()): [key.as_str()] }).to_string(),
405            r#"{"k":["k"]}"#
406        );
407        let none: Option<i32> = None;
408        assert_eq!(json!([none, Some(2)]).to_string(), "[null,2]");
409        assert_eq!(
410            json!({ "a": { "b": { "c": [null, true, false] } } }).to_string(),
411            r#"{"a":{"b":{"c":[null,true,false]}}}"#
412        );
413        assert_eq!(json!({ "f": 0.5 }).to_string(), r#"{"f":0.5}"#);
414    }
415}