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
//! Traits for converting between structural types.
//!
//! The reason these traits exist instead of using `From` and `TryFrom` is,
//! because structural types are usually converted from
//! generic types bounded by the `Foo_SI` traits generated by the `Structural` derive macro,
//! and the `Foo_SI` trait is implemented by the `Foo` type,
//! which means that those impls would overlap with
//! the `impl From<T> for T` impl in the standard lbirary.

use std_::fmt::{self, Display};

#[cfg(feature = "std")]
use std::error::Error as StdError;

/// For conversions between structural types.
///
/// For enums,usually the from enum has to have same variants and
/// at least the same fields as the into enum.<br>
/// For structs,usually the from struct has to have at least the
/// same fields as the into struct.
///
/// # Implementations
///
/// ### Structs
///
/// This trait is usually implemented for structs by:
///
/// - Bounding the trait type parameter with the `*_SI` structural alias generated for the
/// struct by the `Structural` derive.
///
/// - Calling `into_fields` on the parameter to convert it into the fields in common with
/// the `Self` struct.
///
/// ### Enums
///
/// This trait is usually implemented for enums by:
///
/// - Bounding the trait type parameter with the `*_ESI` structural alias generated for the
/// enum by the `Structural` derive.
///
/// - Matching on all the variants of the enum with the switch macro,
/// returning the same variant.
///
/// # Struct Examples
///
/// ### Derivation
///
/// This example demonstrates how this trait can be derived for structs.
///
/// ```rust
/// use structural::{convert::FromStructural, StructuralExt, Structural, fp, make_struct};
///
/// {
///     let this = Point{x: 33, y:45};
///     assert_eq!(this.into_struc::<Entity>(), Entity{x: 33, y: 45, health: 100});
/// }
/// {
///     let this = make_struct!{x: 100, y: 200, foo: "hello"};
///     assert_eq!(this.into_struc::<Entity>(), Entity{x: 100, y: 200, health: 100});
/// }
#[cfg_attr(
    feature = "alloc",
    doc = r###"
{
    // The `Point_SI` trait was generated by the Structural derive on `Point`,
    // aliasing it's accessor trait impls.
    let this: Box<dyn Point_SI<u32>> = Box::new(Point{x: 2016, y: 2080});
    assert_eq!(this.into_struc::<Entity>(), Entity{x: 2016, y: 2080, health: 100});
}
"###
)]
///
/// #[derive(Structural)]
/// struct Point<T>{
///     pub x: T,
///     pub y: u32,
/// }
///
/// #[derive(Debug,PartialEq,Structural)]
/// #[struc(from_structural)]
/// struct Entity{
///     #[struc(public)]
///     x: u32,
///
///     #[struc(public)]
///     y: u32,
///
///     #[struc(init_with_lit = 100)]
///     health: u32,
/// }
/// ```
///
///
/// ### Semi-manual impl
///
/// You can implement the `FromStructural` trait manually by using the `z_impl_from_structural`
/// macro.
///
/// ```rust
///
/// use structural::{convert::FromStructural, StructuralExt, Structural, fp, make_struct};
///
/// {
///     let this = Point{x: 33, y:45};
///     assert_eq!(this.into_struc::<Entity>(), Entity{x: 33, y: 45, health: 100});
/// }
///
/// #[derive(Structural)]
/// struct Point<T>{
///     pub x: T,
///     pub y: u32,
/// }
///
/// #[derive(Debug,PartialEq,Structural)]
/// struct Entity{
///     #[struc(public)]
///     x: u32,
///
///     #[struc(public)]
///     y: u32,
///
///     health: u32,
/// }
///
/// // This macro implements TryFromStructural for Entity by
/// // delegating to the passed-in implementation of `FromStructural`.
/// //
/// // `TryFromStructural` cannot have a blanket impl because it would collide
/// // with user implementations.
/// structural::z_impl_from_structural!{
///     impl[F] FromStructural<F> for Entity
///     where[ F: Entity_SI ]
///     {
///         fn from_structural(from){
///             let (x, y) = from.into_fields(fp!(x, y));
///             Entity{ x, y, health: 100 }
///         }    
///     }
/// }
///
/// ```
///
/// # Enum Examples
///
/// ### Derivation
///
/// This example demonstrates how this trait can be derived for an enum with one
/// private field.
///
/// ```rust
/// use structural::{
///     convert::FromStructural,
///     for_examples::OptionLike,
///     StructuralExt, Structural, switch,
/// };
///
/// assert_eq!(Some(100).into_struc::<UberOption<_>>(), UberOption::Some(100, 0));
/// assert_eq!(None.into_struc::<UberOption<u32>>(), UberOption::None);
///
/// assert_eq!(OptionLike::Some(3).into_struc::<UberOption<_>>(), UberOption::Some(3, 0));
/// assert_eq!(OptionLike::None.into_struc::<UberOption<u32>>(), UberOption::None);
///
/// // Converting an UberOption back to itself with `FromStructural` drops the
/// // `#[struct(not_public)]` field,because it has no accessor impls.
/// assert_eq!(
///     UberOption::Some(5, 200).into_struc::<UberOption<_>>(),
///     UberOption::Some(5, 0)
/// );
/// assert_eq!(
///     UberOption::None.into_struc::<UberOption<u32>>(),
///     UberOption::None,
/// );
///
/// #[derive(Debug,Structural,PartialEq)]
/// #[struc(from_structural(bound = "T: Default"))]
/// enum UberOption<T>{
///     Some(
///         T,
///         #[struc(init_with_default)]
///         T,
///     ),
///     None,
/// }
///
/// ```
///
/// ### Semi-manual
///
/// This example demonstrates how this trait can be semi-manually
/// implemented for an enum with one
/// private field (as in a field that doesn't have accessor impls to get it).
///
/// ```rust
/// use structural::{
///     convert::FromStructural,
///     for_examples::OptionLike,
///     structural_aliases::OptionMove_ESI,
///     StructuralExt, Structural, switch,
/// };
///
/// assert_eq!(Some(100).into_struc::<UberOption<_>>(), UberOption::Some(100, 100));
/// assert_eq!(None.into_struc::<UberOption<u32>>(), UberOption::None);
///
/// assert_eq!(OptionLike::Some(3).into_struc::<UberOption<_>>(), UberOption::Some(3, 3));
/// assert_eq!(OptionLike::None.into_struc::<UberOption<u32>>(), UberOption::None);
///
/// // Converting an UberOption back to itself with `FromStructural` drops the
/// // `#[struct(not_public)]` field,because it has no accessor impls.
/// assert_eq!(
///     UberOption::Some(5, 200).into_struc::<UberOption<_>>(),
///     UberOption::Some(5, 5)
/// );
/// assert_eq!(
///     UberOption::None.into_struc::<UberOption<u32>>(),
///     UberOption::None,
/// );
///
/// #[derive(Debug,Structural,PartialEq)]
/// enum UberOption<T>{
///     Some(
///         T,
///         #[struc(not_public)]
///         T,
///     ),
///     None,
/// }
///
/// // This macro implements TryFromStructural for Entity by
/// // delegating to the passed-in implementation of `FromStructural`.
/// //
/// // `TryFromStructural` cannot have a blanket impl because it would collide
/// // with user implementations.
/// structural::z_impl_from_structural!{
///     impl[F, T] FromStructural<F> for UberOption<T>
///     where[
///         F: OptionMove_ESI<T>,
///         T: Clone,
///     ]{
///         fn from_structural(from){
///             switch!{from;
///                 Some(x) => Self::Some(x.clone(), x),
///                 None => Self::None,
///             }
///         }
///     }
/// }
///
/// ```
///
pub trait FromStructural<T>: TryFromStructural<T> {
    /// Performs the conversion
    fn from_structural(from: T) -> Self;
}

