essm 0.3.0

extremely simple state machine
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
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
//! The `essm!` macro implements a DSL for defining state machines.

//! This DSL is only a shim over the underlying rust API. It removes the boilerplate one would
//! need to implement manually and makes some opinionated decisions. But we do not add new
//! functionality. Anything this macro does can be written by out by hand. We stay close to
//! normal rust syntax and only extend it when we can remove duplicate definitions or add
//! ergonomic benefits.
//!
//! This DSL uses following keywords:
//! * `state`: for defining states.
//! * `impl`: directly following a state definition, refers to that state an can implement
//!           trait methods and state methods. Return types have some auto completion.
//! * `transition`: for defining transitions.
//! * `initial`: for defining initial states (transition from `Primordial`).
//! * `terminal`: for defining terminal states (transition to `Terminated`).
//! * `error`: for defining custom errors.
// PLANNED: error mapping
//!
//! A lot complexity comes from the fact that we support generics and handling mixed error
//! cases. Still this complexity is opt-in since we default to `Infallible` states. Simple
//! state machines do not need to care for adding complex error handling. We make some
//! opinionated choice about implementing `Default` for states that do not carry data and
//! having a shortcut for implementing transitions to states that implement `Default`.
//!

//! On the other hand we remove some complexity and boilerplate by providing completions and
//! runtime casts for contexts.

// automatic Debug and Default unification

#[cfg(doc)]
use crate::*;

/// Defines a state machine with compile-time state and transition guarantees.
///
/// The `essm!` macro generates struct definitions and `impl State` blocks for
/// each declared state. It supports unit, named, and tuple structs with full
/// generics, where clauses, visibility, attributes, doc comments, and inline
/// `impl { }` blocks for custom method definitions.
///
/// All state lifecycle hooks ([`invariant`](State::invariant),
/// [`leave`](State::leave), [`enter`](State::enter)) have blanket no-op
/// defaults. Override them in an `impl { }` block.
///
/// The `impl { }` block must immediately follow the `state` declaration.
/// Methods named `invariant`, `leave`, or `enter` are routed to
/// `impl State for $name`. All other methods become inherent `impl $name`
/// methods.
///
// TODO: doc shortcut impls
// /// **Auto-completion**: When `<Error>` and/or `<Ctx>` generics are omitted,
// /// the macro adds them automatically. A bare `-> Result` return type is
// /// completed to `-> Result<(), Error>`. The `_ctx: &Ctx` parameter on `leave`
// /// and `enter` is auto-added when absent. When explicit generics are
// /// provided, the method signature is preserved as-is (pass-through).

// PLANNED: `error` definitions within the essm macro

// /// # Example
// ///
#[cfg(all(doc, not(doctest)))]
#[macro_export]
macro_rules! essm {
    // TODO: regenerate
    // Unit struct
    (state $name:ident;) => {};
    // Named struct
    (state $name:ident { $($field:ident: $ty:ty),* $(,)? }) => {};
    // Tuple struct
    (state $name:ident ( $($ty:ty),* $(,)? );) => {};
    // Generic state
    (state $name:ident < $($generics:tt)* > { $($fields:tt)* }) => {};
    // Generic state with where clause
    (state $name:ident < $($generics:tt)* > where $($where:tt)* { $($fields:tt)* }) => {};
    // State with impl block
    (state $name:ident; impl { $($body:tt)* }) => {};
    (state $name:ident { $($fields:tt)* }; impl { $($body:tt)* }) => {};
    // Generic state with impl block
    (state $name:ident < $($generics:tt)* > { $($fields:tt)* }; impl { $($body:tt)* }) => {};
    // PLANNED    (error $name:ident < $($generics:tt)* > { $($fields:tt)* }; impl { $($body:tt)* }) => {};
    // Visibility
    ($vis:vis state $($rest:tt)*) => {};
}

