libipld_macro/
lib.rs

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