error-tree 0.6.0

This crate let's us use the `error_tree!` proc macro for ergonomic error hierarchy definition
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
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
crate::ix!();

pub struct ConversionChainKey {
    layers: Vec<Ident>,
}

impl ConversionChainKey {
    pub fn from_conversion_chain(chain: &ConversionChain) -> Self {
        let layers = chain
            .layers
            .iter()
            .map(|layer| layer.outer_enum_name.clone())
            .collect();
        ConversionChainKey { layers }
    }
}

impl Hash for ConversionChainKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for ident in &self.layers {
            ident.to_string().hash(state);
        }
    }
}

impl PartialEq for ConversionChainKey {
    fn eq(&self, other: &Self) -> bool {
        self.layers.len() == other.layers.len()
            && self.layers.iter().zip(&other.layers).all(|(a, b)| a.to_string() == b.to_string())
    }
}

impl Eq for ConversionChainKey {}

//--------------------------------------------------------[chain-layer]
#[derive(Hash, Debug, Clone, PartialEq, Eq)]
pub struct ConversionChainLayer {
    outer_enum_name:   Ident,
    enum_variant_name: Ident,
    inner_type_name:   Box<Type>,
}

/// In the beginning, we have something like this:
/// 
/// ```rust,ignore
///
/// error_tree! {
/// 
///     pub enum PassiveAudioCaptureError {
///         DeviceError(DeviceError),
///         IOError(IOError),
///     }
/// 
///     pub enum DeviceError {
///         DeviceNotAvailable {
///             device_name: String,
///         },
///         Basic(CpalDevicesError),
///         NameError(CpalDeviceNameError),
///     }
/// 
///     pub enum IOError {
///         Basic(std::io::Error),
///     }
/// 
///     // more enum defs
/// }
/// 
/// ```
/// 
/// After we generate the error enum definitions themselves,
/// we want the error_tree! macro to generate the following
/// code:
/// 
/// ```rust,ignore
///
/// impl From<CpalDeviceNameError> for DeviceError {
///     fn from(x: CpalDeviceNameError) -> Self {
///         DeviceError::NameError(x)
///     }
/// }
/// 
/// impl From<CpalDevicesError> for DeviceError {
///     fn from(x: CpalDevicesError) -> Self {
///         DeviceError::Basic(x)
///     }
/// }
/// 
/// impl From<std::io::Error> for IOError {
///     fn from(x: std::io::Error) -> Self {
///         IOError::Basic(x)
///     }
/// }
/// 
/// impl From<IOError> for PassiveAudioCaptureError {
///     fn from(x: IOError) -> Self {
///     }
///
///         PassiveAudioCaptureError::IOError(x)
/// }
/// 
/// impl From<DeviceError> for PassiveAudioCaptureError {
///     fn from(x: DeviceError) -> Self {
///         PassiveAudioCaptureError::DeviceError(x)
///     }
/// }
/// 
/// impl From<CpalDeviceNameError> for PassiveAudioCaptureError {
///     fn from(x: CpalDeviceNameError) -> Self {
///         PassiveAudioCaptureError::DeviceError(DeviceError::NameError(x))
///     }
/// }
/// 
/// impl From<CpalDevicesError> for PassiveAudioCaptureError {
///     fn from(x: CpalDevicesError) -> Self {
///         PassiveAudioCaptureError::DeviceError(DeviceError::Basic(x))
///     }
/// }
/// 
/// impl From<std::io::Error> for PassiveAudioCaptureError {
///     fn from(x: std::io::Error) -> Self {
///         PassiveAudioCaptureError::IOError(IOError::Basic(x))
///     }
/// }
/// ```
/// 
/// The purpose of the ConversionChain struct is to output
/// the function body for each `impl From`
/// 
/// for example: 
/// `fn from(x: T) -> Enum { /* conversion_chain goes here */ }`
/// 
/// Each ConversionChainLayer represents a *layer* of the
/// overall chain.
/// 
/// we support both adding inner and outer layers to the
/// ConversionChain
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversionChain {
    layers: VecDeque<ConversionChainLayer>,
}

impl ConversionChain {

    pub fn n_layers(&self) -> usize {
        self.layers.len()
    }

