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
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
//!  
//!
//! # Main Macros
//!
//! ## [`var_expr!`]
#![doc = include_str!("../var_expr.md")]
//! ## [`var_type!`]
#![doc = include_str!("../var_type.md")]
//! ## [`var_args!`]
#![doc = include_str!("../var_args.md")]

/// module of collection types for variadics
pub mod variadic_collections;
use std::any::Any;

use sealed::sealed;

#[doc = include_str!("../var_expr.md")]
#[macro_export]
macro_rules! var_expr {
    () => ( () );

    (...$a:ident $(,)? ) => ( $a );
    (...$a:expr  $(,)? ) => ( $a );
    (...$a:ident, $( $b:tt )+) => ( $crate::VariadicExt::extend($a, $crate::var_expr!( $( $b )* )) );
    (...$a:expr,  $( $b:tt )+) => ( $crate::VariadicExt::extend($a, $crate::var_expr!( $( $b )* )) );

    ($a:ident $(,)? ) => ( ($a, ()) );
    ($a:expr  $(,)? ) => ( ($a, ()) );
    ($a:ident, $( $b:tt )+) => ( ($a, $crate::var_expr!( $( $b )* )) );
    ($a:expr,  $( $b:tt )+) => ( ($a, $crate::var_expr!( $( $b )* )) );
}

#[doc = include_str!("../var_type.md")]
#[macro_export]
macro_rules! var_type {
    () => ( () );

    (...$a:ty $(,)? ) => ( $a );
    (...$a:ty, $( $b:tt )+) => ( <$a as $crate::VariadicExt>::Extend::<$crate::var_type!( $( $b )* )> );

    ($a:ty $(,)? ) => ( ($a, ()) );
    ($a:ty, $( $b:tt )+) => ( ($a, $crate::var_type!( $( $b )* )) );
}

#[doc = include_str!("../var_args.md")]
#[macro_export]
macro_rules! var_args {
    () => ( () );

    (...$a:pat $(,)? ) => ( $a );
    (...$a:ty, $( $b:tt )+) => ( ::core::compile_error!("`var_args!` can only have the `...` spread syntax on the last field.") );

    ($a:pat $(,)? ) => ( ($a, ()) );
    ($a:pat, $( $b:tt )+) => ( ($a, $crate::var_args!( $( $b )* )) );
}

