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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
//! This module holds the machinery behind LabelledGeneric.
//!
//! A `LabelledGeneric` instance is pretty much exactly the same as a `Generic`
//! instance, except that the generic representation should contain information
//! about field names.
//!
//! Having a separate trait for `LabelledGeneric`s gives us the freedom to
//! derive both labelled and non-labelled generic trait instances for our types.
//!
//! Aside from the main `LabelledGeneric` trait, this module holds helper
//! methods that allow users to use `LabelledGeneric` without using universal
//! function call syntax.
//!
//! In addition, this module holds macro-generated enums that map to letters
//! in field names (identifiers).
//!
//! # Examples
//!
//! ```
//! # fn main() {
//! use frunk::labelled::chars::*;
//! use frunk_core::field;
//!
//! // Optionally alias our tuple that represents our type-level string
//! type name = (n, a, m, e);
//! let labelled = field![name, "Lloyd"];
//! assert_eq!(labelled.name, "name");
//! assert_eq!(labelled.value, "Lloyd")
//! # }
//! ```
//!
//! A more common usage is to use `LabelledGeneric` to transform structs that
//! have mismatched fields!
//!
//! ```
//! // required when using custom derives
//! use frunk::LabelledGeneric;
//!
//! # fn main() {
//! #[derive(LabelledGeneric)]
//! struct NewUser<'a> {
//!     first_name: &'a str,
//!     last_name: &'a str,
//!     age: usize,
//! }
//!
//! // Notice that the fields are mismatched in terms of ordering
//! // *and* also in terms of the number of fields.
//! #[derive(LabelledGeneric)]
//! struct ShortUser<'a> {
//!     last_name: &'a str,
//!     first_name: &'a str,
//! }
//!
//! let n_user = NewUser {
//!     first_name: "Joe",
//!     last_name: "Blow",
//!     age: 30,
//! };
//!
//! // transform_from automagically sculpts the labelled generic
//! // representation of the source object to that of the target type
//! let s_user: ShortUser = frunk::transform_from(n_user); // done
//! # }
//! ```
//!
//! If you have the need to transform types that are similarly-shaped recursively, then
//! use the Transmogrifier trait.
//!
//! ```
//! // required when using custom derives
//! # fn main() {
//! use frunk::labelled::Transmogrifier;
//! use frunk::LabelledGeneric;
//!
//! #[derive(LabelledGeneric)]
//! struct InternalPhoneNumber {
//!     emergency: Option<usize>,
//!     main: usize,
//!     secondary: Option<usize>,
//! }
//!
//! #[derive(LabelledGeneric)]
//! struct InternalAddress<'a> {
//!     is_whitelisted: bool,
//!     name: &'a str,
//!     phone: InternalPhoneNumber,
//! }
//!
//! #[derive(LabelledGeneric)]
//! struct InternalUser<'a> {
//!     name: &'a str,
//!     age: usize,
//!     address: InternalAddress<'a>,
//!     is_banned: bool,
//! }
//!
//! #[derive(LabelledGeneric, PartialEq, Debug)]
//! struct ExternalPhoneNumber {
//!     main: usize,
//! }
//!
//! #[derive(LabelledGeneric, PartialEq, Debug)]
//! struct ExternalAddress<'a> {
//!     name: &'a str,
//!     phone: ExternalPhoneNumber,
//! }
//!
//! #[derive(LabelledGeneric, PartialEq, Debug)]
//! struct ExternalUser<'a> {
//!     age: usize,
//!     address: ExternalAddress<'a>,
//!     name: &'a str,
//! }
//!
//! let internal_user = InternalUser {
//!     name: "John",
//!     age: 10,
//!     address: InternalAddress {
//!         is_whitelisted: true,
//!         name: "somewhere out there",
//!         phone: InternalPhoneNumber {
//!             main: 1234,
//!             secondary: None,
//!             emergency: Some(5678),
//!         },
//!     },
//!     is_banned: true,
//! };
//!
//! /// Boilerplate-free conversion of a top-level InternalUser into an
//! /// ExternalUser, taking care of subfield conversions as well.
//! let external_user: ExternalUser = internal_user.transmogrify();
//!
//! let expected_external_user = ExternalUser {
//!     name: "John",
//!     age: 10,
//!     address: ExternalAddress {
//!         name: "somewhere out there",
//!         phone: ExternalPhoneNumber {
//!             main: 1234,
//!         },
//!     }
//! };
//!
//! assert_eq!(external_user, expected_external_user);
//! # }
//! ```

use crate::hlist::*;
use crate::indices::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use core::fmt;
use core::marker::PhantomData;