#[doc(hidden)]
#[cfg(any(not(doc), doctest))]
#[macro_export]
macro_rules! essm {
    //
    // Translate `state` into `struct`,
    // impl `State` for $name,
    // impl $name,
    //

    // Unit struct
    ($(#[$($mattr:tt)*])* $vis:vis state$(<$err:ty>)? $name:ident; $($rest:tt)*) => {
        $crate::essm!{
            @unify_derive()
            $(#[$($mattr)*])* $vis struct $name ;
        }
        $crate::essm! {
            @state_impl($(<$err>)? $name)
            $($rest)*
        }
    };

    // Empty named struct
    ($(#[$($mattr:tt)*])* $vis:vis state$(<$err:ty>)? $name:ident{} $($rest:tt)*) => {
        $crate::essm!{
            @unify_derive()
            $(#[$($mattr)*])* $vis struct $name{}
        }
        $crate::essm! {
            @state_impl($(<$err>)? $name)
            $($rest)*
        }
    };

    // Empty tuple struct
    ($(#[$($mattr:tt)*])* $vis:vis state$(<$err:ty>)? $name:ident(); $($rest:tt)*) => {
        $crate::essm!{
            @unify_derive()
            $(#[$($mattr)*])* $vis struct $name();
        }
        $crate::essm! {
            @state_impl($(<$err>)? $name)
            $($rest)*
        }
    };

    // Named structs with data
    (
        $(#[$($mattr:tt)*])*
        $vis:vis
        state$(<$err:ty>)? $name:ident
        $(<
           $($lifetimes:lifetime),*$(,)?
           $($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)? $(= $default:ty)?),*$(,)?
        >)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        {$($mvis:vis $entry:ident: $type:ty),+}
        $($rest:tt)*
    ) => {
        $(#[$($mattr)*])*
        $vis
        struct $name
        $(<
            $($lifetimes,)*
            $($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)? $(= $default)?),*
        >)?
        $(where
            $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {
            $($mvis $entry: $type),+
        }
        $crate::essm! {
            @state_impl($(<$err>)? $name $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
                $($(where $where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            )
            $($rest)*
        }
    };

    // Tuple structs with data
    (
        $(#[$($mattr:tt)*])*
        $vis:vis
        state$(<$err:ty>)? $name:ident
        $(<
           $($lifetimes:lifetime),*$(,)?
           $($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)? $(= $default:ty)?),*$(,)?
        >)?
        ($($mvis:vis $type:ty),+)
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)? ;
        $($rest:tt)*
    ) => {
        $(#[$($mattr)*])*
        $vis
        struct $name
        $(<
            $($lifetimes,)*
            $($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)? $(= $default)?),*
        >)?
        (
            $($mvis $type),+
        )
        $(where
            $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)? ;
        $crate::essm! {
            @state_impl($(<$err>)? $name $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
                $($(where $where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            )
            $($rest)*
        }
    };

    ($(#[$($mattr:tt)*])* $vis:vis state $($here:tt $($rest:tt)*)?) => {
        compile_error!(concat!( "essm macro invalid syntax at: state ", $(stringify!($here), " ...")?))
    };

    //
    // Transitions
    //

    // transition A -> B;   with B: Default
    (transition
        $(<
            $($lifetimes:lifetime),*$(,)?
            $terror:ty$(,$oerror:ty$(,$nerror:ty
                $(,$generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*$(,)?
            )?)?
        >)?
        $org:ident$(::$orgcont:ident)*
        $(<
            $($orglt:lifetime),*$(,)?$($orggen:ident),*$(,)?
        >)?
        ->
        $next:ident$(::$nextcont:ident)*
        $(<
            $($nextlt:lifetime),*$(,)?$($nextgen:ident),*$(,)?
        >)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        ; $($rest:tt)*
    ) => {
        impl
        $(<
             $($lifetimes,)*
             $($($($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*)?)?
         >)?
        $crate::Transition<$next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?$(,$terror$(,$oerror$(,$nerror)?)?)?>
        for $org$(::$orgcont)*$(<$($orglt),* $($orggen),*>)?
        where $next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?: Default,
        $($($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {
            fn change(self, _: &dyn Any)
            -> $crate::TransitionResult<$org$(::$orgcont)*$(<$($orglt),* $($orggen),*>)?,
            $next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?
            $(,$terror)?
            >
            {
                Ok(<$next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?>::default())
            }
        }
        $crate::essm! {$($rest)*}
    };

    // // transition A -> B { fn change(self) -> TransitionResult {...}}
    // (transition
    //     $(<$error:ty>)?
    //     // <
    //     //    $($lifetimes:lifetime),*$(,)?
    //     //    $($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*$(,)?
    //     // >)?
    //
    //     $org:ident$(::$orgcont:ident)*$(<$($orglt:lifetime),*$(,)?$($orggen:ident),*$(,)?>)?
    //     ->
    //     $next:ident$(::$nextcont:ident)*$(<$($nextlt:lifetime),*$(,)?$($nextgen:ident),*$(,)?>)?
    //
    //     $(where
    //         $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
    //     {
    //         fn change($self:ident) -> TransitionResult {$($body:tt)*}
    //     }
    //     $($rest:tt)*
    // ) => {
    //     impl
    //     // <$(
    //     //     $($lifetimes,)*
    //     //     $($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*)?,
    //     //     Error = Infallible
    //     // >
    //     $crate::Transition<$next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?, Error>
    //     for $org$(::$orgcont)*$(<$($orglt),* $($orggen),*>)?
    //     where $next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?: Default,
    //     $($($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
    //     {
    //         fn change($self, _: &dyn Any)
    //         -> $crate::TransitionResult<$org$(::$orgcont)*$(<$($orglt),* $($orggen),*>)?, $next$(::$nextcont)*$(<$($nextlt),* $($nextgen),*>)?, Error>
    //         {
    //             $($body)*
    //         }
    //     }
    //     $crate::essm! {$($rest)*}
    // };


    (transition $($here:tt $($rest:tt)*)?) => {
        compile_error!(concat!( "essm macro invalid syntax at: transition ", $(stringify!($here), " ...")?))
    };

    // initial Type;
    (initial
        $(<
            $($lifetimes:lifetime),*$(,)?
            $error:ty
            $(,$generic:ident$(: $genfirst:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*$(,)?
        >)?
        $name:ident$(::$namecont:ident)*$(<$($namelt:lifetime),*$(,)?$($namegen:ident),*$(,)?>)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        ;
        $($rest:tt)*
    ) => {
        impl$(<
            $($lifetimes,)*
            $($generic$(: $genfirst $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*
        >)?
        $crate::Transition<$name$(::$namecont)*$(<$($namelt),* $($namegen),*>)? $(,$error)?>
        for $crate::Primordial
        where
        $name$(::$namecont)*$(<$($namelt),* $($namegen),*>)?: Debug + Default,
        $($($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {
            fn change(self, _: &dyn Any) -> $crate::essm!{
                @complete_transitionresult($crate::Primordial, $name$(::$namecont)*$(<$($namelt),* $($namegen),*>)?) $($error)?
            }
            {
                Ok(<$name$(::$namecont)*$(<$($namelt),* $($namegen),*>)?>::default())
            }
        }
        $crate::essm! {$($rest)*}
    };

    // PLANNED: initial Type { fn new() -> TransitionResult }
    // PLANNED: initial Type { fn new_with() -> TransitionResult }
    // PLANNED: initial Type { fn try_new() -> TransitionResult }
    // PLANNED: initial Type { fn try_new_with() -> TransitionResult }

    (initial $($here:tt $($rest:tt)*)?) => {
        compile_error!(concat!( "essm macro invalid syntax at: initial ", $(stringify!($here), " ...")?))
    };

    (terminal
        $(<
           $($lifetimes:lifetime),*$(,)?
           $error:ty
           $(,$generic:ident$(: $genfirst:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*$(,)?
        >)?
        $name:ident$(::$namecont:ident)*$(<$($namelt:lifetime),*$(,)?$($namegen:ident),*$(,)?>)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        ;
        $($rest:tt)*
    ) => {
        impl$(<
            $($lifetimes,)*
            $($generic$(: $genfirst $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*
        >)?
        $crate::Transition<$crate::Terminated $(,$error)?>
        for $name$(::$namecont)*$(<$($namelt),* $($namegen),*>)?
        $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {
            fn change(self, _: &dyn Any) -> $crate::essm!{
                @complete_transitionresult($name$(::$namecont)*$(<$($namelt),* $($namegen),*>)?, $crate::Terminated) $($error)?
            }
            {
                Ok($crate::Terminated)
            }
        }
        $crate::essm! {$($rest)*}
    };

    // PLANNED: terminal Type { fn terminate() }
    // PLANNED: terminal Type { fn terminate_with() }
    // PLANNED: terminal Type { fn try_terminate() -> TransitionResult }
    // PLANNED: terminal Type { fn try_terminate_with() -> TransitionResult }

    (terminal $($here:tt $($rest:tt)*)?) => {
        compile_error!(concat!( "essm macro invalid syntax at: terminal ", $(stringify!($here), " ...")?))
    };

    //
    // Error definitions
    //

    // unit struct
    (
        $(#[$($mattr:tt)*])*
        $vis:vis
        error $name:ident
        $(<
           $($lifetimes:lifetime),*$(,)?
           $($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)? $(= $default:ty)?),*$(,)?
        >)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        ;
        $($rest:tt)*
    ) => {
//        #[derive(Debug)]
        $(#[$($mattr)*])*
        $vis
        struct $name
        $(<
            $($lifetimes,)*
            $($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)? $(= $default)?),*
        >)?
        $(where
            $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        ;
        impl StateError for $name
        $(<
            $($lifetimes,)*
            $($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*
        >)?
        $(where
            $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {}
        $crate::essm! {$($rest)*}
    };

    // TODO:
    // error tuple struct
    // error named struct
    // error enum
    // PLANNED: @map_err    error Foo; map Bar {map_err} map Baz {map_err}

    (
        $(#[$($mattr:tt)*])*
        $vis:vis
        error $($here:tt $($rest:tt)*)?
    ) => {
        compile_error!(concat!( "essm macro invalid syntax at: error ", $(stringify!($here), " ...")?))
    };

    (
        impl $($here:tt $($rest:tt)*)?
    ) => {
        compile_error!(concat!( "essm macro invalid syntax at: impl ", $(stringify!($here), " ...")?))
    };


    //
    // Handle impl blocks on states
    //
    // Methods named invariant/enter/leave with an auto completed `-> Result` as return are the
    // methods on the `State` trait implementation.
    //
    // Any other method defined here becomes a
    // method on the state itself.
    //

    // The user provided a `impl {}` block, we use that to bootstrap the impls.
    (@state_impl($(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
    ) impl { $($body:tt)* } $($rest:tt)*) => {
        $crate::essm! {
            @filter_methods
            {} {}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($body)*
        }
        $crate::essm! { $($rest)* }
    };

    // No impl block provided, define `impl State for $name` relying on blanket methods.
    // No `impl $name`
    (@state_impl($(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where
            $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
    ) $($rest:tt)*) => {
        impl $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
        $crate::State$(<$err>)? for
        $name $(<$($lifetimes,)*$($generic),*>)?
        $(where
            $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {}
        $crate::essm! { $($rest)* }
    };

    //
    // split impl {} into trait State and struct impl
    //

    // fn invariant(&self) -> Result {$body}
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn invariant(&self) -> Result {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {
                $($state_acc)*
                fn invariant(&self) -> $crate::essm!{@complete_result $($err)?} {$($body)*}
            }
            {$($impl_acc)*}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // fn enter(&self) -> Result {$body}
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn enter(&self) -> Result {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {
                $($state_acc)*
                fn enter(&self, _ctx: &dyn Any) -> $crate::essm!{@complete_result $($err)?} {
                    debug_assert!(_ctx.is::<()>(), "enter(&self) called with non unit context");
                    $($body)*
                }
            }
            {$($impl_acc)*}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // fn enter(&self, ctx) -> Result {$body}
    // PLANNED: ctx: &Type  will add a {let cty = ctx.downcast_ref::<Type>(); to body
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn enter(&self, $ctx:ident $(: &dyn Any)?) -> Result {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {
                $($state_acc)*
                fn enter(&self, $ctx: &dyn Any) -> $crate::essm!{@complete_result $($err)?} {$($body)*}
            }
            {$($impl_acc)*}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // fn leave(&self) -> Result {$body}
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn leave(&self) -> Result {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {
                $($state_acc)*
                fn leave(&self, _ctx: &dyn Any) -> $crate::essm!{@complete_result $($err)?} {
                    debug_assert!(_ctx.is::<()>(), "leave(&self) called with non unit context");
                    $($body)*
                }
            }
            {$($impl_acc)*}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // fn leave(&self, ctx) -> Result {$body}
    // PLANNED: ctx: &Type  will add a {let cty = ctx.downcast_ref::<Type>(); to body
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn leave(&self, $ctx:ident $(: &dyn Any)?) -> Result {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {
                $($state_acc)*
                fn leave(&self, $ctx: &dyn Any) -> $crate::essm!{@complete_result $($err)?} {$($body)*}
            }
            {$($impl_acc)*}
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // any other function becomes part of the `impl $name` block
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
        fn $fnname:ident$(<$($fngenerics:tt)+>)? ($($fnargs:tt)*) $(-> $return:ty)?
        $(where $($fnwhere:ident: $fnwfirst:tt $(:: $fnwrest:ident)* $(+ $fnwmore:tt $(:: $fnwmrest:ident)*)*),*$(,)?)?
        {$($body:tt)*}
        $($rest:tt)*
    ) => {
        $crate::essm! {
            @filter_methods
            {$($state_acc)*}
            {
                $($impl_acc)*
                fn $fnname $(<$($fngenerics)+>)? ($($fnargs)*) $(-> $return)?
                $(where $($fnwhere: $fnwfirst $(:: $fnwrest)* $(+ $fnwmore $(:: $fnwmrest)*)*),*)?
                {$($body)*}
            }
            $(<$err>)? $name
            $(<$($lifetimes,)*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
            $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
            $($rest)*
        }
    };

    // finally emit code
    (@filter_methods
        {$($state_acc:tt)*} {$($impl_acc:tt)*}
        $(<$err:ty>)? $name:ident
        $(<$($lifetimes:lifetime),*$(,)?$($generic:ident$(: $first:tt $(:: $prest:ident)* $(+ $more:tt $(:: $pmrest:ident)*)*)?),*>)?
        $(where $($where:ident: $wfirst:tt $(:: $wrest:ident)* $(+ $wmore:tt $(:: $wmrest:ident)*)*),*$(,)?)?
    ) => {
        impl$(<$($lifetimes),*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
        $crate::State$(<$err>)? for $name$(<$($lifetimes),*$($generic),*>)?
        $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {$($state_acc)*}
        impl$(<$($lifetimes),*$($generic$(: $first $(:: $prest)* $(+ $more $(:: $pmrest)*)*)?),*>)?
        $name$(<$($lifetimes),*$($generic),*>)?
        $(where $($where: $wfirst $(:: $wrest)* $(+ $wmore $(:: $wmrest)*)*),*)?
        {$($impl_acc)*}
    };

    // Complete Result to Result<(), $err|Infallible>
    (@complete_result $err:ty) => {
        Result<(), $err>
    };
    (@complete_result) => {
        Result<(), Infallible>
    };

    (@complete_transitionresult($origin:ty, $next:ty) $($err:ty)?) => {
        $crate::TransitionResult<$origin, $next $(,$err)?>
    };

    //
    // filter derive(Default, Default) from attributes and re-add it
    //
    (@unify_derive($($acc:tt)*) $vis:vis struct $($structdef:tt)*) => {
        // paste accumulator and structdef
        $($acc)*
        #[derive(Debug, Default)]
        $vis struct $($structdef)*
    };

    (@unify_derive($($acc:tt)*) #[derive($($derive:tt)*)] $($rest:tt)*) => {
        // filter derive attribute inners
        $crate::essm!{
            @filter_derive($($acc)*) () $($derive)* @end $($rest)*
        }
    };

    (@unify_derive($($acc:tt)*) #[$(other:tt)*] $($rest:tt)*) => {
        $crate::essm!{
            // append other to acc
            @unify_derive($($acc)* #[$(other)*])
            $($rest)*
        }
    };


    // derive filter
    (@filter_derive($($acc:tt)*) () @end $($rest:tt)*) => {
        $crate::essm!{
            // @end, empty derive(), remove the #[], recurse
            @unify_derive($($acc)*)
            $($rest)*
        }
    };

    (@filter_derive($($acc:tt)*) ($($derive:tt)+) @end $($rest:tt)*) => {
        $crate::essm!{
            // @end, accumulate derive($derive), recurse
            @unify_derive($($acc)* #[derive($($derive)+)])
            $($rest)*
        }
    };

    (@filter_derive($($acc:tt)*) ($($derive:tt)*) Default $($rest:tt)*) => {
        $crate::essm!{
            // skip Default
            @filter_derive($($acc)*) ($($derive)*) $($rest)*
        }
    };

    (@filter_derive($($acc:tt)*) ($($derive:tt)*) Debug $($rest:tt)*) => {
        $crate::essm!{
            // skip Default
            @filter_derive($($acc)*) ($($derive)*) $($rest)*
        }
    };

    (@filter_derive($($acc:tt)*) ($($derive:tt)*) $trait:ident $($rest:tt)*) => {
        $crate::essm!{
            // keep any other $trait
            @filter_derive($($acc)*) ($($derive)* $trait ,) $($rest)*
        }
    };

    (@filter_derive($($acc:tt)*) ($($derive:tt)*) , $($rest:tt)*) => {
        $crate::essm!{
            // remove commas
            @filter_derive($($acc)*) ($($derive)*) $($rest)*
        }
    };


    // // new remove from list clause
    // (@remove_token(10)($($acc:tt)*) 10 $($list:tt)*) => {
    //     $crate::essm!{@remove_token(Debug)($($acc)*) $($list)*}
    // };
    // 
    // (@remove_token($which:tt)($($acc:tt)*) $token:tt $($list:tt)*) => {
    //     $crate::essm!{@remove_token($which)($($acc)* $token) $($list)*}
    // };
    // 
    // // (@remove_from_list(_:ty)($($acc:tt)*) $(,$list:tt)+) => {
    // //     $crate::essm!{@remove_from_list(Debug)($($acc)*) $(,$list)*}
    // // };
    // 
    // (@remove_token($_:tt)($($acc:tt)*)) => {
    //     $($acc)*
    // };

    (@remove_token($_:ty)($($acc:ty),*) $($list:ty),*) => {
        ($($list)*)
    };



    // defaults to this if else is not defined
    (@default_to($($_:tt)*) $($else:tt)+) => {
        $($else)+
    };
    (@default_to($($this:tt)*) ) => {
        $($this)*
    };

    // PLANNED: use *; passthrough

    // termination
    () => {};

    // catch error
    (
        $($here:tt $($rest:tt)*)?
    ) => {
        compile_error!(concat!( "essm macro syntax error at: ", $(stringify!($here), " ...")?))
    };
}