    pub fn new_from_treewalker(
        tree_stack:    &Vec<ErrorEnum>,
        wrapped_ident: &Ident,
        ty:            &Type,

    ) -> Result<Self, ConversionChainError> {

        let mut chain = ConversionChain::new();

        assert!(tree_stack.len() > 0);

        let mut tree_stack          = tree_stack.clone();

        let mut cur_wrapped_ident   = wrapped_ident.clone();
        let mut cur_ty              = ty.clone();

        let stack_item              = tree_stack.pop().unwrap();
        let mut cur_enum_name = stack_item.ident;

        let innermost_layer = ConversionChainLayer {
            outer_enum_name:   cur_enum_name.clone(),
            enum_variant_name: cur_wrapped_ident.clone(),
            inner_type_name:   Box::new(cur_ty.clone()),
        };

        chain.add_inner(innermost_layer)?;

        while let Some(stack_item) = tree_stack.pop() {

            cur_ty            = cur_enum_name.as_type();
            cur_wrapped_ident = stack_item.find_variant_name_wrapping_type(&cur_ty).expect("we expect valid ConversionChain");
            cur_enum_name     = stack_item.ident;

            let layer = ConversionChainLayer {
                outer_enum_name:   cur_enum_name.clone(),
                enum_variant_name: cur_wrapped_ident.clone(),
                inner_type_name:   Box::new(cur_ty.clone()),
            };

            chain.add_outer(layer)?;
        }

        //println!("{:#?}",chain);

        Ok(chain)
    }
}

impl ToTokens for ConversionChain {