/// A trait that converts from a type to a labelled generic representation.
///
/// `LabelledGeneric`s allow us to have completely type-safe,
/// boilerplate free conversions between different structs.
///
/// For the most part, you should be using the derivation that is available
/// through `frunk_derive` to generate instances of this trait for your types.
///
/// # Examples
///
/// ```rust
/// use frunk::LabelledGeneric;
///
/// # fn main() {
/// #[derive(LabelledGeneric)]
/// struct NewUser<'a> {
///     first_name: &'a str,
///     last_name: &'a str,
///     age: usize,
/// }
///
/// // Notice that the fields are mismatched in terms of ordering
/// #[derive(LabelledGeneric)]
/// struct SavedUser<'a> {
///     last_name: &'a str,
///     age: usize,
///     first_name: &'a str,
/// }
///
/// let n_user = NewUser {
///     first_name: "Joe",
///     last_name: "Blow",
///     age: 30,
/// };
///
/// // transform_from automagically sculpts the labelled generic
/// // representation of the source object to that of the target type
/// let s_user: SavedUser = frunk::transform_from(n_user); // done
/// # }
pub trait LabelledGeneric {
    /// The labelled generic representation type.
    type Repr;

    /// Convert a value to its representation type `Repr`.
    fn into(self) -> Self::Repr;

    /// Convert a value's labelled representation type `Repr`
    /// to the values's type.
    fn from(repr: Self::Repr) -> Self;

    /// Convert from one type to another using a type with the same
    /// labelled generic representation
    #[inline(always)]
    fn convert_from<Src>(src: Src) -> Self
    where
        Src: LabelledGeneric<Repr = Self::Repr>,
        Self: Sized,
    {
        let repr = <Src as LabelledGeneric>::into(src);
        <Self as LabelledGeneric>::from(repr)
    }

    /// Converts from another type A into Self assuming that A and Self have
    /// labelled generic representations that can be sculpted into each other.
    ///
    /// Note that this method tosses away the "remainder" of the sculpted representation. In other
    /// words, anything that is not needed from A gets tossed out.
    #[deprecated(note = "obsolete, transform_from instead")]
    fn sculpted_convert_from<A, Indices>(a: A) -> Self
    where
        A: LabelledGeneric,
        Self: Sized,
        // The labelled representation of A must be sculpt-able into the labelled representation of Self
        <A as LabelledGeneric>::Repr: Sculptor<<Self as LabelledGeneric>::Repr, Indices>,
    {
        <Self as LabelledGeneric>::transform_from(a)
    }

    /// Converts from another type `Src` into `Self` assuming that `Src` and
    /// `Self` have labelled generic representations that can be sculpted into
    /// each other.
    ///
    /// Note that this method tosses away the "remainder" of the sculpted
    /// representation. In other words, anything that is not needed from `Src`
    /// gets tossed out.
    #[inline(always)]
    fn transform_from<Src, Indices>(src: Src) -> Self
    where
        Src: LabelledGeneric,
        Self: Sized,
        // The labelled representation of `Src` must be sculpt-able into the labelled representation of `Self`
        <Src as LabelledGeneric>::Repr: Sculptor<<Self as LabelledGeneric>::Repr, Indices>,
    {
        let src_gen = <Src as LabelledGeneric>::into(src);
        // We toss away the remainder.
        let (self_gen, _): (<Self as LabelledGeneric>::Repr, _) = src_gen.sculpt();
        <Self as LabelledGeneric>::from(self_gen)
    }
}

pub trait IntoLabelledGeneric {
    /// The labelled generic representation type.
    type Repr;

    /// Convert a value to its representation type `Repr`.
    fn into(self) -> Self::Repr;
}

impl<A> IntoLabelledGeneric for A
where
    A: LabelledGeneric,
{
    type Repr = <A as LabelledGeneric>::Repr;

    #[inline(always)]
    fn into(self) -> <Self as IntoLabelledGeneric>::Repr {
        self.into()
    }
}

/// Given a labelled generic representation of a `Dst`, returns `Dst`
pub fn from_labelled_generic<Dst, Repr>(repr: Repr) -> Dst
where
    Dst: LabelledGeneric<Repr = Repr>,
{
    <Dst as LabelledGeneric>::from(repr)
}

/// Given a `Src`, returns its labelled generic representation.
pub fn into_labelled_generic<Src, Repr>(src: Src) -> Repr
where
    Src: LabelledGeneric<Repr = Repr>,
{
    <Src as LabelledGeneric>::into(src)
}

/// Converts one type into another assuming they have the same labelled generic
/// representation.
pub fn labelled_convert_from<Src, Dst, Repr>(src: Src) -> Dst
where
    Src: LabelledGeneric<Repr = Repr>,
    Dst: LabelledGeneric<Repr = Repr>,
{
    <Dst as LabelledGeneric>::convert_from(src)
}

