-
Notifications
You must be signed in to change notification settings - Fork 0
/
Macho.hpp
1531 lines (1241 loc) · 48.7 KB
/
Macho.hpp
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef __MACHO_HPP__
#define __MACHO_HPP__
// Macho - C++ Machine Objects
//
// The Machine Objects class library (in short Macho) allows the creation of
// state machines based on the "State" design pattern in straight C++. It
// extends the pattern with the option to create hierarchical state machines,
// making it possible to convert the popular UML statechart notation to working
// code in a straightforward way. Other features are entry and exit actions,
// state histories and state variables.
//
// Copyright (c) 2005 by Eduard Hiti (feedback to [email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// You are encouraged to provide any changes, extensions and corrections for
// this software to the author at the above-mentioned email address for
// inclusion into future versions.
//
//
// Description:
//
// States are represented as C++ classes. The hierarchy of states follows the
// inheritance relation between these state classes. A set of state classes for
// a single state machine derives directly or indirectly from a top state class,
// making it the composite state holding all other states. Events are processed
// by calling virtual methods of the top state class. Substates redefine the
// behaviour of these event handler methods.
//
// Special methods "entry", "exit" and "init" are called on state entry, state
// exit and state initialization of super- and substates (in the order defined
// by statechart semantics and current machine state).
//
// An object of type "Machine" maintains the current state of a state machine
// and dispatches events to it. The "Machine" type is a template class
// parametrized with the top state class of the state machine to be run.
//
// State data is not kept in state classes (because state class instances are
// created just once and then reused, whereas state data should be instantiated
// or destroyed each time its state is entered or left). State data is put in
// "Box" types specific to each state class instead, which are managed by the
// Machine object. Boxes are retrieved by calling the "box" method.
// Superstate boxes are accessible by qualifiying the "box" method with the
// state class name (e.g. TOP::box()).
//
// A history of entered substates can be kept for superstates. With a special
// transition into the superstate the history substate can be reentered. History
// can be shallow (only direct substates) or deep (any substate).
//
//
// Example:
//
// #include "Macho.hpp"
// #include <iostream>
// using namespace std;
//
// namespace Example {
// TOPSTATE(Top) {
// struct Box {
// Box() : data(0) {}
// long data;
// };
//
// STATE(Top)
//
// virtual void event1() {}
// virtual void event2() {}
//
// private:
// void entry();
// void exit();
// void init();
// };
//
// SUBSTATE(Super, Top) {
// STATE(Super)
// HISTORY()
//
// private:
// void entry();
// void exit();
// };
//
// SUBSTATE(StateA, Super) {
// struct Box {
// Box() : data(0) {}
// int data;
// };
//
// STATE(StateA)
//
// void event1();
//
// private:
// void entry();
// void exit();
// void init(int i);
// };
//
// SUBSTATE(StateB, Super) {
// STATE(StateB)
//
// void event2();
//
// private:
// void entry();
// void exit();
// };
//
// void Top::entry() { cout << "Top::entry" << endl; }
// void Top::exit() { cout << "Top::exit" << endl; }
// void Top::init() { setState<StateA>(42); }
//
// void Super::entry() { cout << "Super::entry" << endl; }
// void Super::exit() { cout << "Super::exit" << endl; }
//
// void StateA::entry() { cout << "StateA::entry" << endl; }
// void StateA::init(int i) { box().data = i; }
// void StateA::exit() { cout << "StateA::exit" << endl; }
// void StateA::event1() { setState<StateB>(); }
//
// void StateB::entry() { cout << "StateB::entry" << endl; }
// void StateB::exit() { cout << "StateB::exit" << endl; }
// void StateB::event2() { setState<StateA>(); }
// }
//
// int main() {
// Macho::Machine<Example::Top> m;
// m->event1();
// m->event2();
//
// return 0;
// }
//
// Output is:
//
// Top::entry
// Super::entry
// StateA::entry
// StateA::exit
// StateB::entry
// StateB::exit
// StateA::entry
// StateA::exit
// Super::exit
// Top::exit
//
//
// Version History:
//
// 0.9.7 (released 2007-12-1):
// - Introduction of template states
// - fixed rare memory leak
//
// 0.9.6 (released 2007-09-01):
// - Changes to state transition semantics (see file
//"changes_0_9_6.txt")
// - New mechanism for state initialization
// - Runtime reflection on state relationships now possible
//
// 0.9.5 (released 2007-05-01):
// - Introduction of parametrized state transitions
//
// 0.9.4 (released 2006-06-01):
// - Snapshot functionality added
//
// 0.9.3 (released 2006-04-20):
// - Code reorganization (file Macho.cpp added)
//
// 0.9.2 (released 2006-04-10):
// - Memory leak plugged
// - MSVC6 version updated
//
// 0.9.1 (released 2006-03-30):
// - Introduction of persistent boxes
// - Speed and size optimizations
// - Machine instance can be accessed in event handlers with
// method
//"machine"
//
// 0.9 (released 2006-01-15):
// - Introduction of queuable event type
//
// 0.8.2 (released 2005-12-15):
// - Code size reduction by minimizing use of template classes
//
// 0.8.1 (released 2005-12-01):
// - Added MSVC6 variant (see directory "msvc6")
// - Added method "clearHistoryDeep"
//
// 0.8 (released 2005-11-01):
// - Initial release
//
#include <cassert>
#include <new>
#include <tuple>
#include <utility>
class TestAccess;
////////////////////////////////////////////////////////////////////////////////
// Various macros for state and history declaration
// Use this macro to define your top state class.
#define TOPSTATE(TOP) \
struct TOP : public ::Macho::Link<TOP, ::Macho::TopBase<TOP>>
// Use this macro for all other state classes.
#define SUBSTATE(STATE, SUPERSTATE) \
struct STATE : public ::Macho::Link<STATE, SUPERSTATE>
// Use this macro for template states that receive an anchor as template
// parameter.
#define TSUBSTATE(STATE, SUPERSTATE) \
struct STATE : public ::Macho::Link<STATE<typename SUPERSTATE::ANCHOR>, \
typename SUPERSTATE::SELF>
// Use this macro in your class definition to give it state functionality
// (mandatory). If you have a state box declare it BEFORE macro invocation!
#define STATE(S) \
public: \
typedef S SELF; \
typedef S ANCHOR; /* Anchor is the first non-template state in the \
inheritance chain */ \
/* Constructor and destructor already defined: you can't (and shouldn't) \
* have your own! */ \
/* For the user a state class "constructor" and "destructor" are its entry \
* and exit method! */ \
S(::Macho::_StateInstance &instance) : LINK(instance) {} \
~S() {} \
static const char *_state_name() { return #S; } \
/* Get to your Box with this method: */ \
Box &box() { return *static_cast<Box *>(_box()); } \
friend class ::_VS8_Bug_101615;
// Use this macro in your template class definition to give it state
// functionality
// (mandatory). If you have a state box declare it BEFORE macro invocation!
#define TSTATE(S) \
typedef S SELF; \
typedef typename S::SUPER SUPER; \
typedef typename S::TOP TOP; \
typedef typename S::ANCHOR \
ANCHOR; /* Anchor is the first non-template state in the inheritance \
chain */ \
typedef ::Macho::Link<S, SUPER> LINK; \
S(::Macho::_StateInstance &instance) : LINK(instance) {} \
~S() {} \
static const char *_state_name() { return #S; } \
typename S::Box &box() { \
return *static_cast<typename S::Box *>(this->_box()); \
} \
friend class ::_VS8_Bug_101615; \
using LINK::dispatch; \
using LINK::machine; \
/* must have these methods to quieten gcc */ \
template <class U, class... P> void setState(const P... p) { \
LINK::template setState<U, P...>(p...); \
} \
template <class U> void setStateHistory() { \
LINK::template setStateHistory<U>(); \
} \
void setState(const class Alias &state) { LINK::setState(state); }
// Use this macro to select deep history strategy.
#define DEEPHISTORY() \
private: \
/* If no superstate has history, SUPER::_setHistorySuper is a NOOP */ \
virtual void _saveHistory(::Macho::_StateInstance &self, \
::Macho::_StateInstance &shallow, \
::Macho::_StateInstance &deep) { \
self.setHistory(&deep); \
SELF::SUPER::_setHistorySuper(self, deep); \
} \
\
protected: \
/* Substates may use _setHistorySuper to bubble up history */ \
virtual void _setHistorySuper(::Macho::_StateInstance &self, \
::Macho::_StateInstance &deep) { \
self.setHistorySuper(deep); \
} \
\
public:
// Use this macro to select shallow history strategy.
#define HISTORY() \
private: \
/* If no superstate has history, SUPER::_setHistorySuper is a NOOP */ \
virtual void _saveHistory(::Macho::_StateInstance &self, \
::Macho::_StateInstance &shallow, \
::Macho::_StateInstance &deep) { \
self.setHistory(&shallow); \
SELF::SUPER::_setHistorySuper(self, deep); \
} \
\
protected: \
/* Substates may use _setHistorySuper to bubble up history */ \
virtual void _setHistorySuper(::Macho::_StateInstance &self, \
::Macho::_StateInstance &deep) { \
self.setHistorySuper(deep); \
} \
\
public:
// Use this macro to have boxes survive state transitions
#define PERSISTENT() \
private: \
virtual void _deleteBox(::Macho::_StateInstance &instance) {} \
\
public:
////////////////////////////////////////////////////////////////////////////////
// Everything else is put into namespace 'Macho'.
// Some identifiers are prefixed with an underscore to prevent name clashes with
// deriving classes or to mark things as library internal. Don't touch things
// with an underscore prefix!
namespace Macho {
class _MachineBase;
template <class T> class Machine;
template <class T> class IEvent;
class _StateInstance;
// Unique identifier of states, build from consecutive integers.
// Use Alias to get to ID.
typedef unsigned int ID;
// Key is used to build Alias object (points to _KeyData).
typedef void *Key;
////////////////////////////////////////////////////////////////////////////////
// Metaprogramming tools
// Check type equality at compile time.
template <class T, class U> struct _SameType {};
template <class T> struct _SameType<T, T> { typedef bool Check; };
// Remove reference modifier from type.
template <class R> struct DR { typedef R T; };
template <class R> struct DR<R &> { typedef R T; };
template <class R> struct DR<const R &> { typedef R T; };
////////////////////////////////////////////////////////////////////////////////
// Superstate for template states: allows multiple numbered instances of the
// same
// template state for a single anchor state.
template <class T, int I> struct Anchor : public T {
typedef Anchor<T, I> SELF;
typedef SELF ANCHOR;
enum { NUMBER = I };
protected:
Anchor(_StateInstance &instance) : T(instance) {}
};
////////////////////////////////////////////////////////////////////////////////
// Box for states which don't declare own Box class.
class _EmptyBox {
_EmptyBox() {}
public:
static _EmptyBox theEmptyBox;
};
////////////////////////////////////////////////////////////////////////////////
// Helper functions for box creation
template <class B> void *_createBox(void *&place) {
if (!place)
place = ::operator new(sizeof(B));
new (place) B;
void *box = place;
place = 0;
return box;
}
template <class B> void _deleteBox(void *&box, void *&place) {
assert(box);
assert(!place);
static_cast<B *>(box)->~B();
place = box;
box = 0;
}
#ifdef MACHO_SNAPSHOTS
template <class B> void *_cloneBox(void *other) {
assert(other);
return new B(*static_cast<B *>(other));
}
#endif
// Specializations for EmptyBox:
// EmptyBox object gets reused over and over and never is deleted.
template <> void *_createBox<_EmptyBox>(void *&place);
template <> void _deleteBox<_EmptyBox>(void *&box, void *&place);
#ifdef MACHO_SNAPSHOTS
template <> void *_cloneBox<_EmptyBox>(void *other);
#endif
////////////////////////////////////////////////////////////////////////////////
// Essential information pointed at by state key.
struct _KeyData {
typedef _StateInstance &(*Generator)(_MachineBase &machine);
typedef bool (*Predicate)(Key);
typedef const char *(*NameFn)();
// Get StateInstance object from key.
const Generator instanceGenerator;
// Is state of given key a child state?
const Predicate childPredicate;
const NameFn name;
const ID id;
};
////////////////////////////////////////////////////////////////////////////////
// Base class for all state classes.
// Also serves as 'Root' state. By entering this state we trigger entry
// and exit actions of user's top state.
class _StateSpecification {
public:
virtual ~_StateSpecification() {}
static bool isChild(Key key) { return false; }
protected:
_StateSpecification(_StateInstance &instance) : _myStateInstance(instance) {}
// Initiate transition to a new state.
// Template parameter S is the new state to enter.
// Transition is performed AFTER control flow returns to the Machine object.
// Initiating more than one transition is considered an error!
// The new state may receive parameters for its 'init' methods:
// setState<StateA>("someData");
template <class S, class... P> void setState(const P... p);
// Initiate transition to a state's history.
// If state has no history, transition is to the state itself.
template <class S> void setStateHistory();
// Initiate transition to a new state.
// Parameter 'state' is the new state to enter.
// See above and class 'Alias' for more information.
void setState(const class Alias &state);
// Deprectated!
template <class S> void setStateBox(typename S::Box *box = 0);
// Deprectated!
template <class S> void setStateDirect(typename S::Box *box = 0);
// 'Restore from snapshot' event: set current state.
// Default implementation: Does not trigger entry actions!
virtual void _restore(_StateInstance ¤t);
// only to be used in _restore
void setState(_StateInstance ¤t);
// 'Shutdown machine' event: exit all states.
// Default implementation: Triggers exit actions!
// Override empty to omit calling exit actions.
virtual void _shutdown();
// This is the method to bubble up history information
// for states whose superstates have no history (so does nothing).
virtual void _setHistorySuper(_StateInstance &self, _StateInstance &deep) {}
private:
// State exit. Not allowed to initiate state change.
virtual void exit() {}
// State entry. Not allowed to initiate state change.
virtual void entry() {}
// Special kind of state entry: Upon transition to a new state,
// entry methods of that state and its superstates are called;
// 'init' however is called only on the one state the transition
// actually goes to.
// Is allowed to change state (to child states).
virtual void init() {}
private:
// C++ needs something like package visibility
// for _myStateInstance
template <class T> friend class TopBase;
// for _getInstance
template <class C, class P> friend class Link;
friend class _StateInstance;
friend class _RootInstance;
friend class _MachineBase;
// Create StateInstance object of state.
static _StateInstance &_getInstance(_MachineBase &machine);
virtual void _deleteBox(_StateInstance &instance) {}
// Default history strategy (no history).
virtual void _saveHistory(_StateInstance &self, _StateInstance &shallow,
_StateInstance &deep) {}
private:
_StateInstance &_myStateInstance;
};
////////////////////////////////////////////////////////////////////////////////
// Base class for user defined top state (and indirectly all other states).
template <class T> class TopBase : public _StateSpecification {
public:
// This typedef is an alias for user defined top state in all (sub)states.
typedef T TOP;
protected:
TopBase(_StateInstance &instance) : _StateSpecification(instance) {}
void dispatch(IEvent<TOP> *event);
_MachineBase &machine();
};
////////////////////////////////////////////////////////////////////////////////
// This class links substate specifications to superstate specifications by
// deriving from the superstate and being derived from by the substate.
// Substates inherit event handlers from superstates for reuse or redefinition
// this way.
template <class C, class P> class Link : public P {
public:
// Alias for superstate.
typedef P SUPER;
// Alias for topstate.
typedef typename P::TOP TOP;
// Default box type.
typedef _EmptyBox Box;
// Key is used to build Alias.
static Key key();
// Alias represents state.
static Alias alias();
static bool isChild(Key other) {
return key() == other || SUPER::isChild(other);
}
static bool isParent(Key other) {
return static_cast<_KeyData *>(other)->childPredicate(key());
}
// Is machine m in this state?
static bool isCurrent(const _MachineBase &m);
// Deprecated!
// Is machine m in exactly this state?
static bool isCurrentDirect(const _MachineBase &m);
static void clearHistory(_MachineBase &m);
static void clearHistoryDeep(_MachineBase &m);
static Alias history(const _MachineBase &m);
protected:
// Needed to perform compile time checks.
typedef Link<C, P> LINK;
Link(_StateInstance &instance);
// These definitions seem redundant but they are not!
// They override parent definitions so each substate gets either
// this default or their own, but never its parents definitions.
virtual void entry() {}
virtual void init() {}
virtual void exit() {}
// This method keeps '_myStateInstance' attribute private.
void *_box();
private:
// for _getInstance
template <class U, class V> friend class Link;
// for _getInstance
friend class _StateSpecification;
// for _getInstance
friend class Machine<TOP>;
// for _getInstance
friend class Alias;
// for Tests
friend class ::TestAccess;
// Create StateInstance object of state.
static _StateInstance &_getInstance(_MachineBase &machine);
// Box is by default not persistent. Not redundant!
virtual void _deleteBox(_StateInstance &instance);
// Default history strategy (no history). Not redundant!
virtual void _saveHistory(_StateInstance &self, _StateInstance &shallow,
_StateInstance &deep) {
// Bubble up history. If no superstate has history, _setHistorySuper will do
// nothing.
this->_setHistorySuper(self, deep);
}
private:
_StateInstance &_myStateInstance;
};
////////////////////////////////////////////////////////////////////////////////
// Unique identifier for state S.
template <class S> class StateID {
public:
static const ID value;
};
////////////////////////////////////////////////////////////////////////////////
// StateInstance maintains machine specific data about a state. Keeps history,
// box
// and state object for state. StateInstance object is created the first time
// state
// is entered. There is at most one StateInstance object per state per machine
// instance.
class _StateInstance {
protected:
_StateInstance(_MachineBase &machine, _StateInstance *parent);
public:
virtual ~_StateInstance();
// Perform entry actions.
// 'first' is true on very first call.
void entry(_StateInstance &previous, bool first = true);
// Perform exit actions.
void exit(_StateInstance &next);
// Perform init action.
void init(bool history);
void saveHistory(_StateInstance &shallow, _StateInstance &deep) {
// Check state's history strategy.
mySpecification->_saveHistory(*this, shallow, deep);
}
// Update superstate's history information:
void setHistorySuper(_StateInstance &deep) {
if (myParent)
// Let it choose between deep or shallow history.
myParent->saveHistory(*this, deep);
}
#ifdef MACHO_SNAPSHOTS
// Copy state of another StateInstance object.
void copy(_StateInstance &original);
// Create a clone of StateInstance object for another machine.
_StateInstance *clone(_MachineBase &newMachine);
#endif
void shutdown() { mySpecification->_shutdown(); }
void restore(_StateInstance &instance) {
mySpecification->_restore(instance);
}
virtual ID id() = 0;
virtual Key key() = 0;
virtual const char *name() = 0;
// 'Virtual constructor' needed for cloning.
virtual _StateInstance *create(_MachineBase &machine,
_StateInstance *parent) = 0;
virtual void createBox() = 0;
virtual void deleteBox() = 0;
#ifdef MACHO_SNAPSHOTS
virtual void cloneBox(void *box) = 0;
#endif
// Only needed for top state (constructor of Machine calls this)
void setBox(void *box) {
assert(!myBox);
if (myBoxPlace) {
// Free cached memory of previously used box.
::operator delete(myBoxPlace);
myBoxPlace = 0;
}
myBox = box;
}
// Is 'instance' a superstate?
bool isChild(const _StateInstance &instance) {
return this == &instance || (myParent && myParent->isChild(instance));
}
_StateSpecification &specification() {
assert(mySpecification);
return *mySpecification;
}
void *box() {
assert(myBox);
return myBox;
}
_MachineBase &machine() { return myMachine; }
// const: History can be manipulated even on a const object.
void setHistory(_StateInstance *history) const { myHistory = history; }
_StateInstance *history() const { return myHistory; }
protected:
_MachineBase &myMachine;
_StateSpecification *mySpecification; // Instance of state class
mutable _StateInstance *myHistory;
_StateInstance *myParent;
void *myBox;
void *myBoxPlace; // Reused box heap memory
};
////////////////////////////////////////////////////////////////////////////////
// StateInstance for Root state (the real top state).
class _RootInstance : public _StateInstance {
protected:
friend class _StateSpecification;
_RootInstance(_MachineBase &machine, _StateInstance *parent)
: _StateInstance(machine, parent) {
mySpecification = new _StateSpecification(*this);
}
public:
virtual ID id() { return 0; }
virtual Key key() {
// Can't happen: key is only called by users, and they don't know about
// Root.
assert(false);
return 0;
}
virtual void createBox() {}
virtual void deleteBox() {}
#ifdef MACHO_SNAPSHOTS
virtual void cloneBox(void *box) {}
#endif
virtual const char *name() { return "Root"; }
// 'Virtual constructor' needed for cloning.
virtual _StateInstance *create(_MachineBase &machine,
_StateInstance *parent) {
return new _RootInstance(machine, parent);
}
};
////////////////////////////////////////////////////////////////////////////////
// StateInstance for substates (including Top ;-)
// Has methods to create state specific objects.
template <class S> class _SubstateInstance : public _StateInstance {
protected:
template <class C, class P> friend class Link;
_SubstateInstance(_MachineBase &machine, _StateInstance *parent)
: _StateInstance(machine, parent) {
assert(parent);
this->mySpecification = new S(*this);
}
public:
typedef typename S::Box Box;
virtual ~_SubstateInstance() {
if (this->myBox)
Macho::_deleteBox<Box>(myBox, myBoxPlace);
}
virtual const char *name() { return S::_state_name(); }
virtual ID id() { return StateID<S>::value; }
virtual Key key() { return S::key(); }
// 'Virtual constructor' needed for cloning.
virtual _StateInstance *create(_MachineBase &machine,
_StateInstance *parent) {
return new _SubstateInstance<S>(machine, parent);
}
virtual void createBox() {
if (!this->myBox)
this->myBox = Macho::_createBox<Box>(myBoxPlace);
}
virtual void deleteBox() {
assert(myBox);
Macho::_deleteBox<Box>(myBox, myBoxPlace);
}
#ifdef MACHO_SNAPSHOTS
virtual void cloneBox(void *box) {
assert(!myBox);
assert(!myBoxPlace);
// Needs copy constructor in ALL box types.
myBox = Macho::_cloneBox<Box>(box);
}
#endif
};
////////////////////////////////////////////////////////////////////////////////
// Definitions for queuable event types
// Generic interface for event objects (available only to MachineBase)
class _IEventBase {
public:
virtual ~_IEventBase() {}
virtual void dispatch(_StateInstance &) = 0;
};
// Interface for event objects (bound to a top state)
template <class TOP> class IEvent : protected _IEventBase {
friend class Machine<TOP>;
friend class TopBase<TOP>;
};
template <class TOP, class R, class... P> class _Event : public IEvent<TOP> {
typedef R (TOP::*Signature)(P...);
public:
_Event(Signature handler, const typename DR<P>::T... p)
: myHandler(handler), tuple_(std::tuple<typename DR<P>::T...>(p...)) {}
protected:
void dispatch(_StateInstance &instance) {
callDispatchWithTuple(tuple_, instance,
std::index_sequence_for<typename DR<P>::T...>());
}
Signature myHandler;
private:
template <std::size_t... Is>
void callDispatchWithTuple(const std::tuple<P...> &tuple,
_StateInstance &instance,
std::index_sequence<Is...>) {
TOP &behaviour = static_cast<TOP &>(instance.specification());
(behaviour.*myHandler)(std::get<Is>(tuple)...);
}
std::tuple<typename DR<P>::T...> tuple_;
};
// // Event creating functions using type inference
template <class... P, class R, class TOP>
inline IEvent<TOP> *Event(R (TOP::*handler)(P...),
const typename DR<P>::T... p) {
return new _Event<TOP, R, P...>(handler, p...);
}
} // namespace Macho
////////////////////////////////////////////////////////////////////////////////
// MSVC++ 8.0 does not handle qualified member template friends:
// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101615
// Otherwise call could happen directly in Initializer classes.
class _VS8_Bug_101615 {
public:
template <class S, class... P>
static inline void execute(Macho::_StateInstance &instance, const P... p) {
S &behaviour = static_cast<S &>(instance.specification());
behaviour.init(p...);
}
};
namespace Macho {
////////////////////////////////////////////////////////////////////////////////
// Base class for state initializers.
// Initializer are used to provide parameters to states.
// The 'execute' method of Initializers will call a state's init method with
// the data of the initializer object.
class _Initializer {
public:
virtual ~_Initializer() {}
// Create copy of initializer.
virtual _Initializer *clone() = 0;
// Deallocate object.
virtual void destroy() { delete this; }
virtual Key adapt(Key key) { return key; }
// Initialize given state. State is new current state of a state machine.
virtual void execute(_StateInstance &instance) = 0;
};
// Base class for Singleton initializers.
class _StaticInitializer : public _Initializer {
// Copy of Singleton is Singleton.
virtual _Initializer *clone() { return this; }
// Singletons are never destroyed.
virtual void destroy() {}
};
// Default initializer: provides no parameters, calls state's 'init' method
// only.
class _DefaultInitializer : public _StaticInitializer {
public:
virtual void execute(_StateInstance &instance) { instance.init(false); }
};
// History initializer: provides no parameters, performs transition to
// history of state if available.
class _HistoryInitializer : public _StaticInitializer {
public:
virtual void execute(_StateInstance &instance) { instance.init(true); }
};
// Special initializer: Helps alias impersonate as history state of given state.
class _AdaptingInitializer : public _Initializer {
public:
_AdaptingInitializer(const _MachineBase &machine) : myMachine(machine) {}
virtual void execute(_StateInstance &instance) { instance.init(true); }
virtual _Initializer *clone() { return new _AdaptingInitializer(myMachine); }
virtual Key adapt(Key key);
protected:
const _MachineBase &myMachine;
};
template <class S, class... P> class _InitializerMain : public _Initializer {
public:
_InitializerMain(P... p) : tuple_(std::tuple<P...>(p...)) {}
virtual _Initializer *clone() {
return cloneWithTuple(tuple_, std::index_sequence_for<P...>());
}
virtual void execute(_StateInstance &instance) {
callExecuteWithTuple(tuple_, instance, std::index_sequence_for<P...>());
}
private:
// The helper method.
template <std::size_t... Is>
void callExecuteWithTuple(const std::tuple<P...> &tuple,
_StateInstance &instance,
std::index_sequence<Is...>) {
::_VS8_Bug_101615::execute<S, P...>(instance, std::get<Is>(tuple)...);
}
template <std::size_t... Is>