Overview / Foundation

statemachine

Finite state machine with a declared transition table and run-to-completion dispatch.

Always compiled: part of the core build.Include #include <ethereal/cpp/statemachine/statemachine_inc.hpp>C layer

statemachine_inc.hpp

#include <ethereal/cpp/statemachine/statemachine_inc.hpp>

Aggregate entry point of the StateMachine module.

Declares in one place which state transitions are valid, instead of spreading the rule over 'if' statements inside the methods. Whoever reads the table setup sees the whole graph.

The behaviour rules (event without a transition, run to completion, callback order, internal transitions and ties between guards) are written out at the top of statemachine.hpp. They cannot be deduced from the code, and that is why they are there.

Which one to use:

  • Ethereal::StateMachine::CStateMachine : almost always. Uses the caller's enumerations.
  • Ethereal::StateMachine::CStateMachineCore : the core over integers, for whoever builds the table from data and has no compile time type.

Including this header brings the whole module.

statemachine.hpp

#include <ethereal/cpp/statemachine/statemachine.hpp>

Finite state machine with a declared transition table.

Hand managed state already exists in this library, and that is why this module exists. CDataChunk keeps its whole life cycle in one boolean (bIsInitializedWithDataAllocated), CBitStream has an EMode that decides what is allowed, and CJobManager has Initialize/Stop with nothing that says which calls are valid at which moment. In all of them the transition rule is spread over 'if' statements inside the methods, and no place declares it.

The machine adds that place. The decisions below are the ones that change observable behaviour, and they are written here because none of them can be deduced from the code.

1. An event without a transition is neither an error nor a success. Dispatch returns false and the state does not change. It does not throw, interrupt or log on its own, but it calls SetOnUnhandled, when set, for whoever wants to turn it into a log entry or an assertion. Swallowing it silently would be exactly the hidden behaviour the library refuses.

2. Run to completion: a Dispatch from inside a callback is queued, never recursive. The current transition ends, and only then the new event is handled. Reentering would put two half done transitions on the same stack, with the state changing under the suspended one. The same reentrant design brought down the CMutex of this library through infinite recursion. Here reentrancy is impossible by construction, not by the caller's discipline.

3. The table is immutable during a dispatch. Declaring a transition, a callback or a name from inside a callback is refused, and the method returns false. The machine holds references into its own tables while it runs the transition, and a push_back in the middle would invalidate them (a read of freed memory, on the hottest path of the module). Refusing costs nothing. Copying everything on each dispatch to tolerate the case would cost on every transition that never does it.

4. Callback order is fixed: OnExit( from ) -> transition action -> the state changes -> OnEnter( to ) During the action, Current() still returns the source. The transition is in progress, and announcing the destination before reaching it would lie to whoever asks from inside the action.

5. A transition to the same state has two forms, and they differ. AddTransition( A, e, A ) is external: it leaves A and enters A, firing OnExit and OnEnter. AddInternalTransition( A, e, ... ) is internal: it runs the action and fires neither.

6. The search follows insertion order, and the first guard that approves wins. Several transitions for the same (state, event) pair are legitimate when they have guards: that is how "if X go to B, otherwise go to C" is written. A second transition without a guard for the same pair would be unreachable, so it is refused instead of kept as dead code.

Nothing here is guaranteed to be thread safe.

class

CStateMachineCore

Ethereal::StateMachine#

State machine over integer identifiers.

class CStateMachineCore final

This is the core, and it is rarely used directly: see CStateMachine, which is the same thing with the caller's types.

The split exists for binary size. The transition logic is the same for any pair of enumerations, and if it lived in the template it would be compiled and instantiated in every translation unit of the client. Here it is compiled once, inside the library, and the template on top only converts types.

Not guaranteed to be thread safe.
alias

StateId

#
using StateId = ETL_UINT32;

Identifier of a state.

alias

EventId

#
using EventId = ETL_UINT32;

Identifier of an event.

alias

void

#
using ActionFn = std::function< void( StateId, EventId, StateId ) >;

Action of a transition: ( from, event, to ).

alias

bool

#
using GuardFn = std::function< bool( StateId, EventId, StateId ) >;

Guard of a transition: returns false to veto it.

alias

void

#
using StateFn = std::function< void( StateId ) >;

Entry into or exit from a state.

alias

void

#
using UnhandledFn = std::function< void( StateId, EventId ) >;

Event without a transition: ( current state, event ).

constructor

CStateMachineCore

#
explicit CStateMachineCore( const StateId InitialState );

Creates the machine already in the initial state.

SetOnEnter of the initial state is not fired here: at construction no callback is registered yet. Whoever wants the entry of the initial state calls Start after building the table.

function

AddTransition

#
bool AddTransition( const StateId From, const EventId Event, const StateId To, ActionFn Action = {}, GuardFn Guard = {} );

Declares a transition from From to To on Event.

From
Source state.
Event
Event that triggers the transition.
To
Destination state.
Action
Runs between the exit from the source and the entry into the destination. May be empty.
Guard
Vetoes the transition by returning false. May be empty, and then the transition always applies.
false when a transition without a guard already exists for the same ( From, Event ) pair, because the new one would be unreachable, or when a dispatch is in progress. In both cases nothing is recorded.
The guard is consulted during the dispatch. It must not call Dispatch or Reset, and must not rely on side effects: the machine may consult it without the transition happening, both in CanHandle and while walking candidates to find the one that applies.
function

AddInternalTransition

#
bool AddInternalTransition( const StateId State, const EventId Event, ActionFn Action, GuardFn Guard = {} );

Declares an internal transition: runs the action and does not change state.