/// Converts from one type into another assuming that their labelled generic representations
/// can be sculpted into each other.
///
/// The "Indices" type parameter allows the compiler to figure out that the two representations
/// can indeed be morphed into each other.
#[deprecated(note = "obsolete, transform_from instead")]
pub fn sculpted_convert_from<A, B, Indices>(a: A) -> B
where
    A: LabelledGeneric,
    B: LabelledGeneric,
    // The labelled representation of A must be sculpt-able into the labelled representation of B
    <A as LabelledGeneric>::Repr: Sculptor<<B as LabelledGeneric>::Repr, Indices>,
{
    <B as LabelledGeneric>::transform_from(a)
}
/// Converts from one type into another assuming that their labelled generic representations
/// can be sculpted into each other.
///
/// The "Indices" type parameter allows the compiler to figure out that the two representations
/// can indeed be morphed into each other.
pub fn transform_from<Src, Dst, Indices>(src: Src) -> Dst
where
    Src: LabelledGeneric,
    Dst: LabelledGeneric,
    // The labelled representation of Src must be sculpt-able into the labelled representation of Dst
    <Src as LabelledGeneric>::Repr: Sculptor<<Dst as LabelledGeneric>::Repr, Indices>,
{
    <Dst as LabelledGeneric>::transform_from(src)
}

pub mod chars {
    //! Types for building type-level labels from character sequences.
    //!
    //! This is designed to be glob-imported:
    //!
    //! ```rust
    //! # extern crate frunk;
    //! # fn main() {
    //! # #[allow(unused)]
    //! use frunk::labelled::chars::*;
    //! # }
    //! ```

    macro_rules! create_enums_for {
        ($($i: ident)*) => {
            $(
                #[allow(non_snake_case, non_camel_case_types)]
                #[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
                pub enum $i {}
            )*
        }
    }

    // Add more as needed.
    create_enums_for! {
        // all valid identifier characters
        a b c d e f g h i j k l m n o p q r s t u v w x y z
        A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
        _1 _2 _3 _4 _5 _6 _7 _8 _9 _0 __ _uc uc_
    }

    #[test]
    fn simple_var_names_are_allowed() {
        // Rust forbids variable bindings that shadow unit structs,
        // so unit struct characters would cause a lot of trouble.
        //
        // Good thing I don't plan on adding reified labels. - Exp
        let a = 3;
        #[allow(clippy::match_single_binding)]
        match a {
            a => assert_eq!(a, 3),
        }
    }
}

/// A Label contains a type-level Name, a runtime value, and
/// a reference to a `&'static str` name.
///
/// To construct one, use the `field!` macro.
///
/// # Examples
///
/// ```
/// use frunk::labelled::chars::*;
/// use frunk_core::field;
/// # fn main() {
/// let labelled = field![(n,a,m,e), "joe"];
/// assert_eq!(labelled.name, "name");
/// assert_eq!(labelled.value, "joe")
/// # }
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Field<Name, Type> {
    name_type_holder: PhantomData<Name>,
    pub name: &'static str,
    pub value: Type,
}

/// A version of Field that doesn't have a type-level label, just a
/// value-level one
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct ValueField<Type> {
    pub name: &'static str,
    pub value: Type,
}

impl<Name, Type> fmt::Debug for Field<Name, Type>
where
    Type: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Field")
            // show name without quotes
            .field("name", &DebugAsDisplay(&self.name))
            .field("value", &self.value)
            .finish()
    }
}

impl<Type> fmt::Debug for ValueField<Type>
where
    Type: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ValueField")
            // show name without quotes
            .field("name", &DebugAsDisplay(&self.name))
            .field("value", &self.value)
            .finish()
    }
}

/// Utility type that implements Debug in terms of Display.
struct DebugAsDisplay<T>(T);

impl<T: fmt::Display> fmt::Debug for DebugAsDisplay<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// Returns a new Field for a given value and custom name.
///
/// If you don't want to provide a custom name and want to rely on the type you provide
/// to build a name, then please use the field! macro.
///
/// # Examples
///
/// ```
/// use frunk::labelled::chars::*;
/// use frunk::labelled::field_with_name;
///
/// let l = field_with_name::<(n,a,m,e),_>("name", "joe");
/// assert_eq!(l.value, "joe");
/// assert_eq!(l.name, "name");
/// ```
pub fn field_with_name<Label, Value>(name: &'static str, value: Value) -> Field<Label, Value> {
    Field {
        name_type_holder: PhantomData,
        name,
        value,
    }
}

/// Trait for turning a Field HList into an un-labelled HList
pub trait IntoUnlabelled {
    type Output;

