treeerror 0.1.1

A crate of macros for generating trees of enums, as well as `From` implementations converting between them. Primarily intended for error handling.
Documentation
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
/// Shorthand for mapping one error enum on top of another one.
///
/// This takes things like:
/// ```
/// struct Child0;
/// struct Child1;
/// struct Child2;
/// struct Child3;
/// struct Child4;
///
/// enum Root {
///     ChildVariant0(Child0),
///     ChildVariant1(Child1),
///     ChildVariant2(Child2),
///     ChildVariant3(Child3),
///     ChildVariant4(Child4),
/// }
///
/// enum SimilarRoot {
///     ChildVariant0(Child0),
///     ChildVariant1(Child1),
///     ChildVariant2(Child2),
///     ChildVariant3(Child3),
///     ChildVariant4(Child4),
/// }
///
/// impl From<SimilarRoot> for Root {
///     fn from(r: SimilarRoot) -> Self {
///         match r {
///             SimilarRoot::ChildVariant0(c) => Self::ChildVariant0(c),
///             SimilarRoot::ChildVariant1(c) => Self::ChildVariant1(c),
///             SimilarRoot::ChildVariant2(c) => Self::ChildVariant2(c),
///             SimilarRoot::ChildVariant3(c) => Self::ChildVariant3(c),
///             SimilarRoot::ChildVariant4(c) => Self::ChildVariant4(c),
///         }
///     }
/// }
/// ```
/// and changes it into:
/// ```
/// #![feature(more_qualified_paths)]
/// use treeerror::map_enum;
///
/// struct Child0;
/// struct Child1;
/// struct Child2;
/// struct Child3;
/// struct Child4;
///
/// enum Root {
///     ChildVariant0(Child0),
///     ChildVariant1(Child1),
///     ChildVariant2(Child2),
///     ChildVariant3(Child3),
///     ChildVariant4(Child4),
/// }
///
/// enum SimilarRoot {
///     ChildVariant0(Child0),
///     ChildVariant1(Child1),
///     ChildVariant2(Child2),
///     ChildVariant3(Child3),
///     ChildVariant4(Child4),
/// }
///
/// map_enum!(SimilarRoot > Root {
///     ChildVariant0,
///     ChildVariant1,
///     ChildVariant2,
///     ChildVariant3,
///     ChildVariant4,
/// });
/// ```
///
/// As well as changing things like:
/// ```
/// struct Child0;
/// struct Child1;
///
/// enum Root {
///     ChildVariant0Rename(Child0, Child1),
///     ChildVariant1(Child1, Child0),
/// }
///
/// enum SimilarRoot {
///     ChildVariant0(Child0, Child1),
///     ChildVariant1(Child1, Child0),
/// }
///
/// impl From<SimilarRoot> for Root {
///     fn from(r: SimilarRoot) -> Self {
///         match r {
///             SimilarRoot::ChildVariant0(a, b) => Self::ChildVariant0Rename(a, b),
///             SimilarRoot::ChildVariant1(a, b) => Self::ChildVariant1(a, b),
///         }
///     }
/// }
/// ```
/// into:
/// ```
/// #![feature(more_qualified_paths)]
/// use treeerror::map_enum;
///
/// struct Child0;
/// struct Child1;
///
/// enum Root {
///     ChildVariant0Rename(Child0, Child1),
///     ChildVariant1(Child1, Child0),
/// }
///
/// enum SimilarRoot {
///     ChildVariant0(Child0, Child1),
///     ChildVariant1(Child1, Child0),
/// }
///
/// map_enum!(SimilarRoot > Root {
///     ChildVariant0 > ChildVariant0Rename = (a, b),
///     ChildVariant1 = (a, b),
/// });
/// ```
///
/// This is especially useful when there are multiple external errors that all need to be
/// mapped onto the same error (for example, three crates that depend on `reqwest` which
/// then individually wrap `reqwest`'s error in their own error). This can also be combined
/// with `from_chain!` for more functionality.
/// ```
/// #![feature(more_qualified_paths)]
/// mod impls {
///     use treeerror::{map_enum, from_chain, from_many};
///
///     #[derive(Debug)]
///     pub struct WebError;
///
///     pub mod suberror0 {
///         #[derive(Debug)]
///         pub struct MemoryError;
///         #[derive(Debug)]
///         pub enum E {
///             NotFound,
///             Web(super::WebError),
///             Memory(MemoryError),
///         }
///     }
///
///     pub mod suberror1 {
///         #[derive(Debug)]
///         pub struct MemoryError;
///         #[derive(Debug)]
///         pub enum WrappedMemoryError {
///             SomeError(MemoryError),
///         }
///         #[derive(Debug)]
///         pub enum E {
///             Web(super::WebError),
///             Memory(WrappedMemoryError),
///             WeirdInternalErrorThatShouldNotBeSurfaced,
///         }
///     }
///
///     pub enum SharedError {
///         NotFound,
///         Web(WebError),
///         Memory0(suberror0::MemoryError),
///         Memory1(suberror1::MemoryError),
///     }
///
///     map_enum!(suberror0::E > SharedError {
///         @unit NotFound,
///         Web,
///         Memory > Memory0,
///     });
///
///     map_enum!(suberror1::E > SharedError {
///         Web,
///         Memory = (a) {
///             let suberror1::WrappedMemoryError::SomeError(e) = a else {
///                 unreachable!("only one variant exists");
///             };
///             SharedError::Memory1(e)
///         },
///     } |e| {
///         panic!("this should not happen... {e:?}")
///     });
///
///     from_chain!(SharedError : Memory0, suberror0::MemoryError);
///     from_many!(SharedError = suberror1::WrappedMemoryError, suberror1::MemoryError > suberror1::E);
///     from_chain!(suberror1::E : Memory, suberror1::WrappedMemoryError : SomeError, suberror1::MemoryError);
/// }
///
/// let m: impls::SharedError = impls::suberror1::MemoryError.into();
///
/// ```
#[macro_export]
macro_rules! map_enum {
    // TODO Add support for specifying "dropping out" of some identities.
    ($from:path > $to:path {
        $($(@$m:ident)* $match:ident $(> $wrap:ident)? $(= ($($p:ident),*))? $($blk:block)?),+ $(,)?
    } $($(|$e:ident|)? $catch:block)?) => {
        impl From<$from> for $to {
            fn from(e: $from) -> Self {
                match e {
                    $($crate::map_enum!(@coerce pat $crate::map_enum!(
                        @invocation pat
                        (<$from>::$match)
                        __some_tok
                        $(@$m)*
                        ($($($p),*)?)
                    )) => {
                        $crate::map_enum!(
                            @invocation expr
                            ($crate::map_enum!(@unwrap_opt $($wrap)? $match (<$to>::)))
                            __some_tok
                            $(@$m)*
                            ($($($p),*)?)
                            $($blk)?
                        )
                    })+
                    $(e => {
                        $(let $e = e;)?
                        $catch
                    })?
                }
            }
        }
    };

    // This generates the pattern matching the original value that's being converted
    // from.
    (@invocation pat ($($path:tt)+) $escaped:ident @unit ($($tail:tt)*)) => (
        $($path)+
    );
    (@invocation pat ($($path:tt)+) $escaped:ident $(@$m:ident)* ()) => (
        $($path)+ ($escaped)
    );
    (@invocation pat ($($path:tt)+) $escaped:ident $(@$m:ident)* ($($tail:tt)+)) => (
        $($path)+ ($($tail)+)
    );

    // This generates the value that it's being converted to.
    (@invocation expr ($($path:tt)+) $escaped:ident @unit ($($tail:tt)*)) => (
        $($path)+
    );
    (@invocation expr ($($path:tt)+) $escaped:ident @flatten ()) => (
        $escaped
    );
    (@invocation expr ($($path:tt)+) $escaped:ident @flatten @conv ()) => (
        $escaped.into()
    );
    (@invocation expr ($($path:tt)+) $escaped:ident @conv @flatten ()) => (
        $escaped.into()
    );
    (@invocation expr ($($path:tt)+) $escaped:ident @conv ()) => (
        $($path)+ ($escaped.into())
    );
    (@invocation expr ($($path:tt)+) $escaped:ident @conv ($($tail:tt)+)) => (
        $crate::map_enum!(@paramlist ($($path)+) $($tail)+)
    );
    (@invocation expr ($($path:tt)+) $escaped:ident $(@$m:ident)* ()) => (
        $($path)+ ($escaped)
    );
    (@invocation expr ($($path:tt)+) $escaped:ident $(@$m:ident)* ($($tail:tt)+)) => (
        $($path)+ ($($tail)+)
    );
    (@invocation expr ($($path:tt)+) $escaped:ident $(@$m:ident)* ($($tail:tt)+) $blk:block) => (
        $blk
    );

    // Helps generate conversions on all params being matched against.
    (@paramlist ($($path:tt)+) $($params:ident),*) => (
        $($path)+ ($($params.into()),*)
    );

    // Needed to force the compiler to treat some things as specific kinds of tokens instead of
    // generic token trees.
    (@coerce pat $stuff:pat) => ($stuff);
    (@coerce exprlist ($($stuff:expr),*)) => ($($stuff),*);

    // Simulates an "if this is present use this else use that".
    // The `tail` is necessary since macros need to return a full tree and we sometimes need
    // information to make sure the tokens returned is a valid token tree.
    (@unwrap_opt $opt:ident $base:ident ($($tail:tt)*)) => ($($tail)* $opt);
    (@unwrap_opt $base:ident ($($tail:tt)*)) => ($($tail)* $base);
}

