1 // run-pass
2 use std::ops::*;
3 
4 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
5 struct Nil;
6  // empty HList
7 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
8 struct Cons<H, T: HList>(H, T);
9  // cons cell of HList
10 
11  // trait to classify valid HLists
12 trait HList { }
13 impl HList for Nil { }
14 impl <H, T: HList> HList for Cons<H, T> { }
15 
16 // term-level macro for HLists
17 macro_rules! hlist({  } => { Nil } ; { $ head : expr } => {
18                    Cons ( $ head , Nil ) } ; {
19                    $ head : expr , $ ( $ tail : expr ) , * } => {
20                    Cons ( $ head , hlist ! ( $ ( $ tail ) , * ) ) } ;);
21 
22 // type-level macro for HLists
23 macro_rules! HList({  } => { Nil } ; { $ head : ty } => {
24                    Cons < $ head , Nil > } ; {
25                    $ head : ty , $ ( $ tail : ty ) , * } => {
26                    Cons < $ head , HList ! ( $ ( $ tail ) , * ) > } ;);
27 
28 // nil case for HList append
29 impl <Ys: HList> Add<Ys> for Nil {
30     type
31     Output
32     =
33     Ys;
34 
add(self, rhs: Ys) -> Ys35     fn add(self, rhs: Ys) -> Ys { rhs }
36 }
37 
38 // cons case for HList append
39 impl <Rec: HList + Sized, X, Xs: HList, Ys: HList> Add<Ys> for Cons<X, Xs>
40  where Xs: Add<Ys, Output = Rec> {
41     type
42     Output
43     =
44     Cons<X, Rec>;
45 
add(self, rhs: Ys) -> Cons<X, Rec>46     fn add(self, rhs: Ys) -> Cons<X, Rec> { Cons(self.0, self.1 + rhs) }
47 }
48 
49 // type macro Expr allows us to expand the + operator appropriately
50 macro_rules! Expr({ ( $ ( $ LHS : tt ) + ) } => { Expr ! ( $ ( $ LHS ) + ) } ;
51                   { HList ! [ $ ( $ LHS : tt ) * ] + $ ( $ RHS : tt ) + } => {
52                   < Expr ! ( HList ! [ $ ( $ LHS ) * ] ) as Add < Expr ! (
53                   $ ( $ RHS ) + ) >> :: Output } ; {
54                   $ LHS : tt + $ ( $ RHS : tt ) + } => {
55                   < Expr ! ( $ LHS ) as Add < Expr ! ( $ ( $ RHS ) + ) >> ::
56                   Output } ; { $ LHS : ty } => { $ LHS } ;);
57 
58 // test demonstrating term level `xs + ys` and type level `Expr!(Xs + Ys)`
main()59 fn main() {
60     fn aux<Xs: HList, Ys: HList>(xs: Xs, ys: Ys) -> Expr!(Xs + Ys) where
61      Xs: Add<Ys> {
62         xs + ys
63     }
64 
65     let xs: HList!(& str , bool , Vec < u64 >) =
66         hlist!("foo" , false , vec ! [  ]);
67     let ys: HList!(u64 , [ u8 ; 3 ] , (  )) =
68         hlist!(0 , [ 0 , 1 , 2 ] , (  ));
69 
70     // demonstrate recursive expansion of Expr!
71     let zs:
72             Expr!((
73                   HList ! [ & str ] + HList ! [ bool ] + HList ! [ Vec < u64 >
74                   ] ) + ( HList ! [ u64 ] + HList ! [ [ u8 ; 3 ] , (  ) ] ) +
75                   HList ! [  ]) = aux(xs, ys);
76     assert_eq!(zs , hlist ! [
77                "foo" , false , vec ! [  ] , 0 , [ 0 , 1 , 2 ] , (  ) ])
78 }
79