    /// Turns the current HList into an unlabelled one.
    ///
    /// Effectively extracts the values held inside the individual Field
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() {
    /// use frunk::labelled::chars::*;
    /// use frunk::labelled::IntoUnlabelled;
    /// use frunk_core::{field, hlist};
    ///
    /// let labelled_hlist = hlist![
    ///     field!((n, a, m, e), "joe"),
    ///     field!((a, g, e), 3)
    /// ];
    ///
    /// let unlabelled = labelled_hlist.into_unlabelled();
    ///
    /// assert_eq!(unlabelled, hlist!["joe", 3])
    /// # }
    /// ```
    fn into_unlabelled(self) -> Self::Output;
}

/// Implementation for HNil
impl IntoUnlabelled for HNil {
    type Output = HNil;
    fn into_unlabelled(self) -> Self::Output {
        self
    }
}

/// Implementation when we have a non-empty HCons holding a label in its head
impl<Label, Value, Tail> IntoUnlabelled for HCons<Field<Label, Value>, Tail>
where
    Tail: IntoUnlabelled,
{
    type Output = HCons<Value, <Tail as IntoUnlabelled>::Output>;

    fn into_unlabelled(self) -> Self::Output {
        HCons {
            head: self.head.value,
            tail: self.tail.into_unlabelled(),
        }
    }
}

/// A trait that strips type-level strings from the labels
pub trait IntoValueLabelled {
    type Output;

    /// Turns the current HList into a value-labelled one.
    ///
    /// Effectively extracts the names and values held inside the individual Fields
    /// and puts them into ValueFields, which do not have type-level names.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() {
    /// use frunk::labelled::{ValueField, IntoValueLabelled};
    /// use frunk::labelled::chars::*;
    /// use frunk_core::{field, hlist, HList};
    ///
    /// let labelled_hlist = hlist![
    ///     field!((n, a, m, e), "joe"),
    ///     field!((a, g, e), 3)
    /// ];
    /// // Notice the lack of type-level names
    /// let value_labelled: HList![ValueField<&str>, ValueField<isize>] = labelled_hlist.into_value_labelled();
    ///
    /// assert_eq!(
    ///   value_labelled,
    ///   hlist![
    ///     ValueField {
    ///       name: "name",
    ///       value: "joe",
    ///     },
    ///     ValueField {
    ///       name: "age",
    ///       value: 3,
    ///     },
    /// ]);
    /// # }
    /// ```
    fn into_value_labelled(self) -> Self::Output;
}

impl IntoValueLabelled for HNil {
    type Output = HNil;
    fn into_value_labelled(self) -> Self::Output {
        self
    }
}

impl<Label, Value, Tail> IntoValueLabelled for HCons<Field<Label, Value>, Tail>
where
    Tail: IntoValueLabelled,
{
    type Output = HCons<ValueField<Value>, <Tail as IntoValueLabelled>::Output>;

    fn into_value_labelled(self) -> Self::Output {
        HCons {
            head: ValueField {
                name: self.head.name,
                value: self.head.value,
            },
            tail: self.tail.into_value_labelled(),
        }
    }
}

/// Trait for plucking out a `Field` from a type by type-level `TargetKey`.
pub trait ByNameFieldPlucker<TargetKey, Index> {
    type TargetValue;
    type Remainder;

    /// Returns a pair consisting of the value pointed to by the target key and the remainder.
    fn pluck_by_name(self) -> (Field<TargetKey, Self::TargetValue>, Self::Remainder);
}

/// Implementation when the pluck target key is in the head.
impl<K, V, Tail> ByNameFieldPlucker<K, Here> for HCons<Field<K, V>, Tail> {
    type TargetValue = V;
    type Remainder = Tail;

