-
Notifications
You must be signed in to change notification settings - Fork 0
/
Macho.cpp
372 lines (296 loc) · 10.5 KB
/
Macho.cpp
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
// 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])
//
// Version 0.9.7 (released 2007-12-1)
//
// See Macho.hpp for more information.
#include "Macho.hpp"
using namespace Macho;
////////////////////////////////////////////////////////////////////////////////
// Helper functions for tracing.
#ifdef MACHO_TRACE
#include <iostream>
void MACHO_TRC1(const char *msg) { std::cout << msg << std::endl; }
void MACHO_TRC2(const char *state, const char *msg) {
std::cout << "State " << state << ": " << msg << std::endl;
}
void MACHO_TRC3(const char *state, const char *msg1, const char *msg2) {
std::cout << "State " << state << ": " << msg1 << " " << msg2 << std::endl;
}
#else
#define MACHO_TRC1(MSG)
#define MACHO_TRC2(STATE, MSG)
#define MACHO_TRC3(STATE, MSG1, MSG2)
#endif
////////////////////////////////////////////////////////////////////////////////
// Box for states which don't declare own Box class.
_EmptyBox _EmptyBox::theEmptyBox;
////////////////////////////////////////////////////////////////////////////////
// Helper functions for box creation
template <> void *Macho::_createBox<_EmptyBox>(void *&place) {
return &_EmptyBox::theEmptyBox;
}
template <> void Macho::_deleteBox<_EmptyBox>(void *&box, void *&place) {}
#ifdef MACHO_SNAPSHOTS
template <> void *Macho::_cloneBox<_EmptyBox>(void *other) {
return &_EmptyBox::theEmptyBox;
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Implementation for Alias
void Alias::setState(_MachineBase &machine) const {
machine.setPendingState(key()->instanceGenerator(machine),
myInitializer->clone());
}
////////////////////////////////////////////////////////////////////////////////
// Implementation for StateSpecification
_StateInstance &_StateSpecification::_getInstance(_MachineBase &machine) {
// Look first in machine for existing StateInstance.
_StateInstance *&instance = machine.getInstance(0);
if (!instance)
instance = new _RootInstance(machine, 0);
return *instance;
}
void _StateSpecification::_shutdown() { _myStateInstance.machine().shutdown(); }
void _StateSpecification::_restore(_StateInstance ¤t) {
_myStateInstance.machine().myCurrentState = ¤t;
}
void _StateSpecification::setState(const Alias &state) {
state.setState(_myStateInstance.machine());
}
#ifdef MACHO_SNAPSHOTS
void _StateSpecification::setState(_StateInstance ¤t) {
_myStateInstance.machine().setPendingState(current, &_theDefaultInitializer);
}
#endif
////////////////////////////////////////////////////////////////////////////////
// StateInstance implementation
_StateInstance::_StateInstance(_MachineBase &machine, _StateInstance *parent)
: myMachine(machine), mySpecification(0), myHistory(0), myParent(parent),
myBox(0), myBoxPlace(0) {}
_StateInstance::~_StateInstance() {
if (myBoxPlace)
::operator delete(myBoxPlace);
delete mySpecification;
}
void _StateInstance::entry(_StateInstance &previous, bool first) {
// Only Root has no parent
if (!myParent)
return;
// first entry or previous state is not substate -> perform entry
if (first || !previous.isChild(*this)) {
myParent->entry(previous, false);
createBox();
MACHO_TRC2(name(), "Entry");
mySpecification->entry();
}
}
void _StateInstance::exit(_StateInstance &next) {
// Only Root has no parent
if (!myParent)
return;
// self transition or next state is not substate -> perform exit
if (this == &next || !next.isChild(*this)) {
MACHO_TRC2(name(), "Exit");
mySpecification->exit();
// EmptyBox should be most common box, so optimize for this case.
if (myBox != &_EmptyBox::theEmptyBox)
mySpecification->_deleteBox(*this);
myParent->exit(next);
}
}
void _StateInstance::init(bool history) {
if (history && myHistory) {
MACHO_TRC3(name(), "History transition to", myHistory->name());
myMachine.setPendingState(*myHistory, &_theDefaultInitializer);
} else {
MACHO_TRC2(name(), "Init");
mySpecification->init();
}
myHistory = 0;
}
#ifdef MACHO_SNAPSHOTS
void _StateInstance::copy(_StateInstance &original) {
if (original.myHistory) {
_StateInstance *history = myMachine.getInstance(original.myHistory->id());
assert(history);
setHistory(history);
}
if (original.myBox)
cloneBox(original.myBox);
}
_StateInstance *_StateInstance::clone(_MachineBase &newMachine) {
assert(!newMachine.getInstance(id()));
_StateInstance *parent = 0;
if (myParent)
// Tell other machine to clone parent first.
parent = newMachine.createClone(myParent->id(), myParent);
_StateInstance *clone = create(newMachine, parent);
return clone;
}
#endif
////////////////////////////////////////////////////////////////////////////////
// Base class for Machine objects.
_MachineBase::_MachineBase()
: myCurrentState(0), myPendingState(0), myPendingInit(0),
myPendingBox(0) // Deprecated!
,
myPendingEvent(0) {}
_MachineBase::~_MachineBase() {
assert(!myPendingInit);
delete[] myInstances;
delete myPendingEvent;
}
Alias _MachineBase::currentState() const {
return Alias(myCurrentState->key());
}
void _MachineBase::setState(_StateInstance &instance, _Initializer *init) {
setPendingState(instance, init);
rattleOn();
}
void _MachineBase::setState(const Alias &state) {
state.setState(*this);
rattleOn();
}
void _MachineBase::start(_StateInstance &instance) {
MACHO_TRC1("Starting Machine");
// Start with Root state
myCurrentState = &_StateSpecification::_getInstance(*this);
// Then go to state
setState(instance, &_theDefaultInitializer);
}
void _MachineBase::start(const Alias &state) {
MACHO_TRC1("Starting Machine");
// Start with Root state
myCurrentState = &_StateSpecification::_getInstance(*this);
// Then go to state
setState(state);
}
void _MachineBase::shutdown() {
assert(!myPendingState);
MACHO_TRC1("Shutting down Machine");
// Performs exit actions by going to Root (=StateSpecification) state.
setState(_StateSpecification::_getInstance(*this), &_theDefaultInitializer);
myCurrentState = 0;
}
void _MachineBase::allocate(unsigned int count) {
myInstances = new _StateInstance *[count];
for (unsigned int i = 0; i < count; ++i)
myInstances[i] = 0;
}
void _MachineBase::free(unsigned int count) {
// Free from end of list, so that child states are freed first
unsigned int i = count;
while (i > 0) {
--i;
delete myInstances[i];
myInstances[i] = 0;
}
}
// Clear history of state and children.
void _MachineBase::clearHistoryDeep(unsigned int count,
const _StateInstance &instance) {
for (unsigned int i = 0; i < count; ++i) {
_StateInstance *s = myInstances[i];
if (s && s->isChild(instance))
s->setHistory(0);
}
}
#ifdef MACHO_SNAPSHOTS
void _MachineBase::copy(_StateInstance **others, unsigned int count) {
// Create StateInstance objects
for (ID i = 0; i < count; ++i)
createClone(i, others[i]);
// Copy StateInstance object's state
for (ID i = 0; i < count; ++i) {
_StateInstance *state = myInstances[i];
if (state) {
assert(others[i]);
state->copy(*others[i]);
}
}
}
_StateInstance *_MachineBase::createClone(ID id, _StateInstance *original) {
_StateInstance *&clone = getInstance(id);
// Object already created?
if (!clone && original)
clone = original->clone(*this);
return clone;
}
#endif
// Performs a pending state transition.
void _MachineBase::rattleOn() {
assert(myCurrentState);
while (myPendingState || myPendingEvent) {
// Loop here because init actions might change state again.
while (myPendingState) {
MACHO_TRC3(myCurrentState->name(), "Transition to",
myPendingState->name());
#ifndef NDEBUG
// Entry/Exit actions may not dispatch events: set dummy event.
if (!myPendingEvent)
myPendingEvent = (_IEventBase *)&myPendingEvent;
#endif
// Perform exit actions (which exactly depends on new state).
myCurrentState->exit(*myPendingState);
// Store history information for previous state now.
// Previous state will be used for deep history.
myCurrentState->setHistorySuper(*myCurrentState);
_StateInstance *previous = myCurrentState;
myCurrentState = myPendingState;
// Deprecated!
if (myPendingBox) {
myCurrentState->setBox(myPendingBox);
myPendingBox = 0;
}
// Perform entry actions on next state's parents (which exactly depends on
// previous state).
myCurrentState->entry(*previous);
// State transition complete.
// Clear 'pending' information just now so that setState would assert in
// exits and entries, but not in init.
myPendingState = 0;
// Use initializer to call proper "init" action.
_Initializer *init = myPendingInit;
myPendingInit = 0;
init->execute(*myCurrentState);
init->destroy();
assert("Init may only transition to proper substates" &&
(!myPendingState || (myPendingState->isChild(*myCurrentState) &&
(myCurrentState != myPendingState))));
#ifndef NDEBUG
// Clear dummy event if need be
if (myPendingEvent == (_IEventBase *)&myPendingEvent)
myPendingEvent = 0;
#endif
} // while (myPendingState)
if (myPendingEvent) {
_IEventBase *event = myPendingEvent;
myPendingEvent = 0;
event->dispatch(*myCurrentState);
delete event;
}
} // while (myPendingState || myPendingEvent)
} // rattleOn
////////////////////////////////////////////////////////////////////////////////
// Implementation for _AdaptingInitializer
Key _AdaptingInitializer::adapt(Key key) {
ID id = static_cast<_KeyData *>(key)->id;
const _StateInstance *instance = myMachine.getInstance(id);
_StateInstance *history = 0;
if (instance)
history = instance->history();
return history ? history->key() : key;
}
////////////////////////////////////////////////////////////////////////////////
// Singleton initializers.
_DefaultInitializer _theDefaultInitializer;
_HistoryInitializer _theHistoryInitializer;