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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
#![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)]
#[cfg(feature = "deserialize")]
#[macro_export]
macro_rules! impl_value_deserialize {
    // owned tuple struct (transparent)
    (struct $struct_name:ident transparent) => {
        #[automatically_derived]
        impl<'s> $crate::ValueDeserialize<'s> for $struct_name {
            #[inline(always)]
            fn from_value_ref<'val>(
                value: Option<&'val $crate::Value<'s>>,
            ) -> Result<Self, $crate::MerdeError> {
                Ok($struct_name($crate::ValueDeserialize::from_value_ref(value)?))
            }

            #[inline(always)]
            fn from_value(
                value: Option<$crate::Value<'s>>,
            ) -> Result<Self, $crate::MerdeError> {
                Ok($struct_name($crate::ValueDeserialize::from_value(value)?))
            }
        }
    };

    // lifetimed tuple struct (transparent)
    (struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        #[automatically_derived]
        impl<$lifetime> $crate::ValueDeserialize<$lifetime> for $struct_name<$lifetime> {
            #[inline(always)]
            fn from_value_ref<'val>(
                value: Option<&'val $crate::Value<$lifetime>>,
            ) -> Result<Self, $crate::MerdeError> {
                Ok($struct_name($crate::ValueDeserialize::from_value_ref(value)?))
            }

            #[inline(always)]
            fn from_value(
                value: Option<$crate::Value<$lifetime>>,
            ) -> Result<Self, $crate::MerdeError> {
                Ok($struct_name($crate::ValueDeserialize::from_value(value)?))
            }
        }
    };

    // owned struct
    (struct $struct_name:ident { $($field:ident),+ }) => {
        #[automatically_derived]
        impl<'s> $crate::ValueDeserialize<'s> for $struct_name
        {
            fn from_value_ref(
                value: Option<&$crate::Value<'s>>,
            ) -> 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<'s>>,
            ) -> 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))?,)+
                })
            }
        }
    };

    // lifetimed struct
    (struct $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        #[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))?,)+
                })
            }
        }
    };

    // owned enum (externally tagged)
    (enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<'s> $crate::ValueDeserialize<'s> for $enum_name {
            fn from_value_ref(
                value: Option<&$crate::Value<'s>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let map = value.ok_or(MerdeError::MissingValue)?.as_map()?;
                let (key, val) = map.iter().next().ok_or(MerdeError::MissingValue)?;
                match key.as_ref() {
                    $($variant_str => Ok($enum_name::$variant($crate::ValueDeserialize::from_value_ref(Some(val))?)),)*
                    _ => Err(MerdeError::UnknownProperty(key.to_string())),
                }
            }

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

                let map = value.ok_or(MerdeError::MissingValue)?.into_map()?;
                let (key, val) = map.into_iter().next().ok_or(MerdeError::MissingValue)?;
                match key.as_ref() {
                    $($variant_str => Ok($enum_name::$variant($crate::ValueDeserialize::from_value(Some(val))?)),)*
                    _ => Err(MerdeError::UnknownProperty(key.to_string())),
                }
            }
        }
    };

    // lifetimed enum (externally tagged)
    (enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<$lifetime> $crate::ValueDeserialize<$lifetime> for $enum_name<$lifetime> {
            fn from_value_ref<'val>(
                value: Option<&'val $crate::Value<$lifetime>>,
            ) -> Result<Self, $crate::MerdeError> {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let map = value.ok_or(MerdeError::MissingValue)?.as_map()?;
                let (key, val) = map.iter().next().ok_or(MerdeError::MissingValue)?;
                match key.as_ref() {
                    $($variant_str => Ok($enum_name::$variant($crate::ValueDeserialize::from_value_ref(Some(val))?)),)*
                    _ => Err(MerdeError::UnknownProperty(key.to_string())),
                }
            }

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

                let map = value.ok_or(MerdeError::MissingValue)?.into_map()?;
                let (key, val) = map.into_iter().next().ok_or(MerdeError::MissingValue)?;
                match key.as_ref() {
                    $($variant_str => Ok($enum_name::$variant($crate::ValueDeserialize::from_value(Some(val))?)),)*
                    _ => Err(MerdeError::UnknownProperty(key.to_string())),
                }
            }
        }
    };
}

#[doc(hidden)]
#[cfg(not(feature = "deserialize"))]
#[macro_export]
macro_rules! impl_value_deserialize {
    ($($tt:tt)*) => {};
}