    #[inline(always)]
    fn pluck_by_name(self) -> (Field<K, Self::TargetValue>, Self::Remainder) {
        let field = field_with_name(self.head.name, self.head.value);
        (field, self.tail)
    }
}

/// Implementation when the pluck target key is in the tail.
impl<Head, Tail, K, TailIndex> ByNameFieldPlucker<K, There<TailIndex>> for HCons<Head, Tail>
where
    Tail: ByNameFieldPlucker<K, TailIndex>,
{
    type TargetValue = <Tail as ByNameFieldPlucker<K, TailIndex>>::TargetValue;
    type Remainder = HCons<Head, <Tail as ByNameFieldPlucker<K, TailIndex>>::Remainder>;

    #[inline(always)]
    fn pluck_by_name(self) -> (Field<K, Self::TargetValue>, Self::Remainder) {
        let (target, tail_remainder) =
            <Tail as ByNameFieldPlucker<K, TailIndex>>::pluck_by_name(self.tail);
        (
            target,
            HCons {
                head: self.head,
                tail: tail_remainder,
            },
        )
    }
}

/// Trait for transmogrifying a `Source` type into a `Target` type.
///
/// What is "transmogrifying"? In this context, it means to convert some data of type `A`
/// into data of type `B`, in a typesafe, recursive way, as long as `A` and `B` are "similarly-shaped".
/// In other words, as long as `B`'s fields and their subfields are subsets of `A`'s fields and
/// their respective subfields, then `A` can be turned into `B`.
///
/// # Example
///
/// ```
/// // required when using custom derives
/// # fn main() {
/// use frunk::LabelledGeneric;
/// use frunk::labelled::Transmogrifier;
/// #[derive(LabelledGeneric)]
/// struct InternalPhoneNumber {
///     emergency: Option<usize>,
///     main: usize,
///     secondary: Option<usize>,
/// }
///
/// #[derive(LabelledGeneric)]
/// struct InternalAddress<'a> {
///     is_whitelisted: bool,
///     name: &'a str,
///     phone: InternalPhoneNumber,
/// }
///
/// #[derive(LabelledGeneric)]
/// struct InternalUser<'a> {
///     name: &'a str,
///     age: usize,
///     address: InternalAddress<'a>,
///     is_banned: bool,
/// }
///
/// #[derive(LabelledGeneric, PartialEq, Debug)]
/// struct ExternalPhoneNumber {
///     main: usize,
/// }
///
/// #[derive(LabelledGeneric, PartialEq, Debug)]
/// struct ExternalAddress<'a> {
///     name: &'a str,
///     phone: ExternalPhoneNumber,
/// }
///
/// #[derive(LabelledGeneric, PartialEq, Debug)]
/// struct ExternalUser<'a> {
///     age: usize,
///     address: ExternalAddress<'a>,
///     name: &'a str,
/// }
///
/// let internal_user = InternalUser {
///     name: "John",
///     age: 10,
///     address: InternalAddress {
///         is_whitelisted: true,
///         name: "somewhere out there",
///         phone: InternalPhoneNumber {
///             main: 1234,
///             secondary: None,
///             emergency: Some(5678),
///         },
///     },
///     is_banned: true,
/// };
///
/// /// Boilerplate-free conversion of a top-level InternalUser into an
/// /// ExternalUser, taking care of subfield conversions as well.
/// let external_user: ExternalUser = internal_user.transmogrify();
///
/// let expected_external_user = ExternalUser {
///     name: "John",
///     age: 10,
///     address: ExternalAddress {
///         name: "somewhere out there",
///         phone: ExternalPhoneNumber {
///             main: 1234,
///         },
///     }
/// };
///
/// assert_eq!(external_user, expected_external_user);
/// # }
/// ```
///
/// Credit:
/// 1. Haskell "transmogrify" Github repo: <https://github.com/ivan-m/transmogrify>
pub trait Transmogrifier<Target, TransmogrifyIndexIndices> {
    /// Consume this current object and return an object of the Target type.
    ///
    /// Although similar to sculpting, transmogrifying does its job recursively.
    fn transmogrify(self) -> Target;
}

/// Implementation of `Transmogrifier` for identity plucked `Field` to `Field` Transforms.
impl<Key, SourceValue> Transmogrifier<SourceValue, IdentityTransMog> for Field<Key, SourceValue> {
    #[inline(always)]
    fn transmogrify(self) -> SourceValue {
        self.value
    }
}

/// Implementations of `Transmogrifier` that allow recursion through stdlib container types.
#[cfg(feature = "alloc")]
mod _alloc {
    use super::MappingIndicesWrapper;
    use super::{Field, Transmogrifier};
    use alloc::boxed::Box;
    use alloc::collections::{LinkedList, VecDeque};
    use alloc::vec::Vec;

    macro_rules! transmogrify_seq {
        ($container:ident) => {
            /// Implementation of `Transmogrifier` that maps over a `$container` in a `Field`, transmogrifying the
            /// elements on the way past.
            impl<Key, Source, Target, InnerIndices>
                Transmogrifier<$container<Target>, MappingIndicesWrapper<InnerIndices>>
                for Field<Key, $container<Source>>
            where
                Source: Transmogrifier<Target, InnerIndices>,
            {
                fn transmogrify(self) -> $container<Target> {
                    self.value.into_iter().map(|e| e.transmogrify()).collect()
                }
            }
        };
    }

    transmogrify_seq!(Vec);
    transmogrify_seq!(LinkedList);
    transmogrify_seq!(VecDeque);

