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
//! Note, for best results using `typle` with rust-analyzer, ensure that proc macro attributes are enabled:
//! ```json
//! rust-analyzer.procMacro.enable: true,
//! rust-analyzer.procMacro.attributes.enable: true
//! ```
//!
//! # `#[typle(...)]`
//! The `typle` attribute macro generates code for multiple tuple lengths. This code:
//!
//! ```rust
//! use typle::typle;
//!
//! struct MyStruct<T> {
//! t: T,
//! }
//!
//! #[typle(Tuple for 2..=3)]
//! impl<T: Tuple> From<T> for MyStruct<T>
//! {
//! fn from(t: T) -> Self {
//! MyStruct { t }
//! }
//! }
//! ```
//!
//! generates implementations of the `From` trait for tuples with 2 to 3 components:
//! ```rust
//! # struct MyStruct<T> {
//! # t: T,
//! # }
//! impl<T0, T1> From<(T0, T1)> for MyStruct<(T0, T1)> {
//! fn from(t: (T0, T1)) -> Self {
//! MyStruct { t }
//! }
//! }
//!
//! impl<T0, T1, T2> From<(T0, T1, T2)> for MyStruct<(T0, T1, T2)> {
//! fn from(t: (T0, T1, T2)) -> Self {
//! MyStruct { t }
//! }
//! }
//! ```
//!
//! Individual components of a tuple can be selected using `<{i}>` for types and
//! `[[i]]` for values. The value `i` must be a *typle index expression*, an
//! expression that only uses literal `usize` values or *typle index variables*
//! created by one of several macros in this crate. Typle index expressions can
//! reduce to a single value or to a range.
//!
//! ```rust
//! # use typle::typle;
//! /// Split off the first component of a tuple.
//! #[typle(Tuple for 1..=12)]
//! fn split_first<T: Tuple>(
//! t: T // t: (T<0>, T<1>, T<2>,...)
//! ) -> (T<0>, (T<{1..}>)) // -> (T<0>, (T<1>, T<2>,...))
//! {
//! (t[[0]], (t[[1..]])) // (t.0, (t.1, t.2,...))
//! }
//!
//! let t = ('1', 2, 3.0);
//! let (first, rest) = split_first(t); // first = '1', rest = (2, 3.0)
//! assert_eq!(first, '1');
//! let (first, rest) = split_first(rest); // first = 2, rest = (3.0,)
//! assert_eq!(first, 2);
//! let (first, rest) = split_first(rest); // first = 3.0, rest = ()
//! assert_eq!(first, 3.0);
//! assert_eq!(rest, ());
//! ```
//!
//! The default bounds for a macro range are `0..Tuple::LEN`, encapsulating all
//! components of the tuple.
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 0..12)]
//! fn append<T: Tuple, A>(t: T, a: A) -> (T<{..}>, A) {
//! (t[[..]], a)
//! }
//!
//! assert_eq!(append((1, 2, 3), 4), (1, 2, 3, 4));
//! ```
//!
//! # `typle!`
//!
//! The `typle!` macro generally iterates over a range to create a new comma-separated sequence of
//! elements. A `typle!` macro with a range can only appear where a comma-separated sequence is
//! valid (e.g. a tuple, array, argument list, or where clause).
//!
//! The `typle!` macro can provide an optional typle index variable for each iteration to use in the
//! macro expansion.
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 0..=12)]
//! fn indices<T: Tuple>(t: T) -> (typle! {.. => usize}) { // (usize, usize,...)
//! (typle! {i in .. => i}) // (0, 1,...)
//! }
//!
//! assert_eq!(indices(('a', Some(true), "test", 9)), (0, 1, 2, 3));
//! ```
//!
//! The associated constant `LEN` provides the length of the tuple in each
//! generated item and can be used in typle index expressions.
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 0..=12)]
//! fn reverse<T: Tuple>(t: T) -> (typle! {i in 1..=T::LEN => T<{T::LEN - i}>}) {
//! (typle! {i in 1..=T::LEN => t[[T::LEN - i]]})
//! }
//!
//! assert_eq!(reverse((Some(3), "four", 5)), (5, "four", Some(3)));
//! ```
//!
//! Each iteration can add multiple elements to the new sequence.
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 0..=12)]
//! fn duplicate_components<T: Tuple>(
//! t: T,
//! ) -> (typle! {i in .. => T<{i}>, T<{i}>})
//! where
//! T<_>: Clone,
//! {
//! (typle! {i in .. => t[[i]].clone(), t[[i]]})
//! }
//!
//! assert_eq!(duplicate_components(("one", 2, 3.0)), ("one", "one", 2, 2, 3.0, 3.0));
//! ```
//!
//! The `typle!` macro can be used without a range. In this case it must return
//! a single value but can be used outside a comma-separated sequence. Remember that `typle!`
//! with a range effectively adds a trailing comma to each element that may affect the created type.
//!
//! ```rust
//! # use typle::typle;
//! # #[typle(Tuple for 0..1)]
//! # fn singleton<T: Tuple>(t: T) {
//! // outside a sequence create a single `bool`
//! let result: bool = typle! {=> true};
//! // typle! with a range outside a sequence is an error
//! // let result = typle! {0..1 => true}; // ERROR
//! // inside parentheses without a range create a parenthesized `bool`
//! let result: (bool) = (typle! {=> true});
//! // inside parentheses with a 1-element range create a `bool` 1-tuple
//! let result: (bool,) = (typle! {0..1 => true});
//! // inside brackets both forms create a `bool` array
//! let result: [bool; 1] = [typle! {=> true}];
//! let result: [bool; 1] = [typle! {0..1 => true}];
//! # }
//! ```
//!
//! # Bounds
//!
//! Specify bounds on the tuple components using one of the following
//! forms. Except for the first form, these bounds can only appear in the
//! `where` clause.
//! - `T: Tuple<C>` - all components of the tuple have type `C`.
//! - `T<_>: Clone` - all components of the tuple implement the `Clone` trait.
//! - `T<0>: Clone` - the first component of the tuple implements the `Clone` trait.
//! - `T<{1..=2}>: Clone` - the second and third components implement the `Clone` trait.
//! - `typle!(j in .. => I<{j}>: Iterator<Item=T<{j}>>): Tuple::Bounds` - the most
//! general way to bound components, allowing typle index expressions on both
//! sides of the colon. Note that the suffix `: Tuple::Bounds` is required after
//! the macro, where `Tuple` is the name of the typle trait.
//!
//! ```rust
//! # use typle::typle;
//! use std::{ops::Mul, time::Duration};
//!
//! // Multiply the components of two tuples
//! #[typle(Tuple for 0..=12)]
//! fn multiply<S: Tuple, T: Tuple>(
//! s: S, // s: (S<0>,...)
//! t: T, // t: (T<0>,...)
//! ) -> (typle! {i in .. => <S<{i}> as Mul<T<{i}>>>::Output}) // (<S<0> as Mul<T<0>>>::Output,...)
//! where
//! typle! {i in .. => S<{i}>: Mul<T<{i}>>}: Tuple::Bounds, // S<0>: Mul<T<0>>,...
//! {
//! (typle! {i in .. => s[[i]] * t[[i]]}) // (s.0 * t.0,...)
//! }
//!
//! assert_eq!(
//! multiply((Duration::from_secs(5), 2), (4, 3)),
//! (Duration::from_secs(20), 6)
//! )
//! ```
//!
//! # Conditionals
//!
//! The `typle!` macro accepts an `if` statement with an optional `else` clause.
//! If there is no `else` clause the macro filters out elements that do not match
//! the condition.
//!
//! The `typle_attr_if` attribute allows conditional inclusion of attributes. It works similarly to
//! [`cfg_attr`](https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute)
//! except that the first argument is a boolean typle index expression.
//!
//! ```rust
//! # use typle::typle;
//! #[cfg_attr(not(feature = "big-tuple"), typle(Tuple for 0..=12))]
//! #[cfg_attr(feature = "big-tuple", typle(Tuple for 0..=24))]
//! fn even_to_string<T: Tuple>(
//! t: T,
//! ) -> (typle!(i in .. => if i % 2 == 0 { String } else { T<{i}> }))
//! where
//! typle!(i in .. => if i % 2 == 0 { T<{i}>: ToString }): Tuple::Bounds,
//! {
//! #[typle_attr_if(T::LEN == 0, allow(clippy::unused_unit))]
//! (typle!(i in .. => if i % 2 == 0 { t[[i]].to_string() } else { t[[i]] }))
//! }
//!
//! // `Vec` does not implement `ToString` but, in an odd position, it doesn't need to
//! assert_eq!(even_to_string((0, vec![1], 2, 3)), (0.to_string(), vec![1], 2.to_string(), 3));
//! ```
//!
//! An un-ranged `typle!` macro can be used to add an `if` statement where
//! expressions are otherwise invalid:
//!
//! ```rust
//! # use typle::typle;
//! # struct MyStruct<T> {
//! # t: T,
//! # }
//! trait ReplaceLast {
//! type Last;
//!
//! // Replace the "last" value with a new value, returning the old value
//! fn replace_last(&mut self, new: Self::Last) -> Self::Last;
//! }
//!
//! #[typle(Tuple for 0..=3)]
//! impl<T: Tuple> ReplaceLast for MyStruct<T> {
//! type Last = typle!(=> if T::LEN == 0 { () } else { T<{T::LAST}> });
//!
//! fn replace_last(
//! &mut self,
//! new: typle!(=> if T::LEN == 0 { () } else { T<{T::LAST}>}),
//! ) -> typle!(=> if T::LEN == 0 { () } else { T<{T::LAST}> }) {
//! typle!(=> if T::LEN == 0 { () } else {
//! std::mem::replace(&mut self.t[[T::LAST]], new)
//! })
//! }
//! }
//! ```
//!
//! Note, real code like the above can avoid all these `if`s by using a specific `impl` for `()` and
//! a simplified typle `impl` for `1..=3`.
//!
//! The `typle_const!` macro supports const-if on a boolean typle index expression. const-if allows
//! conditional branches that do not compile, as long as the invalid branch is `false` at compile time.
//!
//! The associated constant `LAST` is always equal to `LEN - 1`. `LAST` is not defined when
//! `LEN == 0` and will cause a compilation error. The following code uses `T::LAST` but compiles
//! successfully for `T::LEN == 0` because `T::LAST` only appears in an `else` branch that is
//! not compiled when `T::LEN == 0`.
//!
//! ```rust
//! # use typle::typle;
//! # #[derive(Clone)]
//! # struct Input {}
//! trait HandleStuff {
//! type Output;
//!
//! fn handle_stuff(&self, input: Input) -> Self::Output;
//! }
//!
//! struct MultipleHandlers<T> {
//! handlers: T,
//! }
//!
//! #[typle(Tuple for 0..=12)]
//! impl<T> HandleStuff for MultipleHandlers<T>
//! where
//! T: Tuple,
//! T<_>: HandleStuff,
//! {
//! type Output = (typle! {i in .. => T<{i}>::Output});
//!
//! // Return a tuple of output from each handler applied to the same input.
//! fn handle_stuff(&self, input: Input) -> Self::Output {
//! if typle_const!(T::LEN == 0) {
//! ()
//! } else {
//! (
//! typle! {
//! i in ..T::LAST => self.handlers[[i]].handle_stuff(input.clone())
//! },
//! // Avoid expensive clone for the last handler.
//! self.handlers[[T::LAST]].handle_stuff(input),
//! )
//! }
//! }
//! }
//! ```
//!
//! # Iteration
//!
//! Use the `typle_index!` macro in a `for` loop to iterate over a range bounded
//! by typle index expressions.
//!
//! ```rust
//! # use typle::typle;
//! # struct MyStruct<T> {
//! # t: T,
//! # }
//! # impl<T0, T1, T2> From<(T0, T1, T2)> for MyStruct<(T0, T1, T2)> {
//! # fn from(t: (T0, T1, T2)) -> Self {
//! # MyStruct { t }
//! # }
//! # }
//! #[typle(Tuple for 1..=3)]
//! impl<T, C> MyStruct<T>
//! where
//! T: Tuple<C>,
//! C: Default + for<'a> std::ops::AddAssign<&'a C>,
//! {
//! // Return the sums of all even positions and all odd positions.
//! fn interleave(&self) -> [C; 2] {
//! let mut even_odd = [C::default(), C::default()];
//! for typle_index!(i) in 0..T::LEN {
//! even_odd[i % 2] += &self.t[[i]];
//! }
//! even_odd
//! }
//! }
//!
//! let m = MyStruct::from((3, 9, 11));
//! assert_eq!(m.interleave(), [14, 9]);
//! ```
//!
//! # Aggregation
//!
//! The [`typle_fold!`] macro reduces a tuple to a single value.
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 0..=12)]
//! fn sum<T: Tuple<u32>>(t: T) -> u32 {
//! typle_fold! {0; i in .. => |total| total + t[[i]]}
//! }
//!
//! assert_eq!(sum(()), 0);
//! assert_eq!(sum((1, 4, 9, 16)), 30);
//! ```
//!
//! # Selection
//!
//! Indexing using `[[i]]` only works with tuple index expressions. To select a component from a
//! tuple value using a variable, use `typle_index!` in a `match` expression:
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 1..=12)]
//! fn get_component<'t, C, T>(t: &'t T, i: usize) -> Option<&'t C>
//! where
//! T: Tuple<C>,
//! {
//! // `i` is a variable, `j` is a typle index variable.
//! match i {
//! j @ typle_index!(0..T::LEN) => Some(&t[[j]]),
//! _ => None,
//! }
//! }
//!
//! let t = ('a', 'b', 'c', 'd', 'e');
//! assert_eq!(get_component(&t, 1), Some(&'b'));
//! assert_eq!(get_component(&t, 7), None);
//! ```
//! ```rust
//! # use typle::typle;
//! /// Trait for types that can treated as an infinitely wrapping sequence of chars.
//! trait WrappingString {
//! /// Return a 2 character substring starting at position `start`.
//! fn wrapping_substring_at(&self, start: usize) -> String;
//! }
//!
//! #[typle(Tuple for 1..=12)]
//! impl<T: Tuple<char>> WrappingString for T {
//! #[typle_attr_if(T::LEN < 2, allow(unused))]
//! fn wrapping_substring_at(&self, start: usize) -> String {
//! if typle_const!(T::LEN == 1) {
//! [ self.0, self.0 ].into_iter().collect()
//! } else {
//! match start % T::LEN {
//! j @ typle_index!(0..T::LAST) => {
//! [ self[[j..=j + 1]] ].into_iter().collect()
//! }
//! T::LAST => {
//! [ self[[T::LAST]], self.0 ].into_iter().collect()
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//! }
//!
//! let t = ('a', 'b', 'c', 'd', 'e');
//! assert_eq!(t.wrapping_substring_at(6), "bc");
//! assert_eq!(t.wrapping_substring_at(4), "ea");
//! assert_eq!(('f',).wrapping_substring_at(12), "ff");
//! ```
//!
//! # `enum`
//!
//! Applying `typle` to an `enum` implements the `enum` once for the maximum length only.
//!
//! The [`typle_variant!`] macro creates multiple enum variants by looping
//! similarly to `typle!`.
//!
//! ```rust
//! # use typle::typle;
//! pub trait Extract {
//! type State;
//! type Output;
//!
//! fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! }
//!
//! #[typle(Tuple for 1..=4)]
//! pub enum TupleSequenceState<T>
//! where
//! T: Tuple,
//! T<_>: Extract,
//! {
//! // The output of all previous components plus the state of the current component.
//! S = typle_variant!(curr in ..T::MAX =>
//! (typle! {prev in ..curr => T::<{prev}>::Output}),
//! Option<T<{curr}>::State>
//! ),
//! }
//! ```
//!
//! The generated implementation:
//! ```rust
//! # pub trait Extract {
//! # type State;
//! # type Output;
//! # fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! # }
//! // enum implemented only for maximum size
//! pub enum TupleSequenceState<T0, T1, T2, T3>
//! where
//! T0: Extract,
//! T1: Extract,
//! T2: Extract,
//! T3: Extract,
//! {
//! S0((), Option<T0::State>),
//! S1((T0::Output,), Option<T1::State>),
//! S2((T0::Output, T1::Output), Option<T2::State>),
//! S3((T0::Output, T1::Output, T2::Output), Option<T3::State>),
//! }
//! ```
//!
//! Other `typle` implementations can refer to this enum using
//! `TupleSequenceState<T<{ ..T::MAX }>>`. This will fill in unused type
//! parameters with the `never` type provided for the `typle` macro. The default
//! type is [`!`] but this is not available in stable Rust.
//! [`std::convert::Infallible`] is an uninhabited type that is available in
//! stable Rust, but any type is permissible.
//!
//! The `typle_ident!` macro concatenates a number to an identifier. For
//! example `S::<typle_ident!(3)>` becomes the identifier `S3`. This is mainly
//! used to refer to enum variants.
//!
//! ```rust
//! # use typle::typle;
//! # pub trait Extract {
//! # type State;
//! # type Output;
//! # fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! # }
//! # #[typle(Tuple for 1..=4)]
//! # pub enum TupleSequenceState<T>
//! # where
//! # T: Tuple,
//! # T<_>: Extract,
//! # {
//! # S = typle_variant!(curr in ..T::MAX =>
//! # (typle! {prev in ..curr => T::<{prev}>::Output}),
//! # Option<T<{curr}>::State>
//! # ),
//! # }
//! // Relevant traits may need to be implemented for the never type.
//! impl Extract for std::convert::Infallible {
//! type State = std::convert::Infallible;
//! type Output = ();
//!
//! fn extract(
//! &self,
//! _state: Option<Self::State>,
//! ) -> Self::Output {
//! ()
//! }
//! }
//!
//! pub struct TupleSequence<T> {
//! tuple: T,
//! }
//!
//! #[typle(Tuple for 1..=4, never=std::convert::Infallible)]
//! impl<T> Extract for TupleSequence<T>
//! where
//! T: Tuple,
//! T<_>: Extract,
//! {
//! // The state contains the output from all previous components and
//! // the state of the current component.
//! type State = TupleSequenceState<T<{ ..T::MAX }>>;
//! // The final output is a tuple of outputs from all components.
//! type Output = (typle! {i in .. => <T<{i}> as Extract>::Output});
//!
//! fn extract(&self, state: Option<Self::State>) -> Self::Output {
//! // When LEN == 1 the code never changes `state`
//! #[typle_attr_if(T::LEN == 1, allow(unused_mut))]
//! let mut state = state.unwrap_or(Self::State::S::<typle_ident!(0)>((), None));
//! for typle_index!(i) in 0..T::LEN {
//! // When i == 0, the `output` state variable does not get used
//! #[typle_attr_if(i == 0, allow(unused_variables))]
//! if let Self::State::S::<typle_ident!(i)>(output, inner_state) = state {
//! let matched = self.tuple[[i]].extract(inner_state);
//! let output = (output[[..i]], matched);
//! if typle_const!(i == T::LAST) {
//! return output;
//! } else {
//! state = Self::State::S::<typle_ident!(i + 1)>(output, None);
//! }
//! }
//! }
//! unreachable!();
//! }
//! }
//! ```
//!
//! Generated implementation for 3-tuples:
//! ```rust
//! # pub trait Extract {
//! # type State;
//! # type Output;
//! # fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! # }
//! # pub enum TupleSequenceState<T0, T1, T2, T3>
//! # where
//! # T0: Extract,
//! # T1: Extract,
//! # T2: Extract,
//! # T3: Extract,
//! # {
//! # S0((), Option<T0::State>),
//! # S1((T0::Output,), Option<T1::State>),
//! # S2((T0::Output, T1::Output), Option<T2::State>),
//! # S3((T0::Output, T1::Output, T2::Output), Option<T3::State>),
//! # }
//! # impl Extract for std::convert::Infallible {
//! # type State = std::convert::Infallible;
//! # type Output = ();
//! # fn extract(&self, _state: Option<Self::State>) -> Self::Output {
//! # ()
//! # }
//! # }
//! # pub struct TupleSequence<T> {
//! # tuple: T,
//! # }
//! impl<T0, T1, T2> Extract for TupleSequence<(T0, T1, T2)>
//! where
//! T0: Extract,
//! T1: Extract,
//! T2: Extract,
//! {
//! // reference to enum uses `never` type for unused type parameters.
//! type State = TupleSequenceState<T0, T1, T2, std::convert::Infallible>;
//! type Output = (
//! <T0 as Extract>::Output,
//! <T1 as Extract>::Output,
//! <T2 as Extract>::Output,
//! );
//! fn extract(&self, state: Option<Self::State>) -> Self::Output {
//! let mut state = state.unwrap_or(Self::State::S0((), None));
//! loop {
//! {
//! #[allow(unused_variables)]
//! if let Self::State::S0(output, inner_state) = state {
//! let matched = self.tuple.0.extract(inner_state);
//! let output = (matched,);
//! {
//! state = Self::State::S1(output, None);
//! }
//! }
//! }
//! {
//! if let Self::State::S1(output, inner_state) = state {
//! let matched = self.tuple.1.extract(inner_state);
//! let output = (output.0, matched);
//! {
//! state = Self::State::S2(output, None);
//! }
//! }
//! }
//! {
//! if let Self::State::S2(output, inner_state) = state {
//! let matched = self.tuple.2.extract(inner_state);
//! let output = (output.0, output.1, matched);
//! {
//! return output;
//! }
//! }
//! }
//! break;
//! }
//! unreachable!();
//! }
//! }
//! ```
//!
//! # Limitations
//!
//! - The typle trait bound (`Tuple` in the examples) can only be applied to an
//! unqualified type identifier, not to non-path types or associated types.
//! - The `#[typle]` macro does not work when the tuple types are only associated types
//! because [associated types cannot distinguish implementations](https://github.com/rust-lang/rust/issues/20400).
//! See [this file](https://github.com/jongiddy/typle/blob/main/tests/compile/unzip.rs)
//! for workarounds.
//! ```rust ignore
//! // ERROR: conflicting implementations of trait `TryUnzip`
//! # use typle::typle;
//! # trait TryUnzip {}
//! #[typle(Tuple for 2..=3)]
//! impl<I, T, E> TryUnzip for I
//! where
//! I: Iterator<Item = Result<T, E>>, // T only appears as associated type of Self
//! T: Tuple,
//! {}
//! ```
//! - Standalone `async` and `unsafe` functions are not supported.
//! - Standalone functions require explicit lifetimes on references:
//! ```rust
//! # use std::hash::{Hash, Hasher};
//! # use typle::typle;
//! #[typle(Tuple for 1..=3)]
//! pub fn hash<'a, T: Tuple, S: Hasher>(tuple: &'a T, state: &'a mut S)
//! where
//! T<_>: Hash,
//! T<{T::LAST}>: ?Sized,
//! {
//! for typle_index!(i) in 0..T::LEN {
//! tuple[[i]].hash(state);
//! }
//! }
//! ```
//! Explicit lifetimes are also required for methods bound by a typle trait
//! inside an impl that is not bound by a typle trait:
//! ```rust
//! # use typle::typle;
//! # struct A {}
//! #[typle(Tuple for 1..=3)]
//! impl A {
//! fn identity<'a, T: Tuple>(&'a self, t: &'a T) -> &'a T {
//! t
//! }
//! }
//! ```
//! - Typle index variables can be shadowed by inner typle index variables
//! but cannot be shadowed by standard variables:
//! ```rust
//! # use typle::typle;
//! # #[typle(Tuple for 1..=1)]
//! # fn test<T>(t: T) where T: Tuple {
//! let mut v = vec![];
//!
//! for typle_index!(i) in 2..=3 {
//! for typle_index!(i) in 4..=5 {
//! let i = 1; // this `i` is ignored
//! v.push(i); // this `i` comes from `4..=5`
//! }
//! v.push(i); // this `i` comes from `2..=3`
//! }
//! assert_eq!(v, [4, 5, 2, 4, 5, 3]);
//! # }
//! # test((1,));
//! ```
//! - Due to interaction of `typle` with other macros, passing some types and
//! expressions to a macro may produce unexpected results. To help work around
//! this, inside a macro invocation the `typle_ty!` macro expands types and the
//! `typle_expr!` macro expands expressions.
//!
//! ```rust
//! # use typle::typle;
//! #[typle(Tuple for 3..=3)]
//! fn test_macro<T: Tuple>(t: T)
//! where
//! T<_>: PartialEq<usize> + std::fmt::Debug,
//! {
//! assert_eq!(
//! stringify!([T, T::LEN, typle_ty!(T), typle_expr!(T::LEN)]),
//! "[T, T :: LEN, (T0, T1, T2), 3]"
//! );
//! for typle_index!(i) in 0..T::LEN {
//! assert_eq!(typle_expr!(t[[i]]), typle_expr!(i));
//! }
//! }
//! test_macro((0, 1, 2));
//! ```
use Rc;
use evaluate_usize;
use TypleContext;
use ;
use ToTokens;
use Spanned as _;
use ;
/// Short-circuiting check that all values are true.
///
/// ```rust
/// # use typle::typle;
/// #[typle(Tuple for 0..=12)]
/// fn all_long<T: Tuple<&str>>(t: T) -> bool {
/// typle_all!(i in .. => t[[i]].len() > 5)
/// }
/// // Return `true` if all words meet the criteria.
/// assert_eq!(all_long(("longest", "phrase")), true);
/// // Return `false` if any words fail to meet the criteria.
/// assert_eq!(all_long(("the", "longest", "word")), false);
/// // Return `true` for an empty tuple as no words fail to meet the criteria.
/// assert_eq!(all_long(()), true);
/// ```
///
/// Short-circuiting check that any values are true.
///
/// ```rust
/// # use typle::typle;
/// #[typle(Tuple for 0..=12)]
/// fn any_long<T: Tuple<&str>>(t: T) -> bool {
/// typle_any!(i in .. => t[[i]].len() > 5)
/// }
/// // Return `true` if any word meets the criteria.
/// assert_eq!(any_long(("the", "longest", "word")), true);
/// // Return `false` if no words meet the criteria.
/// assert_eq!(any_long(("short", "words")), false);
/// // Return `false` for an empty tuple as no words meet the criteria.
/// assert_eq!(any_long(()), false);
/// ```
///
/// Reduce a tuple to a single value.
///
/// The `typle_fold!` macro repeatedly applies an expression to an accumulator
/// to collect tuple components into a single value. The macro starts with an
/// initial value. It then loops through a typle index variable, modifying an
/// accumulator with an expression on each iteration.
///
/// Examples:
/// ```
/// # use typle::typle;
/// #[typle(Tuple for 0..=12)]
/// pub fn sum<T: Tuple<u32>>(t: T) -> u32 {
/// typle_fold!(0; i in .. => |total| total + t[[i]])
/// }
/// // An empty tuple uses the initial value.
/// assert_eq!(sum(()), 0);
/// // Otherwise the accumulator is passed to the expression to create a new
/// // value, which is then passed to the next iteration.
/// assert_eq!(sum((1, 4, 9, 16)), 30);
/// ```
///
/// The name of the accumulator is provided between vertical bars (`|total|`)
/// followed by the expression. This makes it look similar to a closure, which
/// it usually acts like. But there are some differences:
/// - the "closure parameter" naming the accumulator can only contain a single
/// identifier;
/// - a `break` in the expression terminates the fold early with the value of
/// the `break`;
/// - a `return` in the expression returns from the enclosing function (since
/// the expression is not actually in a closure).
///
/// The previous example could have been implemented using a `for` loop.
/// However, unlike a `for` loop, the `typle_fold!` macro allows the accumulator
/// to change type on each iteration.
///
/// In the next example, the type of the accumulator after each iteration is a
/// tuple with one extra component from the prior iteration. The `..=` range
/// provides an extra iteration that wraps the tuple in `Some`.
///
/// ```rust
/// # use typle::typle;
/// trait CoalesceSome<T> {
/// type Output;
///
/// /// Coalesce a tuple of Options into an Option of tuple that is `Some`
/// /// only if all the components are `Some`.
/// fn coalesce_some(self) -> Option<Self::Output>;
/// }
///
/// #[typle(Tuple for 0..=12)]
/// impl<T: Tuple> CoalesceSome<T> for (typle!(i in .. => Option<T<{i}>>)) {
/// type Output = T;
///
/// fn coalesce_some(self) -> Option<Self::Output>
/// {
/// typle_fold!(
/// (); // Initially an empty tuple
/// i in ..=T::LEN => |acc| if typle_const!(i == T::LEN) {
/// // Final iteration: wrap accumulated tuple in `Some`
/// Some(acc)
/// } else if let Some(curr) = self[[i]] {
/// // Append the current value to the prior tuple to create a
/// // new accumulator with the type `(T<0>,...,T<{i}>)`
/// (acc[[..i]], curr)
/// } else {
/// // If `None` is found at any point, short-circuit with a `None` result
/// break None;
/// }
/// )
/// }
/// }
/// assert_eq!(
/// ().coalesce_some(),
/// Some(())
/// );
/// assert_eq!(
/// (Some(1), Some("x")).coalesce_some(),
/// Some((1, "x"))
/// );
/// assert_eq!(
/// (None::<i32>, Some("x")).coalesce_some(),
/// None::<(i32, &str)>
/// );
/// ```
///
/// The `typle_fold!` macro can also be used for recursive types. See the
/// [example in the tests].
///
/// [example in the tests]: https://github.com/jongiddy/typle/blob/main/tests/compile/typle_fold.rs
/// Create variants in an enum.
///
/// In an enum, the `typle_variant` macro allows the creation of variants for each element.
///
/// A variant is created for each index in the range provided.
///
/// The variants will start with the variant name given before the `=` character, followed by the
/// index.
///
/// If the macro uses parentheses the variant will use unnamed fields. If the macro uses braces the
/// variant will use named fields. If the macro uses brackets the variant will have no fields.
///
/// Examples:
///
/// ```
/// # use typle::typle;
/// # trait Process {
/// # type Output;
/// # type State;
/// # }
/// #[typle(Tuple for 0..=2)]
/// pub enum ProcessState<T>
/// where
/// T: Tuple,
/// T<_>: Process<Output = u64>,
/// {
/// S = typle_variant!(i in ..T::MAX => Option<T<{i}>::State>, [u64; i]),
/// U = typle_variant!{i in ..Tuple::MAX => u: [u32; i]},
/// V = typle_variant![..Tuple::MAX],
/// Done([u64; Tuple::MAX]),
/// }
/// ```
/// creates
/// ```
/// # trait Process {
/// # type Output;
/// # type State;
/// # }
/// pub enum ProcessState<T0, T1>
/// where
/// T0: Process<Output = u64>,
/// T1: Process<Output = u64>,
/// {
/// S0(Option<<T0>::State>, [u64; 0]),
/// S1(Option<<T1>::State>, [u64; 1]),
/// U0 { u: [u32; 0] },
/// U1 { u: [u32; 1] },
/// V0,
/// V1,
/// Done([u64; 2]),
/// }
/// ```