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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
#![cfg_attr(feature="nightly", feature(never_type))]
#![deny(warnings)]

//! **Crate features**
//!
//! * `"nightly"`
//! Enabled by default. Disable to make the library compatible with stable and beta Rust channels.

#![no_std]

use core::any::{TypeId, Any, type_name};

#[doc(hidden)]
pub use core::any::Any as std_any_Any;
#[doc(hidden)]
pub use core::any::TypeId as std_any_TypeId;
#[doc(hidden)]
pub use core::compile_error as std_compile_error;
#[doc(hidden)]
pub use core::concat as std_concat;
#[doc(hidden)]
pub use core::ops::FnOnce as std_ops_FnOnce;
#[doc(hidden)]
pub use core::option::Option as std_option_Option;
#[doc(hidden)]
pub use core::stringify as std_stringify;
#[doc(hidden)]
pub use generics::parse as generics_parse;
#[doc(hidden)]
pub use paste::paste as paste_paste;

/// A service provider pattern implementation = associated read-only container with type as a key.
///
/// Useful for building complex systems with callbacks without generic parameters.
///
/// # Examples
///
/// ```rust
/// mod call_back {
///     use dyn_context::Context;
///
///     pub struct CallBack {
///         callback: Option<fn(context: &mut dyn Context)>
///     }
///
///     impl CallBack {
///         pub fn new() -> Self { CallBack { callback: None } }
///
///         pub fn set_callback(&mut self, callback: fn(context: &mut dyn Context)) {
///             self.callback.replace(callback);
///         }
///
///         pub fn call_back(&self, context: &mut dyn Context) {
///             self.callback.map(|callback| callback(context));
///         }
///     }
/// }
///
/// use call_back::CallBack;
/// use dyn_context::{Context, ContextExt};
/// use macro_attr_2018::macro_attr;
/// use std::convert::Into;
///
/// macro_attr! {
///     #[derive(Context!)]
///     struct PrintContext {
///          value: String
///     }
/// }
///
/// # fn main() {
/// let mut call_back = CallBack::new();
/// call_back.set_callback(|context| {
///     let print: &PrintContext = context.get();
///     println!("{}", &print.value);
/// });
/// call_back.call_back(&mut PrintContext { value: "Hello, world!".into() });
/// # }
/// ```
/// 
/// For using `&str` instead of `String` the `context!` macro can be used:
/// ```rust
/// # mod call_back {
/// #     use dyn_context::Context;
/// # 
/// #     pub struct CallBack {
/// #         callback: Option<fn(context: &mut dyn Context)>
/// #     }
/// # 
/// #     impl CallBack {
/// #         pub fn new() -> Self { CallBack { callback: None } }
/// # 
/// #         pub fn set_callback(&mut self, callback: fn(context: &mut dyn Context)) {
/// #             self.callback.replace(callback);
/// #         }
/// # 
/// #         pub fn call_back(&self, context: &mut dyn Context) {
/// #             self.callback.map(|callback| callback(context));
/// #         }
/// #     }
/// # }
/// # 
/// use dyn_context::{context, ContextExt};
/// use call_back::CallBack;
///
/// context! {
///     struct PrintValue {
///         value: ref str
///     }
/// }
///
/// context! {
///     dyn struct PrintContext {
///         value: ref PrintValue
///     }
/// }
///
/// # fn main() {
/// let mut call_back = CallBack::new();
/// call_back.set_callback(|context| {
///     let print_value: &PrintValue = context.get();
///     println!("{}", print_value.value());
/// });
/// PrintValue::call("Hello, world!", |print_value| {
///     PrintContext::call(print_value, |context| call_back.call_back(context));
/// });
/// # }
/// ```
pub trait Context: 'static {
    /// Borrows shareable data entry.
    ///
    /// Prefer high-level [`get`](ContextExt::get) wrap.
    fn get_raw(&self, ty: TypeId) -> Option<&dyn Any>;

    /// Borrows mutable data entry.
    ///
    /// Prefer high-level [`get_mut`](ContextExt::get_mut) wrap.
    fn get_mut_raw(&mut self, ty: TypeId) -> Option<&mut dyn Any>;
}

#[cfg(feature="nightly")]
impl Context for ! {
    fn get_raw(&self, _ty: TypeId) -> Option<&dyn Any> { Some(self) }
    fn get_mut_raw(&mut self, _ty: TypeId) -> Option<&mut dyn Any> { Some(self) }
}

