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
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![doc = include_str!("../README.md")]

#[cfg(feature = "json")]
pub use merde_json as json;

#[cfg(feature = "json")]
#[allow(unused_imports)]
use json::JsonSerialize;

#[cfg(feature = "time")]
pub use merde_time as time;

#[cfg(feature = "core")]
pub use merde_core::*;

#[doc(hidden)]
#[macro_export]
macro_rules! impl_value_deserialize {
    ($struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        #[cfg(feature = "deserialize")]
        #[automatically_derived]
        impl<$lifetime> $crate::ValueDeserialize<$lifetime> for $struct_name<$lifetime>
        {
            fn from_value_ref<'val>(
                value: Option<&'val $crate::Value<$lifetime>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let obj = value.ok_or(MerdeError::MissingValue)?.as_map()?;
                Ok($struct_name {
                    $($field: obj.must_get(stringify!($field))?,)+
                })
            }

            fn from_value(
                value: Option<$crate::Value<$lifetime>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut obj = value.ok_or(MerdeError::MissingValue)?.into_map()?;
                Ok($struct_name {
                    $($field: obj.must_remove(stringify!($field))?,)+
                })
            }
        }
    };

    ($struct_name:ident { $($field:ident),+ }) => {
        #[cfg(feature = "deserialize")]
        #[automatically_derived]
        impl<'s> $crate::ValueDeserialize<'s> for $struct_name
        {
            fn from_value_ref(
                value: Option<&$crate::Value<'_>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let obj = value.ok_or(MerdeError::MissingValue)?.as_map()?;
                Ok($struct_name {
                    $($field: obj.must_get(stringify!($field))?,)+
                })
            }

            fn from_value(
                value: Option<$crate::Value<'_>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut obj = value.ok_or(MerdeError::MissingValue)?.into_map()?;
                Ok($struct_name {
                    $($field: obj.must_remove(stringify!($field))?,)+
                })
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_into_static {
    ($struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        #[cfg(feature = "core")]
        #[automatically_derived]
        impl<$lifetime> $crate::IntoStatic for $struct_name<$lifetime> {
            type Output = $struct_name<'static>;

            fn into_static(self) -> Self::Output {
                #[allow(unused_imports)]
                use $crate::IntoStatic;

                $struct_name {
                    $($field: self.$field.into_static(),)+
                }
            }
        }
    };

    ($struct_name:ident { $($field:ident),+ }) => {
        #[cfg(feature = "core")]
        #[automatically_derived]
        impl $crate::IntoStatic for $struct_name {
            type Output = $struct_name;

            #[inline(always)]
            fn into_static(self) -> Self::Output {
                self
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_json_serialize {
    ($struct_name:ident < $lifetime:lifetime > { $($field:ident),+ }) => {
        #[cfg(all(feature = "core", feature = "json"))]
        #[automatically_derived]
        impl<$lifetime> $crate::json::JsonSerialize for $struct_name<$lifetime> {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut guard = serializer.write_obj();
                $(
                    guard.pair(stringify!($field), &self.$field);
                )+
            }
        }
    };

    ($struct_name:ident { $($field:ident),+ }) => {
        #[cfg(all(feature = "core", feature = "json"))]
        #[automatically_derived]
        impl $crate::json::JsonSerialize for $struct_name {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut guard = serializer.write_obj();
                $(
                    guard.pair(stringify!($field), &self.$field);
                )+
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_trait {
    // borrowed
    (@impl JsonSerialize, $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::impl_json_serialize!($struct_name <$lifetime> { $($field),+ });
    };
    // owned
    (@impl JsonSerialize, $struct_name:ident { $($field:ident),+ }) => {
        $crate::impl_json_serialize!($struct_name { $($field),+ });
    };

    // with lifetime param
    (@impl ValueDeserialize, $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::impl_value_deserialize!($struct_name <$lifetime> { $($field),+ });
    };
    // l
    (@impl ValueDeserialize, $struct_name:ident { $($field:ident),+ }) => {
        $crate::impl_value_deserialize!($struct_name { $($field),+ });
    };

    // with lifetime param
    (@impl IntoStatic, $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::impl_into_static!($struct_name <$lifetime> { $($field),+ });
    };
    // without lifetime param
    (@impl IntoStatic, $struct_name:ident { $($field:ident),+ }) => {
        $crate::impl_into_static!($struct_name { $($field),+ });
    };
}

/// Derives the specified traits for a struct.
///
/// This macro can be used to generate implementations of [`JsonSerialize`], [`ValueDeserialize`],
/// and [`IntoStatic`] traits for a given struct.
///
/// # Usage
///
/// ```rust
/// use merde::ValueDeserialize;
/// use merde::CowStr;
/// use merde::json::JsonSerialize;
///
/// #[derive(Debug, PartialEq)]
/// struct MyStruct<'s> {
///     field1: CowStr<'s>,
///     field2: i32,
///     field3: bool,
/// }
///
/// merde::derive! {
///     impl(JsonSerialize, ValueDeserialize, IntoStatic) for MyStruct<'s> {
///         field1,
///         field2,
///         field3
///     }
/// }
/// ```
///
/// In this example, all three traits are derived, of course you can omit the ones you don't need.
///
/// The struct must have exactly one lifetime parameter. Additionally, even if there are no
/// borrowed fields, the struct must include a `_phantom` field of type `PhantomData<&'a ()>`,
/// where `'a` is the lifetime parameter.
///
/// Implementing other variants (no lifetimes, multiple lifetimes, etc.) with declarative macros
/// would be too complicated. At this point we'd want a whole parser / compiler / code generator
/// for this — or a proc macro, see [serde](https://serde.rs/)'s serde_derive.
#[macro_export]
macro_rules! derive {
    // cow variants
    (impl($($trait:ident),+) for $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::derive!(@step1 { $($trait),+ } $struct_name <$lifetime> { $($field),+ });
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } $struct_name:ident <$lifetime:lifetime> $fields:tt) => {
        $crate::impl_trait!(@impl $trait, $struct_name <$lifetime> $fields);
        $crate::derive!(@step1 { $($rest_traits),* } $struct_name <$lifetime> $fields);
    };
    (@step1 { $trait:ident } $struct_name:ident <$lifetime:lifetime> $fields:tt) => {
        $crate::impl_trait!(@impl $trait, $struct_name <$lifetime> $fields);
    };
    (@step1 { } $struct_name:ident <$lifetime:lifetime> $fields:tt) => {};

    // owned variants
    (impl($($trait:ident),+) for $struct_name:ident { $($field:ident),+ }) => {
        $crate::derive!(@step1 { $($trait),+ } $struct_name { $($field),+ });
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } $struct_name:ident $fields:tt) => {
        $crate::impl_trait!(@impl $trait, $struct_name $fields);
        $crate::derive!(@step1 { $($rest_traits),* } $struct_name $fields);
    };
    (@step1 { $trait:ident } $struct_name:ident $fields:tt) => {
        $crate::impl_trait!(@impl $trait, $struct_name $fields);
    };
    (@step1 { } $struct_name:ident $fields:tt) => {};
}

#[cfg(test)]
#[cfg(feature = "json")]
mod json_tests {
    use super::*;
    use crate::json::{from_str_via_value, JsonSerialize};

    #[test]
    fn test_complex_structs() {
        use std::borrow::Cow;
        use std::collections::HashMap;

        #[derive(Debug, PartialEq)]
        struct SecondStruct<'s> {
            string_field: Cow<'s, str>,
            int_field: i32,
        }

        derive! {
            impl(JsonSerialize, ValueDeserialize) for SecondStruct<'s> {
                string_field,
                int_field
            }
        }

        #[derive(Debug, PartialEq)]
        struct ComplexStruct<'s> {
            string_field: Cow<'s, str>,
            u8_field: u8,
            u16_field: u16,
            u32_field: u32,
            u64_field: u64,
            i8_field: i8,
            i16_field: i16,
            i32_field: i32,
            i64_field: i64,
            usize_field: usize,
            bool_field: bool,
            option_field: Option<i32>,
            vec_field: Vec<i32>,
            hashmap_field: HashMap<String, i32>,
            second_struct_field: SecondStruct<'s>,
        }

        derive! {
            impl(JsonSerialize, ValueDeserialize) for ComplexStruct<'s> {
                string_field,
                u8_field,
                u16_field,
                u32_field,
                u64_field,
                i8_field,
                i16_field,
                i32_field,
                i64_field,
                usize_field,
                bool_field,
                option_field,
                vec_field,
                hashmap_field,
                second_struct_field
            }
        }

        let mut hashmap = HashMap::new();
        hashmap.insert("key".to_string(), 42);

        let original = ComplexStruct {
            string_field: Cow::Borrowed("test string"),
            u8_field: 8,
            u16_field: 16,
            u32_field: 32,
            u64_field: 64,
            i8_field: -8,
            i16_field: -16,
            i32_field: -32,
            i64_field: -64,
            usize_field: 100,
            bool_field: true,
            option_field: Some(42),
            vec_field: vec![1, 2, 3],
            hashmap_field: hashmap,
            second_struct_field: SecondStruct {
                string_field: Cow::Borrowed("nested string"),
                int_field: 100,
            },
        };

        let serialized = original.to_json_string();
        let deserialized: ComplexStruct = from_str_via_value(&serialized).unwrap();

        assert_eq!(original, deserialized);
    }
}

// used to test out doc-tests
mod doctest_playground {
    #[allow(unused_imports)]
    use crate as merde;

    ////////////////////////////////////////////////////////////////////////////////

    // (insert doctest here for testing)

    ////////////////////////////////////////////////////////////////////////////////
}