#[cfg(test)]
mod test {
    macro_rules! test_types {
        ($sub:ident, $full:ident) => {
            #[allow(dead_code)]
            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
            enum $sub {
                I(i32),
                S(String),
                U(u64),
                R(&'static str),
                M(i32, u64),
                Unit,
            }
            #[allow(dead_code)]
            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
            enum $full {
                I(i32),
                S(String),
                U(u64),
                Ra(&'static str),
                Ma(i32, u64),
                Ib(i32),
                Sb(String),
                Ub(u64),
                Rb(&'static str),
                Mb(i32, u64),
                Unit,
            }
        };
    }

    mod invocation {
        test_types!(Submap, Fullmap);

        #[test]
        fn test_expr_unit() {
            let a = map_enum!(@invocation expr (Submap::Unit) __ignored @unit ());
            assert_eq!(a, Submap::Unit, "escaped identifier to be used");
        }

        #[test]
        fn test_expr_single() {
            let sample = 0u64;
            let a = map_enum!(@invocation expr (Submap::U) sample ());
            assert_eq!(a, Submap::U(0), "escaped identifier to be used");
        }

        #[test]
        fn test_expr_multi() {
            let a = 0i32;
            let b = 2u64;
            let a1 = map_enum!(@invocation expr (Submap::M) __ignored (a, b));
            assert_eq!(a1, Submap::M(0, 2), "escaped identifier to be used");
        }

        #[test]
        fn test_expr_single_convert() {
            let sample = 0u32;
            let a = map_enum!(@invocation expr (Submap::U) sample @conv ());
            assert_eq!(a, Submap::U(0), "escaped identifier to be used");
        }

        #[test]
        fn test_expr_multi_convert() {
            let a = 0i16;
            let b = 2u32;
            let a1 = map_enum!(@invocation expr (Submap::M) __ignored @conv (a, b));
            assert_eq!(a1, Submap::M(0, 2), "escaped identifier to be used");
        }

        #[test]
        fn test_pattern_unit() {
            let s = Submap::Unit;
            match s {
                map_enum!(@invocation pat (Submap::Unit) _a @unit ()) => {
                },
                _ => {
                    unimplemented!("`s` should get matched in the previous line.");
                },
            }
        }

        #[test]
        fn test_pattern_single() {
            let s = Submap::I(0);
            match s {
                map_enum!(@invocation pat (Submap::I) a ()) => {
                    assert_eq!(a, 0, "Macro to properly extract the value");
                },
                _ => {
                    unimplemented!("`s` should get matched in the previous line.");
                },
            }
        }

        #[test]
        fn test_pattern_multi() {
            let s = Submap::M(0, 1);
            match s {
                map_enum!(@invocation pat (Submap::M) a (a, b)) => {
                    assert_eq!(a, 0, "Macro to properly extract the value");
                    assert_eq!(b, 1, "Macro to properly extract the value");
                    return;
                },
                _ => {},
            };
            unimplemented!("`s` should get matched in the previous line.");
        }
    }

    mod simple {
        test_types!(Submap, Fullmap);

        map_enum!(Submap > Fullmap {
            I > Ib,
        } |_ignored| {
            Fullmap::Unit
        });
    }

    mod alltogether {
        test_types!(S, F);
        map_enum!(S > F {
            I,
            S,
            U > Ub,
            R > Ra,
            M > Ma = (a, b),
            @unit Unit,
        });
    }
}