/// For conversions between structural types.
///
/// This trait has a blanket implementations for all types that implement `FromStructural`.
///
/// # Example
///
/// This example demonstrates how you can use `IntoStructural` as a bound.
///
/// ```rust
/// use structural::convert::IntoStructural;
///
/// assert_eq!( into_other((0, 1, 2), [3, 4]), [[0, 1], [3, 4]] );
///
/// fn into_other<T, U>(left: T, right: U)-> [U;2]
/// where
///     T: IntoStructural<U>,
/// {
///     [left.into_structural(), right]
/// }
///
/// ```
///
pub trait IntoStructural<T>: Sized {
    /// Performs the conversion
    fn into_structural(self) -> T;
}

impl<This, T> IntoStructural<T> for This
where
    T: FromStructural<This>,
{
    fn into_structural(self) -> T {
        T::from_structural(self)
    }
}

///////////////////////////////////////////////////////////////////////////////

/// For fallible conversions between structural types.
///
/// Usually conversions between enums require the from enum to have at least the
/// fields and variants of the into enum.
///
/// All the examples in this crate are for enums,
/// since converting from an enum to another with a subset of the variants in the
/// first is the motivating usecase for defining this trait.
///
/// # Implementations
///
/// ### Enums
///
/// This trait is usually implemented for enums by:
///
/// - Bounding the trait's type parameter with the `*_SI` structural alias generated for the
/// enum by the `Structural` derive.
///
/// - Matching on all the variants of the enum with the switch macro,
/// returning `Ok` with a variant if the parameter matches that enum variant.
/// If the parameter doesn't match any of the enum variants,an error is returned.
///
/// # Enum Examples
///
/// ### Derived
///
/// This example demonstrates how this trait can be derived.
///
/// ```rust
/// use structural::{
///     convert::{EmptyTryFromError, TryFromError},
///     for_examples::{Enum3, Enum4},
///     Structural, StructuralExt, switch,
/// };
///
/// use std::cmp::Ordering;
///
/// assert_eq!(
///     Enum3::Foo(3, 5).try_into_struc::<Variants>(),
///     Ok(Variants::Foo(3)),
/// );
/// assert_eq!(
///     Enum3::Bar(Ordering::Less, None).try_into_struc::<Variants>(),
///     Ok(Variants::Bar),
/// );
/// assert_eq!(
///     Enum3::Baz{foom: "hi"}.try_into_struc::<Variants>(),
///     Ok(Variants::Baz{foom: "hi"}),
/// );
///
/// let qux=Enum4::Qux { uh: [0; 4], what: (false, false) };
/// assert_eq!(
///     qux.try_into_struc::<Variants>(),
///     Err(TryFromError::with_empty_error(qux)),
/// );
///
///
/// #[derive(Structural, Copy, Clone, Debug, PartialEq)]
/// // This attribute tells the `Structural` derive to generate the
/// // `TryFromStructural` and `FromStructural` impls
/// #[struc(from_structural)]
/// enum Variants {
///     Foo(u8),
///     Bar,
///     Baz { foom: &'static str },
/// }
///
///  
/// ```
///
/// ### Semi-manual impl
///
/// This example demonstrates how this trait can be implemented with the
/// `z_impl_try_from_structural_for_enum` macro.
///
/// ```rust
/// use structural::{
///     convert::{EmptyTryFromError, TryFromError},
///     for_examples::{Enum3, Enum4},
///     Structural, StructuralExt, switch,
/// };
///
/// use std::cmp::Ordering;
///
/// assert_eq!(
///     Enum3::Foo(3, 5).try_into_struc::<Variants>(),
///     Ok(Variants::Foo(3)),
/// );
/// assert_eq!(
///     Enum3::Bar(Ordering::Less, None).try_into_struc::<Variants>(),
///     Ok(Variants::Bar),
/// );
/// assert_eq!(
///     Enum3::Baz{foom: "hi"}.try_into_struc::<Variants>(),
///     Ok(Variants::Baz{foom: "hi"}),
/// );
///
/// let qux=Enum4::Qux { uh: [0; 4], what: (false, false) };
/// assert_eq!(
///     qux.try_into_struc::<Variants>(),
///     Err(TryFromError::with_empty_error(qux)),
/// );
///
///
/// #[derive(Structural, Copy, Clone, Debug, PartialEq)]
/// enum Variants {
///     Foo(u8),
///     Bar,
///     Baz { foom: &'static str },
/// }
///
/// // This macro implements FromStructural in terms of TryFromStructural,
/// //
/// // In order to implement FromStructural,
/// // this macro assumes that the TryFromStructural implementation written by users:
/// //   - Matches on all the variants of the enum
/// //   - Returns `Ok` for all the variants of the enum that were matches by name.
/// structural::z_impl_try_from_structural_for_enum!{
///     impl[F] TryFromStructural<F> for Variants
///     // `Variants_SI` was generated by the `Structural` derive for `Variants`
///     // aliasing its accessor trait impls,
///     // and allows `F` to have more variants than `Foo`,`Bar`,and `Baz`.
///     where[ F: Variants_SI, ]
///     {
///         type Error = EmptyTryFromError;
///
///         fn try_from_structural(this){
///             switch! {this;
///                 Foo(x) => Ok(Self::Foo(x)),
///                 Bar => Ok(Self::Bar),
///                 Baz{foom} => Ok(Self::Baz{foom}),
///                 _ => Err(TryFromError::with_empty_error(this)),
///             }
///         }
///     }
///
///     // `Variants_ESI` was generated by the `Structural` derive for `Variants`
///     // aliasing its accessor trait impls,
///     // and requires `F` to only have the `Foo`,`Bar`,and `Baz` variants.
///     FromStructural
///     where[ F: Variants_ESI, ]
/// }
///  
/// ```
///
/// # Example: Manual implementation
///
/// ```rust
/// use structural::{
///     convert::{EmptyTryFromError, FromStructural, TryFromError, TryFromStructural},
///     for_examples::{Enum3, Enum4},
///     Structural, StructuralExt, switch,
/// };
///
/// use std::cmp::Ordering;
///
/// assert_eq!(
///     Enum3::Foo(3, 5).try_into_struc::<Variants>(),
///     Ok(Variants::Foo(3)),
/// );
/// assert_eq!(
///     Enum3::Bar(Ordering::Less, None).try_into_struc::<Variants>(),
///     Ok(Variants::Bar),
/// );
/// assert_eq!(
///     Enum3::Baz{foom: "hi"}.try_into_struc::<Variants>(),
///     Ok(Variants::Baz{foom: "hi"}),
/// );
///
/// let qux=Enum4::Qux { uh: [0; 4], what: (false, false) };
/// assert_eq!(
///     qux.try_into_struc::<Variants>(),
///     Err(TryFromError::with_empty_error(qux)),
/// );
///
///
/// #[derive(Structural, Copy, Clone, Debug, PartialEq)]
/// enum Variants {
///     Foo(u8),
///     Bar,
///     Baz { foom: &'static str },
/// }
///  
/// impl<F> FromStructural<F> for Variants
/// where
///     // `Variants_ESI` was generated by the `Structural` derive for `Variants`
///     // aliasing its accessor trait impls,
///     // and requires `F` to only have the `Foo`,`Bar`,and `Baz` variants.
///     F: Variants_ESI,
/// {
///     fn from_structural(this: F) -> Self {
///         switch! {this;
///             Foo(x) => Self::Foo(x),
///             Bar => Self::Bar,
///             Baz{foom} => Self::Baz{foom},
///         }
///     }
/// }
///
/// impl<F> TryFromStructural<F> for Variants
/// where
///     // `Variants_SI` was generated by the `Structural` derive for `Variants`
///     // aliasing its accessor trait impls,
///     // and allows `F` to have more variants than `Foo`,`Bar`,and `Baz`.
///     F: Variants_SI,
/// {
///     type Error = EmptyTryFromError;
///
///     fn try_from_structural(this: F) -> Result<Self, TryFromError<F, Self::Error>> {
///         switch! {this;
///             Foo(x) => Ok(Self::Foo(x)),
///             Bar => Ok(Self::Bar),
///             Baz{foom} => Ok(Self::Baz{foom}),
///             _ => Err(TryFromError::with_empty_error(this)),
///         }
///     }
/// }
///  
/// ```
///
pub trait TryFromStructural<T>: Sized {
    /// The error parameter of `TryFromError`,
    /// returned from `try_into_structural` on conversion error.
    type Error;