/// This macro generates a basic variadic trait where each element must fulfill the `where` clause.
///
/// ```rust
/// use variadics::{var_expr, variadic_trait};
///
/// variadic_trait! {
///     /// A variadic list of `Debug` items.
///     pub variadic<Item> DebugList where Item: std::fmt::Debug {}
/// }
///
/// let x = &var_expr!(1, "hello", 5.6);
/// let _: &dyn DebugList = x;
/// println!("{:?}", x);
/// ```
///
/// This uses a special syntax similar to traits, but with the `trait` keyword replaced with
/// `variadic<T>` where `T` is the generic parameter name for each item in the variadic list. `T`
/// can be changed to any valid generic identifier. The bounds on `T` must be put in the where
/// clause; they cannot be expressed directly-- `variadic<T: Clone>` is invalid.
///
/// For now this can only create traits which bounds the `Item`s and cannot have associated
/// methods. This means the body of the variadic trait must be empty. But in the future this
/// declarative macro may be converted into a more powerful procedural macro with associated
/// method support.
#[macro_export]
macro_rules! variadic_trait {
    (
        $( #[$( $attrs:tt )*] )*
        $vis:vis variadic<$item:ident> $name:ident $( $clause:tt )*
    ) => {
        $( #[$( $attrs )*] )*
        $vis trait $name: $crate::Variadic {}
        $( #[$( $attrs )*] )*
        impl $name for $crate::var_type!() {}
        $( #[$( $attrs )*] )*
        impl<$item, __Rest: $name> $name for $crate::var_type!($item, ...__Rest) $( $clause )*
    };
}

/// A variadic tuple list.
///
/// This is a sealed trait, implemented only for `(Item, Rest) where Rest: Variadic` and `()`.
#[sealed]
pub trait Variadic {}
#[sealed]
impl<Item, Rest> Variadic for (Item, Rest) where Rest: Variadic {}
#[sealed]
impl Variadic for () {}

/// Extension methods/types for [`Variadic`]s.
///
/// This is a sealed trait.
#[sealed]
pub trait VariadicExt: Variadic {
    /// The number of items in this variadic (its length).
    const LEN: usize;

    /// Creates a new (longer) variadic type by appending `Suffix` onto the end of this variadc.
    type Extend<Suffix>: VariadicExt
    where
        Suffix: VariadicExt;
    /// Extends this variadic value by appending `suffix` onto the end.
    fn extend<Suffix>(self, suffix: Suffix) -> Self::Extend<Suffix>
    where
        Suffix: VariadicExt;

    /// The reverse of this variadic type.
    type Reverse: VariadicExt;
    /// Reverses this variadic value.
    fn reverse(self) -> Self::Reverse;
    /// Reverses an AsRefVar variadic value
    fn reverse_ref(this: Self::AsRefVar<'_>) -> <Self::Reverse as VariadicExt>::AsRefVar<'_>;

    /// The length of this variadic type
    fn len(&self) -> usize {
        Self::LEN
    }

    /// Checks if this variadic type is empty.
    fn is_empty(&self) -> bool {
        Self::LEN == 0
    }

    /// This as a variadic of references.
    type AsRefVar<'a>: RefVariadic<
        UnRefVar = Self,
        RefVar = Self::AsRefVar<'a>,
        MutVar = Self::AsMutVar<'a>,
    >
    where
        Self: 'a;
    /// Convert a reference to this variadic into a variadic of references.
    /// ```rust
    /// # use variadics::*;
    /// let as_ref: var_type!(&u32, &String, &bool) =
    ///     var_expr!(1_u32, "Hello".to_owned(), false).as_ref_var();
    /// ```
    fn as_ref_var(&self) -> Self::AsRefVar<'_>;

    /// This as a variadic of exclusive (`mut`) references.
    type AsMutVar<'a>: MutVariadic<
        UnRefVar = Self,
        RefVar = Self::AsRefVar<'a>,
        MutVar = Self::AsMutVar<'a>,
    >
    where
        Self: 'a;
    /// Convert an exclusive (`mut`) reference to this variadic into a variadic of exclusive
    /// (`mut`) references.
    /// ```rust
    /// # use variadics::*;
    /// let as_mut: var_type!(&mut u32, &mut String, &mut bool) =
    ///     var_expr!(1_u32, "Hello".to_owned(), false).as_mut_var();
    /// ```
    fn as_mut_var(&mut self) -> Self::AsMutVar<'_>;

    /// Iterator type returned by [`Self::iter_any_ref`].
    type IterAnyRef<'a>: Iterator<Item = &'a dyn Any>
    where
        Self: 'static;
    /// Iterate this variadic as `&dyn Any` references.
    fn iter_any_ref(&self) -> Self::IterAnyRef<'_>
    where
        Self: 'static;

    /// Iterator type returned by [`Self::iter_any_mut`].
    type IterAnyMut<'a>: Iterator<Item = &'a mut dyn Any>
    where
        Self: 'static;
    /// Iterate this variadic as `&mut dyn Any` exclusive references.
    fn iter_any_mut(&mut self) -> Self::IterAnyMut<'_>
    where
        Self: 'static;

    /// type for all elements of the variadic being wrapped in `Option`
    type IntoOption;
    /// wrap all elements of the variadic in `Option``
    fn into_option(self) -> Self::IntoOption;

    /// type for all elements of the variadic being wrapped in `Vec`
    type IntoVec: VecVariadic<UnVec = Self> + Default;
    /// wrap all elements of the variadic in a `Vec`
    fn into_singleton_vec(self) -> Self::IntoVec;
}

#[sealed]
impl<Item, Rest> VariadicExt for (Item, Rest)
where
    Rest: VariadicExt,
{
    const LEN: usize = 1 + Rest::LEN;

    type Extend<Suffix>
        = (Item, Rest::Extend<Suffix>)
    where
        Suffix: VariadicExt;
    fn extend<Suffix>(self, suffix: Suffix) -> Self::Extend<Suffix>
    where
        Suffix: VariadicExt,
    {
        let (item, rest) = self;
        (item, rest.extend(suffix))
    }

    type Reverse = <Rest::Reverse as VariadicExt>::Extend<(Item, ())>;
    fn reverse(self) -> Self::Reverse {
        let (item, rest) = self;
        rest.reverse().extend((item, ()))
    }
    fn reverse_ref(this: Self::AsRefVar<'_>) -> <Self::Reverse as VariadicExt>::AsRefVar<'_> {
        let (item, rest) = this;
        let out = Rest::reverse_ref(rest).extend((item, ()));
        // TODO(mingwei): check if use of unsafe is necessary
        let out2 = unsafe { std::mem::transmute_copy(&out) };
        std::mem::forget(out);
        out2
    }

    type AsRefVar<'a>
        = (&'a Item, Rest::AsRefVar<'a>)
    where
        Self: 'a;
    fn as_ref_var(&self) -> Self::AsRefVar<'_> {
        let (item, rest) = self;
        (item, rest.as_ref_var())
    }

    type AsMutVar<'a>
        = (&'a mut Item, Rest::AsMutVar<'a>)
    where
        Self: 'a;
    fn as_mut_var(&mut self) -> Self::AsMutVar<'_> {
        let (item, rest) = self;
        (item, rest.as_mut_var())
    }

    type IterAnyRef<'a>
        = std::iter::Chain<std::iter::Once<&'a dyn Any>, Rest::IterAnyRef<'a>>
    where
        Self: 'static;
    fn iter_any_ref(&self) -> Self::IterAnyRef<'_>
    where
        Self: 'static,
    {
        let var_args!(item, ...rest) = self;
        let item: &dyn Any = item;
        std::iter::once(item).chain(rest.iter_any_ref())
    }

    type IterAnyMut<'a>
        = std::iter::Chain<std::iter::Once<&'a mut dyn Any>, Rest::IterAnyMut<'a>>
    where
        Self: 'static;
    fn iter_any_mut(&mut self) -> Self::IterAnyMut<'_>
    where
        Self: 'static,
    {
        let var_args!(item, ...rest) = self;
        let item: &mut dyn Any = item;
        std::iter::once(item).chain(rest.iter_any_mut())
    }

    type IntoOption = (Option<Item>, Rest::IntoOption);
    fn into_option(self) -> Self::IntoOption {
        let var_args!(item, ...rest) = self;
        var_expr!(Some(item), ...rest.into_option())
    }

    type IntoVec = (Vec<Item>, Rest::IntoVec);
    fn into_singleton_vec(self) -> Self::IntoVec {
        let var_args!(item, ...rest) = self;
        var_expr!(vec!(item), ...rest.into_singleton_vec())
    }
}

#[sealed]
impl VariadicExt for () {
    const LEN: usize = 0;

    type Extend<Suffix>
        = Suffix
    where
        Suffix: VariadicExt;
    fn extend<Suffix>(self, suffix: Suffix) -> Self::Extend<Suffix>
    where
        Suffix: VariadicExt,
    {
        suffix
    }

    type Reverse = ();
    fn reverse(self) -> Self::Reverse {}
    fn reverse_ref(_this: Self::AsRefVar<'_>) -> <Self::Reverse as VariadicExt>::AsRefVar<'_> {}

    type AsRefVar<'a> = ();
    fn as_ref_var(&self) -> Self::AsRefVar<'_> {}

    type AsMutVar<'a> = ();
    fn as_mut_var(&mut self) -> Self::AsMutVar<'_> {}

    type IterAnyRef<'a>
        = std::iter::Empty<&'a dyn Any>
    where
        Self: 'static;
    fn iter_any_ref(&self) -> Self::IterAnyRef<'_>
    where
        Self: 'static,
    {
        std::iter::empty()
    }

    type IterAnyMut<'a>
        = std::iter::Empty<&'a mut dyn Any>
    where
        Self: 'static;
    fn iter_any_mut(&mut self) -> Self::IterAnyMut<'_>
    where
        Self: 'static,
    {
        std::iter::empty()
    }

    type IntoOption = ();
    fn into_option(self) -> Self::IntoOption {}

    type IntoVec = ();
    fn into_singleton_vec(self) -> Self::IntoVec {}
}

/// A variadic of either shared references, exclusive references, or both.
///
/// Provides the [`Self::UnRefVar`] associated type which is the original variadic of owned values.
///
/// This is a sealed trait.
#[sealed]
pub trait EitherRefVariadic: VariadicExt {
    /// The un-referenced variadic. Each item will have one layer of shared references removed.
    ///
    /// The inverse of [`VariadicExt::AsRefVar`] and [`VariadicExt::AsMutVar`].
    ///
    /// ```rust
    /// # use variadics::*;
    /// let un_ref: <var_type!(&u32, &String, &bool) as EitherRefVariadic>::UnRefVar =
    ///     var_expr!(1_u32, "Hello".to_owned(), false);
    /// ```
    type UnRefVar: VariadicExt;

    /// This type with all exclusive `&mut` references replaced with shared `&` references.
    ///
    /// Returned by [`Self::mut_to_ref`].
    type RefVar: RefVariadic<UnRefVar = Self::UnRefVar, RefVar = Self::RefVar>;
    /// Convert all exclusive (`mut`) references into shared references: [`RefVariadic`].
    ///
    /// ```rust
    /// # use variadics::*;
    /// let mut original = var_expr!(1_u32, "Hello".to_owned(), false);
    /// let as_mut: var_type!(&mut u32, &mut String, &mut bool) = original.as_mut_var();
    /// let as_ref_1: var_type!(&u32, &String, &bool) = as_mut.mut_to_ref();
    /// let as_ref_2: var_type!(&u32, &String, &bool) = as_ref_1; // Can copy the reference version.
    /// drop((as_ref_1, as_ref_2));
    /// ```
    fn mut_to_ref(self) -> Self::RefVar;

    /// This type with all shared `&` references replaced with exclusive references `&mut`.
    ///
    /// Conversion from `&` to `&mut` is generally invalid, so a `ref_to_mut()` method does not exist.
    type MutVar: MutVariadic<UnRefVar = Self::UnRefVar, MutVar = Self::MutVar>;

    /// convert entries to [`<UnRefVar as VariadicExt>::AsRefVar`](VariadicExt::AsRefVar)
    fn unref_ref(&self) -> <Self::UnRefVar as VariadicExt>::AsRefVar<'_>;
}
#[sealed]
impl<'a, Item, Rest> EitherRefVariadic for (&'a Item, Rest)
where
    Rest: EitherRefVariadic,
{
    type UnRefVar = (Item, Rest::UnRefVar);

    type RefVar = (&'a Item, Rest::RefVar);
    fn mut_to_ref(self) -> Self::RefVar {
        let var_args!(item, ...rest) = self;
        var_expr!(item, ...rest.mut_to_ref())
    }

    type MutVar = (&'a mut Item, Rest::MutVar);

    fn unref_ref(&self) -> <Self::UnRefVar as VariadicExt>::AsRefVar<'_> {
        let var_args!(item, ...rest) = self;
        var_expr!(item, ...rest.unref_ref())
    }
}
#[sealed]
impl<'a, Item, Rest> EitherRefVariadic for (&'a mut Item, Rest)
where
    Rest: EitherRefVariadic,
{
    type UnRefVar = (Item, Rest::UnRefVar);

    type RefVar = (&'a Item, Rest::RefVar);
    fn mut_to_ref(self) -> Self::RefVar {
        let var_args!(item, ...rest) = self;
        var_expr!(&*item, ...rest.mut_to_ref())
    }

    type MutVar = (&'a mut Item, Rest::MutVar);

    fn unref_ref(&self) -> <Self::UnRefVar as VariadicExt>::AsRefVar<'_> {
        let var_args!(item, ...rest) = self;
        var_expr!(item, ...rest.unref_ref())
    }
}
#[sealed]
impl EitherRefVariadic for () {
    type UnRefVar = ();

    type RefVar = ();
    fn mut_to_ref(self) -> Self::RefVar {}

    type MutVar = ();

    fn unref_ref(&self) -> <Self::UnRefVar as VariadicExt>::AsRefVar<'_> {}
}

/// A variadic where each item is a shared reference `&item`.
///
/// This can be created using [`VariadicExt::as_ref_var`]:
/// ```rust
/// # use variadics::*;
/// let as_ref: var_type!(&u32, &String, &bool) =
///     var_expr!(1_u32, "Hello".to_owned(), false).as_ref_var();
/// ```
///
/// This is a sealed trait.
#[sealed]
pub trait RefVariadic: EitherRefVariadic<RefVar = Self>
where
    Self: Copy,
{
}
#[sealed]
impl<Item, Rest> RefVariadic for (&Item, Rest) where Rest: RefVariadic {}
#[sealed]
impl RefVariadic for () {}

/// A variadic where each item is an exclusive reference `&mut item`.
///
/// This can be created using [`VariadicExt::as_mut_var`]:
/// ```rust
/// # use variadics::*;
/// let as_mut: var_type!(&mut u32, &mut String, &mut bool) =
///     var_expr!(1_u32, "Hello".to_owned(), false).as_mut_var();
/// ```
///
/// This is a sealed trait.
#[sealed]
pub trait MutVariadic: EitherRefVariadic<MutVar = Self> {}
#[sealed]
impl<Item, Rest> MutVariadic for (&mut Item, Rest) where Rest: MutVariadic {}
#[sealed]
impl MutVariadic for () {}

/// Copy a variadic of references [`EitherRefVariadic`] into a variadic of owned values [`EitherRefVariadic::UnRefVar`].
///
/// ```rust
/// # use variadics::*;
/// let ref_var = var_expr!(&1, &"hello", &false);
/// let copy_var = ref_var.copy_var();
/// assert_eq!(var_expr!(1, "hello", false), copy_var);
/// ```
#[sealed]
pub trait CopyRefVariadic: EitherRefVariadic {
    /// Copy self per-value.
    fn copy_var(&self) -> Self::UnRefVar;
}
#[sealed]
impl<Item, Rest> CopyRefVariadic for (&Item, Rest)
where
    Item: Copy,
    Rest: CopyRefVariadic,
{
    fn copy_var(&self) -> Self::UnRefVar {
        let var_args!(&item, ...rest) = self;
        var_expr!(item, ...rest.copy_var())
    }
}
#[sealed]
impl<Item, Rest> CopyRefVariadic for (&mut Item, Rest)
where
    Item: Copy,
    Rest: CopyRefVariadic,
{
    fn copy_var(&self) -> Self::UnRefVar {
        let var_args!(&mut item, ...rest) = self;
        var_expr!(item, ...rest.copy_var())
    }
}
#[sealed]
impl CopyRefVariadic for () {
    fn copy_var(&self) -> Self::UnRefVar {}
}

/// Clone a variadic of references [`AsRefVar`](VariadicExt::AsRefVar) into a variadic of owned values.
///
/// ```rust
/// # use variadics::*;
/// let ref_var = var_expr!(&1, &format!("hello {}", "world"), &vec![1, 2, 3]);
/// let clone_var = CloneVariadic::clone_ref_var(ref_var);
/// assert_eq!(
///     var_expr!(1, "hello world".to_owned(), vec![1, 2, 3]),
///     clone_var
/// );
/// ```
#[sealed]
pub trait CloneVariadic: VariadicExt + Clone {
    /// Clone a variadic of references [`AsRefVar`](VariadicExt::AsRefVar) into a variadic of owned values.
    fn clone_ref_var(this: Self::AsRefVar<'_>) -> Self;
}
#[sealed]
impl<Item, Rest> CloneVariadic for (Item, Rest)
where
    Item: Clone,
    Rest: CloneVariadic,
{
    fn clone_ref_var(this: Self::AsRefVar<'_>) -> Self {
        let var_args!(item, ...rest) = this;
        var_expr!(item.clone(), ...Rest::clone_ref_var(rest))
    }
}
#[sealed]
impl CloneVariadic for () {
    fn clone_ref_var(_this: Self::AsRefVar<'_>) -> Self {}
}

/// A variadic where all item implement [`PartialEq`].
#[sealed]
pub trait PartialEqVariadic: VariadicExt {
    /// `PartialEq` between a referenced variadic and a variadic of references, of the same types.
    fn eq(&self, other: &Self) -> bool;

    /// `PartialEq` for the `AsRefVar` version op `Self`.
    fn eq_ref(this: Self::AsRefVar<'_>, other: Self::AsRefVar<'_>) -> bool;
}
#[sealed]
impl<Item, Rest> PartialEqVariadic for (Item, Rest)
where
    Item: PartialEq,
    Rest: PartialEqVariadic,
{
    fn eq(&self, other: &Self) -> bool {
        let var_args!(item_self, ...rest_self) = self;
        let var_args!(item_other, ...rest_other) = other;
        item_self == item_other && rest_self.eq(rest_other)
    }

    fn eq_ref(
        this: <Self as VariadicExt>::AsRefVar<'_>,
        other: <Self as VariadicExt>::AsRefVar<'_>,
    ) -> bool {
        let var_args!(item_self, ...rest_self) = this;
        let var_args!(item_other, ...rest_other) = other;
        item_self == item_other && Rest::eq_ref(rest_self, rest_other)
    }
}
#[sealed]
impl PartialEqVariadic for () {
    fn eq(&self, _other: &Self) -> bool {
        true
    }

    fn eq_ref(
        _this: <Self as VariadicExt>::AsRefVar<'_>,
        _other: <Self as VariadicExt>::AsRefVar<'_>,
    ) -> bool {
        true
    }
}

/// A variadic where all elements are the same type, `T`.
///
/// This is a sealed trait.
#[sealed]
pub trait HomogenousVariadic<T>: Variadic {
    /// Returns a reference to an element.
    fn get(&self, i: usize) -> Option<&T>;
    /// Returns an exclusive reference to an element.
    fn get_mut(&mut self, i: usize) -> Option<&mut T>;

    /// Iterator type returned by `into_iter`.
    type IntoIter: Iterator<Item = T>;
    /// Turns this `HomogenousVariadic<T>` into an iterator of items `T`.
    fn into_iter(self) -> Self::IntoIter;
}
#[sealed]
impl<T> HomogenousVariadic<T> for () {
    fn get(&self, _i: usize) -> Option<&T> {
        None
    }
    fn get_mut(&mut self, _i: usize) -> Option<&mut T> {
        None
    }

    type IntoIter = std::iter::Empty<T>;
    fn into_iter(self) -> Self::IntoIter {
        std::iter::empty()
    }
}
#[sealed]
impl<T, Rest> HomogenousVariadic<T> for (T, Rest)
where
    Rest: HomogenousVariadic<T>,
{
    fn get(&self, i: usize) -> Option<&T> {
        let (item, rest) = self;
        if i == 0 {
            Some(item)
        } else {
            rest.get(i - 1)
        }
    }
    fn get_mut(&mut self, i: usize) -> Option<&mut T> {
        let (item, rest) = self;
        if i == 0 {
            Some(item)
        } else {
            rest.get_mut(i - 1)
        }
    }

    type IntoIter = std::iter::Chain<std::iter::Once<T>, Rest::IntoIter>;
    fn into_iter(self) -> Self::IntoIter {
        let (item, rest) = self;
        std::iter::once(item).chain(rest.into_iter())
    }
}

/// Helper trait for splitting a variadic into two parts. `Prefix` is the first part, everything
/// after is the `Suffix` or second part.
///
/// This is a sealed trait.
#[sealed]
pub trait Split<Prefix>: VariadicExt
where
    Prefix: VariadicExt,
{
    /// The second part when splitting this variadic by `Prefix`.
    type Suffix: VariadicExt;
    /// Splits this variadic into two parts, first the `Prefix`, and second the `Suffix`.
    fn split(self) -> (Prefix, Self::Suffix);
    /// Splits a refvar variadic
    fn split_ref(
        this: Self::AsRefVar<'_>,
    ) -> (
        Prefix::AsRefVar<'_>,
        <Self::Suffix as VariadicExt>::AsRefVar<'_>,
    );
}
#[sealed]
impl<Item, Rest, PrefixRest> Split<(Item, PrefixRest)> for (Item, Rest)
where
    PrefixRest: VariadicExt,
    Rest: Split<PrefixRest>,
{
    /// The second part when splitting this variadic by `Prefix`.
    type Suffix = <Rest as Split<PrefixRest>>::Suffix;
    /// Splits this variadic into two parts, first the `Prefix`, and second the `Suffix`.
    fn split(self) -> ((Item, PrefixRest), Self::Suffix) {
        let (item, rest) = self;
        let (prefix_rest, suffix) = rest.split();
        ((item, prefix_rest), suffix)
    }
    /// Splits a refvar variadic
    fn split_ref(
        this: Self::AsRefVar<'_>,
    ) -> (
        <(Item, PrefixRest) as VariadicExt>::AsRefVar<'_>,
        <Self::Suffix as VariadicExt>::AsRefVar<'_>,
    ) {
        let (item, rest) = this;
        let (prefix_rest, suffix) = Rest::split_ref(rest);
        ((item, prefix_rest), suffix)
    }
}
#[sealed]
impl<Rest> Split<var_type!()> for Rest
where
    Rest: VariadicExt,
{
    type Suffix = Rest;
    fn split(self) -> (var_type!(), Self::Suffix) {
        (var_expr!(), self)
    }
    fn split_ref(
        this: Self::AsRefVar<'_>,
    ) -> (var_type!(), <Self::Suffix as VariadicExt>::AsRefVar<'_>) {
        (var_expr!(), this)
    }
}

#[sealed]
/// Helper trait for splitting a variadic into two parts. `Prefix` is the first part, everything
/// after is the `Suffix` or second part.
///
/// This is a sealed trait.
pub trait SplitBySuffix<Suffix>: VariadicExt
where
    Suffix: VariadicExt,
{
    /// The first part when splitting this variadic by `Suffix`.
    type Prefix: VariadicExt;
    /// Splits this variadic into two parts, first the `Prefix`, and second the `Suffix`.
    fn split_by_suffix(self) -> (Self::Prefix, Suffix);
    /// Splits a refvar variadic
    fn split_by_suffix_ref(
        this: Self::AsRefVar<'_>,
    ) -> (
        <Self::Prefix as VariadicExt>::AsRefVar<'_>,
        Suffix::AsRefVar<'_>,
    );
}
#[sealed]
impl<Suffix, This> SplitBySuffix<Suffix> for This
where
    Suffix: VariadicExt,
    This: VariadicExt,
    This::Reverse: Split<Suffix::Reverse>,
    Suffix::Reverse: VariadicExt<Reverse = Suffix>,
{
    /// The second part when splitting this variadic by `Prefix`.
    type Prefix = <<This::Reverse as Split<Suffix::Reverse>>::Suffix as VariadicExt>::Reverse;
    /// Splits this variadic into two parts, first the `Prefix`, and second the `Suffix`.
    fn split_by_suffix(self) -> (Self::Prefix, Suffix) {
        let (rsuffix, rprefix) = self.reverse().split();
        (rprefix.reverse(), rsuffix.reverse())
    }

    fn split_by_suffix_ref(
        this: Self::AsRefVar<'_>,
    ) -> (
        <Self::Prefix as VariadicExt>::AsRefVar<'_>,
        Suffix::AsRefVar<'_>,
    ) {
        let rev = This::reverse_ref(this);
        let (rsuffix, rprefix) = <This::Reverse as Split<Suffix::Reverse>>::split_ref(rev);
        let out = (rprefix.reverse(), rsuffix.reverse());
        // TODO!!!!
        let out2 = unsafe { std::mem::transmute_copy(&out) };
        std::mem::forget(out);
        out2
    }
}

/// trait for Variadic of vecs, as formed by `VariadicExt::into_vec()`
#[sealed]
pub trait VecVariadic: VariadicExt {
    /// Individual variadic items without the Vec wrapper
    type UnVec: VariadicExt<IntoVec = Self>;

    /// zip across all the vecs in this VariadicVec
    fn zip_vecs(&self) -> impl Iterator<Item = <Self::UnVec as VariadicExt>::AsRefVar<'_>>;

    /// append an unvec'ed Variadic into this VariadicVec
    fn push(&mut self, item: Self::UnVec);

    /// get the unvec'ed Variadic at position `index`
    fn get(&mut self, index: usize) -> Option<<Self::UnVec as VariadicExt>::AsRefVar<'_>>;

    /// result type from into_zip
    type IntoZip: Iterator<Item = Self::UnVec>;
    /// Turns into an iterator of items `UnVec` -- i.e. iterate through rows (not columns!).
    fn into_zip(self) -> Self::IntoZip;

    /// result type from drain
    type Drain<'a>: Iterator<Item = Self::UnVec>
    where
        Self: 'a;
    /// Turns into a Drain of items `UnVec` -- i.e. iterate through rows (not columns!).
    fn drain<R>(&mut self, range: R) -> Self::Drain<'_>
    where
        R: std::ops::RangeBounds<usize> + Clone;
}

#[sealed]
impl<Item, Rest> VecVariadic for (Vec<Item>, Rest)
where
    Rest: VecVariadic,
{
    type UnVec = var_type!(Item, ...Rest::UnVec);

    fn zip_vecs(&self) -> impl Iterator<Item = <Self::UnVec as VariadicExt>::AsRefVar<'_>> {
        let (this, rest) = self;
        std::iter::zip(this.iter(), rest.zip_vecs())
    }

    fn push(&mut self, row: Self::UnVec) {
        let (this_vec, rest_vecs) = self;
        let (this_col, rest_cols) = row;
        this_vec.push(this_col);
        rest_vecs.push(rest_cols);
    }

    fn get(&mut self, index: usize) -> Option<<Self::UnVec as VariadicExt>::AsRefVar<'_>> {
        let (this_vec, rest_vecs) = self;
        if let Some(rest) = VecVariadic::get(rest_vecs, index) {
            this_vec.get(index).map(|item| var_expr!(item, ...rest))
        } else {
            None
        }
    }

    type IntoZip = std::iter::Zip<std::vec::IntoIter<Item>, Rest::IntoZip>;
    fn into_zip(self) -> Self::IntoZip {
        let (this, rest) = self;
        std::iter::zip(this, rest.into_zip())
    }

    type Drain<'a>
        = std::iter::Zip<std::vec::Drain<'a, Item>, Rest::Drain<'a>>
    where
        Self: 'a;
    fn drain<R>(&mut self, range: R) -> Self::Drain<'_>
    where
        R: std::ops::RangeBounds<usize> + Clone,
    {
        let (this, rest) = self;
        std::iter::zip(this.drain(range.clone()), rest.drain(range))
    }
}

#[sealed]
impl VecVariadic for var_type!() {
    type UnVec = var_type!();

    fn zip_vecs(&self) -> impl Iterator<Item = <Self::UnVec as VariadicExt>::AsRefVar<'_>> {
        std::iter::repeat(var_expr!())
    }

    fn push(&mut self, _item: Self::UnVec) {}

    fn get(&mut self, _index: usize) -> Option<<Self::UnVec as VariadicExt>::AsRefVar<'_>> {
        Some(())
    }

    type IntoZip = std::iter::Repeat<var_type!()>;
    fn into_zip(self) -> Self::IntoZip {
        std::iter::repeat(var_expr!())
    }

    type Drain<'a>
        = std::iter::Repeat<var_type!()>
    where
        Self: 'a;
    fn drain<R>(&mut self, _range: R) -> Self::Drain<'_>
    where
        R: std::ops::RangeBounds<usize>,
    {
        std::iter::repeat(var_expr!())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    type MyList = var_type!(u8, u16, u32, u64);
    type MyPrefix = var_type!(u8, u16);
    #[expect(dead_code, reason = "compilation test")]
    type MySuffix = <MyList as Split<MyPrefix>>::Suffix;

    const _: MySuffix = var_expr!(0_u32, 0_u64);

    #[test]
    // #[expect(clippy::let_unit_value, reason = "var_expr macro test")]
    fn test_basic_expr() {
        let _ = var_expr!();
        let _ = var_expr!(1);
        let _ = var_expr!(1, "b",);
        let _ = var_expr!("a",);
        let _ = var_expr!(false, true, 1 + 2);
    }

    // commented out because neither #[allow(dead_code)] nor #[expect(dead_code)] made clippy happy
    // variadic_trait! {
    //     /// Variaidic list of futures.
    //     pub variadic<F> FuturesList where F: std::future::Future {
    //     }
    // }

    type _ListA = var_type!(u32, u8, i32);
    type _ListB = var_type!(..._ListA, bool, Option<()>);
    type _ListC = var_type!(..._ListA, bool, Option::<()>);

    #[test]
    fn test_as_ref_var() {
        let my_owned = var_expr!("Hello".to_owned(), Box::new(5));
        let my_ref_a = my_owned.as_ref_var();
        let my_ref_b = my_owned.as_ref_var();
        assert_eq!(my_ref_a, my_ref_b);
    }

    #[test]
    fn test_as_mut_var() {
        let mut my_owned = var_expr!("Hello".to_owned(), Box::new(5));
        let var_args!(mut_str, mut_box) = my_owned.as_mut_var();
        *mut_str += " World";
        *mut_box.as_mut() += 1;

        assert_eq!(var_expr!("Hello World".to_owned(), Box::new(6)), my_owned);
    }

    #[test]
    fn test_iter_any() {
        let mut var = var_expr!(1_i32, false, "Hello".to_owned());

        let mut mut_iter = var.iter_any_mut();
        *mut_iter.next().unwrap().downcast_mut::<i32>().unwrap() += 1;
        *mut_iter.next().unwrap().downcast_mut::<bool>().unwrap() |= true;
        *mut_iter.next().unwrap().downcast_mut::<String>().unwrap() += " World";
        assert!(mut_iter.next().is_none());

        let mut ref_iter = var.iter_any_ref();
        assert_eq!(
            Some(&2),
            ref_iter
                .next()
                .map(<dyn Any>::downcast_ref)
                .map(Option::unwrap)
        );
        assert_eq!(
            Some(&true),
            ref_iter
                .next()
                .map(<dyn Any>::downcast_ref)
                .map(Option::unwrap)
        );
        assert_eq!(
            Some("Hello World"),
            ref_iter
                .next()
                .map(|any| &**any.downcast_ref::<String>().unwrap())
        );
        assert!(ref_iter.next().is_none());
    }

    #[test]
    fn test_homogenous_get() {
        let mut var = var_expr!(0, 1, 2, 3, 4);
        for i in 0..5 {
            assert_eq!(Some(i), var.get(i).copied());
            assert_eq!(Some(i), var.get_mut(i).copied());
        }
    }

    #[test]
    fn test_into_vec() {
        use crate::VecVariadic;

        type Item = var_type!(i32, String);
        let first: Item = var_expr!(1, "Joe".to_string());
        let second: Item = var_expr!(2, "Mingwei".to_string());
        let mut column_store = first.clone().into_singleton_vec();
        column_store.push(second.clone());
        assert_eq!(column_store.len(), 2);
        assert_eq!(column_store.get(0).unwrap(), first.as_ref_var());
        assert_eq!(column_store.get(1).unwrap(), second.as_ref_var());
    }
}

#[test]
fn test_eq_ref_vec() {
    type MyVar = var_type!(i32, bool, &'static str);
    let vec: Vec<MyVar> = vec![
        var_expr!(0, true, "hello"),
        var_expr!(1, true, "world"),
        var_expr!(2, false, "goodnight"),
        var_expr!(3, false, "moon"),
    ];
    let needle: <MyVar as VariadicExt>::AsRefVar<'_> =
        var_expr!(2, false, "goodnight").as_ref_var();
    assert_eq!(
        Some(2),
        vec.iter()
            .position(|item| <MyVar as PartialEqVariadic>::eq_ref(needle, item.as_ref_var()))
    );

    let missing: <MyVar as VariadicExt>::AsRefVar<'_> =
        var_expr!(3, false, "goodnight").as_ref_var();
    assert_eq!(
        None,
        vec.iter()
            .position(|item| <MyVar as PartialEqVariadic>::eq_ref(missing, item.as_ref_var()))
    );
}

#[test]
fn clone_var_test() {
    let ref_var = var_expr!(&1, &format!("hello {}", "world"), &vec![1, 2, 3]);
    let clone_var = CloneVariadic::clone_ref_var(ref_var);
    assert_eq!(
        var_expr!(1, "hello world".to_owned(), vec![1, 2, 3]),
        clone_var
    );
}