    /// Implementation of `Transmogrifier` that maps over an `Box` in a `Field`, transmogrifying the
    /// contained element on the way past.
    impl<Key, Source, Target, InnerIndices>
        Transmogrifier<Box<Target>, MappingIndicesWrapper<InnerIndices>> for Field<Key, Box<Source>>
    where
        Source: Transmogrifier<Target, InnerIndices>,
    {
        fn transmogrify(self) -> Box<Target> {
            Box::new(self.value.transmogrify())
        }
    }
}

/// Implementation of `Transmogrifier` that maps over an `Option` in a `Field`, transmogrifying the
/// contained element on the way past if present.
impl<Key, Source, Target, InnerIndices>
    Transmogrifier<Option<Target>, MappingIndicesWrapper<InnerIndices>>
    for Field<Key, Option<Source>>
where
    Source: Transmogrifier<Target, InnerIndices>,
{
    fn transmogrify(self) -> Option<Target> {
        self.value.map(|e| e.transmogrify())
    }
}

/// Implementation of `Transmogrifier` for when the `Target` is empty and the `Source` is empty.
impl Transmogrifier<HNil, HNil> for HNil {
    #[inline(always)]
    fn transmogrify(self) -> HNil {
        HNil
    }
}

/// Implementation of `Transmogrifier` for when the `Target` is empty and the `Source` is non-empty.
impl<SourceHead, SourceTail> Transmogrifier<HNil, HNil> for HCons<SourceHead, SourceTail> {
    #[inline(always)]
    fn transmogrify(self) -> HNil {
        HNil
    }
}

/// Implementation of `Transmogrifier` for when the target is an `HList`, and the `Source` is a plucked
/// `HList`.
impl<
        SourceHead,
        SourceTail,
        TargetName,
        TargetHead,
        TargetTail,
        TransmogHeadIndex,
        TransmogTailIndices,
    > Transmogrifier<HCons<TargetHead, TargetTail>, HCons<TransmogHeadIndex, TransmogTailIndices>>
    for Field<TargetName, HCons<SourceHead, SourceTail>>
where
    HCons<SourceHead, SourceTail>: Transmogrifier<
        HCons<TargetHead, TargetTail>,
        HCons<TransmogHeadIndex, TransmogTailIndices>,
    >,
{
    #[inline(always)]
    fn transmogrify(self) -> HCons<TargetHead, TargetTail> {
        self.value.transmogrify()
    }
}

/// Non-trivial implementation of `Transmogrifier` where similarly-shaped `Source` and `Target` types are
/// both Labelled HLists, but do not immediately transform into one another due to mis-matched
/// fields, possibly recursively so.
impl<
        SourceHead,
        SourceTail,
        TargetHeadName,
        TargetHeadValue,
        TargetTail,
        PluckSourceHeadNameIndex,
        TransMogSourceHeadValueIndices,
        TransMogTailIndices,
    >
    Transmogrifier<
        HCons<Field<TargetHeadName, TargetHeadValue>, TargetTail>,
        HCons<
            DoTransmog<PluckSourceHeadNameIndex, TransMogSourceHeadValueIndices>,
            TransMogTailIndices,
        >,
    > for HCons<SourceHead, SourceTail>
where
    // Pluck a value out of the Source by the Head Target Name
    HCons<SourceHead, SourceTail>: ByNameFieldPlucker<TargetHeadName, PluckSourceHeadNameIndex>,
    // The value we pluck out needs to be able to be transmogrified to the Head Target Value type
    Field<
        TargetHeadName,
        <HCons<SourceHead, SourceTail> as ByNameFieldPlucker<
            TargetHeadName,
            PluckSourceHeadNameIndex,
        >>::TargetValue,
    >: Transmogrifier<TargetHeadValue, TransMogSourceHeadValueIndices>,
    // The remainder from plucking out the Head Target Name must be able to be transmogrified to the
    // target tail, utilising the other remaining indices
    <HCons<SourceHead, SourceTail> as ByNameFieldPlucker<
        TargetHeadName,
        PluckSourceHeadNameIndex,
    >>::Remainder: Transmogrifier<TargetTail, TransMogTailIndices>,
{
    #[inline(always)]
    fn transmogrify(self) -> HCons<Field<TargetHeadName, TargetHeadValue>, TargetTail> {
        let (source_field_for_head_target_name, remainder) = self.pluck_by_name();
        let name = source_field_for_head_target_name.name;
        let transmogrified_value: TargetHeadValue =
            source_field_for_head_target_name.transmogrify();
        let as_field: Field<TargetHeadName, TargetHeadValue> =
            field_with_name(name, transmogrified_value);
        HCons {
            head: as_field,
            tail: remainder.transmogrify(),
        }
    }
}

impl<Source, Target, TransmogIndices>
    Transmogrifier<Target, LabelledGenericTransmogIndicesWrapper<TransmogIndices>> for Source
where
    Source: LabelledGeneric,
    Target: LabelledGeneric,
    <Source as LabelledGeneric>::Repr:
        Transmogrifier<<Target as LabelledGeneric>::Repr, TransmogIndices>,
{
    #[inline(always)]
    fn transmogrify(self) -> Target {
        let source_as_repr = self.into();
        let source_transmogged = source_as_repr.transmogrify();
        <Target as LabelledGeneric>::from(source_transmogged)
    }
}

// Implementation for when the source value is plucked
impl<Source, TargetName, TargetValue, TransmogIndices>
    Transmogrifier<TargetValue, PluckedLabelledGenericIndicesWrapper<TransmogIndices>>
    for Field<TargetName, Source>
where
    Source: LabelledGeneric,
    TargetValue: LabelledGeneric,
    Source: Transmogrifier<TargetValue, TransmogIndices>,
{
    #[inline(always)]
    fn transmogrify(self) -> TargetValue {
        self.value.transmogrify()
    }
}

#[cfg(test)]
mod tests {
    use super::chars::*;
    use super::*;
    use alloc::collections::{LinkedList, VecDeque};
    use alloc::{boxed::Box, format, vec, vec::Vec};