    /// Performs the conversion
    fn try_from_structural(from: T) -> Result<Self, TryFromError<T, Self::Error>>;
}

/// For fallible conversions between structural types.
///
/// This trait has a blanket implementations for all types that implement `TryFromStructural`.
///
/// # Example
///
/// This example demonstrates how you can use `TryIntoStructural` as a bound.
///
/// ```rust
/// use structural::{
///     convert::TryIntoStructural,
///     for_examples::{Enum2, Enum3}
/// };
///
/// use std::cmp::{Ordering::{Less, Equal, Greater}, PartialEq};
///
/// compare_eq(Enum3::Foo(3, 5), Enum2::Foo(3, 5)      , true  );
/// compare_eq(Enum3::Foo(5, 8), Enum2::Foo(5, 8)      , true  );
/// compare_eq(Enum3::Foo(3, 5), Enum2::Foo(4, 5)      , false );
/// compare_eq(Enum3::Foo(3, 5), Enum2::Bar(Less, None), false );
///
/// compare_eq(Enum3::Bar(Less, None), Enum2::Foo(3, 5)       , false );
/// compare_eq(Enum3::Bar(Less, None), Enum2::Bar(Less, None) , true  );
/// compare_eq(Enum3::Bar(Equal,None), Enum2::Bar(Equal, None), true  );
/// compare_eq(Enum3::Bar(Less, None), Enum2::Bar(Equal, None), false );
///
/// // `Enum3::Baz{..}` is never equal to an `Enum2`,because it doesn't have a `Baz` variant.
/// compare_eq(Enum3::Baz{foom: "hello"}, Enum2::Foo(3, 5)       , false );
/// compare_eq(Enum3::Baz{foom: "hello"}, Enum2::Bar(Less, None) , false );
///
/// fn compare_eq<T, U>(left: T, right: U, expected: bool)
/// where
///     T: TryIntoStructural<U>,
///     U: PartialEq,
/// {
///     let is_equal = match left.try_into_structural() {
///         Ok(left) => left==right,
///         Err(_) => false,
///     };
///
///     assert_eq!( is_equal, expected );
/// }
///
/// ```
///
pub trait TryIntoStructural<T>: Sized {
    /// The error parameter of `TryFromError`,
    /// returned from `try_into_structural` on conversion error.
    type Error;