#[doc(hidden)]
#[macro_export]
#[cfg(feature = "core")]
macro_rules! impl_into_static {
    // owned tuple struct (transparent)
    (struct $struct_name:ident transparent) => {
        #[automatically_derived]
        impl $crate::IntoStatic for $struct_name {
            type Output = $struct_name;

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

    // lifetimed tuple struct (transparent)
    (struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        #[automatically_derived]
        impl<$lifetime> $crate::IntoStatic for $struct_name<$lifetime> {
            type Output = $struct_name<$lifetime>;

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

    // owned struct
    (struct $struct_name:ident { $($field:ident),+ }) => {
        #[automatically_derived]
        impl $crate::IntoStatic for $struct_name {
            type Output = $struct_name;

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

    // lifetimed struct
    (struct $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        #[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(),)+
                }
            }
        }
    };

    // owned enum (externally tagged)
    (enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl $crate::IntoStatic for $enum_name {
            type Output = $enum_name;

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

    // lifetimed enum (externally tagged)
    (enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<$lifetime> $crate::IntoStatic for $enum_name<$lifetime> {
            type Output = $enum_name<$lifetime>;

            #[inline(always)]
            fn into_static(self) -> Self::Output {
                match self {
                    $(
                        Self::$variant(value) => Self::$variant(value.into_static()),
                    )+
                }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "core"))]
macro_rules! impl_into_static {
    ($($tt:tt)*) => {};
}

#[doc(hidden)]
#[macro_export]
#[cfg(feature = "core")]
macro_rules! impl_with_lifetime {
    // owned tuple struct (transparent)
    (struct $struct_name:ident transparent) => {
        #[automatically_derived]
        impl<'s> $crate::WithLifetime<'s> for $struct_name {
            type Lifetimed = $struct_name;
        }
    };

    // lifetimed tuple struct (transparent)
    (struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        #[automatically_derived]
        impl<'s> $crate::WithLifetime<'s> for $struct_name<$lifetime> {
            type Lifetimed = $struct_name<$lifetime>;
        }
    };

    // owned struct
    (struct $struct_name:ident { $($field:ident),+ }) => {
        #[automatically_derived]
        impl<'s> $crate::WithLifetime<'s> for $struct_name {
            type Lifetimed = $struct_name;
        }
    };

    // lifetimed struct
    (struct $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        #[automatically_derived]
        impl<$lifetime, 'instantiated_lifetime> $crate::WithLifetime<'instantiated_lifetime>
            for $struct_name<$lifetime>
        {
            type Lifetimed = $struct_name<'instantiated_lifetime>;
        }
    };

    // owned enum (externally tagged)
    (enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<'s> $crate::WithLifetime<'s> for $enum_name {
            type Lifetimed = $enum_name;
        }
    };

    // lifetimed enum (externally tagged)
    (enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<'s> $crate::WithLifetime<'s> for $enum_name<$lifetime> {
            type Lifetimed = $enum_name<$lifetime>;
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "core"))]
macro_rules! impl_with_lifetime {
    ($($tt:tt)*) => {};
}

#[doc(hidden)]
#[macro_export]
#[cfg(all(feature = "core", feature = "json"))]
macro_rules! impl_json_serialize {
    // owned tuple struct (transparent)
    (struct $struct_name:ident transparent) => {
        #[automatically_derived]
        impl $crate::json::JsonSerialize for $struct_name {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                self.0.json_serialize(serializer)
            }
        }
    };

    // lifetimed tuple struct (transparent)
    (struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        #[automatically_derived]
        impl<$lifetime> $crate::json::JsonSerialize for $struct_name<$lifetime> {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                self.0.json_serialize(serializer)
            }
        }
    };

    // lifetimed struct
    (struct $struct_name:ident < $lifetime:lifetime > { $($field:ident),+ }) => {
        #[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);
                )+
            }
        }
    };

    // owned struct
    (struct $struct_name:ident { $($field:ident),+ }) => {
        #[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);
                )+
            }
        }
    };

    // owned enum (externally tagged)
    (enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl $crate::json::JsonSerialize for $enum_name {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut guard = serializer.write_obj();
                match self {
                    $(
                        Self::$variant(value) => {
                            guard.pair($variant_str, &value);
                        }
                    )+
                }
            }
        }
    };

    // lifetimed enum (externally tagged)
    (enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        #[automatically_derived]
        impl<$lifetime> $crate::json::JsonSerialize for $enum_name<$lifetime> {
            fn json_serialize(&self, serializer: &mut $crate::json::JsonSerializer) {
                #[allow(unused_imports)]
                use $crate::MerdeError;

                let mut guard = serializer.write_obj();
                match self {
                    $(
                        Self::$variant(value) => {
                            guard.pair($variant_str, &value);
                        }
                    )+
                }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(all(feature = "core", feature = "json")))]
macro_rules! impl_json_serialize {
    ($($tt:tt)*) => {};
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_trait {
    // owned struct
    (@impl JsonSerialize, struct $struct_name:ident { $($field:ident),+ }) => {
        $crate::impl_json_serialize!(struct $struct_name { $($field),+ });
    };
    // lifetimed struct
    (@impl JsonSerialize, struct $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::impl_json_serialize!(struct $struct_name <$lifetime> { $($field),+ });
    };
    // owned enum (externally tagged)
    (@impl JsonSerialize, enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::impl_json_serialize!(enum $enum_name externally_tagged {
            $($variant_str => $variant),+
        });
    };
    // lifetimed enum (externally tagged)
    (@impl JsonSerialize, enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::impl_json_serialize!(enum $enum_name <$lifetime> externally_tagged {
            $($variant_str => $variant),+
        });
    };
    // owned tuple struct (transparent)
    (@impl JsonSerialize, struct $struct_name:ident transparent) => {
        $crate::impl_json_serialize!(struct $struct_name transparent);
    };
    // lifetimed tuple struct (transparent)
    (@impl JsonSerialize, struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        $crate::impl_json_serialize!(struct $struct_name <$lifetime> transparent);
    };

    // owned struct
    (@impl ValueDeserialize, struct $struct_name:ident { $($field:ident),+ }) => {
        $crate::impl_value_deserialize!(struct $struct_name { $($field),+ });
        $crate::impl_into_static!(struct $struct_name { $($field),+ });
        $crate::impl_with_lifetime!(struct $struct_name { $($field),+ });
    };
    // lifetimed struct
    (@impl ValueDeserialize, struct $struct_name:ident <$lifetime:lifetime> { $($field:ident),+ }) => {
        $crate::impl_value_deserialize!(struct $struct_name <$lifetime> { $($field),+ });
        $crate::impl_into_static!(struct $struct_name <$lifetime> { $($field),+ });
        $crate::impl_with_lifetime!(struct $struct_name <$lifetime> { $($field),+ });
    };
    // owned enum (externally tagged)
    (@impl ValueDeserialize, enum $enum_name:ident externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::impl_value_deserialize!(enum $enum_name externally_tagged {
            $($variant_str => $variant),+
        });
    };
    // lifetimed enum (externally tagged)
    (@impl ValueDeserialize, enum $enum_name:ident <$lifetime:lifetime> externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::impl_value_deserialize!(enum $enum_name <$lifetime> externally_tagged {
            $($variant_str => $variant),+
        });
    };
    // owned tuple struct (transparent)
    (@impl ValueDeserialize, struct $struct_name:ident transparent) => {
        $crate::impl_value_deserialize!(struct $struct_name transparent);
    };
    // lifetimed tuple struct (transparent)
    (@impl ValueDeserialize, struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        $crate::impl_value_deserialize!(struct $struct_name <$lifetime> transparent);
    };
}

/// Derives the specified traits for a struct.
///
/// This macro can be used to generate implementations of [`JsonSerialize`] and [`ValueDeserialize`],
/// traits for a given struct.
///
/// # Usage
///
/// ```rust
/// struct MyStruct<'s> {
///     a: merde::CowStr<'s>,
///     b: i32,
///     c: bool,
/// }
///
/// merde::derive! {
///     impl (JsonSerialize, ValueDeserialize) for struct MyStruct<'s> { a, b, c }
/// }
/// ```
///
/// In this example, both traits are derived, of course you can omit the ones you don't need.
///
/// Structs without lifetime parameters are also allowed: the macro can tell the difference
/// from the fact that the lifetime parameter is not present in the invocation:
///
/// ```rust
/// struct MyStruct {
///     a: String,
///     b: i32,
///     c: bool,
/// }
///
/// merde::derive! {
///     //                                no lifetime param here 👇
///     impl (JsonSerialize, ValueDeserialize) for struct MyStruct { a, b, c }
/// }
/// ```
///
/// 1-tuple structs (newtypes) are supported, only in the "transparent" style: serializing
/// a `String` or a `MyStruct` will give `"foobar"` all the same, as if the newtype wrapper
/// was stripped, or, well, transparent:
///
/// ```rust
/// struct MyStruct(String);
///
/// merde::derive! {
///     impl (JsonSerialize, ValueDeserialize) for struct MyStruct transparent
/// }
///
/// use merde::json::JsonSerialize;
/// assert_eq!(
///   MyStruct("foobar".into()).to_json_string(),
///   r#""foobar""#
/// );
/// ```
///
/// Externally tagged enums are also supported. For both owned and lifetimed variants:
///
/// ```rust
/// enum MyEnum {
///     Variant1(String),
///     Variant2(i32),
/// }
///
/// merde::derive! {
///     impl (JsonSerialize, ValueDeserialize) for enum MyEnum
///     externally_tagged {
///         "variant1" => Variant1,
///         "variant2" => Variant2,
///     }
/// }
///
/// enum MyLifetimedEnum<'a> {
///     Variant1(merde::CowStr<'a>),
///     Variant2(i32),
/// }
///
/// merde::derive! {
///     impl (JsonSerialize, ValueDeserialize) for enum MyLifetimedEnum<'a>
///     externally_tagged {
///         "variant1" => Variant1,
///         "variant2" => Variant2,
///     }
/// }
/// ```
///
/// This will serialize `MyEnum::Variant1("hello".into())` as `{"variant1":"hello"}`,
/// and `MyEnum::Variant2(42)` as `{"variant2":42}`.
#[macro_export]
macro_rules! derive {
    // owned tuple structs (transparent)
    (impl ($($trait:ident),+) for struct $struct_name:ident transparent) => {
        $crate::derive!(@step1 { $($trait),+ } struct $struct_name transparent);
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } struct $struct_name:ident transparent) => {
        $crate::impl_trait!(@impl $trait, struct $struct_name transparent);
        $crate::derive!(@step1 { $($rest_traits),* } struct $struct_name transparent);
    };
    (@step1 { $trait:ident } struct $struct_name:ident transparent) => {
        $crate::impl_trait!(@impl $trait, struct $struct_name transparent);
    };
    (@step1 { } struct $struct_name:ident transparent) => {};

    // lifetimed tuple structs (transparent)
    (impl ($($trait:ident),+) for struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        $crate::derive!(@step1 { $($trait),+ } struct $struct_name <$lifetime> transparent);
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        $crate::impl_trait!(@impl $trait, struct $struct_name <$lifetime> transparent);
        $crate::derive!(@step1 { $($rest_traits),* } struct $struct_name <$lifetime> transparent);
    };
    (@step1 { $trait:ident } struct $struct_name:ident <$lifetime:lifetime> transparent) => {
        $crate::impl_trait!(@impl $trait, struct $struct_name <$lifetime> transparent);
    };
    (@step1 { } struct $enum_name:ident <$lifetime:lifetime> transparent) => {};

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

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

    // owned enums (externally tagged)
    (impl ($($trait:ident),+) for enum $enum_name:ident
    externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::derive!(@step1 { $($trait),+ } enum $enum_name externally_tagged {
            $($variant_str => $variant),+
        });
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } enum $enum_name:ident
    externally_tagged $variants:tt) => {
        $crate::impl_trait!(@impl $trait, enum $enum_name externally_tagged $variants);
        $crate::derive!(@step1 { $($rest_traits),* } enum $enum_name externally_tagged $variants);
    };
    (@step1 { $trait:ident } enum $enum_name:ident externally_tagged $variants:tt) => {
        $crate::impl_trait!(@impl $trait, enum $enum_name externally_tagged $variants);
    };
    (@step1 { } enum $enum_name:ident externally_tagged $variants:tt) => {};

    // lifetimed enums (externally tagged)
    (impl ($($trait:ident),+) for enum $enum_name:ident <$lifetime:lifetime>
    externally_tagged {
        $($variant_str:literal => $variant:ident),+ $(,)?
    }) => {
        $crate::derive!(@step1 { $($trait),+ } enum $enum_name <$lifetime> externally_tagged {
            $($variant_str => $variant),+
        });
    };
    (@step1 { $trait:ident, $($rest_traits:ident),* } enum $enum_name:ident <$lifetime:lifetime>
    externally_tagged $variants:tt) => {
        $crate::impl_trait!(@impl $trait, enum $enum_name <$lifetime> externally_tagged $variants);
        $crate::derive!(@step1 { $($rest_traits),* } enum $enum_name <$lifetime> externally_tagged $variants);
    };
    (@step1 { $trait:ident } enum $enum_name:ident <$lifetime:lifetime> externally_tagged $variants:tt) => {
        $crate::impl_trait!(@impl $trait, enum $enum_name <$lifetime> externally_tagged $variants);
    };
    (@step1 { } enum $enum_name:ident <$lifetime:lifetime> externally_tagged $variants: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 struct 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 struct 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, with `#[test]` above fn main())

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