impl Context for () {
    fn get_raw(&self, _ty: TypeId) -> Option<&dyn Any> { None }
    fn get_mut_raw(&mut self, _ty: TypeId) -> Option<&mut dyn Any> { None }
}

/// Extends [`Context`](trait@Context) with methods that make it easier to access the content of the context.
pub trait ContextExt: Context {
    /// Borrows shareable data reference.
    ///
    /// Panics if the context does not provide requested type.
    fn get<T: 'static>(&self) -> &T {
        self.get_raw(TypeId::of::<T>())
            .unwrap_or_else(|| panic!("{} required", type_name::<T>()))
            .downcast_ref::<T>().expect("invalid cast")
    }

    /// Borrows mutable data reference.
    ///
    /// Panics if the context does not provide requested type.
    fn get_mut<T: 'static>(&mut self) -> &mut T {
        self.get_mut_raw(TypeId::of::<T>())
            .unwrap_or_else(|| panic!("{} required", type_name::<T>()))
            .downcast_mut::<T>().expect("invalid cast")
    }
}

impl<T: Context + ?Sized> ContextExt for T { }

/// A [macro attribute](https://crates.io/crates/macro-attr-2018)
/// deriving trivial [`Context`](trait@Context) implementation.
/// A trivial-implemented context is a context containing itself only.
///
/// # Examples
///
/// ```rust
/// # use dyn_context::{Context, ContextExt};
/// # use macro_attr_2018::macro_attr;
/// #
/// macro_attr! {
///     #[derive(Context!)]
///     struct SomeData {
///         data: u16,
///     }
/// }
///
/// fn get_data_from_context(context: &dyn Context) -> u16 {
///     let some_data: &SomeData = context.get();
///     some_data.data
/// }
///
/// # fn main() {
/// let some_data = SomeData { data: 7 };
/// let data_from_context = get_data_from_context(&some_data);
/// assert_eq!(data_from_context, 7);
/// # }
#[macro_export]
macro_rules! Context {
    (
        ()
        $vis:vis struct $name:ident $($body:tt)*
    ) => {
        $crate::generics_parse! {
            $crate::Context { @impl [$name] } $($body)*
        }
    };
    (
        ()
        $vis:vis enum $name:ident $($body:tt)*
    ) => {
        $crate::generics_parse! {
            $crate::Context { @impl [$name] } $($body)*
        }
    };
    (
        @impl [$name:ident] [$($g:tt)*] [$($r:tt)*] [$($w:tt)*] $($body:tt)*
    ) => {
        impl $($g)* $crate::Context for $name $($r)* $($w)* {
            fn get_raw(
                &self,
                ty: $crate::std_any_TypeId
            ) -> $crate::std_option_Option<&dyn $crate::std_any_Any> {
                if ty == $crate::std_any_TypeId::of::<Self>() {
                    $crate::std_option_Option::Some(self)
                } else {
                    $crate::std_option_Option::None
                }
            }

            fn get_mut_raw(
                &mut self,
                ty: $crate::std_any_TypeId
            ) -> $crate::std_option_Option<&mut dyn $crate::std_any_Any> {
                if ty == $crate::std_any_TypeId::of::<Self>() {
                    $crate::std_option_Option::Some(self)
                } else {
                    $crate::std_option_Option::None
                }
            }
        }
    };
}