    /// Performs the conversion
    fn try_into_structural(self) -> Result<T, TryFromError<Self, Self::Error>>;
}

impl<This, T> TryIntoStructural<T> for This
where
    T: TryFromStructural<This>,
{
    type Error = T::Error;

    fn try_into_structural(self) -> Result<T, TryFromError<Self, Self::Error>> {
        T::try_from_structural(self)
    }
}

///////////////////////////////////////////////////////////////////////////////

/// The error type returned by  `TryFromStructural` and `TryIntoStructural`.
#[derive(Debug, Clone, PartialEq)]
pub struct TryFromError<T, E> {
    /// The paramter of `TryFromStructural::try_from_structural`
    /// (or self in `TryIntoStructural::try_into_structural`)
    /// that failed to be conevrted.
    pub from: T,
    /// The `TryFromStructural::Error` associated type.
    pub error: E,
}

impl<T, E> TryFromError<T, E> {
    /// Constructs this error.
    pub fn new(from: T, error: E) -> Self {
        Self { from, error }
    }
}

impl<T> TryFromError<T, EmptyTryFromError> {
    /// Constructs this error,with `EmptyTryFromError` as the error.
    pub fn with_empty_error(from: T) -> Self {
        Self {
            from,
            error: EmptyTryFromError,
        }
    }
}

impl<T, E> Display for TryFromError<T, E>
where
    E: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.error, f)
    }
}

#[cfg(feature = "std")]
#[allow(deprecated)]
impl<T, E> StdError for TryFromError<T, E>
where
    T: fmt::Debug,
    E: StdError,
{
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.error.source()
    }
    fn description(&self) -> &str {
        self.error.description()
    }
    fn cause(&self) -> Option<&dyn StdError> {
        self.error.cause()
    }
}

///////////////////////////////////////////////////////////////////////////////

/// The "default" error for the `TryFromStructural::Error` associated type,
/// for when there are no details for how the conversion failed.
#[derive(Debug, Clone, PartialEq)]
pub struct EmptyTryFromError;

impl Display for EmptyTryFromError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt("failed TryIntoStructural conversion", f)
    }
}

#[cfg(feature = "std")]
impl StdError for EmptyTryFromError {}