Fires neither SetOnExit nor SetOnEnter. That is the difference from AddTransition( State, Event, State ), which fires both.

State
State where the transition applies.
Event
Event that triggers it.
Action
The action.
Guard
Optional guard.
false in the same cases as AddTransition.
function

SetOnEnter

#
bool SetOnEnter( const StateId State, StateFn Callback );

Registers what to do when entering State. One per state, the last one wins.

function

SetOnExit

#
bool SetOnExit( const StateId State, StateFn Callback );

Registers what to do when leaving State. One per state, the last one wins.

function

SetOnUnhandled

#
bool SetOnUnhandled( UnhandledFn Callback );

Registers what to do when an event has no transition in the current state.

function

SetStateName

#
bool SetStateName( const StateId State, std::string_view Name );

Declares the name of a state.

function

SetEventName

#
bool SetEventName( const EventId Event, std::string_view Name );

Declares the name of an event.

function

StateName

#
std::string_view StateName( const StateId State ) const noexcept;

The declared name of a state, or empty when there is none.

The view points to the stored name, and is valid until it is replaced.
function

EventName

#
std::string_view EventName( const EventId Event ) const noexcept;

The declared name of an event, or empty when there is none.

function

Start

#
void Start();

Fires SetOnEnter of the current state, once.

Calling again fires again. The machine does not record whether it was started, because restarting on purpose is a legitimate use.

function

Dispatch

#
bool Dispatch( const EventId Event );

Delivers an event to the machine.

Walks the transitions in declaration order and applies the first one whose ( current state, event ) pair matches and whose guard approves.

Event
The event.
true when a transition was applied. Called from inside a callback, true means queued, not applied: at that moment it is not known whether the event will have a transition when its turn comes. If it does not, SetOnUnhandled fires normally while the queue is drained, so the case is not missed. IsDispatching tells which of the two cases applies.
function

CanHandle

#
bool CanHandle( const EventId Event ) const;

Tells whether Event would be applied in the current state.

Consults the guards, so it only holds while nothing they read changes. Between CanHandle and Dispatch there is no promise at all.
function

Reset

#
bool Reset( const StateId State, const bool bFireOnEnter = false );

Forces the state, ignoring the transition table.

The emergency exit, and the only operation that does not follow the graph. SetOnExit of the current state is not fired: there was no exit, only an imposition.

State
The new state.
bFireOnEnter
Fires SetOnEnter of the new state.
false when called from inside a callback, and nothing happens. Changing the state in the middle of a transition would fire the entry of the destination for a state the machine is no longer in.
function

Current

#
StateId Current() const noexcept;

The current state.

function

IsIn

#
bool IsIn( const StateId State ) const noexcept;

true when the machine is in State.

function

IsDispatching

#
bool IsDispatching() const noexcept;

Tells that a dispatch is in progress, and so that this call comes from inside a callback.

function

TransitionCount

#
std::size_t TransitionCount() const noexcept;

Number of declared transitions, internal ones included.

class

CStateMachine

Ethereal::StateMachine#
template< typename TState, typename TEvent > class CStateMachine final
alias

void

#
using ActionFn = std::function< void( TState, TEvent, TState ) >;

Callback types, as in CStateMachineCore but with the caller's types.

alias

bool

#
using GuardFn = std::function< bool( TState, TEvent, TState ) >;
alias

void

#
using StateFn = std::function< void( TState ) >;
alias

void

#
using UnhandledFn = std::function< void( TState, TEvent ) >;
constructor

CStateMachine

#
explicit CStateMachine( const TState InitialState ) : m_Core( ToId( InitialState ) )

Creates the machine already in the initial state.

function

AddTransition

#
bool AddTransition( const TState From, const TEvent Event, const TState To, ActionFn Action = {}, GuardFn Guard = {} )

See CStateMachineCore::AddTransition.

function

AddInternalTransition

#
bool AddInternalTransition( const TState State, const TEvent Event, ActionFn Action, GuardFn Guard = {} )

See CStateMachineCore::AddInternalTransition.

function

SetOnEnter

#
bool SetOnEnter( const TState State, StateFn Callback )

See CStateMachineCore::SetOnEnter.

function

SetOnExit

#
bool SetOnExit( const TState State, StateFn Callback )

See CStateMachineCore::SetOnExit.

function

SetOnUnhandled

#
bool SetOnUnhandled( UnhandledFn Callback )

See CStateMachineCore::SetOnUnhandled.

function

SetStateName

#
bool SetStateName( const TState State, std::string_view Name )

Declare and read the names of states and events.

function

SetEventName

#
bool SetEventName( const TEvent Event, std::string_view Name )
function

StateName

#
std::string_view StateName( const TState State ) const noexcept
function

EventName

#
std::string_view EventName( const TEvent Event ) const noexcept
function

Start

#
void Start()

See CStateMachineCore::Start.

function

Dispatch

#
bool Dispatch( const TEvent Event )

See CStateMachineCore::Dispatch.

function

CanHandle

#
bool CanHandle( const TEvent Event ) const

See CStateMachineCore::CanHandle.

function

Reset

#
bool Reset( const TState State, const bool bFireOnEnter = false )

See CStateMachineCore::Reset.

function

Current

#
TState Current() const noexcept

See the queries of CStateMachineCore.

function

IsIn

#
bool IsIn( const TState State ) const noexcept
function

IsDispatching

#
bool IsDispatching() const noexcept
function

TransitionCount

#
std::size_t TransitionCount() const noexcept
function

Core

#
CStateMachineCore & Core() noexcept

Access to the core, for whoever needs something the facade does not expose.

function

Core

#
const CStateMachineCore & Core() const noexcept