Skip to main content

jsonx_lib/
macros.rs

1//! The `json!` macro.
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. Each item costs the compiler a few levels of macro
16/// recursion, so a very long literal may need `#![recursion_limit]` raised;
17/// build large values in code instead.
18///
19/// # Examples
20///
21/// ```
22/// use jsonx_lib::json;
23///
24/// let id = 7;
25/// let method = String::from("textDocument/hover");
26/// let field = "line";
27/// let msg = json!({
28///     "jsonrpc": "2.0",
29///     "id": id,
30///     "method": method,
31///     "params": { "position": { (field): 3, "character": 1 + 1 } },
32///     "flags": [true, null, -1.5],
33/// });
34/// assert_eq!(
35///     msg.to_string(),
36///     r#"{"jsonrpc":"2.0","id":7,"method":"textDocument/hover","params":{"position":{"line":3,"character":2}},"flags":[true,null,-1.5]}"#
37/// );
38/// ```
39#[macro_export]
40macro_rules! json {
41    ($($tt:tt)+) => {
42        $crate::__json_value!($($tt)+)
43    };
44}
45
46/// Implementation detail of [`json!`].
47#[doc(hidden)]
48#[macro_export]
49macro_rules! __json_value {
50    (null) => {
51        $crate::Value::Null
52    };
53    (true) => {
54        $crate::Value::Bool(true)
55    };
56    (false) => {
57        $crate::Value::Bool(false)
58    };
59    ([]) => {
60        $crate::Value::Array($crate::Array::new())
61    };
62    ([ $($tt:tt)+ ]) => {
63        $crate::Value::Array($crate::Array::from(
64            $crate::__json_array!([] [] $($tt)+)
65        ))
66    };
67    ({}) => {
68        $crate::Value::Object($crate::Object::new())
69    };
70    ({ $($tt:tt)+ }) => {
71        $crate::Value::Object($crate::Object::from(
72            $crate::__json_object!([] $($tt)+)
73        ))
74    };
75    ($other:expr) => {
76        $crate::Value::from($other)
77    };
78}
79
80/// Implementation detail of [`json!`]: munches array items, splitting at
81/// top-level commas. State: `[done items] [tokens of the current item] rest`.
82#[doc(hidden)]
83#[macro_export]
84macro_rules! __json_array {
85    // The end, after a trailing comma or with nothing pending.
86    ([$($done:expr,)*] []) => {
87        $crate::__private::vec![$($done,)*]
88    };
89    // The end, with the last item pending.
90    ([$($done:expr,)*] [$($item:tt)+]) => {
91        $crate::__private::vec![$($done,)* $crate::__json_value!($($item)+)]
92    };
93    // A comma ends the pending item.
94    ([$($done:expr,)*] [$($item:tt)+] , $($rest:tt)*) => {
95        $crate::__json_array!([$($done,)* $crate::__json_value!($($item)+),] [] $($rest)*)
96    };
97    // Any other token joins the pending item.
98    ([$($done:expr,)*] [$($item:tt)*] $next:tt $($rest:tt)*) => {
99        $crate::__json_array!([$($done,)*] [$($item)* $next] $($rest)*)
100    };
101}
102
103/// Implementation detail of [`json!`]: munches object members. A key is a
104/// literal or a parenthesized expression, then `:`, then the value's tokens up
105/// to a top-level comma.
106#[doc(hidden)]
107#[macro_export]
108macro_rules! __json_object {
109    // The end.
110    ([$($done:expr,)*]) => {
111        $crate::__private::vec![$($done,)*]
112    };
113    // A key; start collecting its value.
114    ([$($done:expr,)*] $key:literal : $($rest:tt)+) => {
115        $crate::__json_member!([$($done,)*] ($key) [] $($rest)+)
116    };
117    ([$($done:expr,)*] ($key:expr) : $($rest:tt)+) => {
118        $crate::__json_member!([$($done,)*] ($key) [] $($rest)+)
119    };
120}
121
122/// Implementation detail of [`json!`]: collects one member's value.
123#[doc(hidden)]
124#[macro_export]
125macro_rules! __json_member {
126    // The last member, without a trailing comma.
127    ([$($done:expr,)*] ($key:expr) [$($value:tt)+]) => {
128        $crate::__json_object!([$($done,)* $crate::__private::member($key, $crate::__json_value!($($value)+)),])
129    };
130    // A comma ends the value.
131    ([$($done:expr,)*] ($key:expr) [$($value:tt)+] , $($rest:tt)*) => {
132        $crate::__json_object!([$($done,)* $crate::__private::member($key, $crate::__json_value!($($value)+)),] $($rest)*)
133    };
134    // Any other token joins the value.
135    ([$($done:expr,)*] ($key:expr) [$($value:tt)*] $next:tt $($rest:tt)*) => {
136        $crate::__json_member!([$($done,)*] ($key) [$($value)* $next] $($rest)*)
137    };
138}
139
140#[cfg(test)]
141mod tests {
142    use alloc::string::{String, ToString};
143
144    use crate::Value;
145
146    #[test]
147    fn test_json_macro_shapes() {
148        assert_eq!(json!(null), Value::Null);
149        assert_eq!(json!([]).to_string(), "[]");
150        assert_eq!(json!({}).to_string(), "{}");
151        assert_eq!(json!([1, [2, [3]], {}]).to_string(), "[1,[2,[3]],{}]");
152        assert_eq!(json!([1,]).to_string(), "[1]");
153        assert_eq!(json!({ "a": 1, }).to_string(), r#"{"a":1}"#);
154        assert_eq!(json!(-5).to_string(), "-5");
155        assert_eq!(json!([-5, -6]).to_string(), "[-5,-6]");
156        let key = String::from("k");
157        assert_eq!(
158            json!({ (key.clone()): [key.as_str()] }).to_string(),
159            r#"{"k":["k"]}"#
160        );
161        let none: Option<i32> = None;
162        assert_eq!(json!([none, Some(2)]).to_string(), "[null,2]");
163        assert_eq!(
164            json!({ "a": { "b": { "c": [null, true, false] } } }).to_string(),
165            r#"{"a":{"b":{"c":[null,true,false]}}}"#
166        );
167        assert_eq!(json!({ "f": 0.5 }).to_string(), r#"{"f":0.5}"#);
168    }
169}