platform_value/
macros.rs

1/// Construct a `serde_platform_value::Value` from a JSON literal.
2///
3/// ```
4/// # use platform_value::platform_value;
5/// #
6/// let value = platform_value!({
7///     "code": 200,
8///     "success": true,
9///     "payload": {
10///         "features": [
11///             "serde",
12///             "platform_value"
13///         ]
14///     }
15/// });
16/// ```
17///
18/// Variables or expressions can be interpolated into the JSON literal. Any type
19/// interpolated into an array element or object value must implement Serde's
20/// `Serialize` trait, while any type interpolated into a object key must
21/// implement `Into<String>`. If the `Serialize` implementation of the
22/// interpolated type decides to fail, or if the interpolated type contains a
23/// map with non-string keys, the `platform_value!` macro will panic.
24///
25/// ```
26/// # use platform_value::platform_value;
27/// #
28/// let code = 200;
29/// let features = vec!["serde", "platform_value"];
30///
31/// let value = platform_value!({
32///     "code": code,
33///     "success": code == 200,
34///     "payload": {
35///         features[0]: features[1]
36///     }
37/// });
38/// ```
39///
40/// Trailing commas are allowed inside both arrays and objects.
41///
42/// ```
43/// # use platform_value::platform_value;
44/// #
45/// let value = platform_value!([
46///     "notice",
47///     "the",
48///     "trailing",
49///     "comma -->",
50/// ]);
51/// ```
52#[macro_export(local_inner_macros)]
53macro_rules! platform_value {
54    // Hide distracting implementation details from the generated rustdoc.
55    ($($platform_value:tt)+) => {
56        platform_value_internal!($($platform_value)+)
57    };
58}
59
60// Changes are fine as long as `platform_value_internal!` does not call any new helper
61// macros and can still be invoked as `platform_value_internal!($($platform_value)+)`.
62#[macro_export(local_inner_macros)]
63#[doc(hidden)]
64macro_rules! platform_value_internal {
65    //////////////////////////////////////////////////////////////////////////
66    // TT muncher for parsing the inside of an array [...]. Produces a vec![...]
67    // of the elements.
68    //
69    // Must be invoked as: platform_value_internal!(@array [] $($tt)*)
70    //////////////////////////////////////////////////////////////////////////
71
72    // Done with trailing comma.
73    (@array [$($elems:expr,)*]) => {
74        platform_value_internal_vec![$($elems,)*]
75    };
76
77    // Done without trailing comma.
78    (@array [$($elems:expr),*]) => {
79        platform_value_internal_vec![$($elems),*]
80    };
81
82    // Next element is `null`.
83    (@array [$($elems:expr,)*] null $($rest:tt)*) => {
84        platform_value_internal!(@array [$($elems,)* platform_value_internal!(null)] $($rest)*)
85    };
86
87    // Next element is `true`.
88    (@array [$($elems:expr,)*] true $($rest:tt)*) => {
89        platform_value_internal!(@array [$($elems,)* platform_value_internal!(true)] $($rest)*)
90    };
91
92    // Next element is `false`.
93    (@array [$($elems:expr,)*] false $($rest:tt)*) => {
94        platform_value_internal!(@array [$($elems,)* platform_value_internal!(false)] $($rest)*)
95    };
96
97    // Next element is an array.
98    (@array [$($elems:expr,)*] [$($array:tt)*] $($rest:tt)*) => {
99        platform_value_internal!(@array [$($elems,)* platform_value_internal!([$($array)*])] $($rest)*)
100    };
101
102    // Next element is a map.
103    (@array [$($elems:expr,)*] {$($map:tt)*} $($rest:tt)*) => {
104        platform_value_internal!(@array [$($elems,)* platform_value_internal!({$($map)*})] $($rest)*)
105    };
106
107    // Next element is an expression followed by comma.
108    (@array [$($elems:expr,)*] $next:expr, $($rest:tt)*) => {
109        platform_value_internal!(@array [$($elems,)* platform_value_internal!($next),] $($rest)*)
110    };
111
112    // Last element is an expression with no trailing comma.
113    (@array [$($elems:expr,)*] $last:expr) => {
114        platform_value_internal!(@array [$($elems,)* platform_value_internal!($last)])
115    };
116
117    // Comma after the most recent element.
118    (@array [$($elems:expr),*] , $($rest:tt)*) => {
119        platform_value_internal!(@array [$($elems,)*] $($rest)*)
120    };
121
122    // Unexpected token after most recent element.
123    (@array [$($elems:expr),*] $unexpected:tt $($rest:tt)*) => {
124        platform_value_unexpected!($unexpected)
125    };
126
127    //////////////////////////////////////////////////////////////////////////
128    // TT muncher for parsing the inside of an object {...}. Each entry is
129    // inserted into the given map variable.
130    //
131    // Must be invoked as: platform_value_internal!(@object $map () ($($tt)*) ($($tt)*))
132    //
133    // We require two copies of the input tokens so that we can match on one
134    // copy and trigger errors on the other copy.
135    //////////////////////////////////////////////////////////////////////////
136
137    // Done.
138    (@object $object:ident () () ()) => {};
139
140    // Insert the current entry followed by trailing comma.
141    (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => {
142        let _ = $object.push((($($key)+).into(), $value));
143        platform_value_internal!(@object $object () ($($rest)*) ($($rest)*));
144    };
145
146    // Current entry followed by unexpected token.
147    (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($rest:tt)*) => {
148        platform_value_unexpected!($unexpected);
149    };
150
151    // Insert the last entry without trailing comma.
152    (@object $object:ident [$($key:tt)+] ($value:expr)) => {
153        let _ = $object.push((($($key)+).into(), $value));
154    };
155
156    // Next value is `null`.
157    (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => {
158        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!(null)) $($rest)*);
159    };
160
161    // Next value is `true`.
162    (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => {
163        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!(true)) $($rest)*);
164    };
165
166    // Next value is `false`.
167    (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => {
168        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!(false)) $($rest)*);
169    };
170
171    // Next value is an array.
172    (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => {
173        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!([$($array)*])) $($rest)*);
174    };
175
176    // Next value is a map.
177    (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => {
178        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!({$($map)*})) $($rest)*);
179    };
180
181    // Next value is an expression followed by comma.
182    (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => {
183        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!($value)) , $($rest)*);
184    };
185
186    // Last value is an expression with no trailing comma.
187    (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => {
188        platform_value_internal!(@object $object [$($key)+] (platform_value_internal!($value)));
189    };
190
191    // Missing value for last entry. Trigger a reasonable error message.
192    (@object $object:ident ($($key:tt)+) (:) $copy:tt) => {
193        // "unexpected end of macro invocation"
194        platform_value_internal!();
195    };
196
197    // Missing colon and value for last entry. Trigger a reasonable error
198    // message.
199    (@object $object:ident ($($key:tt)+) () $copy:tt) => {
200        // "unexpected end of macro invocation"
201        platform_value_internal!();
202    };
203
204    // Misplaced colon. Trigger a reasonable error message.
205    (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => {
206        // Takes no arguments so "no rules expected the token `:`".
207        platform_value_unexpected!($colon);
208    };
209
210    // Found a comma inside a key. Trigger a reasonable error message.
211    (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => {
212        // Takes no arguments so "no rules expected the token `,`".
213        platform_value_unexpected!($comma);
214    };
215
216    // Key is fully parenthesized. This avoids clippy double_parens false
217    // positives because the parenthesization may be necessary here.
218    (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => {
219        platform_value_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*));
220    };
221
222    // Refuse to absorb colon token into key expression.
223    (@object $object:ident ($($key:tt)*) (: $($unexpected:tt)+) $copy:tt) => {
224        platform_value_expect_expr_comma!($($unexpected)+);
225    };
226
227    // Munch a token into the current key.
228    (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => {
229        platform_value_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*));
230    };
231
232    //////////////////////////////////////////////////////////////////////////
233    // The main implementation.
234    //
235    // Must be invoked as: platform_value_internal!($($platform_value)+)
236    //////////////////////////////////////////////////////////////////////////
237
238    (null) => {
239        $crate::Value::Null
240    };
241
242    (true) => {
243        $crate::Value::Bool(true)
244    };
245
246    (false) => {
247        $crate::Value::Bool(false)
248    };
249
250    ([]) => {
251        $crate::Value::Array(platform_value_internal_vec![])
252    };
253
254    ([ $($tt:tt)+ ]) => {
255        $crate::Value::Array(platform_value_internal!(@array [] $($tt)+))
256    };
257
258    ({}) => {
259        $crate::Value::Map($crate::ValueMap::new())
260    };
261
262    ({ $($tt:tt)+ }) => {
263        $crate::Value::Map({
264            let mut object = $crate::ValueMap::new();
265            platform_value_internal!(@object object () ($($tt)+) ($($tt)+));
266            object
267        })
268    };
269
270    // Any Serialize type: numbers, strings, struct literals, variables etc.
271    // Must be below every other rule.
272    ($other:expr) => {
273        $crate::to_value(&$other).unwrap()
274    };
275}
276
277// The platform_value_internal macro above cannot invoke vec directly because it uses
278// local_inner_macros. A vec invocation there would resolve to $crate::vec.
279// Instead invoke vec here outside of local_inner_macros.
280#[macro_export]
281#[doc(hidden)]
282macro_rules! platform_value_internal_vec {
283    ($($content:tt)*) => {
284        vec![$($content)*]
285    };
286}
287
288#[macro_export]
289#[doc(hidden)]
290macro_rules! platform_value_unexpected {
291    () => {};
292}
293
294#[macro_export]
295#[doc(hidden)]
296macro_rules! platform_value_expect_expr_comma {
297    ($e:expr , $($tt:tt)*) => {};
298}
299
300#[cfg(test)]
301mod test {
302    use crate::types::binary_data::BinaryData;
303    use crate::{to_value, Identifier, Value};
304
305    #[test]
306    fn test_null() {
307        let value = platform_value!(null);
308        assert_eq!(value, Value::Null)
309    }
310
311    #[test]
312    fn test_identity_is_kept() {
313        let id = Identifier::new([0; 32]);
314        let value = to_value(id).unwrap();
315        assert_eq!(value, Value::Identifier(id.to_buffer()));
316        let value = platform_value!(id);
317        assert_eq!(value, Value::Identifier(id.to_buffer()))
318    }
319
320    #[test]
321    fn test_binary_is_kept() {
322        let id = BinaryData::new([0; 44].to_vec());
323        let value = to_value(id.clone()).unwrap();
324        assert_eq!(value, Value::Bytes(id.to_vec()));
325        let value = platform_value!(id);
326        assert_eq!(value, Value::Bytes(id.to_vec()));
327    }
328}