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
#![no_std]
#![forbid(unsafe_code)]

//! [![crates.io]](https://crates.io/crates/transitive_from)
//! [![github]](https://github.com/steffahn/transitive_from)
//! [![MIT / Apache 2.0 licensed]](https://github.com/steffahn/transitive_from#License)
//! [![unsafe forbidden]](https://github.com/rust-secure-code/safety-dance/)
//!
//! Helper macros for creating hierarchies of transitive [`From`] implementations.
//!
//! Currently, this crate only consists of the [`transitive_from::hierarchy`](hierarchy) macro.  
//! Please use the link to go to its page for further documentation.
//!
//! [github]: https://img.shields.io/badge/github-steffahn/transitive__from-yellowgreen.svg
//! [crates.io]: https://img.shields.io/crates/v/transitive_from.svg
//! [MIT / Apache 2.0 licensed]: https://img.shields.io/crates/l/replace_with.svg
//! [docs.rs]: https://docs.rs/transitive_from/badge.svg
//! [unsafe forbidden]: https://img.shields.io/badge/unsafe-forbidden-success.svg

/**
Helper macro to create transitive [`From`] implementations.

This macro can work on tree-shaped hierarchies of
implementations `impl From<Child> for Parent` along the tree edges.
It will produce new `From` implementations along paths towards
the root by chaining [`From::from()`] calls along the edges.
There must not be any pre-existing `impl From`s for anything but
the immediate edges.

For further details, study the example below.

The syntax supports arbitrary type expressions where the example just
uses simple names like `A`, `B`, `C`, etc; the macro does
however not produce any generic implementations. Inside of each `{` `}`
block, a trailing comma is optional.

# Examples
```
// Here’s a drawing of an example hierarchy.
//
//            ┌─ E
//      ┌─ B ─┤     ┌─ J
//      │     └─ F ─┤
//      │           └─ K
//   A ─┼─ C ─── G
//      │
//      │     ┌─ H
//      └─ D ─┤
//            └─ I ─── L
//
// For example, all these types could be error types and we
// would like to fully support upcasting with the `?` operator
// from anywhere to anywhere in this hierarchy.
struct A;
struct B;
struct C;
struct D;
struct E;
struct F;
struct G;
struct H;
struct I;
struct J;
struct K;
struct L;

// We need to provide implementation for all the tree edges
// (all the immediate "child -> parent" steps) manually,
// or by some other means. In this example we use a small macro
// to save some boilerplate.
macro_rules! impl_From {
    (<$B:ident> for $A:ident) => {
        impl From<$B> for $A {
            fn from(_: $B) -> $A {
                $A
            }
        }
    }
}
impl_From!(<B> for A);
impl_From!(<C> for A);
impl_From!(<D> for A);
impl_From!(<E> for B);
impl_From!(<F> for B);
impl_From!(<G> for C);
impl_From!(<H> for D);
impl_From!(<I> for D);
impl_From!(<J> for F);
impl_From!(<K> for F);
impl_From!(<L> for I);

// Now, to produce all the remaining (transitive) implementations
// and complete the hierarchy, call the macro like this:
transitive_from::hierarchy! {
    A {
        B {
            E,
            F { J, K },
        },
        C { G },
        D {
            H,
            I { L },
        },
    }
}
// Note how the syntax resembles the tree drawn at the top of this example.

// Finally, a few demonstration/test cases:
A::from(K);
A::from(E);
B::from(K);
D::from(L);
A::from(L);
```
*/
#[macro_export]
macro_rules! hierarchy {

    ($($root:ty $({
        $($child:ty $({
            $($grandchildren_parsed_recursively:tt)*
        })?),* $(,)?
    })?),* $(,)?) => {
        $($(
            $crate::hierarchy!{
                $($child $({
                    $($grandchildren_parsed_recursively)*
                })?),*
            }
            $($(
                $crate::__hierarchy_internals!{
                    [$root][$child][
                        $($grandchildren_parsed_recursively)*
                    ]
                }
            )?)*
        )?)*

    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __hierarchy_internals {
    ([$root:ty][$child:ty][
        $($grandchild:ty $({
            $($further:tt)*
        })?),* $(,)?
    ]) => {
        $(
            $($crate::__hierarchy_internals!{
                [$root][$child][
                    $($further)*
                ]
            })?
            impl ::core::convert::From<$grandchild> for $root {
                fn from(g: $grandchild) -> Self {
                    <$root>::from(<$child>::from(g))
                }
            }
        )*
    };
}

#[cfg(test)]
mod test {
    #![allow(unused)]
    pub enum GlobalError {
        Shape(ShapeError),
        Color(ColorError),
    }
    impl From<ShapeError> for GlobalError {
        fn from(e: ShapeError) -> Self {
            Self::Shape(e)
        }
    }
    impl From<ColorError> for GlobalError {
        fn from(e: ColorError) -> Self {
            Self::Color(e)
        }
    }

    pub enum ShapeError {
        Circle(CircleError),
        Rectangle(RectangleError),
    }
    impl From<CircleError> for ShapeError {
        fn from(e: CircleError) -> Self {
            Self::Circle(e)
        }
    }
    impl From<RectangleError> for ShapeError {
        fn from(e: RectangleError) -> Self {
            Self::Rectangle(e)
        }
    }

    pub struct CircleError {
        msg: &'static str,
        radius: f64,
    }

    pub enum RectangleError {
        Square(SquareError),
        ArbitraryRectangleError { msg: &'static str, a: f64, b: f64 },
    }
    impl From<SquareError> for RectangleError {
        fn from(e: SquareError) -> Self {
            Self::Square(e)
        }
    }

    pub struct SquareError {
        msg: &'static str,
        a: f64,
    }

    pub enum ColorError {
        Red(RedError),
        Blue(BlueError),
    }
    impl From<RedError> for ColorError {
        fn from(e: RedError) -> Self {
            Self::Red(e)
        }
    }
    impl From<BlueError> for ColorError {
        fn from(e: BlueError) -> Self {
            Self::Blue(e)
        }
    }

    pub struct RedError {
        msg: &'static str,
    }

    pub struct BlueError {
        msg: &'static str,
    }

    crate::hierarchy! {
        GlobalError {
            ShapeError {
                CircleError,
                RectangleError { SquareError },
            },
            ColorError { RedError, BlueError }
        }
    }

    fn foo() -> Result<(), SquareError> {
        Err(SquareError {
            msg: "hello world",
            a: 42.0,
        })
    }

    fn bar() -> Result<(), GlobalError> {
        foo()?;
        Ok(())
    }

    #[test]
    fn conversion_test() {
        bar().err().unwrap();
    }
}