    // Set up some aliases
    #[allow(non_camel_case_types)]
    type abc = (a, b, c);
    #[allow(non_camel_case_types)]
    type name = (n, a, m, e);
    #[allow(non_camel_case_types)]
    type age = (a, g, e);
    #[allow(non_camel_case_types)]
    type is_admin = (i, s, __, a, d, m, i, n);
    #[allow(non_camel_case_types)]
    type inner = (i, n, n, e, r);

    #[test]
    fn test_label_new_building() {
        let l1 = field!(abc, 3);
        assert_eq!(l1.value, 3);
        assert_eq!(l1.name, "abc");
        let l2 = field!((a, b, c), 3);
        assert_eq!(l2.value, 3);
        assert_eq!(l2.name, "abc");

        // test named
        let l3 = field!(abc, 3, "nope");
        assert_eq!(l3.value, 3);
        assert_eq!(l3.name, "nope");
        let l4 = field!((a, b, c), 3, "nope");
        assert_eq!(l4.value, 3);
        assert_eq!(l4.name, "nope");
    }

    #[test]
    fn test_field_construction() {
        let f1 = field!(age, 3);
        let f2 = field!((a, g, e), 3);
        assert_eq!(f1, f2)
    }

    #[test]
    fn test_field_debug() {
        let field = field!(age, 3);
        let hlist_pat![value_field] = hlist![field].into_value_labelled();

        // names don't have quotation marks
        assert!(format!("{:?}", field).contains("name: age"));
        assert!(format!("{:?}", value_field).contains("name: age"));
        // :#? works
        assert!(format!("{:#?}", field).contains('\n'));
        assert!(format!("{:#?}", value_field).contains('\n'));
    }

    #[test]
    fn test_anonymous_record_usage() {
        let record = hlist![field!(name, "Joe"), field!((a, g, e), 30)];
        let (name, _): (Field<name, _>, _) = record.pluck();
        assert_eq!(name.value, "Joe")
    }

    #[test]
    fn test_unlabelling() {
        let labelled_hlist = hlist![field!(name, "joe"), field!((a, g, e), 3)];
        let unlabelled = labelled_hlist.into_unlabelled();
        assert_eq!(unlabelled, hlist!["joe", 3])
    }

    #[test]
    fn test_value_labelling() {
        let labelled_hlist = hlist![field!(name, "joe"), field!((a, g, e), 3)];
        let value_labelled: HList![ValueField<&str>, ValueField<isize>] =
            labelled_hlist.into_value_labelled();
        let hlist_pat!(f1, f2) = value_labelled;
        assert_eq!(f1.name, "name");
        assert_eq!(f2.name, "age");
    }

    #[test]
    fn test_name() {
        let labelled = field!(name, "joe");
        assert_eq!(labelled.name, "name")
    }

    #[test]
    fn test_transmogrify_hnil_identity() {
        let hnil_again: HNil = HNil.transmogrify();
        assert_eq!(HNil, hnil_again);
    }

