From 2d87fa91455604c5416963be0f2152ee22b80da0 Mon Sep 17 00:00:00 2001 From: Christian Granzin <130151349+chandryan@users.noreply.github.com> Date: Tue, 15 Apr 2025 14:32:20 +0200 Subject: [PATCH] First backmp11 version (#4) First version of the backmp11 backend. Contains: - favor_runtime_speed policy that mainly replaces MPL with Mp11 - favor_compile_time that uses a new mechanism with dispatch tables per state --- .gitignore | 5 + CMakeLists.txt | 10 +- include/boost/msm/backmp11/README.md | 63 + include/boost/msm/backmp11/common_types.hpp | 38 + include/boost/msm/backmp11/dispatch_table.hpp | 413 +++ .../boost/msm/backmp11/favor_compile_time.hpp | 328 ++ .../boost/msm/backmp11/history_policies.hpp | 206 ++ include/boost/msm/backmp11/metafunctions.hpp | 951 ++++++ include/boost/msm/backmp11/state_machine.hpp | 3012 +++++++++++++++++ include/boost/msm/common.hpp | 6 + .../mpl_graph/detail/incidence_list_graph.ipp | 1 - test/Anonymous.cpp | 2 + test/AnonymousAndGuard.cpp | 3 + test/AnonymousEuml.cpp | 2 + test/BackCommon.hpp | 21 +- test/BigWithFunctors.cpp | 2 + test/CMakeLists.txt | 14 +- test/CompositeEuml.cpp | 11 +- test/CompositeMachine.cpp | 11 +- test/Constructor.cpp | 2 + test/Entries.cpp | 12 +- test/EventQueue.cpp | 2 + test/History.cpp | 14 +- test/ManyDeferTransitions.cpp | 2 + test/OnlyStringPuml.cpp | 2 + test/OrthogonalDeferred.cpp | 13 +- test/OrthogonalDeferred2.cpp | 13 +- test/OrthogonalDeferred3.cpp | 1 + test/OrthogonalDeferredEuml.cpp | 11 +- test/PumlCommon.hpp | 8 +- test/Serialize.cpp | 2 + test/SerializeSimpleEuml.cpp | 3 + test/SerializeWithHistory.cpp | 13 +- test/SetStates.cpp | 13 +- test/SimpleEuml.cpp | 2 + test/SimpleEuml2.cpp | 2 + test/SimpleInternal.cpp | 2 + test/SimpleInternalEuml.cpp | 2 + test/SimpleInternalFunctors.cpp | 2 + test/SimpleInternalWithPuml.cpp | 4 +- test/SimpleMachine.cpp | 2 + test/SimpleWithFunctors.cpp | 10 +- test/SimpleWithPuml.cpp | 4 +- test/StringTerminatePuml.cpp | 4 +- test/Test2RegionsAnonymous.cpp | 3 +- test/TestConstructor.cpp | 7 +- test/TestConstructorMovableOnlyTypes.cpp | 2 + test/TestDeferAndMessageQueue.cpp | 3 +- test/TestDeferAndMessageQueue2.cpp | 3 +- test/TestDeferAndMessageQueue3.cpp | 3 +- test/TestDeferIn2Regions.cpp | 3 +- test/Throwing.cpp | 3 +- test/TransitionSkipping.cpp | 3 + test/main.cpp | 2 + 54 files changed, 5183 insertions(+), 93 deletions(-) create mode 100644 .gitignore create mode 100644 include/boost/msm/backmp11/README.md create mode 100644 include/boost/msm/backmp11/common_types.hpp create mode 100644 include/boost/msm/backmp11/dispatch_table.hpp create mode 100644 include/boost/msm/backmp11/favor_compile_time.hpp create mode 100644 include/boost/msm/backmp11/history_policies.hpp create mode 100644 include/boost/msm/backmp11/metafunctions.hpp create mode 100644 include/boost/msm/backmp11/state_machine.hpp create mode 100644 test/main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6952458 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/.cache +/.vscode +/build +/cmp_*.cpp +/format.cpp \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 6642ddd..0bf4cc2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,12 @@ cmake_minimum_required(VERSION 3.5...3.16) project(boost_msm VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) +# Temporary settings for development, need to be cleaned up later. +# Required for testing puml frontend +# set(CMAKE_CXX_STANDARD 20) +# Required due to bug in clang19 +# add_compile_options("-Wno-missing-template-arg-list-after-template-kw") +# add_compile_options("-ftime-trace") add_library(boost_msm INTERFACE) add_library(Boost::msm ALIAS boost_msm) @@ -34,8 +40,6 @@ target_link_libraries(boost_msm ) if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") - + enable_testing() add_subdirectory(test) - endif() - diff --git a/include/boost/msm/backmp11/README.md b/include/boost/msm/backmp11/README.md new file mode 100644 index 0000000..0027a04 --- /dev/null +++ b/include/boost/msm/backmp11/README.md @@ -0,0 +1,63 @@ +# Boost MSM backmp11 backend + +The new backend `backmp11` is a new backwards-compatible backend that has the following goals: + +- reduce compilation runtime and RAM usage +- reduce state machine runtime + +It is named after the metaprogramming library Boost Mp11, the main contributor to the optimizations: +It replaces usages of MPL with Mp11 to get rid of the C++03 emulation of variadic templates. +This backend contains additional optimizations that are further described below. + + +## How to use it + +The backend and both its policies `favor_runtime_speed` and `favor_compile_time` should be compatible with existing code. Required replacements to try it out: +- use `boost::msm::backmp11::state_machine` in place of `boost::msm::back::state_machine` and +- use `boost::msm::backmp11::favor_compile_time` in place of `boost::msm::back::favor_compile_time` + +When using the `favor_compile_time` policy, a different macro to generate missing parts of a SM is needed: +- use `BOOST_MSM_BACKMP11_GENERATE_DISPATCH_TABLE()` in place of `BOOST_MSM_BACK_GENERATE_PROCESS_EVENT()` + + +## General optimizations + +- Replacement of CPU-intensive calls due to C++03 recursion from MPL to Mp11 +- Applied type punning where useful (to reduce template instantiations, e.g. std::deque & other things around the dispatch table) + + +## Optimizations applied to the `favor_runtime_speed` policy + +Summary: +- Optimized cell initialization with initializer arrays (to reduce template instantiations) + - TODO: double-check optimization +- Default-initialized everything and afterwards only defer transition cells + + +## Optimizations applied to the `favor_compile_time` policy + +Once an event is given to the FSM for processing, it is immediately converted to `any` and processing continues with this `any` event. +The structure of the dispatch table has been reworked, one dispatch table is created per state as a hash map. +The state dispatch tables are designed to directly work with the `any` event, they use the event's type index via its `type()` function as hash value. + +This mechanism enables SMs to forward events to sub-SMs without requiring additional template instantiations just for forwarding as was needed with the `process_any_event` mechanism. +The new mechanism renders the `process_any_event` function obsolete and enables **forwarding of events to sub-SMs in O(1) complexity instead of O(N)**. + +Summary: +- Use one dispatch table per state to reduce compiler processing time + - The algorithms for procesing the STT and states are optimized to go through rows and states only once + - These dispatch tables are hash tables with type_id as key +- Apply type erasure with boost::any as early as possible and do further processing only with any events + - each dispatch table only has to cover the events it's handling, no template instantiations required for forwarding events to sub-SMs +- Use `std::any` if C++17 is available (up to 30% runtime impact because of small value optimization in `std::any`) + + +## Learnings: + +- If only a subset needs to be processed, prefer copy_if & transform over fold +- Selecting a template-based function overload in Mp11 seems more efficient than using enable_if/disable_if + + +## TODOs: + +- Consider trying out the tuple impl from SML diff --git a/include/boost/msm/backmp11/common_types.hpp b/include/boost/msm/backmp11/common_types.hpp new file mode 100644 index 0000000..836f262 --- /dev/null +++ b/include/boost/msm/backmp11/common_types.hpp @@ -0,0 +1,38 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_COMMON_TYPES_H +#define BOOST_MSM_BACKMP11_COMMON_TYPES_H + +#include + +namespace boost { namespace msm { namespace backmp11 +{ + +using back::HandledEnum; +using back::HANDLED_FALSE; +using back::HANDLED_TRUE; +using back::HANDLED_GUARD_REJECT; +using back::HANDLED_DEFERRED; + +using back::execute_return; + +using back::EVENT_SOURCE_DEFAULT; +using back::EVENT_SOURCE_DIRECT; +using back::EVENT_SOURCE_DEFERRED; +using back::EVENT_SOURCE_MSG_QUEUE; + +using back::EventSource; + +}}} // namespace boost::msm::backmp11 + + +#endif // BOOST_MSM_BACKMP11_COMMON_TYPES_H \ No newline at end of file diff --git a/include/boost/msm/backmp11/dispatch_table.hpp b/include/boost/msm/backmp11/dispatch_table.hpp new file mode 100644 index 0000000..96a8039 --- /dev/null +++ b/include/boost/msm/backmp11/dispatch_table.hpp @@ -0,0 +1,413 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_DISPATCH_TABLE_H +#define BOOST_MSM_BACKMP11_DISPATCH_TABLE_H + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace boost { namespace msm { namespace backmp11 +{ + +// Value used to initialize a cell of the dispatch table +template +struct init_cell_value +{ + size_t index; + Cell address; +}; +template +struct init_cell_constant +{ + static constexpr init_cell_value value = {v1, v2}; +}; + +// Type-punned init cell value to suppress redundant template instantiations +typedef HandledEnum (*generic_cell)(); +struct generic_init_cell_value +{ + size_t index; + generic_cell address; +}; + +// Helper to create an array of init cell values for table initialization +template +static const init_cell_value* const get_init_cells_impl(mp11::index_sequence) +{ + static constexpr init_cell_value values[] {mp11::mp_at_c::value...}; + return values; +} +template +static const generic_init_cell_value* const get_init_cells() +{ + return reinterpret_cast( + get_init_cells_impl(mp11::make_index_sequence::value>{})); +} + +template +struct cell_initializer; + +template<> +struct cell_initializer +{ + static void init(generic_cell* entries, const generic_init_cell_value* array, size_t size) + { + for (size_t i=0; i +struct table_index +{ + using type = mp11::mp_if< + mp11::mp_or< + mp11::mp_not>, + typename has_state_delayed_event::type + >, + mp11::mp_size_t::type, State>::value + 1>, + mp11::mp_size_t<0> + >; +}; +template +struct table_index +{ + using type = mp11::mp_if< + mp11::mp_not>, + mp11::mp_size_t::type, State>::value + 1>, + mp11::mp_size_t<0> + >; +}; +template +using get_table_index = typename table_index::type; + +// Generates a singleton runtime lookup table that maps current state +// to a function that makes the SM take its transition on the given +// Event type. +template +class dispatch_table; + +template +class dispatch_table +{ +public: + // Dispatch function for a specific event. + template + using cell = HandledEnum (*)(Fsm&, int,int,Event const&); + + // Dispatch an event. + template + static HandledEnum dispatch(Fsm& fsm, int region_id, int state_id, const Event& event) + { + return event_dispatch_table::instance().entries[state_id+1](fsm, region_id, state_id, event); + } + + // Dispatch an event to the FSM's internal table. + template + static HandledEnum dispatch_internal(Fsm& fsm, int region_id, int state_id, const Event& event) + { + return event_dispatch_table::instance().entries[0](fsm, region_id, state_id, event); + } + +private: + // Compute the maximum state value in the sm so we know how big + // to make the tables + typedef typename generate_state_set::state_set_mp11 state_set_mp11; + BOOST_STATIC_CONSTANT(int, max_state = (mp11::mp_size::value)); + + // Dispatch table for a specific event. + template + class event_dispatch_table + { + public: + using cell = cell; + + // The singleton instance. + static const event_dispatch_table& instance() { + static event_dispatch_table table; + return table; + } + + private: + // initialize the dispatch table for a given Event and Fsm + event_dispatch_table() + { + // Initialize cells for no transition + for (size_t i=0;i::state_set_mp11, + state_filter_predicate + > filtered_states; + typedef mp11::mp_transform< + preprocess_state, + filtered_states + > preprocessed_states; + cell_initializer::init( + reinterpret_cast(entries), + get_init_cells(), + mp11::mp_size::value + ); + + // build chaining rows for rows coming from the same state and the current event + // first we build a map of sequence for every source + // in reverse order so that the frow's are handled first (UML priority) + typedef mp11::mp_fold< + mp11::mp_copy_if< + typename to_mp_list::type, + event_filter_predicate + >, + mp11::mp_list<>, + map_updater + > map_of_row_seq; + // and then build chaining rows for all source states having more than 1 row + typedef mp11::mp_transform< + row_chainer, + map_of_row_seq + > chained_rows; + typedef mp11::mp_transform< + preprocess_row, + chained_rows + > chained_and_preprocessed_rows; + // Go back and fill in cells for matching transitions. + cell_initializer::init( + reinterpret_cast(entries), + get_init_cells(), + mp11::mp_size::value + ); + } + + // class used to build a chain (or sequence) of transitions for a given event and start state + // (like an UML diamond). Allows transition conflicts. + template< typename Seq,typename AnEvent,typename State > + struct chain_row + { + typedef State current_state_type; + typedef AnEvent transition_event; + + // helper for building a disable/enable_if-controlled execute function + struct execute_helper + { + template + static + HandledEnum + execute(Fsm& , int, int, Event const& , ::boost::mpl::true_ const & ) + { + // if at least one guard rejected, this will be ignored, otherwise will generate an error + return HANDLED_FALSE; + } + + template + static + HandledEnum + execute(Fsm& fsm, int region_index , int state, Event const& evt, + ::boost::mpl::false_ const & ) + { + // try the first guard + typedef typename ::boost::mpl::front::type first_row; + HandledEnum res = first_row::execute(fsm,region_index,state,evt); + if (HANDLED_TRUE!=res && HANDLED_DEFERRED!=res) + { + // if the first rejected, move on to the next one + HandledEnum sub_res = + execute::type>(fsm,region_index,state,evt, + ::boost::mpl::bool_< + ::boost::mpl::empty::type>::type::value>()); + // if at least one guards rejects, the event will not generate a call to no_transition + if ((HANDLED_FALSE==sub_res) && (HANDLED_GUARD_REJECT==res) ) + return HANDLED_GUARD_REJECT; + else + return sub_res; + } + return res; + } + }; + // Take the transition action and return the next state. + static HandledEnum execute(Fsm& fsm, int region_index, int state, Event const& evt) + { + // forward to helper + return execute_helper::template execute(fsm,region_index,state,evt, + ::boost::mpl::bool_< ::boost::mpl::empty::type::value>()); + } + }; + // nullary metafunction whose only job is to prevent early evaluation of _1 + template< typename Entry > + struct make_chain_row_from_map_entry + { + // if we have more than one frow with the same state as source, remove the ones extra + // note: we know the frow's are located at the beginning so we remove at the beginning (number of frows - 1) elements + enum { number_frows = boost::mp11::mp_count_if::value }; + + //erases the first NumberToDelete rows + template + struct erase_first_rows + { + typedef typename ::boost::mpl::erase< + typename Entry::second, + typename ::boost::mpl::begin::type, + typename ::boost::mpl::advance< + typename ::boost::mpl::begin::type, + ::boost::mpl::int_ >::type + >::type type; + }; + // if we have more than 1 frow with this event (not allowed), delete the spare + typedef typename ::boost::mpl::eval_if< + typename ::boost::mpl::bool_< number_frows >= 2 >::type, + erase_first_rows, + ::boost::mpl::identity + >::type filtered_stt; + + typedef chain_row type; + }; + // helper for lazy evaluation in eval_if of change_frow_event + template + struct replace_event + { + typedef typename Transition::template replace_event::type type; + }; + // changes the event type for a frow to the event we are dispatching + // this helps ensure that an event does not get processed more than once because of frows and base events. + template + struct change_frow_event + { + typedef typename ::boost::mp11::mp_if_c< + has_is_frow::type::value, + replace_event, + boost::mp11::mp_identity + >::type type; + }; + + template + struct convert_event_and_forward + { + static HandledEnum execute(Fsm& fsm, int region_index, int state, Event const& evt) + { + typename Transition::transition_event forwarded(evt); + return Transition::execute(fsm,region_index,state,forwarded); + } + }; + + using init_cell_value = init_cell_value; + + template + using init_cell_constant = init_cell_constant; + + template + using cell_constant = std::integral_constant; + + using cell_initializer = cell_initializer; + + // Helpers for state processing + template + using state_filter_predicate = typename has_state_delayed_event::type; + template + using preprocess_state = init_cell_constant::value, &fsm::defer_transition>; + + // Helpers for row processing + // First operation (fold) + template + using event_filter_predicate = mp11::mp_and< + mp11::mp_not>, + mp11::mp_or< + is_base_of, + typename is_kleene_event::type + > + >; + template + using push_map_value = mp11::mp_push_front< + mp11::mp_second>, + Value>; + template + using map_updater = mp11::mp_map_replace< + M, + mp11::mp_list< + typename T::current_state_type, + mp11::mp_eval_if_c< + !mp11::mp_map_contains::value, + // first row on this source state, make a list with 1 element + mp11::mp_list::type>, + // list already exists, add the row + push_map_value, + M, + typename T::current_state_type, + typename change_frow_event::type + > + > + >; + // Second operation (transform) + template + using to_mpl_map_entry = mpl::pair< + mp11::mp_first, + mp11::mp_second + >; + template + using row_chainer = mp11::mp_if_c< + (mp11::mp_size>::type>::value > 1), + // we need row chaining + typename make_chain_row_from_map_entry>::type, + // just one row, no chaining, we rebuild the row like it was before + mp11::mp_front> + >; + template + using preprocess_row_helper = cell_constant<&Transition::execute>; + template + using preprocess_row = init_cell_constant< + // Offset into the entries array + get_table_index::value, + // Address of the execute function + mp11::mp_eval_if_c< + is_kleene_event::type::value, + cell_constant< + &convert_event_and_forward::execute + >, + preprocess_row_helper, + Transition + >::value + >; + + // data members + public: + // max_state+1, because 0 is reserved for this fsm (internal transitions) + cell entries[max_state+1]; + }; +}; + +}}} // boost::msm::backmp11 + + +#endif //BOOST_MSM_BACKMP11_DISPATCH_TABLE_H + diff --git a/include/boost/msm/backmp11/favor_compile_time.hpp b/include/boost/msm/backmp11/favor_compile_time.hpp new file mode 100644 index 0000000..f717a47 --- /dev/null +++ b/include/boost/msm/backmp11/favor_compile_time.hpp @@ -0,0 +1,328 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_FAVOR_COMPILE_TIME_H +#define BOOST_MSM_BACKMP11_FAVOR_COMPILE_TIME_H + +#if __cplusplus >= 201703L +#include +#endif +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace boost { namespace msm { namespace backmp11 +{ + +#define BOOST_MSM_BACKMP11_GENERATE_DISPATCH_TABLE(fsmname) \ + template<> \ + const fsmname::sm_dispatch_table& fsmname::sm_dispatch_table::instance() \ + { \ + static dispatch_table table; \ + return table; \ + } + +struct favor_compile_time +{ + typedef int compile_policy; + typedef ::boost::mpl::false_ add_forwarding_rows; +#if __cplusplus >= 201703L + typedef std::any any_event; +#else + typedef boost::any any_event; +#endif +}; + +template +struct is_completion_event +{ + static bool value(const Event& event) + { + return (event.type() == boost::typeindex::type_id()); + } +}; + +template +struct get_real_rows +{ + template + using is_real_row = mp11::mp_not::type>; + typedef mp11::mp_copy_if type; +}; + +// Convert an event to a type index. +template +inline std::type_index to_type_index() +{ + return std::type_index{typeid(Event)}; +} + +// Helper class to manage end interrupt events. +class end_interrupt_event_helper +{ + public: + template + end_interrupt_event_helper(const Fsm& fsm) + { + mp11::mp_for_each>( + init_helper{fsm, m_is_flag_active_functions}); + } + + bool is_end_interrupt_event(const favor_compile_time::any_event& event) const + { + auto it = m_is_flag_active_functions.find(event.type()); + if (it != m_is_flag_active_functions.end()) + { + return (it->second)(); + } + return false; + } + + private: + using map = std::unordered_map>; + + template + class init_helper + { + public: + init_helper(const Fsm& fsm, map& is_flag_active_functions) + : m_fsm(fsm), m_is_flag_active_functions(is_flag_active_functions) {} + + template + void operator()(mp11::mp_identity) + { + using Flag = EndInterruptFlag; + const Fsm* fsm = &m_fsm; + m_is_flag_active_functions[to_type_index()] = + [fsm](){return fsm->template is_flag_active();}; + } + + private: + const Fsm& m_fsm; + map& m_is_flag_active_functions; + }; + + map m_is_flag_active_functions; +}; + +struct chain_row +{ + using any_event = favor_compile_time::any_event; + + template + HandledEnum operator()(Fsm& fsm, int region, int state, any_event const& evt) const + { + typedef HandledEnum (*real_cell)(Fsm&, int, int, any_event const&); + HandledEnum res = HANDLED_FALSE; + typename std::deque::const_iterator it = one_state.begin(); + while (it != one_state.end() && (res != HANDLED_TRUE && res != HANDLED_DEFERRED )) + { + auto fnc = reinterpret_cast(reinterpret_cast(*it)); + HandledEnum handled = (*fnc)(fsm,region,state,evt); + // reject is considered as erasing an error (HANDLED_FALSE) + if ((HANDLED_FALSE==handled) && (HANDLED_GUARD_REJECT==res) ) + res = HANDLED_GUARD_REJECT; + else + res = handled; + ++it; + } + return res; + } + // Use a deque with a generic type to avoid unnecessary template instantiations. + std::deque one_state; +}; + +// Generates a singleton runtime lookup table that maps current state +// to a function that makes the SM take its transition on the given +// Event type. +template +struct dispatch_table +{ + using any_event = favor_compile_time::any_event; +public: + // Dispatch an event. + static HandledEnum dispatch(Fsm& fsm, int region_id, int state_id, const any_event& event) + { + return instance().m_state_dispatch_tables[state_id+1].dispatch(fsm, region_id, state_id, event); + } + + // Dispatch an event to the FSM's internal table. + static HandledEnum dispatch_internal(Fsm& fsm, int region_id, int state_id, const any_event& event) + { + return instance().m_state_dispatch_tables[0].dispatch(fsm, region_id, state_id, event); + } + +private: + // Adapter for calling a row's execute function. + template + static HandledEnum convert_and_execute(Fsm& fsm, int region_id, int state_id, const any_event& event) + { + return Row::execute(fsm, region_id, state_id, *any_cast(&event)); + } + + // Dispatch table for one state. + class state_dispatch_table + { + public: + // Initialize the table for the given state. + template + void init() + { + // Fill in cells for deferred events. + mp11::mp_for_each>>( + deferred_event_init_helper{m_entries}); + + init_call_submachine(); + } + + template + typename ::boost::enable_if, void>::type + init_call_submachine() + { + m_call_submachine = [](Fsm& fsm, const any_event& evt) + { + return (fsm.template get_state()).process_event_internal(evt); + }; + } + + template + typename ::boost::disable_if, void>::type + init_call_submachine() + { + } + + template + chain_row& get_chain_row() + { + return m_entries[to_type_index()]; + } + + // Dispatch an event. + HandledEnum dispatch(Fsm& fsm, int region_id, int state_id, const any_event& event) const + { + HandledEnum handled = HANDLED_FALSE; + if (m_call_submachine) + { + handled = m_call_submachine(fsm, event); + if (handled) + { + return handled; + } + } + auto it = m_entries.find(event.type()); + if (it != m_entries.end()) + { + handled = (it->second)(fsm, region_id, state_id, event); + } + return handled; + } + + private: + class deferred_event_init_helper + { + public: + deferred_event_init_helper(std::unordered_map& entries) + : m_entries(entries) {} + + template + void operator()(mp11::mp_identity) + { + auto& chain_row = m_entries[to_type_index()]; + chain_row.one_state.push_front(reinterpret_cast(&Fsm::template defer_transition)); + } + + private: + std::unordered_map& m_entries; + }; + + std::unordered_map m_entries; + // Special functor if the state is a composite + std::function m_call_submachine; + }; + + class row_init_helper + { + public: + row_init_helper(state_dispatch_table* state_dispatch_tables) + : m_state_dispatch_tables(state_dispatch_tables) {} + + template + void operator()(Row) + { + using Event = typename Row::transition_event; + using StateId = get_state_id; + auto& chain_row = m_state_dispatch_tables[StateId::value+1].template get_chain_row(); + chain_row.one_state.push_front(reinterpret_cast(&convert_and_execute)); + } + + private: + state_dispatch_table* m_state_dispatch_tables; + }; + + class state_init_helper + { + public: + state_init_helper(state_dispatch_table* state_dispatch_tables) + : m_state_dispatch_tables(state_dispatch_tables) {} + + template + void operator()(mp11::mp_identity) + { + m_state_dispatch_tables[get_state_id::value+1].template init(); + } + + private: + state_dispatch_table* m_state_dispatch_tables; + }; + + // Filter a state to check whether state-specific initialization + // needs to be performed. + template + using state_filter_predicate = mp11::mp_or< + mp11::mp_not>>, + is_composite_state + >; + + dispatch_table() + { + // Execute row-specific initializations. + mp11::mp_for_each::type>( + row_init_helper(m_state_dispatch_tables)); + + // Execute state-specific initializations. + using filtered_states = mp11::mp_copy_if; + mp11::mp_for_each>( + state_init_helper(m_state_dispatch_tables)); + } + + // The singleton instance. + static const dispatch_table& instance(); + + // Compute the maximum state value in the sm so we know how big + // to make the table + typedef typename generate_state_set::state_set_mp11 state_set_mp11; + BOOST_STATIC_CONSTANT(int, max_state = (mp11::mp_size::value)); + state_dispatch_table m_state_dispatch_tables[max_state+1]; +}; + +}}} // boost::msm::backmp11 + +#endif //BOOST_MSM_BACKMP11_FAVOR_COMPILE_TIME_H diff --git a/include/boost/msm/backmp11/history_policies.hpp b/include/boost/msm/backmp11/history_policies.hpp new file mode 100644 index 0000000..1ac9528 --- /dev/null +++ b/include/boost/msm/backmp11/history_policies.hpp @@ -0,0 +1,206 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_HISTORY_POLICIES_H +#define BOOST_MSM_BACKMP11_HISTORY_POLICIES_H + +#include + +namespace boost { namespace msm { namespace backmp11 +{ + +// policy classes + +// Default: no history used +template +class NoHistoryImpl +{ +public: + NoHistoryImpl(){} + ~NoHistoryImpl(){} + void set_initial_states(int* const initial_states) + { + for (int i=0;i + const int* history_entry(Event const& ) + { + // always come back to the original state + return m_initialStates; + } + NoHistoryImpl& operator=(NoHistoryImpl const& rhs) + { + for (int i=0; i + bool process_deferred_events(Event const&)const + { + return false; + } + template + void serialize(Archive & ar, const unsigned int) + { + ar & m_initialStates; + } +private: + int m_initialStates[NumberOfRegions]; +}; + +// not UML standard. Always activates history, no matter which event generated the transition +template +class AlwaysHistoryImpl +{ +public: + AlwaysHistoryImpl(){} + ~AlwaysHistoryImpl(){} + void set_initial_states(int* const initial_states) + { + for (int i=0;i + const int* history_entry(Event const& ) + { + // always load back the last active state + return m_initialStates; + } + AlwaysHistoryImpl& operator=(AlwaysHistoryImpl const& rhs) + { + for (int i=0; i + bool process_deferred_events(Event const&)const + { + return true; + } + + template + void serialize(Archive & ar, const unsigned int) + { + ar & m_initialStates; + } +private: + int m_initialStates[NumberOfRegions]; +}; + +// UML Shallow history. For deep history, just use this policy for all the contained state machines +template +class ShallowHistoryImpl +{ + typedef typename to_mp_list::type EventsMp11; + +public: + ShallowHistoryImpl(){} + ~ShallowHistoryImpl(){} + void set_initial_states(int* const initial_states) + { + for (int i=0;i + const int* history_entry(Event const&) + { + if (mp11::mp_contains::value) + { + return m_currentStates; + } + // not one of our events, no history + return m_initialStates; + } + ShallowHistoryImpl& operator=(ShallowHistoryImpl const& rhs) + { + for (int i=0; i + bool process_deferred_events(Event const&)const + { + return mp11::mp_contains::value; + } + template + void serialize(Archive & ar, const unsigned int) + { + ar & m_initialStates; + ar & m_currentStates; + } +private: + int m_initialStates[NumberOfRegions]; + int m_currentStates[NumberOfRegions]; +}; + +struct NoHistory +{ + typedef int history_policy; + template + struct apply + { + typedef NoHistoryImpl type; + }; +}; +struct AlwaysHistory +{ + typedef int history_policy; + template + struct apply + { + typedef AlwaysHistoryImpl type; + }; +}; +template +struct ShallowHistory +{ + typedef int history_policy; + template + struct apply + { + typedef ShallowHistoryImpl type; + }; +}; + +}}} // boost::msm::backmp11 + +#endif //BOOST_MSM_BACKMP11_HISTORY_POLICIES_H diff --git a/include/boost/msm/backmp11/metafunctions.hpp b/include/boost/msm/backmp11/metafunctions.hpp new file mode 100644 index 0000000..bf27b87 --- /dev/null +++ b/include/boost/msm/backmp11/metafunctions.hpp @@ -0,0 +1,951 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_METAFUNCTIONS_H +#define BOOST_MSM_BACKMP11_METAFUNCTIONS_H + +#include "boost/msm/front/completion_event.hpp" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +// mpl_graph graph implementation and depth first search +#include +#include + +#include +#include + +namespace boost { namespace msm { namespace backmp11 +{ + +using back::favor_runtime_speed; + +template +struct set_insert_range +{ + typedef typename ::boost::mpl::fold< + Range,Sequence, + ::boost::mpl::insert< ::boost::mpl::placeholders::_1, ::boost::mpl::placeholders::_2 > + >::type type; +}; + +// returns the current state type of a transition +template +struct transition_source_type +{ + typedef typename Transition::current_state_type type; +}; + +// returns the target state type of a transition +template +struct transition_target_type +{ + typedef typename Transition::next_state_type type; +}; + +// Helper to convert a MPL sequence to Mp11 +template +struct to_mp_list +{ + typedef typename mpl::copy>>::type type; +}; +template +struct to_mp_list> +{ + typedef mp11::mp_list type; +}; +template +using to_mp_list_t = typename to_mp_list::type; + +template +struct generate_state_set; + +template +struct get_active_state_switch_policy_helper +{ + typedef typename Fsm::active_state_switch_policy type; +}; +template +struct get_active_state_switch_policy_helper2 +{ + typedef typename boost::mpl::deref::type Fsm; + typedef typename Fsm::active_state_switch_policy type; +}; +// returns the active state switching policy +template +struct get_active_state_switch_policy +{ + typedef typename ::boost::mpl::find_if< + typename Fsm::configuration, + has_active_state_switch_policy< ::boost::mpl::placeholders::_1 > >::type iter; + + typedef typename ::boost::mpl::eval_if< + typename ::boost::is_same< + iter, + typename ::boost::mpl::end::type + >::type, + get_active_state_switch_policy_helper, + get_active_state_switch_policy_helper2< iter > + >::type type; +}; + +// returns a mpl::vector containing the init states of a state machine +template +struct get_initial_states +{ + typedef typename ::boost::mpl::if_< + ::boost::mpl::is_sequence, + States, + typename ::boost::mpl::push_back< ::boost::mpl::vector0<>,States>::type >::type type; +}; +// returns a mpl::int_ containing the size of a region. If the argument is not a sequence, returns 1 +template +struct get_number_of_regions +{ + typedef typename mpl::if_< + ::boost::mpl::is_sequence, + ::boost::mpl::size, + ::boost::mpl::int_<1> >::type type; +}; + +// builds a mpl::vector of initial states +//TODO remove duplicate from get_initial_states +template +struct get_regions_as_sequence +{ + typedef typename ::boost::mpl::if_< + ::boost::mpl::is_sequence, + region, + typename ::boost::mpl::push_back< ::boost::mpl::vector0<>,region>::type >::type type; +}; + +template +struct get_explicit_creation_as_sequence +{ + typedef typename ::boost::mpl::if_< + ::boost::mpl::is_sequence, + ToCreateSeq, + typename ::boost::mpl::push_back< ::boost::mpl::vector0<>,ToCreateSeq>::type >::type type; +}; + +// returns true for composite states +template +struct is_composite_state +{ + enum {value = has_composite_tag::type::value}; + typedef typename has_composite_tag::type type; +}; + +// iterates through a transition table to generate an ordered state set +// first the source states, transition up to down +// then the target states, up to down +template +struct generate_state_set +{ + typedef typename to_mp_list::type stt_mp11; + // first add the source states + template + using set_push_source_state = mp11::mp_set_push_back< + V, + typename T::current_state_type + >; + typedef typename mp11::mp_fold< + typename to_mp_list::type, + mp11::mp_list<>, + set_push_source_state + > source_state_set_mp11; + // then add the target states + template + using set_push_target_state = mp11::mp_set_push_back< + V, + typename T::next_state_type + >; + typedef typename mp11::mp_fold< + stt_mp11, + source_state_set_mp11, + set_push_target_state + > state_set_mp11; +}; + +// extends a state set to a map with key=state and value=id +template +struct generate_state_map +{ + typedef typename generate_state_set::state_set_mp11 state_set; + typedef mp11::mp_iota> indices; + typedef mp11::mp_transform_q< + mp11::mp_bind, + state_set, + indices + > type; +}; + +// filters the state set to contain only composite states +template +struct generate_composite_state_set +{ + typedef typename generate_state_set::state_set_mp11 state_set; + template + using is_composite = typename is_composite_state::type; + typedef mp11::mp_copy_if< + state_set, + is_composite + > type; +}; + +// returns the id of a given state +template +struct get_state_id +{ + typedef mp11::mp_second::type, + State + >> type; + + static constexpr typename type::value_type value = type::value; +}; + +// iterates through the transition table and generate a set containing all the events +template +struct generate_event_set +{ + typedef typename to_mp_list::type stt_mp11; + template + using event_set_pusher = mp11::mp_set_push_back< + V, + typename T::transition_event + >; + typedef mp11::mp_fold< + typename to_mp_list::type, + mp11::mp_list<>, + event_set_pusher + > event_set_mp11; +}; + +// extends an event set to a map with key=event and value=id +template +struct generate_event_map +{ + typedef typename generate_event_set::event_set_mp11 event_set; + typedef mp11::mp_iota> indices; + typedef mp11::mp_transform_q< + mp11::mp_bind, + event_set, + indices + > type; +}; + +// returns the id of a given event +template +struct get_event_id +{ + typedef mp11::mp_second::type, + Event + >> type; + enum {value = type::value}; +}; + +// returns a mpl::bool_ if State has Event as deferred event +template +struct has_state_delayed_event +{ + typedef typename mp11::mp_contains< + typename to_mp_list::type, + Event + > type; +}; +// returns a mpl::bool_ if State has any deferred event +template +struct has_state_delayed_events +{ + typedef typename mp11::mp_not::type + >> type; +}; + +// Template used to create dummy entries for initial states not found in the stt. +template< typename T1 > +struct not_a_row +{ + typedef int not_real_row_tag; + struct dummy_event + { + }; + typedef T1 current_state_type; + typedef T1 next_state_type; + typedef dummy_event transition_event; +}; + +// metafunctions used to find out if a state is entry, exit or something else +template +struct is_pseudo_entry +{ + typedef typename ::boost::mpl::if_< typename has_pseudo_entry::type, + ::boost::mpl::bool_,::boost::mpl::bool_ + >::type type; +}; +// says if a state is an exit pseudo state +template +struct is_pseudo_exit +{ + typedef typename has_pseudo_exit::type type; +}; +// says if a state is an entry pseudo state or an explicit entry +template +struct is_direct_entry +{ + typedef typename ::boost::mpl::if_< typename has_explicit_entry_state::type, + ::boost::mpl::bool_, ::boost::mpl::bool_ + >::type type; +}; + +//converts a "fake" (simulated in a state_machine_ description )state into one which will really get created +template +struct convert_fake_state +{ + // converts a state (explicit entry) into the state we really are going to create (explicit<>) + typedef typename ::boost::mpl::if_< + typename is_direct_entry::type, + typename CompositeType::template direct, + typename ::boost::mpl::identity::type + >::type type; +}; + +template +struct get_explicit_creation +{ + typedef typename StateType::explicit_creation type; +}; + +template +struct get_wrapped_entry +{ + typedef typename StateType::wrapped_entry type; +}; +// used for states created with explicit_creation +// if the state is an explicit entry, we reach for the wrapped state +// otherwise, this returns the state itself +template +struct get_wrapped_state +{ + typedef typename ::boost::mpl::eval_if< + typename has_wrapped_entry::type, + get_wrapped_entry, + ::boost::mpl::identity >::type type; +}; + +template +struct create_stt +{ + //typedef typename Derived::transition_table stt; + typedef typename Derived::real_transition_table Stt; + // get the state set + typedef typename generate_state_set::state_set_mp11 states; + // transform the initial region(s) in a sequence + typedef typename get_regions_as_sequence::type init_states; + // iterate through the initial states and add them in the stt if not already there + template + using states_pusher = mp11::mp_if_c< + mp11::mp_set_contains::value, + V, + mp11::mp_push_back< + V, + not_a_row::type> + > + >; + typedef typename mp11::mp_fold< + typename to_mp_list::type, + typename to_mp_list::type, + states_pusher + > with_init; + + // do the same for states marked as explicitly created + typedef typename get_explicit_creation_as_sequence< + typename ::boost::mpl::eval_if< + typename has_explicit_creation::type, + get_explicit_creation, + ::boost::mpl::vector0<> >::type + >::type fake_explicit_created; + + typedef typename + ::boost::mpl::transform< + fake_explicit_created,convert_fake_state< ::boost::mpl::placeholders::_1,Derived> >::type explicit_created; + + typedef typename mp11::mp_fold< + typename to_mp_list::type, + with_init, + states_pusher + > type; +}; + +// returns the transition table of a Composite state +template +struct get_transition_table +{ + typedef typename create_stt::type type; +}; + +// recursively builds an internal table including those of substates, sub-substates etc. +// variant for submachines +template +struct recursive_get_internal_transition_table +{ + // get the composite's internal table + typedef typename StateType::internal_transition_table composite_table; + // and for every substate (state of submachine), recursively get the internal transition table + typedef typename generate_state_set::state_set_mp11 composite_states; + template + using append_recursive_internal_transition_table = mp11::mp_append< + V, + typename recursive_get_internal_transition_table::type>::type + >; + typedef typename mp11::mp_fold< + composite_states, + typename to_mp_list::type, + append_recursive_internal_transition_table + > type; +}; +// stop iterating on leafs (simple states) +template +struct recursive_get_internal_transition_table +{ + typedef typename to_mp_list< + typename StateType::internal_transition_table + >::type type; +}; +// recursively get a transition table for a given composite state. +// returns the transition table for this state + the tables of all composite sub states recursively +template +struct recursive_get_transition_table +{ + // get the transition table of the state if it's a state machine + template + using get_transition_table_mp11 = typename get_transition_table::type; + typedef typename mp11::mp_eval_if_c< + !has_composite_tag::type::value, + mp11::mp_list<>, + get_transition_table_mp11, + Composite + > org_table; + + typedef typename generate_state_set::state_set_mp11 states; + + // and for every substate, recursively get the transition table if it's a state machine + template + using append_recursive_transition_table = mp11::mp_append< + V, + typename recursive_get_transition_table::type + >; + typedef typename mp11::mp_fold< + states, + org_table, + append_recursive_transition_table> type; +}; + +// metafunction used to say if a SM has pseudo exit states +template +struct has_fsm_deferred_events +{ + typedef typename create_stt::type Stt; + typedef typename generate_state_set::state_set_mp11 state_set_mp11; + + template + using has_activate_deferred_events_mp11 = typename has_activate_deferred_events::type; + template + using has_state_delayed_events_mp11 = typename has_state_delayed_events::type; + typedef typename mp11::mp_or< + typename has_activate_deferred_events::type, + mp11::mp_any_of< + typename to_mp_list::type, + has_activate_deferred_events_mp11 + >, + mp11::mp_any_of< + state_set_mp11, + has_state_delayed_events_mp11 + > + > type; +}; + +struct favor_compile_time; + +// returns a mpl::bool_ if State has any delayed event +template +struct is_completion_event; +template +struct is_completion_event +{ + typedef typename ::boost::mpl::if_< + has_completion_event, + ::boost::mpl::bool_, + ::boost::mpl::bool_ >::type type; + + static constexpr bool value(const Event&) + { + return type::value; + } +}; + +// metafunction used to say if a SM has eventless transitions +template +struct has_fsm_eventless_transition +{ + typedef typename create_stt::type Stt; + typedef typename generate_event_set::event_set_mp11 event_list; + + typedef mp11::mp_any_of type; +}; +template +struct find_completion_events +{ + typedef typename create_stt::type Stt; + typedef typename generate_event_set::event_set_mp11 event_list; + + template + using has_completion_event_mp11 = typename has_completion_event::type; + typedef typename mp11::mp_copy_if< + event_list, + has_completion_event_mp11 + > type; +}; + +template +struct make_vector +{ + typedef ::boost::mpl::vector type; +}; +template< typename Entry > +struct get_first_element_pair_second +{ + typedef typename ::boost::mpl::front::type type; +}; + + //returns the owner of an explicit_entry state + //which is the containing SM if the transition originates from outside the containing SM + //or else the explicit_entry state itself +template +struct get_owner +{ + typedef typename ::boost::mpl::if_< + typename ::boost::mpl::not_::type>::type, + typename State::owner, + State >::type type; +}; + +template +struct get_fork_owner +{ + typedef typename ::boost::mpl::front::type seq_front; + typedef typename ::boost::mpl::if_< + typename ::boost::mpl::not_< + typename ::boost::is_same::type>::type, + typename seq_front::owner, + seq_front >::type type; +}; + +template +struct make_exit +{ + typedef typename ::boost::mpl::if_< + typename is_pseudo_exit::type , + typename ContainingSM::template exit_pt, + typename ::boost::mpl::identity::type + >::type type; +}; + +template +struct make_entry +{ + typedef typename ::boost::mpl::if_< + typename is_pseudo_entry::type , + typename ContainingSM::template entry_pt, + typename ::boost::mpl::if_< + typename is_direct_entry::type, + typename ContainingSM::template direct, + typename ::boost::mpl::identity::type + >::type + >::type type; +}; +// metafunction used to say if a SM has pseudo exit states +template +struct has_exit_pseudo_states_helper +{ + typedef typename StateType::stt Stt; + typedef typename generate_state_set::type state_list; + + typedef ::boost::mpl::bool_< ::boost::mpl::count_if< + state_list,is_pseudo_exit< ::boost::mpl::placeholders::_1> >::value != 0> type; +}; +template +struct has_exit_pseudo_states +{ + typedef typename ::boost::mpl::eval_if::type, + has_exit_pseudo_states_helper, + ::boost::mpl::bool_ >::type type; +}; + +// builds flags (add internal_flag_list and flag_list). internal_flag_list is used for terminate/interrupt states +template +struct get_flag_list +{ + typedef typename mp11::mp_append< + typename to_mp_list::type, + typename to_mp_list::type + > type; +}; + +template +struct is_state_blocking +{ + template + using has_event_blocking_flag_mp11 = typename has_event_blocking_flag::type; + typedef typename mp11::mp_any_of< + typename get_flag_list::type, + has_event_blocking_flag_mp11 + > type; + +}; +// returns a mpl::bool_ if fsm has an event blocking flag in one of its substates +template +struct has_fsm_blocking_states +{ + typedef typename create_stt::type Stt; + typedef typename generate_state_set::state_set_mp11 state_set_mp11; + + template + using is_state_blocking_mp11 = typename is_state_blocking::type; + typedef typename mp11::mp_any_of< + state_set_mp11, + is_state_blocking_mp11 + > type; +}; + +template +struct is_no_exception_thrown +{ + typedef ::boost::mpl::bool_< ::boost::mpl::count_if< + typename StateType::configuration, + has_no_exception_thrown< ::boost::mpl::placeholders::_1 > >::value != 0> found; + + typedef typename ::boost::mpl::or_< + typename has_no_exception_thrown::type, + found + >::type type; +}; + +template +struct is_no_message_queue +{ + typedef ::boost::mpl::bool_< ::boost::mpl::count_if< + typename StateType::configuration, + has_no_message_queue< ::boost::mpl::placeholders::_1 > >::value != 0> found; + + typedef typename ::boost::mpl::or_< + typename has_no_message_queue::type, + found + >::type type; +}; + +template +struct is_active_state_switch_policy +{ + typedef ::boost::mpl::bool_< ::boost::mpl::count_if< + typename StateType::configuration, + has_active_state_switch_policy< ::boost::mpl::placeholders::_1 > >::value != 0> found; + + typedef typename ::boost::mpl::or_< + typename has_active_state_switch_policy::type, + found + >::type type; +}; + +template +struct get_initial_event +{ + typedef typename StateType::initial_event type; +}; + +template +struct get_final_event +{ + typedef typename StateType::final_event type; +}; + +template +struct build_one_orthogonal_region +{ + template + struct row_to_incidence : + mp11::mp_list< + ::boost::mpl::pair< + typename Row::next_state_type, + typename Row::transition_event>, + typename Row::current_state_type, + typename Row::next_state_type + > {}; + + typedef typename mp11::mp_transform< + row_to_incidence, + typename to_mp_list::type + > transition_incidence_list; + + typedef ::boost::msm::mpl_graph::incidence_list_graph + transition_graph; + + struct preordering_dfs_visitor : + ::boost::msm::mpl_graph::dfs_default_visitor_operations + { + template + struct discover_vertex : + ::boost::mpl::insert + {}; + }; + + typedef typename mpl::first< + typename ::boost::msm::mpl_graph::depth_first_search< + transition_graph, + preordering_dfs_visitor, + ::boost::mpl::set<>, + InitState + >::type + >::type type; +}; + +template +struct find_entry_states +{ + typedef mp11::mp_copy_if< + typename Fsm::substate_list, + has_explicit_entry_state + > type; +}; + +template +struct is_common_element +{ + typedef typename ::boost::mpl::fold< + Set1, ::boost::mpl::false_, + ::boost::mpl::if_< + ::boost::mpl::has_key< + Set2, + ::boost::mpl::placeholders::_2 + >, + ::boost::mpl::true_, + ::boost::mpl::placeholders::_1 + > + >::type type; +}; + +template +struct add_entry_region +{ + typedef typename ::boost::mpl::transform< + AllRegions, + ::boost::mpl::if_< + is_common_element, + set_insert_range< ::boost::mpl::placeholders::_1, EntryRegion>, + ::boost::mpl::placeholders::_1 + > + >::type type; +}; + +// build a vector of regions states (as a set) +// one set of states for every region +template +struct build_orthogonal_regions +{ + typedef typename + ::boost::mpl::fold< + InitStates, ::boost::mpl::vector0<>, + ::boost::mpl::push_back< + ::boost::mpl::placeholders::_1, + build_one_orthogonal_region< typename Fsm::stt, ::boost::mpl::placeholders::_2 > > + >::type without_entries; + + typedef typename + ::boost::mpl::fold< + typename find_entry_states::type, ::boost::mpl::vector0<>, + ::boost::mpl::push_back< + ::boost::mpl::placeholders::_1, + build_one_orthogonal_region< typename Fsm::stt, ::boost::mpl::placeholders::_2 > > + >::type only_entries; + + typedef typename ::boost::mpl::fold< + only_entries , without_entries, + add_entry_region< ::boost::mpl::placeholders::_2, ::boost::mpl::placeholders::_1> + >::type type; +}; + +template +struct find_region_index +{ + typedef typename + ::boost::mpl::fold< + GraphAsSeqOfSets, ::boost::mpl::pair< ::boost::mpl::int_< -1 > /*res*/, ::boost::mpl::int_<0> /*counter*/ >, + ::boost::mpl::if_< + ::boost::mpl::has_key< ::boost::mpl::placeholders::_2, StateType >, + ::boost::mpl::pair< + ::boost::mpl::second< ::boost::mpl::placeholders::_1 >, + ::boost::mpl::next< ::boost::mpl::second< ::boost::mpl::placeholders::_1 > > + >, + ::boost::mpl::pair< + ::boost::mpl::first< ::boost::mpl::placeholders::_1 >, + ::boost::mpl::next< ::boost::mpl::second< ::boost::mpl::placeholders::_1 > > + > + > + >::type result_pair; + typedef typename ::boost::mpl::first::type type; + enum {value = type::value}; +}; + +template +struct check_regions_orthogonality +{ + typedef typename build_orthogonal_regions< Fsm,typename Fsm::initial_states>::type regions; + + typedef typename mp11::mp_apply< + mp11::mp_plus, + mp11::mp_transform< + mp11::mp_size, + typename to_mp_list::type + > + > number_of_states_in_regions; + + typedef typename ::boost::mpl::fold< + regions,mpl::set0<>, + set_insert_range< + ::boost::mpl::placeholders::_1, + ::boost::mpl::placeholders::_2 > + >::type one_big_states_set; + + enum {states_in_regions_raw = number_of_states_in_regions::value}; + enum {cumulated_states_in_regions_raw = ::boost::mpl::size::value}; +}; + +template +struct check_no_unreachable_state +{ + typedef typename check_regions_orthogonality::one_big_states_set states_in_regions; + + typedef typename set_insert_range< + states_in_regions, + typename ::boost::mpl::eval_if< + typename has_explicit_creation::type, + get_explicit_creation, + ::boost::mpl::vector0<> + >::type + >::type with_explicit_creation; + + enum {states_in_fsm = ::boost::mpl::size< typename Fsm::substate_list >::value}; + enum {cumulated_states_in_regions = ::boost::mpl::size< with_explicit_creation >::value}; +}; + +// helper to find out if a SM has an active exit state and is therefore waiting for exiting +template +inline +typename ::boost::enable_if::type, + typename is_pseudo_exit::type>,bool >::type +is_exit_state_active(FSM& fsm) +{ + typedef typename OwnerFct::type Composite; + //typedef typename create_stt::type stt; + typedef typename Composite::stt stt; + int state_id = get_state_id::type::value; + Composite& comp = fsm.template get_state(); + return (std::find(comp.current_state(),comp.current_state()+Composite::nr_regions::value,state_id) + !=comp.current_state()+Composite::nr_regions::value); +} +template +inline +typename ::boost::disable_if::type, + typename is_pseudo_exit::type>,bool >::type +is_exit_state_active(FSM&) +{ + return false; +} + +// transformation metafunction to end interrupt flags +template +struct transform_to_end_interrupt +{ + typedef boost::msm::EndInterruptFlag type; +}; +// transform a sequence of events into another one of EndInterruptFlag +template +struct apply_end_interrupt_flag +{ + typedef typename + ::boost::mpl::transform< + Events,transform_to_end_interrupt< ::boost::mpl::placeholders::_1> >::type type; +}; +// returns a mpl vector containing all end interrupt events if sequence, otherwise the same event +template +struct get_interrupt_events +{ + typedef typename ::boost::mpl::eval_if< + ::boost::mpl::is_sequence, + apply_end_interrupt_flag, + boost::mpl::vector1 > >::type type; +}; + +template +struct build_interrupt_state_flag_list +{ + typedef ::boost::mpl::vector first_part; + typedef typename ::boost::mpl::insert_range< + first_part, + typename ::boost::mpl::end< first_part >::type, + Events + >::type type; +}; + +}}} // boost::msm::backmp11 + +#endif // BOOST_MSM_BACKMP11_METAFUNCTIONS_H diff --git a/include/boost/msm/backmp11/state_machine.hpp b/include/boost/msm/backmp11/state_machine.hpp new file mode 100644 index 0000000..bd32f35 --- /dev/null +++ b/include/boost/msm/backmp11/state_machine.hpp @@ -0,0 +1,3012 @@ +// Copyright 2025 Christian Granzin +// Copyright 2008 Christophe Henry +// henry UNDERSCORE christophe AT hotmail DOT com +// This is an extended version of the state machine available in the boost::mpl library +// Distributed under the same license as the original. +// Copyright for the original version: +// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed +// under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +#ifndef BOOST_MSM_BACKMP11_STATEMACHINE_H +#define BOOST_MSM_BACKMP11_STATEMACHINE_H + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#ifndef BOOST_NO_RTTI +#include +#endif + +#include + +#define BOOST_PARAMETER_CAN_USE_MP11 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef BOOST_MSM_CONSTRUCTOR_ARG_SIZE +#define BOOST_MSM_CONSTRUCTOR_ARG_SIZE 5 // default max number of arguments for constructors +#endif + +namespace boost { namespace msm { namespace backmp11 +{ + +using back::no_fsm_check; +using back::queue_container_deque; +using back::FoldToList; + + +// event used internally for wrapping a direct entry +template +struct direct_entry_event +{ + typedef int direct_entry; + typedef StateType active_state; + typedef Event contained_event; + + direct_entry_event(Event const& evt):m_event(evt){} + Event const& m_event; +}; + +BOOST_PARAMETER_TEMPLATE_KEYWORD(front_end) +BOOST_PARAMETER_TEMPLATE_KEYWORD(history_policy) +BOOST_PARAMETER_TEMPLATE_KEYWORD(compile_policy) +BOOST_PARAMETER_TEMPLATE_KEYWORD(fsm_check_policy) +BOOST_PARAMETER_TEMPLATE_KEYWORD(queue_container_policy) + +typedef ::boost::parameter::parameters< + ::boost::parameter::required< tag::front_end > + , ::boost::parameter::optional< + ::boost::parameter::deduced< tag::history_policy>, has_history_policy< ::boost::mpl::_ > + > + , ::boost::parameter::optional< + ::boost::parameter::deduced< tag::compile_policy>, has_compile_policy< ::boost::mpl::_ > + > + , ::boost::parameter::optional< + ::boost::parameter::deduced< tag::fsm_check_policy>, has_fsm_check< ::boost::mpl::_ > + > + , ::boost::parameter::optional< + ::boost::parameter::deduced< tag::queue_container_policy>, + has_queue_container_policy< ::boost::mpl::_ > + > +> state_machine_signature; + +// just here to disable use of proto when not needed +template +struct make_euml_terminal; +template +struct make_euml_terminal >::type> +{}; +template +struct make_euml_terminal >::type> + : public proto::extends::type, T, boost::msm::state_domain> +{}; + +// library-containing class for state machines. Pass the actual FSM class as +// the Concrete parameter. +// A0=Derived,A1=NoHistory,A2=CompilePolicy,A3=FsmCheckPolicy > +template < + class A0 + , class A1 = parameter::void_ + , class A2 = parameter::void_ + , class A3 = parameter::void_ + , class A4 = parameter::void_ +> +class state_machine : //public Derived + public ::boost::parameter::binding< + typename state_machine_signature::bind::type, tag::front_end + >::type + , public make_euml_terminal, + typename ::boost::parameter::binding< + typename state_machine_signature::bind::type, tag::front_end + >::type + > +{ +public: + // Create ArgumentPack + typedef typename + state_machine_signature::bind::type + state_machine_args; + + // Extract first logical parameter. + typedef typename ::boost::parameter::binding< + state_machine_args, tag::front_end>::type Derived; + + typedef typename ::boost::parameter::binding< + state_machine_args, tag::history_policy, NoHistory >::type HistoryPolicy; + + typedef typename ::boost::parameter::binding< + state_machine_args, tag::compile_policy, favor_runtime_speed >::type CompilePolicy; + + typedef typename ::boost::parameter::binding< + state_machine_args, tag::fsm_check_policy, no_fsm_check >::type FsmCheckPolicy; + + typedef typename ::boost::parameter::binding< + state_machine_args, tag::queue_container_policy, + queue_container_deque >::type QueueContainerPolicy; + +private: + + typedef state_machine< + A0,A1,A2,A3,A4> library_sm; + + typedef ::std::function< + execute_return ()> transition_fct; + typedef ::std::function< + execute_return () > deferred_fct; + typedef typename QueueContainerPolicy:: + template In< + std::pair >::type deferred_events_queue_t; + typedef typename QueueContainerPolicy:: + template In::type events_queue_t; + + typedef typename boost::mpl::eval_if< + typename is_active_state_switch_policy::type, + get_active_state_switch_policy, + // default + ::boost::mpl::identity + >::type active_state_switching; + + typedef bool (*flag_handler)(library_sm const&); + + // all state machines are friend with each other to allow embedding any of them in another fsm + template friend class state_machine; + + // helper to add, if needed, visitors to all states + // version without visitors + template + struct visitor_fct_helper + { + public: + visitor_fct_helper(){} + void fill_visitors(int) + { + } + template + void insert(int,FCT) + { + } + template + void execute(int,VISITOR) + { + } + }; + // version with visitors + template + struct visitor_fct_helper >::type> + { + public: + visitor_fct_helper():m_state_visitors(){} + void fill_visitors(int number_of_states) + { + m_state_visitors.resize(number_of_states); + } + template + void insert(int index,FCT fct) + { + m_state_visitors[index]=fct; + } + void execute(int index) + { + m_state_visitors[index](); + } + +#define MSM_VISITOR_HELPER_EXECUTE_SUB(z, n, unused) ARG ## n vis ## n +#define MSM_VISITOR_HELPER_EXECUTE(z, n, unused) \ + template \ + void execute(int index BOOST_PP_COMMA_IF(n) \ + BOOST_PP_ENUM(n, MSM_VISITOR_HELPER_EXECUTE_SUB, ~ ) ) \ + { \ + m_state_visitors[index](BOOST_PP_ENUM_PARAMS(n,vis)); \ + } + BOOST_PP_REPEAT_FROM_TO(1,BOOST_PP_ADD(BOOST_MSM_VISITOR_ARG_SIZE,1), MSM_VISITOR_HELPER_EXECUTE, ~) +#undef MSM_VISITOR_HELPER_EXECUTE +#undef MSM_VISITOR_HELPER_EXECUTE_SUB + private: + typedef typename StateType::accept_sig::type visitor_fct; + typedef std::vector visitors; + + visitors m_state_visitors; + }; + + template + struct deferred_msg_queue_helper + { + void clear(){} + }; + template + struct deferred_msg_queue_helper::type,int >::type> + { + public: + deferred_msg_queue_helper():m_deferred_events_queue(),m_cur_seq(0){} + void clear() + { + m_deferred_events_queue.clear(); + } + deferred_events_queue_t m_deferred_events_queue; + char m_cur_seq; + }; + + public: + // tags + typedef int composite_tag; + + // in case someone needs to know + typedef HistoryPolicy history_policy; + + struct InitEvent { }; + struct ExitEvent { }; + // flag handling + struct Flag_AND + { + typedef std::logical_and type; + }; + struct Flag_OR + { + typedef std::logical_or type; + }; + typedef typename Derived::BaseAllStates BaseState; + typedef Derived ConcreteSM; + + // if the front-end fsm provides an initial_event typedef, replace InitEvent by this one + typedef typename ::boost::mpl::eval_if< + typename has_initial_event::type, + get_initial_event, + ::boost::mpl::identity + >::type fsm_initial_event; + + // if the front-end fsm provides an exit_event typedef, replace ExitEvent by this one + typedef typename ::boost::mpl::eval_if< + typename has_final_event::type, + get_final_event, + ::boost::mpl::identity + >::type fsm_final_event; + + template + struct exit_pt : public ExitPoint + { + // tags + typedef ExitPoint wrapped_exit; + typedef int pseudo_exit; + typedef library_sm owner; + typedef int no_automatic_create; + typedef typename + ExitPoint::event Event; + typedef ::boost::function + forwarding_function; + + // forward event to the higher-level FSM + template + void forward_event(ForwardEvent const& incomingEvent) + { + // use helper to forward or not + ForwardHelper< ::boost::is_convertible::value>::helper(incomingEvent,m_forward); + } + void set_forward_fct(::boost::function fct) + { + m_forward = fct; + } + exit_pt():m_forward(){} + // by assignments, we keep our forwarding functor unchanged as our containing SM did not change + template + exit_pt(RHS&):m_forward(){} + exit_pt& operator= (const exit_pt& ) + { + return *this; + } + private: + forwarding_function m_forward; + + // using partial specialization instead of enable_if because of VC8 bug + template + struct ForwardHelper + { + template + static void helper(ForwardEvent const& ,forwarding_function& ) + { + // Not our event, assert + BOOST_ASSERT(false); + } + }; + template + struct ForwardHelper + { + template + static void helper(ForwardEvent const& incomingEvent,forwarding_function& forward_fct) + { + // call if handler set, if not, this state is simply a terminate state + if (forward_fct) + forward_fct(incomingEvent); + } + }; + + }; + template + struct entry_pt : public EntryPoint + { + // tags + typedef EntryPoint wrapped_entry; + typedef int pseudo_entry; + typedef library_sm owner; + typedef int no_automatic_create; + }; + template + struct direct : public EntryPoint + { + // tags + typedef EntryPoint wrapped_entry; + typedef int explicit_entry_state; + typedef library_sm owner; + typedef int no_automatic_create; + }; + typedef typename get_number_of_regions::type nr_regions; + // Template used to form rows in the transition table + template< + typename ROW + > + struct row_ + { + //typedef typename ROW::Source T1; + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + // if the source is an exit pseudo state, then + // current_state_type becomes the result of get_owner + // meaning the containing SM from which the exit occurs + typedef typename ::boost::mpl::eval_if< + typename has_pseudo_exit::type, + get_owner, + ::boost::mpl::identity >::type current_state_type; + + // if Target is a sequence, then we have a fork and expect a sequence of explicit_entry + // else if Target is an explicit_entry, next_state_type becomes the result of get_owner + // meaning the containing SM if the row is "outside" the containing SM or else the explicit_entry state itself + typedef typename ::boost::mpl::eval_if< + typename ::boost::mpl::is_sequence::type, + get_fork_owner, + ::boost::mpl::eval_if< + typename has_no_automatic_create::type, + get_owner, + ::boost::mpl::identity > + >::type next_state_type; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list ) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int region_index, int state, transition_event const& evt) + { + + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + BOOST_STATIC_CONSTANT(int, next_state = (get_state_id::type::value)); + boost::ignore_unused(state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + // if T1 is an exit pseudo state, then take the transition only if the pseudo exit state is active + if (has_pseudo_exit::type::value && + !backmp11::is_exit_state_active >(fsm)) + { + return HANDLED_FALSE; + } + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + fsm.m_states[region_index] = active_state_switching::after_guard(current_state,next_state); + + // the guard condition has already been checked + execute_exit + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_exit(current_state,next_state); + + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + fsm.m_states[region_index] = active_state_switching::after_action(current_state,next_state); + + // and finally the entry method of the new current state + convert_event_and_execute_entry + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_entry(current_state,next_state); + return res; + } + }; + + // row having only a guard condition + template< + typename ROW + > + struct g_row_ + { + //typedef typename ROW::Source T1; + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + // if the source is an exit pseudo state, then + // current_state_type becomes the result of get_owner + // meaning the containing SM from which the exit occurs + typedef typename ::boost::mpl::eval_if< + typename has_pseudo_exit::type, + get_owner, + ::boost::mpl::identity >::type current_state_type; + + // if Target is a sequence, then we have a fork and expect a sequence of explicit_entry + // else if Target is an explicit_entry, next_state_type becomes the result of get_owner + // meaning the containing SM if the row is "outside" the containing SM or else the explicit_entry state itself + typedef typename ::boost::mpl::eval_if< + typename ::boost::mpl::is_sequence::type, + get_fork_owner, + ::boost::mpl::eval_if< + typename has_no_automatic_create::type, + get_owner, + ::boost::mpl::identity > + >::type next_state_type; + + // if a guard condition is defined, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list )) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int region_index, int state, transition_event const& evt) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + BOOST_STATIC_CONSTANT(int, next_state = (get_state_id::type::value)); + boost::ignore_unused(state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + // if T1 is an exit pseudo state, then take the transition only if the pseudo exit state is active + if (has_pseudo_exit::type::value && + !backmp11::is_exit_state_active >(fsm)) + { + return HANDLED_FALSE; + } + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + fsm.m_states[region_index] = active_state_switching::after_guard(current_state,next_state); + + // the guard condition has already been checked + execute_exit + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_exit(current_state,next_state); + fsm.m_states[region_index] = active_state_switching::after_action(current_state,next_state); + + // and finally the entry method of the new current state + convert_event_and_execute_entry + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_entry(current_state,next_state); + return HANDLED_TRUE; + } + }; + + // row having only an action method + template< + typename ROW + > + struct a_row_ + { + //typedef typename ROW::Source T1; + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + // if the source is an exit pseudo state, then + // current_state_type becomes the result of get_owner + // meaning the containing SM from which the exit occurs + typedef typename ::boost::mpl::eval_if< + typename has_pseudo_exit::type, + get_owner, + ::boost::mpl::identity >::type current_state_type; + + // if Target is a sequence, then we have a fork and expect a sequence of explicit_entry + // else if Target is an explicit_entry, next_state_type becomes the result of get_owner + // meaning the containing SM if the row is "outside" the containing SM or else the explicit_entry state itself + typedef typename ::boost::mpl::eval_if< + typename ::boost::mpl::is_sequence::type, + get_fork_owner, + ::boost::mpl::eval_if< + typename has_no_automatic_create::type, + get_owner, + ::boost::mpl::identity > + >::type next_state_type; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int region_index, int state, transition_event const& evt) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + BOOST_STATIC_CONSTANT(int, next_state = (get_state_id::type::value)); + boost::ignore_unused(state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + + // if T1 is an exit pseudo state, then take the transition only if the pseudo exit state is active + if (has_pseudo_exit::type::value && + !backmp11::is_exit_state_active >(fsm)) + { + return HANDLED_FALSE; + } + fsm.m_states[region_index] = active_state_switching::after_guard(current_state,next_state); + + // no need to check the guard condition + // first call the exit method of the current state + execute_exit + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_exit(current_state,next_state); + + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + fsm.m_states[region_index] = active_state_switching::after_action(current_state,next_state); + + // and finally the entry method of the new current state + convert_event_and_execute_entry + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_entry(current_state,next_state); + return res; + } + }; + + // row having no guard condition or action, simply transitions + template< + typename ROW + > + struct _row_ + { + //typedef typename ROW::Source T1; + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + // if the source is an exit pseudo state, then + // current_state_type becomes the result of get_owner + // meaning the containing SM from which the exit occurs + typedef typename ::boost::mpl::eval_if< + typename has_pseudo_exit::type, + get_owner, + ::boost::mpl::identity >::type current_state_type; + + // if Target is a sequence, then we have a fork and expect a sequence of explicit_entry + // else if Target is an explicit_entry, next_state_type becomes the result of get_owner + // meaning the containing SM if the row is "outside" the containing SM or else the explicit_entry state itself + typedef typename ::boost::mpl::eval_if< + typename ::boost::mpl::is_sequence::type, + get_fork_owner, + ::boost::mpl::eval_if< + typename has_no_automatic_create::type, + get_owner, + ::boost::mpl::identity > + >::type next_state_type; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int region_index, int state, transition_event const& evt) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + BOOST_STATIC_CONSTANT(int, next_state = (get_state_id::type::value)); + boost::ignore_unused(state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + + // if T1 is an exit pseudo state, then take the transition only if the pseudo exit state is active + if (has_pseudo_exit::type::value && + !backmp11::is_exit_state_active >(fsm)) + { + return HANDLED_FALSE; + } + fsm.m_states[region_index] = active_state_switching::after_guard(current_state,next_state); + + // first call the exit method of the current state + execute_exit + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_exit(current_state,next_state); + fsm.m_states[region_index] = active_state_switching::after_action(current_state,next_state); + + + // and finally the entry method of the new current state + convert_event_and_execute_entry + (std::get::value>(fsm.m_substate_list),evt,fsm); + fsm.m_states[region_index] = active_state_switching::after_entry(current_state,next_state); + return HANDLED_TRUE; + } + }; + // "i" rows are rows for internal transitions + template< + typename ROW + > + struct irow_ + { + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + typedef typename ROW::Source current_state_type; + typedef T2 next_state_type; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list)) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int , int state, transition_event const& evt) + { + + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + boost::ignore_unused(state, current_state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + + // call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + return res; + } + }; + + // row having only a guard condition + template< + typename ROW + > + struct g_irow_ + { + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + typedef typename ROW::Source current_state_type; + typedef T2 next_state_type; + + // if a guard condition is defined, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int , int state, transition_event const& evt) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + boost::ignore_unused(state, current_state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + return HANDLED_TRUE; + } + }; + + // row having only an action method + template< + typename ROW + > + struct a_irow_ + { + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + + typedef typename ROW::Evt transition_event; + typedef typename ROW::Source current_state_type; + typedef T2 next_state_type; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int , int state, transition_event const& evt) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + boost::ignore_unused(state, current_state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + + // call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + + return res; + } + }; + // row simply ignoring the event + template< + typename ROW + > + struct _irow_ + { + typedef typename make_entry::type T1; + typedef typename make_exit::type T2; + typedef typename ROW::Evt transition_event; + typedef typename ROW::Source current_state_type; + typedef T2 next_state_type; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& , int , int state, transition_event const& ) + { + BOOST_STATIC_CONSTANT(int, current_state = (get_state_id::type::value)); + boost::ignore_unused(state, current_state); // Avoid warnings if BOOST_ASSERT expands to nothing. + BOOST_ASSERT(state == (current_state)); + return HANDLED_TRUE; + } + }; + // transitions internal to this state machine (no substate involved) + template< + typename ROW, + typename StateType + > + struct internal_ + { + typedef StateType current_state_type; + typedef StateType next_state_type; + typedef typename ROW::Evt transition_event; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int , int , transition_event const& evt) + { + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + return res; + } + }; + template< + typename ROW + > + struct internal_ + { + typedef library_sm current_state_type; + typedef library_sm next_state_type; + typedef typename ROW::Evt transition_event; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + fsm, + fsm, + fsm.m_substate_list) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int , int , transition_event const& evt) + { + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + fsm, + fsm, + fsm.m_substate_list); + return res; + } + }; + + template< + typename ROW, + typename StateType + > + struct a_internal_ + { + typedef StateType current_state_type; + typedef StateType next_state_type; + typedef typename ROW::Evt transition_event; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int, int, transition_event const& evt) + { + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list); + return res; + } + }; + template< + typename ROW + > + struct a_internal_ + { + typedef library_sm current_state_type; + typedef library_sm next_state_type; + typedef typename ROW::Evt transition_event; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int, int, transition_event const& evt) + { + // then call the action method + HandledEnum res = ROW::action_call(fsm,evt, + fsm, + fsm, + fsm.m_substate_list); + return res; + } + }; + template< + typename ROW, + typename StateType + > + struct g_internal_ + { + typedef StateType current_state_type; + typedef StateType next_state_type; + typedef typename ROW::Evt transition_event; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + std::get::value>(fsm.m_substate_list), + std::get::value>(fsm.m_substate_list), + fsm.m_substate_list) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int, int, transition_event const& evt) + { + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + return HANDLED_TRUE; + } + }; + template< + typename ROW + > + struct g_internal_ + { + typedef library_sm current_state_type; + typedef library_sm next_state_type; + typedef typename ROW::Evt transition_event; + + // if a guard condition is here, call it to check that the event is accepted + static bool check_guard(library_sm& fsm,transition_event const& evt) + { + if ( ROW::guard_call(fsm,evt, + fsm, + fsm, + fsm.m_substate_list) ) + return true; + return false; + } + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int, int, transition_event const& evt) + { + if (!check_guard(fsm,evt)) + { + // guard rejected the event, we stay in the current one + return HANDLED_GUARD_REJECT; + } + return HANDLED_TRUE; + } + }; + template< + typename ROW, + typename StateType + > + struct _internal_ + { + typedef StateType current_state_type; + typedef StateType next_state_type; + typedef typename ROW::Evt transition_event; + static HandledEnum execute(library_sm& , int , int , transition_event const& ) + { + return HANDLED_TRUE; + } + }; + template< + typename ROW + > + struct _internal_ + { + typedef library_sm current_state_type; + typedef library_sm next_state_type; + typedef typename ROW::Evt transition_event; + static HandledEnum execute(library_sm& , int , int , transition_event const& ) + { + return HANDLED_TRUE; + } + }; + // Template used to form forwarding rows in the transition table for every row of a composite SM + template< + typename T1 + , class Evt + > + struct frow + { + typedef T1 current_state_type; + typedef T1 next_state_type; + typedef Evt transition_event; + // tag to find out if a row is a forwarding row + typedef int is_frow; + + // Take the transition action and return the next state. + static HandledEnum execute(library_sm& fsm, int region_index, int , transition_event const& evt) + { + // false as second parameter because this event is forwarded from outer fsm + execute_return res = + (std::get::value>(fsm.m_substate_list)).process_event_internal(evt); + fsm.m_states[region_index]=get_state_id::type::value; + return res; + } + // helper metafunctions used by dispatch table and give the frow a new event + // (used to avoid double entries in a table because of base events) + template + struct replace_event + { + typedef frow type; + }; + }; + + template + struct create_backend_stt + { + }; + template + struct create_backend_stt + { + typedef g_row_ type; + }; + template + struct create_backend_stt + { + typedef a_row_ type; + }; + template + struct create_backend_stt<_row_tag,Transition,StateType> + { + typedef _row_ type; + }; + template + struct create_backend_stt + { + typedef row_ type; + }; + // internal transitions + template + struct create_backend_stt + { + typedef g_irow_ type; + }; + template + struct create_backend_stt + { + typedef a_irow_ type; + }; + template + struct create_backend_stt + { + typedef irow_ type; + }; + template + struct create_backend_stt<_irow_tag,Transition,StateType> + { + typedef _irow_ type; + }; + template + struct create_backend_stt + { + typedef a_internal_ type; + }; + template + struct create_backend_stt + { + typedef g_internal_ type; + }; + template + struct create_backend_stt + { + typedef internal_ type; + }; + template + struct create_backend_stt + { + typedef _internal_ type; + }; + template + struct make_row_tag + { + typedef typename create_backend_stt::type type; + }; + + // add to the stt the initial states which could be missing (if not being involved in a transition) + template + struct create_real_stt + { + //typedef typename BaseType::transition_table stt_simulated; + template + using make_row_tag_base_type = typename make_row_tag::type; + typedef typename boost::mp11::mp_transform< + make_row_tag_base_type, + typename to_mp_list::type + > type; + }; + + template + struct add_forwarding_row_helper + { + typedef typename generate_event_set::event_set_mp11 all_events; + + template + using frow_state_type = frow; + typedef mp11::mp_append< + typename to_mp_list::type, + mp11::mp_transform + > type; + }; + // gets the transition table from a composite and make from it a forwarding row + template + struct get_internal_transition_table + { + // first get the table of a composite + typedef typename recursive_get_transition_table::type original_table; + + // we now look for the events the composite has in its internal transitions + // the internal ones are searched recursively in sub-sub... states + // we go recursively because our states can also have internal tables or substates etc. + typedef typename recursive_get_internal_transition_table::type recursive_istt; + template + using make_row_tag_state_type = typename make_row_tag::type; + typedef boost::mp11::mp_transform< + make_row_tag_state_type, + typename to_mp_list::type + > recursive_istt_with_tag; + + typedef boost::mp11::mp_append table_with_all_events; + + // and add for every event a forwarding row + typedef typename ::boost::mpl::eval_if< + typename CompilePolicy::add_forwarding_rows, + add_forwarding_row_helper,StateType>, + ::boost::mpl::identity< mp11::mp_list<> > + >::type type; + }; + template + struct get_internal_transition_table + { + typedef typename create_real_stt::type type; + }; + // typedefs used internally + typedef typename create_real_stt::type real_transition_table; + typedef typename create_stt::type stt; + typedef typename get_initial_states::type initial_states; + typedef typename generate_state_set::state_set_mp11 state_set_mp11; + typedef typename generate_state_map::type state_map_mp11; + typedef typename generate_event_set::event_set_mp11 event_set_mp11; + typedef typename HistoryPolicy::template apply::type concrete_history; + + typedef mp11::mp_rename substate_list; + typedef typename generate_event_set< + typename create_real_stt::type + >::event_set_mp11 processable_events_internal_table; + + // extends the transition table with rows from composite states + template + struct extend_table + { + // add the init states + //typedef typename create_stt::type stt; + typedef typename Composite::stt Stt; + + // add the internal events defined in the internal_transition_table + // Note: these are added first because they must have a lesser prio + // than the deeper transitions in the sub regions + // table made of a stt + internal transitions of composite + template + using make_row_tag_composite = typename make_row_tag::type; + typedef typename boost::mp11::mp_transform< + make_row_tag_composite, + typename to_mp_list::type + > internal_stt; + + typedef boost::mp11::mp_append< + typename to_mp_list::type, + internal_stt + > stt_plus_internal; + + // for every state, add its transition table (if any) + // transformed as frow + template + using F = boost::mp11::mp_append< + V, + typename get_internal_transition_table::type>::type + >; + typedef boost::mp11::mp_fold< + state_set_mp11, + stt_plus_internal, + F + > type; + }; + // extend the table with tables from composite states + typedef typename extend_table::type complete_table; + // define the dispatch table used for event dispatch + typedef dispatch_table sm_dispatch_table; + // build a sequence of regions + typedef typename get_regions_as_sequence::type seq_initial_states; + // Member functions + + // start the state machine (calls entry of the initial state) + void start() + { + // reinitialize our list of currently active states with the ones defined in Derived::initial_state + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + // call on_entry on this SM + (static_cast(this))->on_entry(fsm_initial_event(),*this); + ::boost::mpl::for_each > + (call_init(fsm_initial_event(),this)); + // give a chance to handle an anonymous (eventless) transition + handle_eventless_transitions_helper eventless_helper(this,true); + eventless_helper.process_completion_event(); + } + + // start the state machine (calls entry of the initial state passing incomingEvent to on_entry's) + template + void start(Event const& incomingEvent) + { + // reinitialize our list of currently active states with the ones defined in Derived::initial_state + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + // call on_entry on this SM + (static_cast(this))->on_entry(incomingEvent,*this); + ::boost::mpl::for_each > + (call_init(incomingEvent,this)); + // give a chance to handle an anonymous (eventless) transition + handle_eventless_transitions_helper eventless_helper(this,true); + eventless_helper.process_completion_event(); + } + + // stop the state machine (calls exit of the current state) + void stop() + { + do_exit(fsm_final_event(),*this); + } + + // stop the state machine (calls exit of the current state passing finalEvent to on_exit's) + template + void stop(Event const& finalEvent) + { + do_exit(finalEvent,*this); + } + + // Main function used by clients of the derived FSM to make transitions. + template + execute_return process_event(Event const& evt) + { + return process_event_internal(evt, EVENT_SOURCE_DIRECT); + } + + template + void enqueue_event_helper(EventType const& evt, ::boost::mpl::false_ const &) + { + m_events_queue.m_events_queue.push_back( + [this, evt] {return process_event_internal(evt, static_cast(EVENT_SOURCE_MSG_QUEUE));}); + } + template + void enqueue_event_helper(EventType const& , ::boost::mpl::true_ const &) + { + // no queue + } + + void execute_queued_events_helper(::boost::mpl::false_ const &) + { + while(!m_events_queue.m_events_queue.empty()) + { + execute_single_queued_event_helper(::boost::mpl::false_{}); + } + } + void execute_queued_events_helper(::boost::mpl::true_ const &) + { + // no queue required + } + void execute_single_queued_event_helper(::boost::mpl::false_ const &) + { + transition_fct to_call = m_events_queue.m_events_queue.front(); + m_events_queue.m_events_queue.pop_front(); + to_call(); + } + void execute_single_queued_event_helper(::boost::mpl::true_ const &) + { + // no queue required + } + // enqueues an event in the message queue + // call execute_queued_events to process all queued events. + // Be careful if you do this during event processing, the event will be processed immediately + // and not kept in the queue + template + void enqueue_event(EventType const& evt) + { + enqueue_event_helper(evt, typename is_no_message_queue::type()); + } + + // empty the queue and process events + void execute_queued_events() + { + execute_queued_events_helper(typename is_no_message_queue::type()); + } + void execute_single_queued_event() + { + execute_single_queued_event_helper(typename is_no_message_queue::type()); + } + typename events_queue_t::size_type get_message_queue_size() const + { + return m_events_queue.m_events_queue.size(); + } + + events_queue_t& get_message_queue() + { + return m_events_queue.m_events_queue; + } + + const events_queue_t& get_message_queue() const + { + return m_events_queue.m_events_queue; + } + + void clear_deferred_queue() + { + m_deferred_events_queue.clear(); + } + + deferred_events_queue_t& get_deferred_queue() + { + return m_deferred_events_queue.m_deferred_events_queue; + } + + const deferred_events_queue_t& get_deferred_queue() const + { + return m_deferred_events_queue.m_deferred_events_queue; + } + + // Getter that returns the current state of the FSM + const int* current_state() const + { + return this->m_states; + } + + template + struct serialize_state + { + serialize_state(Archive& ar):ar_(ar){} + + template + typename ::boost::enable_if< + typename ::boost::mpl::or_< + typename has_do_serialize::type, + typename is_composite_state::type + >::type + ,void + >::type + operator()(T& t) const + { + ar_ & t; + } + template + typename ::boost::disable_if< + typename ::boost::mpl::or_< + typename has_do_serialize::type, + typename is_composite_state::type + >::type + ,void + >::type + operator()(T&) const + { + // no state to serialize + } + Archive& ar_; + }; + + template + void serialize(Archive & ar, const unsigned int) + { + // invoke serialization of the base class + (serialize_state(ar))(boost::serialization::base_object(*this)); + // now our attributes + ar & m_states; + // queues cannot be serialized => skip + ar & m_history; + ar & m_event_processing; + ar & m_is_included; + // visitors cannot be serialized => skip + mp11::tuple_for_each(m_substate_list, serialize_state(ar)); + } + + // linearly search for the state with the given id + struct get_state_id_helper + { + get_state_id_helper(int id,const BaseState** res,const library_sm* self_): + result_state(res),searched_id(id),self(self_) {} + + template + void operator()(boost::msm::wrap const&) + { + // look for the state id until found + BOOST_STATIC_CONSTANT(int, id = (get_state_id::value)); + if (!*result_state && (id == searched_id)) + { + *result_state = &std::get::value>(self->m_substate_list); + } + } + const BaseState** result_state; + int searched_id; + const library_sm* self; + }; + // return the state whose id is passed or 0 if not found + // caution if you need this, you probably need polymorphic states + // complexity: O(number of states) + BaseState* get_state_by_id(int id) + { + const BaseState* result_state=0; + ::boost::mpl::for_each > (get_state_id_helper(id,&result_state,this)); + return const_cast(result_state); + } + const BaseState* get_state_by_id(int id) const + { + const BaseState* result_state=0; + ::boost::mpl::for_each > (get_state_id_helper(id,&result_state,this)); + return result_state; + } + // true if the sm is used in another sm + bool is_contained() const + { + return m_is_included; + } + // get the history policy class + concrete_history& get_history() + { + return m_history; + } + concrete_history const& get_history() const + { + return m_history; + } + + // get a state (const version) + // as a pointer + template + typename ::boost::enable_if::type,State >::type + get_state(::boost::msm::back::dummy<0> = 0) const + { + return const_cast + (& + (std::get::type>::type>::value>(m_substate_list))); + } + // as a reference + template + typename ::boost::enable_if::type,State >::type + get_state(::boost::msm::back::dummy<1> = 0) const + { + return const_cast + ( std::get::type>::type>::value>(m_substate_list) ); + } + // get a state (non const version) + // as a pointer + template + typename ::boost::enable_if::type,State >::type + get_state(::boost::msm::back::dummy<0> = 0) + { + return &(static_cast::type>::type > + (std::get::type>::value>(m_substate_list))); + } + // as a reference + template + typename ::boost::enable_if::type,State >::type + get_state(::boost::msm::back::dummy<1> = 0) + { + return std::get::type>::value>(m_substate_list); + } + + // checks if a flag is active using the BinaryOp as folding function + template + bool is_flag_active() const + { + flag_handler* flags_entries = get_entries_for_flag(); + bool res = (*flags_entries[ m_states[0] ])(*this); + for (int i = 1; i < nr_regions::value ; ++i) + { + res = typename BinaryOp::type() (res,(*flags_entries[ m_states[i] ])(*this)); + } + return res; + } + // checks if a flag is active using no binary op if 1 region, or OR if > 1 regions + template + bool is_flag_active() const + { + return FlagHelper1)>::helper(*this,get_entries_for_flag()); + } + + // Checks if an event is an end interrupt event. + template + typename std::enable_if::value, bool>::type + is_end_interrupt_event(const Event&) + { + return is_flag_active>(); + } + template + typename std::enable_if::value, bool>::type + is_end_interrupt_event(const favor_compile_time::any_event& event) + { + static end_interrupt_event_helper helper{*this}; + return helper.is_end_interrupt_event(event); + } + + // visit the currently active states (if these are defined as visitable + // by implementing accept) + void visit_current_states() + { + for (int i=0; i \ + void visit_current_states(BOOST_PP_ENUM(n, MSM_VISIT_STATE_SUB, ~ ) ) \ + { \ + for (int i=0; i + typename::boost::disable_if< + mp11::mp_and< + typename ::boost::msm::is_kleene_event::type, + std::is_same + >, + void>::type + defer_event(Event const& e) + { + // to call this function, you need either a state with a deferred_events typedef + // or that the fsm provides the activate_deferred_events typedef + BOOST_MPL_ASSERT(( has_fsm_deferred_events )); + + // Deferred events are added with a correlation sequence that helps to + // identify when an event was added - This is typically to distinguish + // between events deferred in this processing versus previous. + m_deferred_events_queue.m_deferred_events_queue.push_back( + std::make_pair( + [this, e] { return process_event_internal(e, static_cast(EVENT_SOURCE_DIRECT|EVENT_SOURCE_DEFERRED));}, + static_cast(m_deferred_events_queue.m_cur_seq+1))); + } +protected: + template + struct defer_event_kleene_helper + { + defer_event_kleene_helper(KleeneEvent const& e, Fsm* fsm, bool& found) + : m_event(e), m_fsm(fsm), m_found(found) {} + + // History initializer function object, used with mpl::for_each + template + void operator()(Event const& ev) + { + if (m_event.type() == boost::typeindex::type_id().type_info()) + { + m_found = true; + // to call this function, you need either a state with a deferred_events typedef + // or that the fsm provides the activate_deferred_events typedef + BOOST_MPL_ASSERT((has_fsm_deferred_events)); + + // Deferred events are added with a correlation sequence that helps to + // identify when an event was added - This is typically to distinguish + // between events deferred in this processing versus previous. + auto fsm = m_fsm; + auto event = m_event; + m_fsm->m_deferred_events_queue.m_deferred_events_queue.push_back( + std::make_pair( + [fsm, event] { return fsm->process_event_internal( + boost::any_cast(event), + static_cast<::boost::msm::back::EventSource>(::boost::msm::back::EVENT_SOURCE_DIRECT | ::boost::msm::back::EVENT_SOURCE_DEFERRED)); + }, + static_cast(m_fsm->m_deferred_events_queue.m_cur_seq + 1))); + } + } + KleeneEvent const& m_event; + Fsm* m_fsm; + bool& m_found; + }; + +public: + template + typename::boost::enable_if< + mp11::mp_and< + typename ::boost::msm::is_kleene_event::type, + std::is_same + >, + void>::type + defer_event(Event const& e) + { + typedef typename generate_event_set::event_set_mp11 event_list; + bool found = false; + boost::mp11::mp_for_each( + defer_event_kleene_helper(e,this,found)); + if (!found) + { + for (int i = 0; i < nr_regions::value; ++i) + { + this->no_transition(e, *this, this->m_states[i]); + } + } + } + + + protected: // interface for the derived class + + // helper used to fill the initial states + struct init_states + { + init_states(int* const init):m_initial_states(init),m_index(-1){} + + // History initializer function object, used with mpl::for_each + template + void operator()(::boost::msm::wrap const&) + { + m_initial_states[++m_index]=get_state_id::type::value; + } + int* const m_initial_states; + int m_index; + }; + public: + struct update_state + { + update_state(substate_list& to_overwrite_):to_overwrite(&to_overwrite_){} + template + void operator()(StateType const& astate) const + { + std::get::value>(*to_overwrite)=astate; + } + substate_list* to_overwrite; + }; + template + void set_states(Expr const& expr) + { + ::boost::fusion::for_each( + ::boost::fusion::as_vector(FoldToList()(expr, boost::fusion::nil_())),update_state(this->m_substate_list)); + } + + // Construct with the default initial states + state_machine() + :Derived() + ,m_events_queue() + ,m_deferred_events_queue() + ,m_history() + ,m_event_processing(false) + ,m_is_included(false) + ,m_visitors() + ,m_substate_list() + { + // initialize our list of states with the ones defined in Derived::initial_state + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + m_history.set_initial_states(m_states); + // create states + fill_states(this); + } + + // Construct with the default initial states and some default argument(s) +#if defined (BOOST_NO_CXX11_RVALUE_REFERENCES) \ + || defined (BOOST_NO_CXX11_VARIADIC_TEMPLATES) \ + || defined (BOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS) + template + state_machine + (Expr const& expr, typename ::boost::enable_if::type >::type* = 0) + :Derived() + , m_events_queue() + , m_deferred_events_queue() + , m_history() + , m_event_processing(false) + , m_is_included(false) + , m_visitors() + , m_substate_list() + { + BOOST_MPL_ASSERT_MSG( + (::boost::proto::matches::value), + THE_STATES_EXPRESSION_PASSED_DOES_NOT_MATCH_GRAMMAR, + (FoldToList)); + + // initialize our list of states with the ones defined in Derived::initial_state + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + m_history.set_initial_states(m_states); + // create states + set_states(expr); + fill_states(this); + } +#define MSM_CONSTRUCTOR_HELPER_EXECUTE_SUB(z, n, unused) ARG ## n t ## n +#define MSM_CONSTRUCTOR_HELPER_EXECUTE(z, n, unused) \ + template \ + state_machine(BOOST_PP_ENUM(n, MSM_CONSTRUCTOR_HELPER_EXECUTE_SUB, ~ ), \ + typename ::boost::disable_if::type >::type* =0 ) \ + :Derived(BOOST_PP_ENUM_PARAMS(n,t)) \ + ,m_events_queue() \ + ,m_deferred_events_queue() \ + ,m_history() \ + ,m_event_processing(false) \ + ,m_is_included(false) \ + ,m_visitors() \ + ,m_substate_list() \ + { \ + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > \ + (init_states(m_states)); \ + m_history.set_initial_states(m_states); \ + fill_states(this); \ + } \ + template \ + state_machine(Expr const& expr,BOOST_PP_ENUM(n, MSM_CONSTRUCTOR_HELPER_EXECUTE_SUB, ~ ), \ + typename ::boost::enable_if::type >::type* =0 ) \ + :Derived(BOOST_PP_ENUM_PARAMS(n,t)) \ + ,m_events_queue() \ + ,m_deferred_events_queue() \ + ,m_history() \ + ,m_event_processing(false) \ + ,m_is_included(false) \ + ,m_visitors() \ + ,m_substate_list() \ + { \ + BOOST_MPL_ASSERT_MSG( \ + ( ::boost::proto::matches::value), \ + THE_STATES_EXPRESSION_PASSED_DOES_NOT_MATCH_GRAMMAR, \ + (FoldToList)); \ + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > \ + (init_states(m_states)); \ + m_history.set_initial_states(m_states); \ + set_states(expr); \ + fill_states(this); \ + } + + BOOST_PP_REPEAT_FROM_TO(1,BOOST_PP_ADD(BOOST_MSM_CONSTRUCTOR_ARG_SIZE,1), MSM_CONSTRUCTOR_HELPER_EXECUTE, ~) +#undef MSM_CONSTRUCTOR_HELPER_EXECUTE +#undef MSM_CONSTRUCTOR_HELPER_EXECUTE_SUB + +#else + template ::type >::type> + state_machine(ARG0&& t0,ARG&&... t) + :Derived(std::forward(t0), std::forward(t)...) + ,m_events_queue() + ,m_deferred_events_queue() + ,m_history() + ,m_event_processing(false) + ,m_is_included(false) + ,m_visitors() + ,m_substate_list() + { + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + m_history.set_initial_states(m_states); + fill_states(this); + } + template ::type >::type> + state_machine(Expr const& expr,ARG&&... t) + :Derived(std::forward(t)...) + ,m_events_queue() + ,m_deferred_events_queue() + ,m_history() + ,m_event_processing(false) + ,m_is_included(false) + ,m_visitors() + ,m_substate_list() + { + BOOST_MPL_ASSERT_MSG( + ( ::boost::proto::matches::value), + THE_STATES_EXPRESSION_PASSED_DOES_NOT_MATCH_GRAMMAR, + (FoldToList)); + ::boost::mpl::for_each< seq_initial_states, ::boost::msm::wrap > + (init_states(m_states)); + m_history.set_initial_states(m_states); + set_states(expr); + fill_states(this); + } +#endif + + + // assignment operator using the copy policy to decide if non_copyable, shallow or deep copying is necessary + library_sm& operator= (library_sm const& rhs) + { + if (this != &rhs) + { + Derived::operator=(rhs); + do_copy(rhs); + } + return *this; + } + state_machine(library_sm const& rhs) + : Derived(rhs) + { + if (this != &rhs) + { + // initialize our list of states with the ones defined in Derived::initial_state + fill_states(this); + do_copy(rhs); + } + } + + // the following 2 functions handle the terminate/interrupt states handling + // if one of these states is found, the first one is used + template + bool is_event_handling_blocked_helper(const Event& event, mp11::mp_true) + { + // if the state machine is terminated, do not handle any event + if (is_flag_active< ::boost::msm::TerminateFlag>()) + return true; + // if the state machine is interrupted, do not handle any event + // unless the event is the end interrupt event + if ( is_flag_active< ::boost::msm::InterruptedFlag>() && + !is_end_interrupt_event(event)) + return true; + return false; + } + // otherwise simple handling, no flag => continue + template + bool is_event_handling_blocked_helper(const Event& event, mp11::mp_false) + { + // no terminate/interrupt states detected + return false; + } + void do_handle_prio_msg_queue_deferred_queue(EventSource source, HandledEnum handled, ::boost::mpl::true_ const &) + { + // non-default. Handle msg queue with higher prio than deferred queue + if (!(EVENT_SOURCE_MSG_QUEUE & source)) + { + execute_queued_events(); + if (!(EVENT_SOURCE_DEFERRED & source)) + { + handle_defer_helper defer_helper(m_deferred_events_queue); + defer_helper.do_handle_deferred(HANDLED_TRUE & handled); + } + } + } + void do_handle_prio_msg_queue_deferred_queue(EventSource source, HandledEnum handled, ::boost::mpl::false_ const &) + { + // default. Handle deferred queue with higher prio than msg queue + if (!(EVENT_SOURCE_DEFERRED & source)) + { + handle_defer_helper defer_helper(m_deferred_events_queue); + defer_helper.do_handle_deferred(HANDLED_TRUE & handled); + + // Handle any new events generated into the queue, but only if + // we're not already processing from the message queue. + if (!(EVENT_SOURCE_MSG_QUEUE & source)) + { + execute_queued_events(); + } + } + } + // the following functions handle pre/post-process handling of a message queue + template + bool do_pre_msg_queue_helper(EventType const&, ::boost::mpl::true_ const &) + { + // no message queue needed + return true; + } + template + bool do_pre_msg_queue_helper(EventType const& evt, ::boost::mpl::false_ const &) + { + // if we are already processing an event + if (m_event_processing) + { + // event has to be put into the queue + m_events_queue.m_events_queue.push_back( + [this, evt] { return process_event_internal(evt, static_cast(EVENT_SOURCE_DIRECT | EVENT_SOURCE_MSG_QUEUE));}); + + return false; + } + + // event can be handled, processing + m_event_processing = true; + return true; + } + void do_allow_event_processing_after_transition( ::boost::mpl::true_ const &) + { + // no message queue needed + } + void do_allow_event_processing_after_transition( ::boost::mpl::false_ const &) + { + m_event_processing = false; + } + // the following 2 functions handle the processing either with a try/catch protection or without + template + HandledEnum do_process_helper(EventType const& evt, ::boost::mpl::true_ const &, bool is_direct_call) + { + return this->do_process_event(evt,is_direct_call); + } + template + HandledEnum do_process_helper(EventType const& evt, ::boost::mpl::false_ const &, bool is_direct_call) + { + // when compiling without exception support there is no formal parameter "e" in the catch handler. + // Declaring a local variable here does not hurt and will be "used" to make the code in the handler + // compilable although the code will never be executed. + std::exception e; + BOOST_TRY + { + return this->do_process_event(evt,is_direct_call); + } + BOOST_CATCH (std::exception& e) + { + // give a chance to the concrete state machine to handle + this->exception_caught(evt,*this,e); + return ::boost::msm::back::HANDLED_FALSE; + } + BOOST_CATCH_END + return HANDLED_TRUE; + } + // handling of deferred events + // if none is found in the SM, take the following empty main version + template + struct handle_defer_helper + { + handle_defer_helper(deferred_msg_queue_helper& ){} + void do_handle_deferred(bool) + { + } + }; + // otherwise the standard version handling the deferred events + template + struct handle_defer_helper + ::type,int >::type> + { + struct sort_greater + { + bool operator()( + typename deferred_events_queue_t::value_type const& d1, + typename deferred_events_queue_t::value_type const& d2) + { + return d1.second > d2.second; + } + }; + struct set_sequence + { + set_sequence(char s) :seq_(s) {} + void operator()(typename deferred_events_queue_t::value_type& d) + { + d.second = seq_; + } + char seq_; + }; + handle_defer_helper(deferred_msg_queue_helper& a_queue): + m_events_queue(a_queue) {} + void do_handle_deferred(bool new_seq=false) + { + // A new sequence is typically started upon initial entry to the + // state, or upon a new transition. When this occurs we want to + // process all previously deferred events by incrementing the + // correlation sequence. + if (new_seq) + { + ++m_events_queue.m_cur_seq; + } + + char& cur_seq = m_events_queue.m_cur_seq; + + // Iteratively process all of the events within the deferred + // queue upto (but not including) newly deferred events. + // if we did not defer one in the queue, then we need to try again + bool not_only_deferred = false; + while (!m_events_queue.m_deferred_events_queue.empty()) + { + typename deferred_events_queue_t::value_type& pair = + m_events_queue.m_deferred_events_queue.front(); + + if (cur_seq != pair.second) + { + break; + } + + deferred_fct next = pair.first; + m_events_queue.m_deferred_events_queue.pop_front(); + boost::msm::back::execute_return res = next(); + if (res != ::boost::msm::back::HANDLED_FALSE && res != ::boost::msm::back::HANDLED_DEFERRED) + { + not_only_deferred = true; + } + if (not_only_deferred) + { + // handled one, stop processing deferred until next block reorders + break; + } + } + if (not_only_deferred) + { + // attempt to go back to the situation prior to processing, + // in case some deferred events would have been re-queued + // in that case those would have a higher sequence number + std::stable_sort( + m_events_queue.m_deferred_events_queue.begin(), + m_events_queue.m_deferred_events_queue.end(), + sort_greater() + ); + // reset sequence number for all + std::for_each( + m_events_queue.m_deferred_events_queue.begin(), + m_events_queue.m_deferred_events_queue.end(), + set_sequence(m_events_queue.m_cur_seq + 1) + ); + // one deferred event was successfully processed, try again + do_handle_deferred(true); + } + } + + private: + deferred_msg_queue_helper& m_events_queue; + }; + + // handling of eventless transitions + // if none is found in the SM, nothing to do + template + struct handle_eventless_transitions_helper + { + handle_eventless_transitions_helper(library_sm* , bool ){} + void process_completion_event(EventSource = EVENT_SOURCE_DEFAULT){} + }; + // otherwise + template + struct handle_eventless_transitions_helper + ::type >::type> + { + handle_eventless_transitions_helper(library_sm* self_, bool handled_):self(self_),handled(handled_){} + void process_completion_event(EventSource source = EVENT_SOURCE_DEFAULT) + { + typedef typename ::boost::mpl::deref< + typename ::boost::mpl::begin< + typename find_completion_events::type + >::type + >::type first_completion_event; + if (handled) + { + self->process_event_internal( + first_completion_event(), + source | EVENT_SOURCE_DIRECT); + } + } + + private: + library_sm* self; + bool handled; + }; + + // helper class called in case the event to process has been found in the fsm's internal stt and is therefore processable + template + struct process_fsm_internal_table + { + typedef mp11::mp_set_contains is_event_processable; + + // forward to the correct do_process + static void process(Event const& evt,library_sm* self_,HandledEnum& result) + { + do_process(evt,self_,result,is_event_processable()); + } + private: + // the event is processable, let's try! + static void do_process(Event const& evt,library_sm* self_,HandledEnum& result, mp11::mp_true) + { + if (result != HANDLED_TRUE) + { + typedef dispatch_table table; + HandledEnum res_internal = table::dispatch_internal(*self_, 0, self_->m_states[0], evt); + result = (HandledEnum)((int)result | (int)res_internal); + } + } + // version doing nothing if the event is not in the internal stt and we can save ourselves the time trying to process + static void do_process(Event const& ,library_sm* ,HandledEnum& , mp11::mp_false) + { + // do nothing + } + }; + + template + struct region_processing_helper + { + public: + region_processing_helper(library_sm* self_,HandledEnum& result_) + :self(self_),result(result_){} + template + void process(Event const& evt) + { + // use this table as if it came directly from the user + typedef dispatch_table table; + HandledEnum res = table::dispatch(*self, 0, self->m_states[0], evt); + result = (HandledEnum)((int)result | (int)res); + // process the event in the internal table of this fsm if the event is processable (present in the table) + process_fsm_internal_table::process(evt,self,result); + } + library_sm* self; + HandledEnum& result; + }; + // version with visitors + template + struct region_processing_helper >::type> + { + private: + // process event in one region + template + struct In + { + template + static void process(Event const& evt,library_sm* self_,HandledEnum& result_) + { + // use this table as if it came directly from the user + typedef dispatch_table table; + HandledEnum res = table::dispatch( + *self_, region_id::value , self_->m_states[region_id::value], evt); + result_ = (HandledEnum)((int)result_ | (int)res); + In< ::boost::mpl::int_ >::process(evt,self_,result_); + } + }; + template + struct In< ::boost::mpl::int_,Dummy> + { + // end of processing + template + static void process(Event const& evt,library_sm* self_,HandledEnum& result_) + { + // process the event in the internal table of this fsm if the event is processable (present in the table) + process_fsm_internal_table::process(evt,self_,result_); + } + }; + public: + region_processing_helper(library_sm* self_,HandledEnum& result_) + :self(self_),result(result_){} + template + void process(Event const& evt) + { + In< ::boost::mpl::int_<0> >::process(evt,self,result); + } + + library_sm* self; + HandledEnum& result; + }; + + template + typename enable_if, execute_return>::type + process_event_internal(Event const& evt, + EventSource source = EVENT_SOURCE_DEFAULT) + { + return process_event_internal_impl(evt, source); + } + + template + typename enable_if, execute_return>::type + process_event_internal(Event const& evt, + EventSource source = EVENT_SOURCE_DEFAULT) + { + return process_event_internal_impl(favor_compile_time::any_event(evt), source); + } + + template + typename enable_if, execute_return>::type + process_event_internal(favor_compile_time::any_event const& evt, + EventSource source = EVENT_SOURCE_DEFAULT) + { + return process_event_internal_impl(evt, source); + } + + // Main function used internally to make transitions + // Can only be called for internally (for example in an action method) generated events. + template + execute_return process_event_internal_impl(Event const& evt, EventSource source) + { + // if the state machine has terminate or interrupt flags, check them, otherwise skip + if (is_event_handling_blocked_helper + (evt, typename has_fsm_blocking_states::type())) + { + return HANDLED_TRUE; + } + + // if a message queue is needed and processing is on the way + if (!do_pre_msg_queue_helper + (evt,::boost::mpl::bool_::type::value>())) + { + // wait for the end of current processing + return HANDLED_TRUE; + } + else + { + // Process event + HandledEnum handled = this->do_process_helper( + evt, + ::boost::mpl::bool_::type::value>(), + (EVENT_SOURCE_DIRECT & source)); + + // at this point we allow the next transition be executed without enqueing + // so that completion events and deferred events execute now (if any) + do_allow_event_processing_after_transition( + ::boost::mpl::bool_::type::value>()); + + // Process completion transitions BEFORE any other event in the + // pool (UML Standard 2.3 15.3.14) + handle_eventless_transitions_helper + eventless_helper(this,(HANDLED_TRUE & handled)); + eventless_helper.process_completion_event(source); + + // After handling, take care of the deferred events, but only if + // we're not already processing from the deferred queue. + do_handle_prio_msg_queue_deferred_queue( + source,handled, + ::boost::mpl::bool_::type::value>()); + return handled; + } + } + + // minimum event processing without exceptions, queues, etc. + template + HandledEnum do_process_event(Event const& evt, bool is_direct_call) + { + HandledEnum handled = HANDLED_FALSE; + + // dispatch the event to every region + region_processing_helper helper(this,handled); + helper.process(evt); + + // if the event has not been handled and we have orthogonal zones, then + // generate an error on every active state + // for state machine states contained in other state machines, do not handle + // but let the containing sm handle the error, unless the event was generated in this fsm + // (by calling process_event on this fsm object, is_direct_call == true) + // completion events do not produce an error + if ( (!is_contained() || is_direct_call) && !handled && !is_completion_event::value(evt)) + { + for (int i=0; ino_transition(evt,*this,this->m_states[i]); + } + } + return handled; + } + + // default row arguments for the compilers which accept this + template + bool no_guard(Event const&){return true;} + template + void no_action(Event const&){} + +private: + // composite accept implementation. First calls accept on the composite, then accept on all its active states. + void composite_accept() + { + this->accept(); + this->visit_current_states(); + } + +#define MSM_COMPOSITE_ACCEPT_SUB(z, n, unused) ARG ## n vis ## n +#define MSM_COMPOSITE_ACCEPT_SUB2(z, n, unused) boost::ref( vis ## n ) +#define MSM_COMPOSITE_ACCEPT_EXECUTE(z, n, unused) \ + template \ + void composite_accept(BOOST_PP_ENUM(n, MSM_COMPOSITE_ACCEPT_SUB, ~ ) ) \ + { \ + this->accept(BOOST_PP_ENUM_PARAMS(n,vis)); \ + this->visit_current_states(BOOST_PP_ENUM(n,MSM_COMPOSITE_ACCEPT_SUB2, ~)); \ + } + BOOST_PP_REPEAT_FROM_TO(1,BOOST_PP_ADD(BOOST_MSM_VISITOR_ARG_SIZE,1), MSM_COMPOSITE_ACCEPT_EXECUTE, ~) +#undef MSM_COMPOSITE_ACCEPT_EXECUTE +#undef MSM_COMPOSITE_ACCEPT_SUB +#undef MSM_COMPOSITE_ACCEPT_SUB2 + + // helper used to call the init states at the start of the state machine + template + struct call_init + { + call_init(Event const& an_event,library_sm* self_): + evt(an_event),self(self_){} + template + void operator()(boost::msm::wrap const&) + { + execute_entry(std::get::value>(self->m_substate_list),evt,*self); + } + private: + Event const& evt; + library_sm* self; + }; + // helper for flag handling. Uses OR by default on orthogonal zones. + template + struct FlagHelper + { + static bool helper(library_sm const& sm,flag_handler* ) + { + // by default we use OR to accumulate the flags + return sm.is_flag_active(); + } + }; + template + struct FlagHelper + { + static bool helper(library_sm const& sm,flag_handler* flags_entries) + { + // just one active state, so we can call operator[] with 0 + return flags_entries[sm.current_state()[0]](sm); + } + }; + // handling of flag + // defines a true and false functions plus a forwarding one for composite states + template + struct FlagHandler + { + static bool flag_true(library_sm const& ) + { + return true; + } + static bool flag_false(library_sm const& ) + { + return false; + } + static bool forward(library_sm const& fsm) + { + return std::get::value>(fsm.m_substate_list).template is_flag_active(); + } + }; + template + struct init_flags + { + private: + // helper function, helps hiding the forward function for non-state machines states. + template + void helper (flag_handler* an_entry,int offset, ::boost::mpl::true_ const & ) + { + // composite => forward + an_entry[offset] = &FlagHandler::forward; + } + template + void helper (flag_handler* an_entry,int offset, ::boost::mpl::false_ const & ) + { + // default no flag + an_entry[offset] = &FlagHandler::flag_false; + } + // attributes + flag_handler* entries; + + public: + init_flags(flag_handler* entries_) + : entries(entries_) + {} + + // Flags initializer function object, used with for_each + template + void operator()( mp11::mp_identity const& ) + { + typedef typename get_flag_list::type flags; + typedef mp11::mp_contains found; + + BOOST_STATIC_CONSTANT(int, state_id = (get_state_id::type::value)); + if (found::type::value) + { + // the type defined the flag => true + entries[state_id] = &FlagHandler::flag_true; + } + else + { + // false or forward + typedef typename ::boost::mpl::and_< + typename is_composite_state::type, + typename ::boost::mpl::not_< + typename has_non_forwarding_flag::type>::type >::type composite_no_forward; + + helper(entries,state_id,::boost::mpl::bool_()); + } + } + }; + // maintains for every flag a static array containing the flag value for every state + template + flag_handler* get_entries_for_flag() const + { + BOOST_STATIC_CONSTANT(int, max_state = (mp11::mp_size::value)); + + static flag_handler flags_entries[max_state]; + // build a state list, but only once + static flag_handler* flags_entries_ptr = + (mp11::mp_for_each> + (init_flags(flags_entries)), + flags_entries); + return flags_entries_ptr; + } + + // helper used to create a state using the correct constructor + template + struct create_state_helper + { + static void set_sm(library_sm* ) + { + // state doesn't need its sm + } + }; + // create a state requiring a pointer to the state machine + template + struct create_state_helper::type> + { + static void set_sm(library_sm* sm) + { + // create and set the fsm + std::get::value>(sm->m_substate_list).set_sm_ptr(sm); + } + }; + // main unspecialized helper class + template + struct visitor_args; + +#define MSM_VISITOR_ARGS_SUB(z, n, unused) BOOST_PP_CAT(::boost::placeholders::_,BOOST_PP_ADD(n,1)) +#define MSM_VISITOR_ARGS_TYPEDEF_SUB(z, n, unused) typename StateType::accept_sig::argument ## n + +#define MSM_VISITOR_ARGS_EXECUTE(z, n, unused) \ + template \ + struct visitor_args \ + { \ + template \ + static typename enable_if_c::value,void >::type \ + helper (library_sm* sm, \ + int id,StateType& astate) \ + { \ + sm->m_visitors.insert(id, boost::bind(&StateType::accept, \ + ::boost::ref(astate) BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, MSM_VISITOR_ARGS_SUB, ~) )); \ + } \ + template \ + static typename enable_if_c::value,void >::type \ + helper (library_sm* sm, \ + int id,StateType& astate) \ + { \ + void (StateType::*caccept)(BOOST_PP_ENUM(n, MSM_VISITOR_ARGS_TYPEDEF_SUB, ~ ) ) \ + = &StateType::composite_accept; \ + sm->m_visitors.insert(id, boost::bind(caccept, \ + ::boost::ref(astate) BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, MSM_VISITOR_ARGS_SUB, ~) )); \ + } \ +}; +BOOST_PP_REPEAT(BOOST_PP_ADD(BOOST_MSM_VISITOR_ARG_SIZE,1), MSM_VISITOR_ARGS_EXECUTE, ~) +#undef MSM_VISITOR_ARGS_EXECUTE +#undef MSM_VISITOR_ARGS_SUB + +// the IBM compiler seems to have problems with nested classes +// the same seems to apply to the Apple version of gcc 4.0.1 (just in case we do for < 4.1) +// and also to MS VC < 8 +#if defined (__IBMCPP__) || (__GNUC__ == 4 && __GNUC_MINOR__ < 1) || (defined(_MSC_VER) && (_MSC_VER < 1400)) + public: +#endif + template + void set_containing_sm(ContainingSM* sm) + { + m_is_included=true; + mp11::tuple_for_each(m_substate_list,add_state(this,sm)); + } +#if defined (__IBMCPP__) || (__GNUC__ == 4 && __GNUC_MINOR__ < 1) || (defined(_MSC_VER) && (_MSC_VER < 1400)) + private: +#endif + // A function object for use with mpl::for_each that stuffs + // states into the state list. + template + struct add_state + { + add_state(library_sm* self_,ContainingSM* sm) + : self(self_),containing_sm(sm){} + + // State is a sub fsm with exit pseudo states and gets a pointer to this fsm, so it can build a callback + template + typename ::boost::enable_if< + typename is_composite_state::type,void >::type + new_state_helper(boost::msm::back::dummy<0> = 0) const + { + std::get::value>(self->m_substate_list).set_containing_sm(containing_sm); + } + // State is a sub fsm without exit pseudo states and does not get a callback to this fsm + // or state is a normal state and needs nothing except creation + template + typename ::boost::enable_if< + typename boost::mpl::and_::type>::type, + typename boost::mpl::not_ + ::type>::type + >::type,void>::type + new_state_helper( ::boost::msm::back::dummy<1> = 0) const + { + //nothing to do + } + // state is exit pseudo state and gets callback to target fsm + template + typename ::boost::enable_if::type,void >::type + new_state_helper( ::boost::msm::back::dummy<2> = 0) const + { + execute_return (ContainingSM::*pf) (typename StateType::event const& evt)= + &ContainingSM::process_event; + ::boost::function fct = + ::boost::bind(pf,containing_sm,::boost::placeholders::_1); + std::get::value>(self->m_substate_list).set_forward_fct(fct); + } + // for every defined state in the sm + template + void operator()( State const&) const + { + //create a new state with the defined id and type + BOOST_STATIC_CONSTANT(int, state_id = (get_state_id::value)); + + this->new_state_helper(), + create_state_helper::set_sm(self); + // create a visitor callback + visitor_helper(state_id,std::get::value>(self->m_substate_list), + ::boost::mpl::bool_::type::value>()); + } + private: + // support possible use of a visitor if accept_sig is defined + template + void visitor_helper(int id,StateType& astate, ::boost::mpl::true_ const & ) const + { + visitor_args:: + template helper(self,id,astate); + } + template + void visitor_helper(int ,StateType& , ::boost::mpl::false_ const &) const + { + // nothing to do + } + + library_sm* self; + ContainingSM* containing_sm; + }; + + // helper used to copy every state if needed + struct copy_helper + { + copy_helper(library_sm* sm): + m_sm(sm){} + template + void operator()( ::boost::msm::wrap const& ) + { + BOOST_STATIC_CONSTANT(int, state_id = (get_state_id::type::value)); + // possibly also set the visitor + visitor_helper(state_id); + + // and for states that keep a pointer to the fsm, reset the pointer + create_state_helper::set_sm(m_sm); + } + template + typename ::boost::enable_if::type,void >::type + visitor_helper(int id) const + { + visitor_args::template helper + (m_sm,id,std::get::value>(m_sm->m_substate_list)); + } + template + typename ::boost::disable_if::type,void >::type + visitor_helper(int) const + { + // nothing to do + } + + library_sm* m_sm; + }; + // helper to copy the active states attribute + template + struct region_copy_helper + { + static void do_copy(library_sm* self_,library_sm const& rhs) + { + self_->m_states[region_id::value] = rhs.m_states[region_id::value]; + region_copy_helper< ::boost::mpl::int_ >::do_copy(self_,rhs); + } + }; + template + struct region_copy_helper< ::boost::mpl::int_,Dummy> + { + // end of processing + static void do_copy(library_sm*,library_sm const& ){} + }; + // copy functions for deep copy (no need of a 2nd version for NoCopy as noncopyable handles it) + void do_copy (library_sm const& rhs, + ::boost::msm::back::dummy<0> = 0) + { + // deep copy simply assigns the data + region_copy_helper< ::boost::mpl::int_<0> >::do_copy(this,rhs); + m_events_queue = rhs.m_events_queue; + m_deferred_events_queue = rhs.m_deferred_events_queue; + m_history = rhs.m_history; + m_event_processing = rhs.m_event_processing; + m_is_included = rhs.m_is_included; + m_substate_list = rhs.m_substate_list; + // except for the states themselves, which get duplicated + + ::boost::mpl::for_each > + (copy_helper(this)); + } + + // helper used to call the correct entry method + // unfortunately in O(number of states in the sub-sm) but should be better than a virtual call + template + struct entry_helper + { + entry_helper(int id,Event const& e,library_sm* self_): + state_id(id),evt(e),self(self_){} + + template + void operator()(StateAndId const&) + { + using State = mp11::mp_first; + using Id = mp11::mp_second; + BOOST_STATIC_CONSTANT(int, id = (Id::value)); + if (id == state_id) + { + execute_entry(std::get(self->m_substate_list),evt,*self); + } + } + private: + int state_id; + Event const& evt; + library_sm* self; + }; + + // helper used to call the correct exit method + // unfortunately in O(number of states in the sub-sm) but should be better than a virtual call + template + struct exit_helper + { + exit_helper(int id,Event const& e,library_sm* self_): + state_id(id),evt(e),self(self_){} + + template + void operator()(StateAndId const&) + { + using State = mp11::mp_first; + using Id = mp11::mp_second; + BOOST_STATIC_CONSTANT(int, id = (Id::value)); + if (id == state_id) + { + execute_exit(std::get(self->m_substate_list),evt,*self); + } + } + private: + int state_id; + Event const& evt; + library_sm* self; + }; + + // start for states machines which are themselves embedded in other state machines (composites) + template + void internal_start(Event const& incomingEvent) + { + for (size_t region_id=0; region_id + (entry_helper(m_states[region_id],incomingEvent,this)); + } + // give a chance to handle an anonymous (eventless) transition + handle_eventless_transitions_helper eventless_helper(this,true); + eventless_helper.process_completion_event(); + } + + template + struct find_region_id + { + template + struct In + { + enum {region_index=region}; + }; + // if the user provides no region, find it! + template + struct In<-1,Dummy> + { + typedef typename build_orthogonal_regions< + library_sm, + initial_states + >::type all_regions; + enum {region_index= find_region_index::value }; + }; + enum {region_index = In::region_index }; + }; + // helper used to set the correct state as active state upon entry into a fsm + struct direct_event_start_helper + { + direct_event_start_helper(library_sm* self_):self(self_){} + // this variant is for the standard case, entry due to activation of the containing FSM + template + typename ::boost::disable_if::type,void>::type + operator()(EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<0> = 0) + { + (static_cast(self))->on_entry(evt,fsm); + self->internal_start(evt); + } + + // this variant is for the direct entry case (just one entry, not a sequence of entries) + template + typename ::boost::enable_if< + typename ::boost::mpl::and_< + typename ::boost::mpl::not_< typename is_pseudo_entry< + typename EventType::active_state>::type >::type, + typename ::boost::mpl::and_::type, + typename ::boost::mpl::not_::type >::type + >::type>::type,void + >::type + operator()(EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<1> = 0) + { + (static_cast(self))->on_entry(evt,fsm); + int state_id = get_state_id::value; + BOOST_STATIC_ASSERT(find_region_id::region_index >= 0); + BOOST_STATIC_ASSERT(find_region_id::region_index < nr_regions::value); + // just set the correct zone, the others will be default/history initialized + self->m_states[find_region_id::region_index] = state_id; + self->internal_start(evt.m_event); + } + + // this variant is for the fork entry case (a sequence on entries) + template + typename ::boost::enable_if< + typename ::boost::mpl::and_< + typename ::boost::mpl::not_< + typename is_pseudo_entry::type >::type, + typename ::boost::mpl::and_::type, + typename ::boost::mpl::is_sequence< + typename EventType::active_state>::type + >::type>::type,void + >::type + operator()(EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<2> = 0) + { + (static_cast(self))->on_entry(evt,fsm); + ::boost::mpl::for_each > + (fork_helper(self,evt)); + // set the correct zones, the others (if any) will be default/history initialized + self->internal_start(evt.m_event); + } + + // this variant is for the pseudo state entry case + template + typename ::boost::enable_if< + typename is_pseudo_entry::type,void + >::type + operator()(EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<3> = 0) + { + // entry on the FSM + (static_cast(self))->on_entry(evt,fsm); + int state_id = get_state_id::value; + BOOST_STATIC_ASSERT(find_region_id::region_index >= 0); + BOOST_STATIC_ASSERT(find_region_id::region_index < nr_regions::value); + // given region starts with the entry pseudo state as active state + self->m_states[find_region_id::region_index] = state_id; + self->internal_start(evt.m_event); + // and we process the transition in the zone of the newly active state + // (entry pseudo states are, according to UML, a state connecting 1 transition outside to 1 inside + self->process_event(evt.m_event); + } + private: + // helper for the fork case, does almost like the direct entry + library_sm* self; + template + struct fork_helper + { + fork_helper(library_sm* self_,EventType const& evt_): + helper_self(self_),helper_evt(evt_){} + template + void operator()( ::boost::msm::wrap const& ) + { + int state_id = get_state_id::value; + BOOST_STATIC_ASSERT(find_region_id::region_index >= 0); + BOOST_STATIC_ASSERT(find_region_id::region_index < nr_regions::value); + helper_self->m_states[find_region_id::region_index] = state_id; + } + private: + library_sm* helper_self; + EventType const& helper_evt; + }; + }; + + // entry/exit for states machines which are themselves embedded in other state machines (composites) + template + void do_entry(Event const& incomingEvent,FsmType& fsm) + { + // by default we activate the history/init states, can be overwritten by direct_event_start_helper + for (size_t region_id=0; region_id defer_helper(m_deferred_events_queue); + defer_helper.do_handle_deferred(true); + execute_queued_events(); + } + template + void do_exit(Event const& incomingEvent,FsmType& fsm) + { + // first recursively exit the sub machines + // forward the event for handling by sub state machines + for (size_t region_id=0; region_id + (exit_helper(m_states[region_id],incomingEvent,this)); + } + // then call our own exit + (static_cast(this))->on_exit(incomingEvent,fsm); + // give the history a chance to handle this (or not). + m_history.history_exit(this->m_states); + // history decides what happens with deferred events + if (!m_history.process_deferred_events(incomingEvent)) + { + clear_deferred_queue(); + } + } + + // the IBM and VC<8 compilers seem to have problems with the friend declaration of dispatch_table +#if defined (__IBMCPP__) || (defined(_MSC_VER) && (_MSC_VER < 1400)) + public: +#endif + // no transition for event. + template + static HandledEnum call_no_transition(library_sm& , int , int , Event const& ) + { + return HANDLED_FALSE; + } + // no transition for event for internal transitions (not an error). + template + static HandledEnum call_no_transition_internal(library_sm& , int , int , Event const& ) + { + //// reject to give others a chance to handle + //return HANDLED_GUARD_REJECT; + return HANDLED_FALSE; + } + // called for deferred events. Address set in the dispatch_table at init + template + static HandledEnum defer_transition(library_sm& fsm, int , int , Event const& e) + { + fsm.defer_event(e); + return HANDLED_DEFERRED; + } + // called for completion events. Default address set in the dispatch_table at init + // prevents no-transition detection for completion events + template + static HandledEnum default_eventless_transition(library_sm&, int, int , Event const&) + { + return HANDLED_FALSE; + } +#if defined (__IBMCPP__) || (defined(_MSC_VER) && (_MSC_VER < 1400)) + private: +#endif + // helper function. In cases where the event is wrapped (target is a direct entry states) + // we want to send only the real event to on_entry, not the wrapper. + template + static + typename boost::enable_if::type,typename EventType::contained_event const& >::type + remove_direct_entry_event_wrapper(EventType const& evt,boost::msm::back::dummy<0> = 0) + { + return evt.m_event; + } + template + static typename boost::disable_if::type,EventType const& >::type + remove_direct_entry_event_wrapper(EventType const& evt,boost::msm::back::dummy<1> = 0) + { + // identity. No wrapper + return evt; + } + // calls the entry/exit or on_entry/on_exit depending on the state type + // (avoids calling virtually) + // variant for FSMs + template + static + typename boost::enable_if::type,void >::type + execute_entry(StateType& astate,EventType const& evt,FsmType& fsm,boost::msm::back::dummy<0> = 0) + { + // calls on_entry on the fsm then handles direct entries, fork, entry pseudo state + astate.do_entry(evt,fsm); + } + // variant for states + template + static + typename ::boost::disable_if< + typename ::boost::mpl::or_::type, + typename is_pseudo_exit::type >::type,void >::type + execute_entry(StateType& astate,EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<1> = 0) + { + // simple call to on_entry + astate.on_entry(remove_direct_entry_event_wrapper(evt),fsm); + } + // variant for exit pseudo states + template + static + typename ::boost::enable_if::type,void >::type + execute_entry(StateType& astate,EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<2> = 0) + { + // calls on_entry on the state then forward the event to the transition which should be defined inside the + // contained fsm + astate.on_entry(evt,fsm); + astate.forward_event(evt); + } + template + static + typename ::boost::enable_if::type,void >::type + execute_exit(StateType& astate,EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<0> = 0) + { + astate.do_exit(evt,fsm); + } + template + static + typename ::boost::disable_if::type,void >::type + execute_exit(StateType& astate,EventType const& evt,FsmType& fsm, ::boost::msm::back::dummy<1> = 0) + { + // simple call to on_exit + astate.on_exit(evt,fsm); + } + + // helper allowing special handling of direct entries / fork + template + static + typename ::boost::disable_if< + typename ::boost::mpl::or_::type, + ::boost::mpl::is_sequence >::type,void>::type + convert_event_and_execute_entry(StateType& astate,EventType const& evt, FsmType& fsm, ::boost::msm::back::dummy<1> = 0) + { + // if the target is a normal state, do the standard entry handling + execute_entry(astate,evt,fsm); + } + template + static + typename ::boost::enable_if< + typename ::boost::mpl::or_::type, + ::boost::mpl::is_sequence >::type,void >::type + convert_event_and_execute_entry(StateType& astate,EventType const& evt, FsmType& fsm, ::boost::msm::back::dummy<0> = 0) + { + // for the direct entry, pack the event in a wrapper so that we handle it differently during fsm entry + execute_entry(astate,direct_entry_event(evt),fsm); + } + + // creates all the states + template + void fill_states(ContainingSM* containing_sm=0) + { + // checks that regions are truly orthogonal + FsmCheckPolicy::template check_orthogonality(); + // checks that all states are reachable + FsmCheckPolicy::template check_unreachable_states(); + + BOOST_STATIC_CONSTANT(int, max_state = (mp11::mp_size::value)); + // allocate the place without reallocation + m_visitors.fill_visitors(max_state); + mp11::tuple_for_each(m_substate_list,add_state(this,containing_sm)); + } + +private: + template + struct msg_queue_helper + { + public: + msg_queue_helper():m_events_queue(){} + events_queue_t m_events_queue; + }; + template + struct msg_queue_helper::type >::type> + { + }; + + template + friend class dispatch_table; + + friend class end_interrupt_event_helper; + + // data members + int m_states[nr_regions::value]; + msg_queue_helper m_events_queue; + deferred_msg_queue_helper + m_deferred_events_queue; + concrete_history m_history; + bool m_event_processing; + bool m_is_included; + visitor_fct_helper m_visitors; + substate_list m_substate_list; + + +}; + +}}} // boost::msm::backmp11 + +#endif //BOOST_MSM_BACKMP11_STATEMACHINE_H diff --git a/include/boost/msm/common.hpp b/include/boost/msm/common.hpp index 6a80b82..bbd7e1d 100644 --- a/include/boost/msm/common.hpp +++ b/include/boost/msm/common.hpp @@ -20,6 +20,12 @@ struct wrap{}; // tag to use in grammars where states are seen (init_<<, states_<<...) struct state_tag{}; +// helper to print types within metafunctions +// TODO: +// Remove again +template +struct [[deprecated]] print_types {}; + } } // boost::msm #endif //BOOST_MSM_COMMON_H diff --git a/include/boost/msm/mpl_graph/detail/incidence_list_graph.ipp b/include/boost/msm/mpl_graph/detail/incidence_list_graph.ipp index 30bfffc..5f3c00e 100644 --- a/include/boost/msm/mpl_graph/detail/incidence_list_graph.ipp +++ b/include/boost/msm/mpl_graph/detail/incidence_list_graph.ipp @@ -36,7 +36,6 @@ #include #include #include -#include namespace boost { diff --git a/test/Anonymous.cpp b/test/Anonymous.cpp index 0eaa179..297acf4 100644 --- a/test/Anonymous.cpp +++ b/test/Anonymous.cpp @@ -181,3 +181,5 @@ namespace } } +using backmp11_fsm = boost::msm::backmp11::state_machine; +BOOST_MSM_BACKMP11_GENERATE_DISPATCH_TABLE(backmp11_fsm); \ No newline at end of file diff --git a/test/AnonymousAndGuard.cpp b/test/AnonymousAndGuard.cpp index 7bba946..6b5e065 100644 --- a/test/AnonymousAndGuard.cpp +++ b/test/AnonymousAndGuard.cpp @@ -105,3 +105,6 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(anonymous_and_guard_test2, MyStateMachine, MyState BOOST_CHECK_MESSAGE(sm.current_state()[0] == 0, "Running should be active"); BOOST_CHECK_MESSAGE(sm.current_state()[1] == 3, "Completed should be active"); } + +using backmp11_fsm = boost::msm::backmp11::state_machine; +BOOST_MSM_BACKMP11_GENERATE_DISPATCH_TABLE(backmp11_fsm); \ No newline at end of file diff --git a/test/AnonymousEuml.cpp b/test/AnonymousEuml.cpp index 6d1e815..cca60a7 100644 --- a/test/AnonymousEuml.cpp +++ b/test/AnonymousEuml.cpp @@ -164,3 +164,5 @@ namespace } } +using backmp11_fsm = boost::msm::backmp11::state_machine; +BOOST_MSM_BACKMP11_GENERATE_DISPATCH_TABLE(backmp11_fsm); \ No newline at end of file diff --git a/test/BackCommon.hpp b/test/BackCommon.hpp index f2747c6..482e423 100644 --- a/test/BackCommon.hpp +++ b/test/BackCommon.hpp @@ -11,15 +11,28 @@ // back-end #include #include +#include +#include #include template using get_test_machines = boost::mpl::vector< boost::msm::back::state_machine, boost::msm::back::state_machine, + boost::msm::backmp11::state_machine, + boost::msm::backmp11::state_machine, boost::msm::back11::state_machine >; +template