/// Creates structure, allowing to pack several references into
/// a one reference to a `'static` type,
/// optionally implementing the [`Context`](trait@Context) trait. 
///
/// In Rust, lifetimes are intrusive, and sometimes it can lead to
/// an inadequately complex code. Moreover, in some cases it can lead to an _impossible code_,
/// means code so complex, so it can not make to compiles, even it is logically meaningful.
/// (Such situations could occur because Rust does not support existential types
/// with infinite parameters list.)
///
/// The `context` macro allows to "compress" several lifetimes into a one.
///
/// For example, using `context` you can pack together two `str` references and use them with
/// a code, requiring a `'static` type:
/// ```rust
/// # use dyn_context::{context};
/// #
/// context! {
///     struct DoubleStr {
///         str_1: ref str,
///         str_2: ref str
///     }
/// }
///
/// fn call_back<T: 'static, R>(t: &T, callback: impl FnOnce(&T) -> R) -> R {
///     callback(t)
/// }
///
/// # fn main() {
/// let s_1 = String::from("str1");
/// let s_2 = String::from("str2");
/// let r = DoubleStr::call(&s_1[1..], &s_2[2..], |double_str| call_back(double_str, |double_str| {
///     format!("{}{}", double_str.str_1(), double_str.str_2())
/// }));
/// assert_eq!(r, "tr1r2");
/// # }
/// ```
///
/// The `context` macro also allows automatically implement the [`Context`](trait@Context) trait.
#[macro_export]
macro_rules! context {
    (
        $(#[$attr:meta])*
        $vis:vis struct $name:ident $($body:tt)*
    ) => {
        $crate::generics_parse! {
            $crate::context_impl {
                @struct [$([$attr])*] [$vis] [$name]
            }
            $($body)*
        }
    };
    (
        $(#[$attr:meta])*
        $vis:vis dyn struct $name:ident $($body:tt)*
    ) => {
        $crate::generics_parse! {
            $crate::context_impl {
                @struct dyn [$([$attr])*] [$vis] [$name]
            }
            $($body)*
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! context_impl {
    (
        @struct [$([$attr:meta])*] [$vis:vis] [$name:ident] [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        {
            $($(
                $field_1:ident $($field_2:ident)? : $field_mod:ident $field_ty:ty
            ),+ $(,)?)?
        }
    ) => {
        $crate::context_impl! {
            @impl struct [static]
            [$name] [$([$attr])*] [$vis] [ty] [this]
            [$($g)*] [$($r)*] [$($w)*]
            [] [] [] []
            [$($([$field_1 $($field_2)? : $field_mod $field_ty])+)?]
        }
    };
    (
        @struct dyn [$([$attr:meta])*] [$vis:vis] [$name:ident] [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        {
            $($(
                $field_1:ident $($field_2:ident)? : $field_mod:ident $field_ty:ty
            ),+ $(,)?)?
        }
    ) => {
        $crate::context_impl! {
            @impl struct [dyn]
            [$name] [$([$attr])*] [$vis] [ty] [this]
            [$($g)*] [$($r)*] [$($w)*]
            [] [] [] []
            [$($([$field_1 $($field_2)? : $field_mod $field_ty])+)?]
        }
        $crate::context_impl! {
            @impl trait
            [$name] [ty] [this]
            [$($g)*] [$($r)*] [$($w)*]
            [] []
            [$($([$field_1 $($field_2)? : $field_mod $field_ty])+)?]
        }
    };
    (
        @struct $(dyn)? [$([$attr:meta])*] [$vis:vis] [$name:ident] [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        $($body:tt)*
    ) => {
        $crate::std_compile_error!("\
            invalid context definition, allowed form is\n\
            \n\
            $(#[attr])* $vis $(dyn)? struct $name {\n\
                $(dyn)? $field_1_name: $(ref | mut | const) $field_1_type,\n\
                $(dyn)? $field_2_name: $(ref | mut | const) $field_2_type,\n\
                ...\n\
            }\n\
            \n\
        ");
    };
    (
        @impl struct [static]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[dyn $($field_2:ident)? : $field_mod:ident $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::std_compile_error!($crate::std_concat!(
            "dynamic fields in non-dynamic context are not allowed, ",
            "consider changing 'struct' to 'dyn struct' or remove 'dyn' from field definition: '",
            $crate::std_stringify!(dyn $($field_2)? : $field_mod $field_ty),
            "'"
        ));
    };
    (
        @impl struct [$channel:ident]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[$field:ident : ref $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [$channel] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : *const $field_ty,
            ]
            [
                $($ctor_args)*
                $field : &$field_ty,
            ]
            [
                $($ctor_assignments)*
                $field : $field as *const $field_ty,
            ]
            [
                $($struct_methods)*
                $vis fn $field (&self) -> &$field_ty { unsafe { &*self.$field } }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [dyn]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[dyn $field:ident : ref $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [dyn] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : *const $field_ty,
            ]
            [
                $($ctor_args)*
                $field : &$field_ty,
            ]
            [
                $($ctor_assignments)*
                $field : $field as *const $field_ty,
            ]
            [
                $($struct_methods)*
                $vis fn $field (&self) -> &$field_ty { unsafe { &*self.$field } }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [$channel:ident]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[$field:ident : mut $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [$channel] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : *mut $field_ty,
            ]
            [
                $($ctor_args)*
                $field : &mut $field_ty,
            ]
            [
                $($ctor_assignments)*
                $field : $field as *mut $field_ty,
            ]
            [
                $($struct_methods)*

                #[allow(dead_code)]
                $vis fn $field (&self) -> &$field_ty { unsafe { &*self.$field } }

                #[allow(dead_code)]
                $vis fn [< $field _mut >] (&mut self) -> &mut $field_ty { unsafe { &mut *self.$field } }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [dyn]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[dyn $field:ident : mut $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [dyn] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : *mut $field_ty,
            ]
            [
                $($ctor_args)*
                $field : &mut $field_ty,
            ]
            [
                $($ctor_assignments)*
                $field : $field as *mut $field_ty,
            ]
            [
                $($struct_methods)*

                #[allow(dead_code)]
                $vis fn $field (&self) -> &$field_ty { unsafe { &*self.$field } }

                #[allow(dead_code)]
                $vis fn [< $field _mut >] (&mut self) -> &mut $field_ty { unsafe { &mut *self.$field } }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [$channel:ident]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[$field:ident : const $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [$channel] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : $field_ty,
            ]
            [
                $($ctor_args)*
                $field : $field_ty,
            ]
            [
                $($ctor_assignments)*
                $field,
            ]
            [
                $($struct_methods)*
                $vis fn $field (&self) -> $field_ty { self.$field }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [dyn]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[$field:ident : const $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl struct [dyn] [$name] [$([$attr])*] [$vis] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($struct_fields)*
                $field : $field_ty,
            ]
            [
                $($ctor_args)*
                $field : $field_ty,
            ]
            [
                $($ctor_assignments)*
                $field,
            ]
            [
                $($struct_methods)*
                $vis fn $field (&self) -> $field_ty { self.$field }
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl struct [$channel:ident]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        [[$field_1:ident $($field_2:ident)? : $field_mod:ident $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::std_compile_error!($crate::std_concat!(
            "invalid context field '",
            $crate::std_stringify!($field_1 $($field_2)? : $field_mod $field_ty),
            "', allowed form is '$(dyn)? $name: $(const | ref | mut) $type'",
        ));
    };
    (
        @impl struct [$channel:ident]
        [$name:ident] [$([$attr:meta])*] [$vis:vis] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($struct_fields:tt)*]
        [$($ctor_args:tt)*]
        [$($ctor_assignments:tt)*]
        [$($struct_methods:tt)*]
        []
    ) => {
        $crate::paste_paste! {
            $(#[$attr])*
            $vis struct $name $($g)* $($w)* {
                $($struct_fields)*
            }

            impl $($g)* $name $($r)* $($w)* {
                $vis fn call<ContextCallReturnType>(
                    $($ctor_args)*
                    f: impl $crate::std_ops_FnOnce(&mut Self) -> ContextCallReturnType 
                ) -> ContextCallReturnType {
                    let mut context = Self {
                        $($ctor_assignments)*
                    };
                    f(&mut context)
                }

                $($struct_methods)*
            }

            unsafe impl $($g)* Send for $name $($r)* $($w)* { }
            unsafe impl $($g)* Sync for $name $($r)* $($w)* { }
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[$field:ident : ref $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if $ty == $crate::std_any_TypeId::of::<$field_ty>() {
                    Some($this.$field())
                } else
            ]
            [
                $($trait_impl_mut)*
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[dyn $field:ident : ref $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if let Some(res) = $crate::Context::get_raw($this.$field(), $ty) {
                    Some(res)
                } else
            ]
            [
                $($trait_impl_mut)*
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[$field:ident : mut $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if $ty == $crate::std_any_TypeId::of::<$field_ty>() {
                    Some($this.$field())
                } else
            ]
            [
                $($trait_impl_mut)*
                if $ty == $crate::std_any_TypeId::of::<$field_ty>() {
                    Some($this. [< $field _mut >] ())
                } else
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[dyn $field:ident : mut $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if let Some(res) = $crate::Context::get_raw($this.$field(), $ty) {
                    Some(res)
                } else
            ]
            [
                $($trait_impl_mut)*
                if let Some(res) = $crate::Context::get_mut_raw($this. [< $field _mut >] (), $ty) {
                    Some(res)
                } else
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[$field:ident : const $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if $ty == $crate::std_any_TypeId::of::<$field_ty>() {
                    Some(&$this.$field)
                } else
            ]
            [
                $($trait_impl_mut)*
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[dyn $field:ident : const $field_ty:ty] $($other_fields:tt)*]
    ) => {
        $crate::context_impl! {
            @impl trait [$name] [$ty] [$this] [$($g)*] [$($r)*] [$($w)*]
            [
                $($trait_impl_ref)*
                if let Some(res) = $crate::Context::get_raw(&$this.$field, $ty) {
                    Some(res)
                } else
            ]
            [
                $($trait_impl_mut)*
            ]
            [$($other_fields)*]
        }
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        [[$field_1:ident $($field_2:ident)? : $field_mod:ident $field_ty:ty] $($other_fields:tt)*]
    ) => {
    };
    (
        @impl trait
        [$name:ident] [$ty:ident] [$this:ident]
        [$($g:tt)*] [$($r:tt)*] [$($w:tt)*]
        [$($trait_impl_ref:tt)*]
        [$($trait_impl_mut:tt)*]
        []
    ) => {
        $crate::paste_paste! {
            impl $($g)* $crate::Context for $name $($r)* $($w)* {
                fn get_raw(&self, $ty: $crate::std_any_TypeId) -> Option<&dyn $crate::std_any_Any> {
                    let $this = self;
                    $($trait_impl_ref)*
                    { None }
                }

                fn get_mut_raw(&mut self, $ty: $crate::std_any_TypeId) -> Option<&mut dyn $crate::std_any_Any> {
                    let $this = self;
                    $($trait_impl_mut)*
                    { None }
                }
            }
        }
    };
}

#[cfg(docsrs)]
pub mod example {
    //! [`context`](context) macro expansion example.
    //!
    //! ```ignore
    //! context! {
    //!     pub struct StrData {
    //!         r: ref str,
    //!     }
    //! }
    //!
    //! context! {
    //!     pub dyn struct ExampleContext {
    //!         data: ref Data,
    //!         str_data: mut StrData,
    //!         id: const usize,
    //!     }
    //! }
    //! ```

    pub struct Data {
        pub x: i16,
        pub y: i16
    }

    context! {
        pub struct StrData {
            r: ref str,
        }
    }

    context! {
        pub dyn struct ExampleContext {
            data: ref Data,
            str_data: mut StrData,
            id: const usize,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::ContextExt;
    use core::mem::replace;

    context! {
        struct Context1 {
            a: const u8,
            b: ref u16,
            c: mut u32,
        }
    }

    #[test]
    fn test_context_1() {
        let mut x = 3;
        let res = Context1::call(1, &2, &mut x, |context| {
            assert_eq!(context.a(), 1u8);
            assert_eq!(context.b(), &2u16);
            assert_eq!(replace(context.c_mut(), 12), 3u32);
            "res"
        });
        assert_eq!(res, "res");
        assert_eq!(x, 12);
    }

    context! {
        dyn struct Context2 {
            a: const u8,
            b: ref u16,
            c: mut u32,
        }
    }

    #[test]
    fn test_context_2() {
        let mut x = 3;
        let res = Context2::call(1, &2, &mut x, |context| {
            assert_eq!(context.a(), 1u8);
            assert_eq!(context.b(), &2u16);
            assert_eq!(replace(context.c_mut(), 12), 3u32);
            assert_eq!(context.get::<u32>(), &12);
            "res"
        });
        assert_eq!(res, "res");
        assert_eq!(x, 12);
    }

    #[derive(Debug, Clone, Copy)]
    struct PrivStr;

    context! {
        dyn struct Context3 {
            a: const PrivStr,
            b: ref u16,
            c: mut u32,
        }
    }

    #[test]
    fn test_context_3() {
        let mut x = 3;
        let res = Context3::call(PrivStr, &2, &mut x, |context| {
            let _ = context.a();
            assert_eq!(context.b(), &2u16);
            assert_eq!(replace(context.c_mut(), 12), 3u32);
            assert_eq!(context.get::<u32>(), &12);
            assert_eq!(context.get::<u16>(), &2);
            "res"
        });
        assert_eq!(res, "res");
        assert_eq!(x, 12);
    }

    context! {
        dyn struct Context4<T> where T: Copy + 'static {
            dyn c_3: mut Context3,
            b: const T
        }
    }

    #[test]
    fn test_context_4() {
        let mut x = 3;
        let res = Context3::call(PrivStr, &2, &mut x, |context| {
            Context4::call(context, 7u8, |context| {
                assert_eq!(context.b(), 7);
                assert_eq!(replace(context.get_mut::<u32>(), 9), 3);
                assert_eq!(context.get::<u8>(), &7);
                "res"
            })
        });
        assert_eq!(res, "res");
        assert_eq!(x, 9);
    }
}