    #[test]
    fn test_transmogrify_hcons_sculpting_super_simple() {
        type Source = HList![Field<name, &'static str>, Field<age, i32>, Field<is_admin, bool>];
        type Target = HList![Field<age, i32>];
        let hcons: Source = hlist!(field!(name, "joe"), field!(age, 3), field!(is_admin, true));
        let t_hcons: Target = hcons.transmogrify();
        assert_eq!(t_hcons, hlist!(field!(age, 3)));
    }

    #[test]
    fn test_transmogrify_hcons_sculpting_somewhat_simple() {
        type Source = HList![Field<name, &'static str>, Field<age, i32>, Field<is_admin, bool>];
        type Target = HList![Field<is_admin, bool>, Field<name, &'static str>];
        let hcons: Source = hlist!(field!(name, "joe"), field!(age, 3), field!(is_admin, true));
        let t_hcons: Target = hcons.transmogrify();
        assert_eq!(t_hcons, hlist!(field!(is_admin, true), field!(name, "joe")));
    }

    #[test]
    fn test_transmogrify_hcons_recursive_simple() {
        type Source = HList![
            Field<name,  HList![
                Field<inner, f32>,
                Field<is_admin, bool>,
            ]>,
            Field<age, i32>,
            Field<is_admin, bool>];
        type Target = HList![
            Field<is_admin, bool>,
            Field<name,  HList![
                Field<is_admin, bool>,
            ]>,
        ];
        let source: Source = hlist![
            field!(name, hlist![field!(inner, 42f32), field!(is_admin, true)]),
            field!(age, 32),
            field!(is_admin, true)
        ];
        let target: Target = source.transmogrify();
        assert_eq!(
            target,
            hlist![
                field!(is_admin, true),
                field!(name, hlist![field!(is_admin, true)]),
            ]
        )
    }

    #[test]
    fn test_transmogrify_hcons_sculpting_required_simple() {
        type Source = HList![Field<name, &'static str>, Field<age, i32>, Field<is_admin, bool>];
        type Target = HList![Field<is_admin, bool>, Field<name, &'static str>, Field<age, i32>];
        let hcons: Source = hlist!(field!(name, "joe"), field!(age, 3), field!(is_admin, true));
        let t_hcons: Target = hcons.transmogrify();
        assert_eq!(
            t_hcons,
            hlist!(field!(is_admin, true), field!(name, "joe"), field!(age, 3))
        );
    }

    #[test]
    fn test_transmogrify_identical_transform_labelled_fields() {
        type Source = HList![
            Field<name,  &'static str>,
            Field<age, i32>,
            Field<is_admin, bool>
        ];
        type Target = Source;
        let source: Source = hlist![field!(name, "joe"), field!(age, 32), field!(is_admin, true)];
        let target: Target = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "joe"), field!(age, 32), field!(is_admin, true)]
        )
    }

    #[test]
    fn test_transmogrify_through_containers() {
        type SourceOuter<T> = HList![
            Field<name, &'static str>,
            Field<inner, T>,
        ];
        type SourceInner = HList![
            Field<is_admin, bool>,
            Field<age, i32>,
        ];
        type TargetOuter<T> = HList![
            Field<name, &'static str>,
            Field<inner, T>,
        ];
        type TargetInner = HList![
            Field<age, i32>,
            Field<is_admin, bool>,
        ];

        fn create_inner() -> (SourceInner, TargetInner) {
            let source_inner: SourceInner = hlist![field!(is_admin, true), field!(age, 14)];
            let target_inner: TargetInner = hlist![field!(age, 14), field!(is_admin, true)];
            (source_inner, target_inner)
        }

        // Vec -> Vec
        let (source_inner, target_inner) = create_inner();
        let source: SourceOuter<Vec<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, vec![source_inner])];
        let target: TargetOuter<Vec<TargetInner>> = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "Joe"), field!(inner, vec![target_inner])]
        );

        // LInkedList -> LinkedList
        let (source_inner, target_inner) = create_inner();
        let source_inner = {
            let mut list = LinkedList::new();
            list.push_front(source_inner);
            list
        };
        let target_inner = {
            let mut list = LinkedList::new();
            list.push_front(target_inner);
            list
        };
        let source: SourceOuter<LinkedList<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, source_inner)];
        let target: TargetOuter<LinkedList<TargetInner>> = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "Joe"), field!(inner, target_inner)]
        );

        // VecDeque -> VecDeque
        let (source_inner, target_inner) = create_inner();
        let source_inner = {
            let mut list = VecDeque::new();
            list.push_front(source_inner);
            list
        };
        let target_inner = {
            let mut list = VecDeque::new();
            list.push_front(target_inner);
            list
        };
        let source: SourceOuter<VecDeque<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, source_inner)];
        let target: TargetOuter<VecDeque<TargetInner>> = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "Joe"), field!(inner, target_inner)]
        );

        // Option -> Option
        let (source_inner, target_inner) = create_inner();
        let source_inner = Some(source_inner);
        let target_inner = Some(target_inner);
        let source: SourceOuter<Option<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, source_inner)];
        let target: TargetOuter<Option<TargetInner>> = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "Joe"), field!(inner, target_inner)]
        );
        let source: SourceOuter<Option<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, None)];
        let target: TargetOuter<Option<TargetInner>> = source.transmogrify();
        assert_eq!(target, hlist![field!(name, "Joe"), field!(inner, None)]);

        // Box -> Box
        let (source_inner, target_inner) = create_inner();
        let source_inner = Box::new(source_inner);
        let target_inner = Box::new(target_inner);
        let source: SourceOuter<Box<SourceInner>> =
            hlist![field!(name, "Joe"), field!(inner, source_inner)];
        let target: TargetOuter<Box<TargetInner>> = source.transmogrify();
        assert_eq!(
            target,
            hlist![field!(name, "Joe"), field!(inner, target_inner)]
        );
    }

    //    #[test]
    //    fn test_transmogrify_identical_transform_nested_labelled_fields() {
    //        type Source = HList![
    //    Field<name,  HList![
    //        Field<inner, f32>,
    //        Field<is_admin, bool>,
    //    ]>,
    //    Field<age, i32>,
    //    Field<is_admin, bool>];
    //        type Target = Source;
    //        let source: Source = hlist![
    //            field!(name, hlist![field!(inner, 42f32), field!(is_admin, true)]),
    //            field!(age, 32),
    //            field!(is_admin, true)
    //        ];
    //        let target: Target = source.transmogrify();
    //        assert_eq!(
    //            target,
    //            hlist![
    //                field!(name, hlist![field!(inner, 42f32), field!(is_admin, true)]),
    //                field!(age, 32),
    //                field!(is_admin, true)
    //            ]
    //        )
    //    }
}