    /// Generates the token stream for the conversion chain
    fn to_tokens(&self, tokens: &mut TokenStream2) {

        let nlayers = self.layers.len();

        let mut conversion_chain = TokenStream2::new();

        for (i, layer) in self.layers.iter().enumerate().rev() {

            let ConversionChainLayer { outer_enum_name, enum_variant_name, inner_type_name: _ } = layer;

            // Check if it's the first layer in the original order
            if i == nlayers - 1 {
                conversion_chain = quote!(#outer_enum_name::#enum_variant_name(x));
            } else {
                // Wrap the conversion chain for other layers
                conversion_chain = quote!(#outer_enum_name::#enum_variant_name(#conversion_chain));
            }
        }

        tokens.extend(conversion_chain);
    }
}

impl ConversionChain {

    /// Constructs a new, empty ConversionChain
    pub fn new() -> Self {
        Self { layers: VecDeque::new() }
    }

    pub fn source(&self) -> Option<Box<Type>> {
        Some(self.layers.back()?.inner_type_name.clone())
    }

    pub fn destination(&self) -> Option<Ident> {
        Some(self.layers.front()?.outer_enum_name.clone())
    }

    /// Adds an inner layer to the overall ConversionChain
    pub fn add_inner(&mut self, layer: ConversionChainLayer) 
        -> Result<(), ConversionChainError> 
    {
        if !self.can_wrap_layer_in_current_chain(&layer) {
            return Err(ConversionChainError::WrapLayerInChainFailed {
                layer_outer_enum_name: layer.outer_enum_name.clone(),
                chain_inner_type_name: self.get_current_chain_inner_type_name().unwrap(),
            });
        }

        self.layers.push_back(layer);

        Ok(())
    }

    /// Adds an inner layer to the overall ConversionChain
    pub fn add_outer(&mut self, layer: ConversionChainLayer) 
        -> Result<(), ConversionChainError> 
    {
        if !self.can_wrap_current_chain_in_layer(&layer) {
            return Err(ConversionChainError::WrapChainInLayerFailed {
                chain_outer_enum_name: self.get_current_chain_outer_enum_name().unwrap(),
                layer_inner_type_name: layer.inner_type_name.clone(),
            });
        }

        self.layers.push_front(layer);

        Ok(())
    }

    fn get_current_chain_inner_type_name(&self) -> Option<Box<Type>> {

        Some(self.layers.back()?.inner_type_name.clone())
    }

    fn get_current_chain_outer_enum_name(&self) -> Option<Ident> {

        Some(self.layers.front()?.outer_enum_name.clone())
    }

    fn can_wrap_current_chain_in_layer(&self, layer: &ConversionChainLayer) 
        -> bool 
    {
        match self.layers.front() {
            Some(outer_layer) => {
                layer.inner_type_name.matches_identifier(
                    &outer_layer.outer_enum_name,
                )
            },
            None => true,
        }
    }

    fn can_wrap_layer_in_current_chain(&self, layer: &ConversionChainLayer) 
        -> bool 
    {
        match self.layers.back() {
            Some(inner_layer) => {
                inner_layer.inner_type_name.matches_identifier(
                    &layer.outer_enum_name
                )
            },
            None => true,
        }
    }
}

#[cfg(test)]
mod conversion_chain_tests {

    use super::*;
    use syn::parse_quote;

    #[test]
    fn test_empty_conversion_chain() {
        let chain = ConversionChain::new();
        assert!(chain.layers.is_empty());
    }

    #[test]
    fn test_add_inner() -> Result<(),ConversionChainError> {
        let mut chain = ConversionChain::new();

        let layer = ConversionChainLayer {
            outer_enum_name: Ident::new("MyEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("MyVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        };

        chain.add_inner(layer.clone())?;

        assert_eq!(chain.layers.len(), 1);
        assert_eq!(chain.layers[0], layer);

        Ok(())
    }

    #[test]
    fn test_generate_token_stream_single_layer() -> Result<(),ConversionChainError> {

        let mut chain = ConversionChain::new();

        chain.add_inner(ConversionChainLayer {
            outer_enum_name: Ident::new("MyEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("MyVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        })?;

        let token_stream = chain.into_token_stream();
        let expected_stream: TokenStream2 = quote!(MyEnum::MyVariant(x));
        assert_eq!(token_stream.to_string(), expected_stream.to_string());

        Ok(())
    }

    #[test]
    fn test_add_inner_valid() {

        let mut chain = ConversionChain::new();

        let outer_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("SecondEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("SecondVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(FirstEnum)),
        };

        let inner_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("FirstEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("FirstVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        };

        assert!(chain.add_inner(outer_layer).is_ok());
        assert!(chain.add_inner(inner_layer).is_ok());
        assert_eq!(chain.layers.len(), 2);
    }

    #[test]
    fn test_add_inner_invalid() {

        let mut chain = ConversionChain::new();

        let outer_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("FirstEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("FirstVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        };

        let inner_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("SecondEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("SecondVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(u32)),
        };

        assert!(chain.add_inner(outer_layer).is_ok());
        assert!(chain.add_inner(inner_layer).is_err());
    }

    #[test]
    fn test_generate_token_stream_multiple_layers() -> Result<(),ConversionChainError> {
        let mut chain = ConversionChain::new();

        chain.add_inner(ConversionChainLayer {
            outer_enum_name:   Ident::new("OuterEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("OuterVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(InnerEnum)),
        })?;

        chain.add_inner(ConversionChainLayer {
            outer_enum_name:   Ident::new("InnerEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("InnerVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(i32)),
        })?;

        let token_stream = chain.into_token_stream();
        let expected_stream: TokenStream2 = quote!(OuterEnum::OuterVariant(InnerEnum::InnerVariant(x)));
        assert_eq!(token_stream.to_string(), expected_stream.to_string());

        Ok(())
    }

    #[test]
    fn test_add_outer_valid() {
        let mut chain = ConversionChain::new();

        let inner_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("InnerEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("InnerVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        };

        let outer_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("OuterEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("OuterVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(InnerEnum)),
        };

        assert!(chain.add_inner(inner_layer).is_ok());
        assert!(chain.add_outer(outer_layer).is_ok());
        assert_eq!(chain.layers.len(), 2);
    }

    #[test]
    fn test_add_outer_invalid() {
        let mut chain = ConversionChain::new();

        let inner_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("InnerEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("InnerVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(i32)),
        };

        let outer_layer = ConversionChainLayer {
            outer_enum_name: Ident::new("OuterEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("OuterVariant", proc_macro2::Span::call_site()),
            inner_type_name: Box::new(parse_quote!(u32)),
        };

        assert!(chain.add_inner(inner_layer).is_ok());
        assert!(chain.add_outer(outer_layer).is_err());
    }

    // Test for interleaved add_inner and add_outer with token stream validation
    #[test]
    fn test_interleaved_add_and_token_stream_generation() 
        -> Result<(), ConversionChainError> 
    {
        let mut chain = ConversionChain::new();

        // First inner layer
        chain.add_inner(ConversionChainLayer {
            outer_enum_name:   Ident::new("FirstEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("FirstVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(ThirdEnum)),
        })?;

        // First outer layer
        chain.add_outer(ConversionChainLayer {
            outer_enum_name:   Ident::new("SecondEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("SecondVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(FirstEnum)),
        })?;

        // Second inner layer
        chain.add_inner(ConversionChainLayer {
            outer_enum_name:   Ident::new("ThirdEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("ThirdVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(i32)),
        })?;

        // Second outer layer
        chain.add_outer(ConversionChainLayer {
            outer_enum_name:   Ident::new("FourthEnum", proc_macro2::Span::call_site()),
            enum_variant_name: Ident::new("FourthVariant", proc_macro2::Span::call_site()),
            inner_type_name:   Box::new(parse_quote!(SecondEnum)),
        })?;

        let token_stream = chain.into_token_stream();

        let expected_stream: TokenStream2 = quote!(
            FourthEnum::FourthVariant(
                SecondEnum::SecondVariant(
                    FirstEnum::FirstVariant(
                        ThirdEnum::ThirdVariant(x)
                    )
                )
            )
        );

        assert_eq!(token_stream.to_string(), expected_stream.to_string());

        Ok(())
    }
}