state_machine.hpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. // Copyright 2025 Christian Granzin
  2. // Copyright 2008 Christophe Henry
  3. // henry UNDERSCORE christophe AT hotmail DOT com
  4. // This is an extended version of the state machine available in the boost::mpl library
  5. // Distributed under the same license as the original.
  6. // Copyright for the original version:
  7. // Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
  8. // under the Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at
  10. // http://www.boost.org/LICENSE_1_0.txt)
  11. #ifndef BOOST_MSM_BACKMP11_STATE_MACHINE_H
  12. #define BOOST_MSM_BACKMP11_STATE_MACHINE_H
  13. #include <array>
  14. #include <exception>
  15. #include <functional>
  16. #include <list>
  17. #include <utility>
  18. #include <boost/core/no_exceptions_support.hpp>
  19. #include <boost/core/ignore_unused.hpp>
  20. #include <boost/mp11.hpp>
  21. #include <boost/mpl/eval_if.hpp>
  22. #include <boost/mpl/identity.hpp>
  23. #include <boost/mpl/is_sequence.hpp>
  24. #include <boost/mpl/bool.hpp>
  25. #include <boost/mpl/and.hpp>
  26. #include <boost/assert.hpp>
  27. #include <boost/ref.hpp>
  28. #include <boost/type_traits/remove_pointer.hpp>
  29. #include <boost/type_traits/add_reference.hpp>
  30. #include <boost/utility/enable_if.hpp>
  31. #include <boost/type_traits/is_convertible.hpp>
  32. #include <boost/msm/active_state_switching_policies.hpp>
  33. #include <boost/msm/row_tags.hpp>
  34. #include <boost/msm/backmp11/detail/history_impl.hpp>
  35. #include <boost/msm/backmp11/common_types.hpp>
  36. #include <boost/msm/backmp11/detail/favor_runtime_speed.hpp>
  37. #include <boost/msm/backmp11/state_machine_config.hpp>
  38. namespace boost { namespace msm { namespace backmp11
  39. {
  40. // Check whether a state is a composite state.
  41. using detail::is_composite;
  42. namespace detail
  43. {
  44. constexpr bool is_valid(visit_mode mode) {
  45. constexpr uint8_t state_mask = 0b011;
  46. const uint8_t state_bits = static_cast<uint8_t>(mode) & state_mask;
  47. return state_bits == 0b001 || state_bits == 0b010;
  48. }
  49. template <
  50. class FrontEnd,
  51. class Config,
  52. class Derived
  53. >
  54. class state_machine_base : public FrontEnd
  55. {
  56. static_assert(
  57. is_composite<FrontEnd>::value,
  58. "FrontEnd must be a composite state");
  59. static_assert(
  60. is_config<Config>::value,
  61. "Config must be an instance of state machine config");
  62. public:
  63. using config_t = Config;
  64. using root_sm_t = typename config_t::root_sm;
  65. using context_t = typename config_t::context;
  66. using front_end_t = FrontEnd;
  67. using derived_t = Derived;
  68. using events_queue_t = typename config_t::template
  69. queue_container<std::function<process_result()>>;
  70. // Event that describes the SM is starting.
  71. // Used when the front-end does not define an initial_event.
  72. struct starting {};
  73. // Event that describes the SM is stopping.
  74. // Used when the front-end does not define a final_event.
  75. struct stopping {};
  76. template <class ExitPoint>
  77. struct exit_pt : public ExitPoint
  78. {
  79. // tags
  80. typedef ExitPoint wrapped_exit;
  81. typedef int pseudo_exit;
  82. typedef derived_t owner;
  83. typedef int no_automatic_create;
  84. typedef typename
  85. ExitPoint::event Event;
  86. typedef std::function<process_result (Event const&)>
  87. forward_function;
  88. // forward event to the higher-level FSM
  89. template <class ForwardEvent>
  90. void forward_event(ForwardEvent const& incomingEvent)
  91. {
  92. // use helper to forward or not
  93. ForwardHelper< ::boost::is_convertible<ForwardEvent,Event>::value>::helper(incomingEvent,m_forward);
  94. }
  95. void set_forward_fct(forward_function fct)
  96. {
  97. m_forward = fct;
  98. }
  99. exit_pt():m_forward(){}
  100. // by assignments, we keep our forwarding functor unchanged as our containing SM did not change
  101. template <class RHS>
  102. exit_pt(RHS&):m_forward(){}
  103. exit_pt<ExitPoint>& operator= (const exit_pt<ExitPoint>& )
  104. {
  105. return *this;
  106. }
  107. private:
  108. forward_function m_forward;
  109. // using partial specialization instead of enable_if because of VC8 bug
  110. template <bool OwnEvent, int Dummy=0>
  111. struct ForwardHelper
  112. {
  113. template <class ForwardEvent>
  114. static void helper(ForwardEvent const& ,forward_function& )
  115. {
  116. // Not our event, assert
  117. BOOST_ASSERT(false);
  118. }
  119. };
  120. template <int Dummy>
  121. struct ForwardHelper<true,Dummy>
  122. {
  123. template <class ForwardEvent>
  124. static void helper(ForwardEvent const& incomingEvent,forward_function& forward_fct)
  125. {
  126. // call if handler set, if not, this state is simply a terminate state
  127. if (forward_fct)
  128. forward_fct(incomingEvent);
  129. }
  130. };
  131. };
  132. template <class EntryPoint>
  133. struct entry_pt : public EntryPoint
  134. {
  135. // tags
  136. typedef EntryPoint wrapped_entry;
  137. typedef int pseudo_entry;
  138. typedef derived_t owner;
  139. typedef int no_automatic_create;
  140. };
  141. template <class EntryPoint>
  142. struct direct : public EntryPoint
  143. {
  144. // tags
  145. typedef EntryPoint wrapped_entry;
  146. typedef int explicit_entry_state;
  147. typedef derived_t owner;
  148. typedef int no_automatic_create;
  149. };
  150. struct internal
  151. {
  152. using tag = back_end_tag;
  153. using initial_states = to_mp_list_t<typename front_end_t::initial_state>;
  154. static constexpr int nr_regions = mp11::mp_size<initial_states>::value;
  155. template <class State, typename Enable = void>
  156. struct make_entry
  157. {
  158. using type = State;
  159. };
  160. template <class State>
  161. struct make_entry<State, std::enable_if_t<has_pseudo_entry<State>::value>>
  162. {
  163. using type = entry_pt<State>;
  164. };
  165. template <class State>
  166. struct make_entry<State, std::enable_if_t<has_direct_entry<State>::value>>
  167. {
  168. using type = direct<State>;
  169. };
  170. template <class State, typename Enable = void>
  171. struct make_exit
  172. {
  173. using type = State;
  174. };
  175. template <class State>
  176. struct make_exit<State, std::enable_if_t<has_pseudo_exit<State>::value>>
  177. {
  178. using type = exit_pt<State>;
  179. };
  180. template<typename Row, bool HasGuard, typename Event, typename Source, typename Target>
  181. static bool call_guard_or_true(state_machine_base& sm, const Event& event, Source& source, Target& target)
  182. {
  183. if constexpr (HasGuard)
  184. {
  185. return Row::guard_call(sm.get_fsm_argument(), event, source, target, sm.m_states);
  186. }
  187. else
  188. {
  189. return true;
  190. }
  191. }
  192. template<typename Row, bool HasAction, typename Event, typename Source, typename Target>
  193. static process_result call_action_or_true(state_machine_base& sm, const Event& event, Source& source, Target& target)
  194. {
  195. if constexpr (HasAction)
  196. {
  197. return Row::action_call(sm.get_fsm_argument(), event, source, target, sm.m_states);
  198. }
  199. else
  200. {
  201. return process_result::HANDLED_TRUE;
  202. }
  203. }
  204. // Template used to create transitions from rows in the transition table
  205. // (normal transitions).
  206. template<typename Row, bool HasAction, bool HasGuard>
  207. struct Transition
  208. {
  209. typedef typename Row::Evt transition_event;
  210. typedef typename make_entry<typename Row::Source>::type T1;
  211. // if the source is an exit pseudo state, then
  212. // current_state_type becomes the result of get_owner
  213. // meaning the containing SM from which the exit occurs
  214. typedef typename ::boost::mpl::eval_if<
  215. typename has_pseudo_exit<T1>::type,
  216. get_owner<T1,derived_t>,
  217. ::boost::mpl::identity<typename Row::Source> >::type current_state_type;
  218. typedef typename make_exit<typename Row::Target>::type T2;
  219. // if Target is a sequence, then we have a fork and expect a sequence of explicit_entry
  220. // else if Target is an explicit_entry, next_state_type becomes the result of get_owner
  221. // meaning the containing SM if the row is "outside" the containing SM or else the explicit_entry state itself
  222. typedef typename ::boost::mpl::eval_if<
  223. typename ::boost::mpl::is_sequence<T2>::type,
  224. get_fork_owner<T2,derived_t>,
  225. ::boost::mpl::eval_if<
  226. typename has_no_automatic_create<T2>::type,
  227. get_owner<T2,derived_t>,
  228. ::boost::mpl::identity<T2> >
  229. >::type next_state_type;
  230. // Take the transition action and return the next state.
  231. static process_result execute(state_machine_base& sm, int region_index, int state, transition_event const& event)
  232. {
  233. BOOST_STATIC_CONSTANT(int, current_state = (get_state_id<current_state_type>()));
  234. BOOST_STATIC_CONSTANT(int, next_state = (get_state_id<next_state_type>()));
  235. boost::ignore_unused(state); // Avoid warnings if BOOST_ASSERT expands to nothing.
  236. BOOST_ASSERT(state == (current_state));
  237. // if T1 is an exit pseudo state, then take the transition only if the pseudo exit state is active
  238. if (has_pseudo_exit<T1>::type::value &&
  239. !sm.is_exit_state_active<T1, get_owner<T1,derived_t>>())
  240. {
  241. return process_result::HANDLED_FALSE;
  242. }
  243. auto& source = sm.get_state<current_state_type>();
  244. auto& target = sm.get_state<next_state_type>();
  245. if (!call_guard_or_true<Row, HasGuard>(sm, event, source, target))
  246. {
  247. // guard rejected the event, we stay in the current one
  248. return process_result::HANDLED_GUARD_REJECT;
  249. }
  250. sm.m_active_state_ids[region_index] = active_state_switching::after_guard(current_state,next_state);
  251. // first call the exit method of the current state
  252. source.on_exit(event, sm.get_fsm_argument());
  253. sm.m_active_state_ids[region_index] = active_state_switching::after_exit(current_state,next_state);
  254. // then call the action method
  255. process_result res = call_action_or_true<Row, HasAction>(sm, event, source, target);
  256. sm.m_active_state_ids[region_index] = active_state_switching::after_action(current_state,next_state);
  257. // and finally the entry method of the new current state
  258. convert_event_and_execute_entry<T2>(target,event,sm);
  259. sm.m_active_state_ids[region_index] = active_state_switching::after_entry(current_state,next_state);
  260. return res;
  261. }
  262. };
  263. // Template used to create transitions from rows in the transition table
  264. // (internal transitions).
  265. template<typename Row, bool HasAction, bool HasGuard, typename State = typename Row::Source>
  266. struct InternalTransition
  267. {
  268. typedef typename Row::Evt transition_event;
  269. typedef State current_state_type;
  270. typedef current_state_type next_state_type;
  271. // Take the transition action and return the next state.
  272. static process_result execute(state_machine_base& sm, int , int state, transition_event const& event)
  273. {
  274. BOOST_STATIC_CONSTANT(int, current_state = (get_state_id<current_state_type>()));
  275. boost::ignore_unused(state, current_state); // Avoid warnings if BOOST_ASSERT expands to nothing.
  276. BOOST_ASSERT(state == (current_state));
  277. auto& source = sm.get_state<current_state_type>();
  278. auto& target = source;
  279. if (!call_guard_or_true<Row, HasGuard>(sm, event, source, target))
  280. {
  281. // guard rejected the event, we stay in the current one
  282. return process_result::HANDLED_GUARD_REJECT;
  283. }
  284. // call the action method
  285. return call_action_or_true<Row, HasAction>(sm, event, source, target);
  286. }
  287. };
  288. template <class Tag, class Row,class State>
  289. struct create_backend_stt;
  290. template <class Row,class State>
  291. struct create_backend_stt<g_row_tag,Row,State>
  292. {
  293. using type = Transition<Row, false, true>;
  294. };
  295. template <class Row,class State>
  296. struct create_backend_stt<a_row_tag,Row,State>
  297. {
  298. using type = Transition<Row, true, false>;
  299. };
  300. template <class Row,class State>
  301. struct create_backend_stt<_row_tag,Row,State>
  302. {
  303. using type = Transition<Row, false, false>;
  304. };
  305. template <class Row,class State>
  306. struct create_backend_stt<row_tag,Row,State>
  307. {
  308. using type = Transition<Row, true, true>;
  309. };
  310. template <class Row,class State>
  311. struct create_backend_stt<g_irow_tag,Row,State>
  312. {
  313. using type = InternalTransition<Row, false, true>;
  314. };
  315. template <class Row,class State>
  316. struct create_backend_stt<a_irow_tag,Row,State>
  317. {
  318. using type = InternalTransition<Row, true, false>;
  319. };
  320. template <class Row,class State>
  321. struct create_backend_stt<irow_tag,Row,State>
  322. {
  323. using type = InternalTransition<Row, true, true>;
  324. };
  325. template <class Row,class State>
  326. struct create_backend_stt<_irow_tag,Row,State>
  327. {
  328. using type = InternalTransition<Row, false, false>;
  329. };
  330. template <class Row,class State>
  331. struct create_backend_stt<sm_a_i_row_tag,Row,State>
  332. {
  333. using type = InternalTransition<Row, true, false, State>;
  334. };
  335. template <class Row,class State>
  336. struct create_backend_stt<sm_g_i_row_tag,Row,State>
  337. {
  338. using type = InternalTransition<Row, false, true, State>;
  339. };
  340. template <class Row,class State>
  341. struct create_backend_stt<sm_i_row_tag,Row,State>
  342. {
  343. using type = InternalTransition<Row, true, true, State>;
  344. };
  345. template <class Row,class State>
  346. struct create_backend_stt<sm__i_row_tag,Row,State>
  347. {
  348. using type = InternalTransition<Row, false, false, State>;
  349. };
  350. template <class Row,class State=void>
  351. struct transition_cell
  352. {
  353. using type = typename create_backend_stt<typename Row::row_type_tag,Row,State>::type;
  354. };
  355. // add to the stt the initial states which could be missing (if not being involved in a transition)
  356. template <class TFrontEnd, class stt_simulated = typename TFrontEnd::transition_table>
  357. struct create_real_stt
  358. {
  359. template<typename T>
  360. using get_transition_cell = typename transition_cell<T, TFrontEnd>::type;
  361. typedef typename boost::mp11::mp_transform<
  362. get_transition_cell,
  363. to_mp_list_t<stt_simulated>
  364. > type;
  365. };
  366. using stt = typename get_transition_table<state_machine_base>::type;
  367. using state_set = typename generate_state_set<stt>::state_set;
  368. };
  369. typedef mp11::mp_rename<typename internal::state_set, std::tuple> states_t;
  370. private:
  371. using stt = typename internal::stt;
  372. using state_set = typename internal::state_set;
  373. static constexpr int nr_regions = internal::nr_regions;
  374. using active_state_ids_t = std::array<int, nr_regions>;
  375. using initial_states_identity = mp11::mp_transform<mp11::mp_identity, typename internal::initial_states>;
  376. using compile_policy = typename config_t::compile_policy;
  377. using compile_policy_impl = detail::compile_policy_impl<compile_policy>;
  378. template<class Row, class State>
  379. using transition_cell = typename internal::template transition_cell<Row, State>;
  380. template<class TFrontEnd, class stt_simulated>
  381. using create_real_stt = typename internal::template create_real_stt<TFrontEnd, stt_simulated>;
  382. template<typename T>
  383. using get_active_state_switch_policy = typename T::active_state_switch_policy;
  384. using active_state_switching =
  385. boost::mp11::mp_eval_or<active_state_switch_after_entry,
  386. get_active_state_switch_policy, front_end_t>;
  387. typedef bool (*flag_handler)(state_machine_base const &);
  388. // all state machines are friend with each other to allow embedding any of them in another fsm
  389. template <class, class, class>
  390. friend class state_machine_base;
  391. template <typename Policy>
  392. friend struct detail::compile_policy_impl;
  393. // Allow access to private members for serialization.
  394. // WARNING:
  395. // No guarantee is given on the private member layout.
  396. // Future changes may break existing serializer implementations.
  397. template<typename T, typename A0, typename A1, typename A2>
  398. friend void serialize(T&, state_machine_base<A0, A1, A2>&);
  399. template <typename T>
  400. using get_initial_event = typename T::initial_event;
  401. using fsm_initial_event =
  402. boost::mp11::mp_eval_or<starting, get_initial_event, front_end_t>;
  403. template <typename T>
  404. using get_final_event = typename T::final_event;
  405. using fsm_final_event =
  406. boost::mp11::mp_eval_or<stopping, get_final_event, front_end_t>;
  407. // Template used to form forwarding rows in the transition table for every row of a composite SM
  408. template <typename T1, class Evt>
  409. struct frow
  410. {
  411. typedef T1 current_state_type;
  412. typedef T1 next_state_type;
  413. typedef Evt transition_event;
  414. // tag to find out if a row is a forwarding row
  415. typedef int is_frow;
  416. // Take the transition action and return the next state.
  417. static process_result execute(state_machine_base& sm, int region_index, int , transition_event const& event)
  418. {
  419. // false as second parameter because this event is forwarded from outer fsm
  420. process_result res =
  421. (sm.get_state<current_state_type>()).process_event_internal(event);
  422. sm.m_active_state_ids[region_index]=get_state_id<T1>();
  423. return res;
  424. }
  425. // helper metafunctions used by dispatch table and give the frow a new event
  426. // (used to avoid double entries in a table because of base events)
  427. template <class NewEvent>
  428. struct replace_event
  429. {
  430. typedef frow<T1,NewEvent> type;
  431. };
  432. };
  433. template <class Table,class Intermediate,class State>
  434. struct add_forwarding_row_helper
  435. {
  436. typedef typename generate_event_set<Table>::event_set_mp11 all_events;
  437. template<typename T>
  438. using frow_state_type = frow<State, T>;
  439. typedef mp11::mp_append<
  440. to_mp_list_t<Intermediate>,
  441. mp11::mp_transform<frow_state_type, all_events>
  442. > type;
  443. };
  444. // gets the transition table from a composite and make from it a forwarding row
  445. template <class State,bool IsComposite>
  446. struct get_internal_transition_table
  447. {
  448. // first get the table of a composite
  449. typedef typename recursive_get_transition_table<State>::type original_table;
  450. // we now look for the events the composite has in its internal transitions
  451. // the internal ones are searched recursively in sub-sub... states
  452. // we go recursively because our states can also have internal tables or substates etc.
  453. typedef typename recursive_get_internal_transition_table<State, true>::type recursive_istt;
  454. template<typename T>
  455. using get_transition_cell = typename transition_cell<T, State>::type;
  456. typedef boost::mp11::mp_transform<
  457. get_transition_cell,
  458. to_mp_list_t<recursive_istt>
  459. > recursive_istt_with_tag;
  460. typedef boost::mp11::mp_append<original_table, recursive_istt_with_tag> table_with_all_events;
  461. // and add for every event a forwarding row
  462. typedef typename ::boost::mpl::eval_if<
  463. typename compile_policy_impl::add_forwarding_rows,
  464. add_forwarding_row_helper<table_with_all_events,mp11::mp_list<>,State>,
  465. ::boost::mpl::identity< mp11::mp_list<> >
  466. >::type type;
  467. };
  468. template <class State>
  469. struct get_internal_transition_table<State, false>
  470. {
  471. typedef typename create_real_stt<State, typename State::internal_transition_table >::type type;
  472. };
  473. typedef typename generate_state_map<state_set>::type state_map_mp11;
  474. typedef typename generate_event_set<stt>::event_set_mp11 event_set_mp11;
  475. typedef history_impl<typename front_end_t::history, nr_regions> concrete_history;
  476. typedef typename generate_event_set<
  477. typename create_real_stt<front_end_t, typename front_end_t::internal_transition_table >::type
  478. >::event_set_mp11 processable_events_internal_table;
  479. // extends the transition table with rows from composite states
  480. template <class Composite>
  481. struct extend_table
  482. {
  483. // add the init states
  484. //typedef typename get_transition_table<Composite>::type stt;
  485. typedef typename Composite::stt Stt;
  486. // add the internal events defined in the internal_transition_table
  487. // Note: these are added first because they must have a lesser prio
  488. // than the deeper transitions in the sub regions
  489. // table made of a stt + internal transitions of composite
  490. template<typename T>
  491. using get_transition_cell = typename transition_cell<T, Composite>::type;
  492. typedef typename boost::mp11::mp_transform<
  493. get_transition_cell,
  494. to_mp_list_t<typename Composite::internal_transition_table>
  495. > internal_stt;
  496. typedef boost::mp11::mp_append<
  497. to_mp_list_t<Stt>,
  498. internal_stt
  499. > stt_plus_internal;
  500. // for every state, add its transition table (if any)
  501. // transformed as frow
  502. template<typename V, typename State>
  503. using F = boost::mp11::mp_append<
  504. V,
  505. typename get_internal_transition_table<State, is_composite<State>::value>::type
  506. >;
  507. typedef boost::mp11::mp_fold<
  508. state_set,
  509. stt_plus_internal,
  510. F
  511. > type;
  512. };
  513. // extend the table with tables from composite states
  514. typedef typename extend_table<state_machine_base>::type complete_table;
  515. // define the dispatch table used for event dispatch
  516. using sm_dispatch_table = typename compile_policy_impl::template dispatch_table<state_machine_base>;
  517. struct deferred_event_t
  518. {
  519. std::function<process_result()> process_event;
  520. std::function<bool()> is_event_deferred;
  521. // Deferred events are added with a correlation sequence that helps to
  522. // identify when an event was added.
  523. // Newly deferred events will not be considered for procesing
  524. // within the same sequence.
  525. size_t seq_cnt;
  526. };
  527. using deferred_events_queue_t = std::list<deferred_event_t>;
  528. struct deferred_events_t
  529. {
  530. deferred_events_queue_t queue;
  531. size_t cur_seq_cnt;
  532. };
  533. using has_any_deferred_event =
  534. mp11::mp_any_of<state_set, has_state_deferred_events>;
  535. using deferred_events_member =
  536. optional_instance<deferred_events_t,
  537. has_any_deferred_event::value ||
  538. has_activate_deferred_events<front_end_t>::value>;
  539. using events_queue_member =
  540. optional_instance<events_queue_t,
  541. !has_no_message_queue<front_end_t>::value>;
  542. using context_member =
  543. optional_instance<context_t*,
  544. !std::is_same_v<context_t, no_context> &&
  545. (std::is_same_v<root_sm_t, no_root_sm> ||
  546. std::is_same_v<root_sm_t, derived_t>)>;
  547. template <bool C = deferred_events_member::value,
  548. typename = std::enable_if_t<C>>
  549. deferred_events_t& get_deferred_events()
  550. {
  551. return m_optional_members.template get<deferred_events_member>();
  552. }
  553. template <bool C = deferred_events_member::value,
  554. typename = std::enable_if_t<C>>
  555. const deferred_events_t& get_deferred_events() const
  556. {
  557. return m_optional_members.template get<deferred_events_member>();
  558. }
  559. template <class Event>
  560. bool is_event_deferred(const Event& event) const
  561. {
  562. return compile_policy_impl::is_event_deferred(
  563. *const_cast<state_machine_base*>(this), event);
  564. }
  565. // Visit states with a compile-time filter (reduces template instantiations).
  566. template <template <typename> typename Predicate, visit_mode Mode, typename Visitor>
  567. void visit_if(Visitor&& visitor)
  568. {
  569. // TODO:
  570. // Filter needs to be passed to visit to reduce template instantiations.
  571. visit<Mode>(
  572. [&visitor](auto& state)
  573. {
  574. using State = std::decay_t<decltype(state)>;
  575. if constexpr (Predicate<State>())
  576. {
  577. std::invoke(std::forward<Visitor>(visitor), state);
  578. }
  579. });
  580. }
  581. public:
  582. // Construct and forward constructor arguments to the front-end.
  583. template <typename... Args>
  584. state_machine_base(Args&&... args)
  585. : front_end_t(std::forward<Args>(args)...)
  586. {
  587. static_assert(
  588. std::is_base_of_v<state_machine_base, derived_t>,
  589. "Derived must inherit from state_machine");
  590. if constexpr (!std::is_same_v<context_t, no_context>)
  591. {
  592. static_assert(
  593. std::is_constructible_v<derived_t, context_t&>,
  594. "Derived must inherit the base class constructors");
  595. }
  596. if constexpr (std::is_same_v<root_sm_t, no_root_sm> ||
  597. std::is_same_v<root_sm_t, derived_t>)
  598. {
  599. // create states
  600. init(*static_cast<derived_t*>(this));
  601. }
  602. reset_active_state_ids();
  603. }
  604. // Construct with a context and forward further constructor arguments to the front-end.
  605. template <bool C = context_member::value,
  606. typename = std::enable_if_t<C>,
  607. typename... Args>
  608. state_machine_base(context_t& context, Args&&... args)
  609. : state_machine_base(std::forward<Args>(args)...)
  610. {
  611. m_optional_members.template get<context_member>() = &context;
  612. if constexpr (std::is_same_v<root_sm_t, no_root_sm>)
  613. {
  614. constexpr visit_mode mode = visit_mode::all_states | visit_mode::recursive;
  615. visit_if<is_back_end, mode>(
  616. [&context](auto &state_machine)
  617. {
  618. state_machine.m_optional_members.template get<context_member>() = &context;
  619. });
  620. }
  621. }
  622. // Copy constructor.
  623. state_machine_base(state_machine_base const& rhs)
  624. : front_end_t(rhs)
  625. {
  626. if constexpr (std::is_same_v<root_sm_t, no_root_sm> ||
  627. std::is_same_v<root_sm_t, derived_t>)
  628. {
  629. // create states
  630. init(*static_cast<derived_t*>(this));
  631. }
  632. // Copy all members except the root sm pointer.
  633. m_active_state_ids = rhs.m_active_state_ids;
  634. m_optional_members = rhs.m_optional_members;
  635. m_history = rhs.m_history;
  636. m_event_processing = rhs.m_event_processing;
  637. m_states = rhs.m_states;
  638. m_running = rhs.m_running;
  639. }
  640. // Copy assignment operator.
  641. state_machine_base& operator= (state_machine_base const& rhs)
  642. {
  643. if (this != &rhs)
  644. {
  645. front_end_t::operator=(rhs);
  646. // Copy all members except the root sm pointer.
  647. m_active_state_ids = rhs.m_active_state_ids;
  648. m_optional_members = rhs.m_optional_members;
  649. m_history = rhs.m_history;
  650. m_event_processing = rhs.m_event_processing;
  651. m_states = rhs.m_states;
  652. m_running = rhs.m_running;
  653. }
  654. return *this;
  655. }
  656. // Start the state machine (calls entry of the initial state).
  657. void start()
  658. {
  659. // Assert for a case where root sm was not set up correctly
  660. // after construction.
  661. if constexpr (!std::is_same_v<typename Config::root_sm, no_root_sm>)
  662. {
  663. BOOST_ASSERT_MSG(&(this->get_root_sm()),
  664. "Root sm must be passed as Derived and configured as root_sm");
  665. }
  666. start(fsm_initial_event{});
  667. }
  668. // Start the state machine (calls entry of the initial state with initial_event to on_entry's).
  669. template <class Event>
  670. void start(Event const& initial_event)
  671. {
  672. if (!m_running)
  673. {
  674. internal_start<Event, fsm_parameter_t, true>(initial_event, get_fsm_argument());
  675. }
  676. }
  677. // stop the state machine (calls exit of the current state)
  678. void stop()
  679. {
  680. stop(fsm_final_event{});
  681. }
  682. // stop the state machine (calls exit of the current state passing finalEvent to on_exit's)
  683. template <class Event>
  684. void stop(Event const& final_event)
  685. {
  686. if (m_running)
  687. {
  688. on_exit(final_event, get_fsm_argument());
  689. m_running = false;
  690. }
  691. }
  692. // Check whether a state is currently active.
  693. public:
  694. template <typename State>
  695. bool is_state_active() const
  696. {
  697. bool found = false;
  698. const_cast<state_machine_base*>(this)->visit(
  699. [&found](const auto& state)
  700. {
  701. using StateToCheck = std::decay_t<decltype(state)>;
  702. found |= std::is_same_v<State, StateToCheck>;
  703. });
  704. return found;
  705. }
  706. // Main function to process events.
  707. template<class Event>
  708. process_result process_event(Event const& event)
  709. {
  710. return process_event_internal(event, EventSource::EVENT_SOURCE_DIRECT);
  711. }
  712. // Enqueues an event in the message queue.
  713. // Call process_queued_events to process all queued events.
  714. // Be careful if you do this during event processing, the event will be processed immediately
  715. // and not kept in the queue.
  716. template <class Event,
  717. bool C = events_queue_member::value,
  718. typename = std::enable_if_t<C>>
  719. void enqueue_event(Event const& event)
  720. {
  721. get_events_queue().push_back(
  722. [this, event]
  723. {
  724. return process_event_internal(
  725. event,
  726. EventSource::EVENT_SOURCE_DIRECT |
  727. EventSource::EVENT_SOURCE_MSG_QUEUE);
  728. }
  729. );
  730. }
  731. // Process all queued events.
  732. template <bool C = events_queue_member::value,
  733. typename = std::enable_if_t<C>>
  734. void process_queued_events()
  735. {
  736. while(!get_events_queue().empty())
  737. {
  738. process_single_queued_event();
  739. }
  740. }
  741. // Process a single queued event.
  742. template <bool C = events_queue_member::value,
  743. typename = std::enable_if_t<C>>
  744. void process_single_queued_event()
  745. {
  746. auto to_call = get_events_queue().front();
  747. get_events_queue().pop_front();
  748. to_call();
  749. }
  750. // Get the context of the state machine.
  751. template <bool C = !std::is_same_v<context_t, no_context>,
  752. typename = std::enable_if_t<C>>
  753. context_t& get_context()
  754. {
  755. if constexpr (context_member::value)
  756. {
  757. return *m_optional_members.template get<context_member>();
  758. }
  759. else
  760. {
  761. return get_root_sm().get_context();
  762. }
  763. }
  764. // Get the context of the state machine.
  765. template <bool C = !std::is_same_v<context_t, no_context>,
  766. typename = std::enable_if_t<C>>
  767. const context_t& get_context() const
  768. {
  769. if constexpr (context_member::value)
  770. {
  771. return *m_optional_members.template get<context_member>();
  772. }
  773. else
  774. {
  775. return get_root_sm().get_context();
  776. }
  777. }
  778. // Get the events queued for later processing.
  779. template <bool C = events_queue_member::value,
  780. typename = std::enable_if_t<C>>
  781. events_queue_t& get_events_queue()
  782. {
  783. return m_optional_members.template get<events_queue_member>();
  784. }
  785. // Get the events queued for later processing.
  786. template <bool C = events_queue_member::value,
  787. typename = std::enable_if_t<C>>
  788. const events_queue_t& get_events_queue() const
  789. {
  790. return m_optional_members.template get<events_queue_member>();
  791. }
  792. // Get the deferred events queued for later processing.
  793. template <bool C = deferred_events_member::value,
  794. typename = std::enable_if_t<C>>
  795. deferred_events_queue_t& get_deferred_events_queue()
  796. {
  797. return get_deferred_events().queue;
  798. }
  799. // Get the deferred events queued for later processing.
  800. template <bool C = deferred_events_member::value,
  801. typename = std::enable_if_t<C>>
  802. const deferred_events_queue_t& get_deferred_events_queue() const
  803. {
  804. return get_deferred_events().queue;
  805. }
  806. // Getter that returns the currently active state ids of the FSM.
  807. const active_state_ids_t& get_active_state_ids() const
  808. {
  809. return m_active_state_ids;
  810. }
  811. // Get the root sm.
  812. template <typename T = root_sm_t,
  813. typename = std::enable_if_t<!std::is_same_v<T, no_root_sm>>>
  814. root_sm_t& get_root_sm()
  815. {
  816. return *static_cast<root_sm_t*>(m_root_sm);
  817. }
  818. // Get the root sm.
  819. template <typename T = root_sm_t,
  820. typename = std::enable_if_t<!std::is_same_v<T, no_root_sm>>>
  821. const root_sm_t& get_root_sm() const
  822. {
  823. return *static_cast<const root_sm_t*>(m_root_sm);
  824. }
  825. // Return the id of a state in the sm.
  826. template<typename State>
  827. static constexpr int get_state_id(const State&)
  828. {
  829. static_assert(mp11::mp_map_contains<state_map_mp11, State>::value);
  830. return detail::get_state_id<state_map_mp11, State>::type::value;
  831. }
  832. // Return the id of a state in the sm.
  833. template<typename State>
  834. static constexpr int get_state_id()
  835. {
  836. static_assert(mp11::mp_map_contains<state_map_mp11, State>::value);
  837. return detail::get_state_id<state_map_mp11, State>::type::value;
  838. }
  839. // True if the sm is used in another sm.
  840. bool is_contained() const
  841. {
  842. return (static_cast<const void*>(this) != m_root_sm);
  843. }
  844. // Get a state.
  845. template <class State>
  846. State& get_state()
  847. {
  848. return std::get<std::remove_reference_t<State>>(m_states);
  849. }
  850. // Get a state.
  851. template <class State>
  852. const State& get_state() const
  853. {
  854. return std::get<std::remove_reference_t<State>>(m_states);
  855. }
  856. // checks if a flag is active using the BinaryOp as folding function
  857. template <class Flag,class BinaryOp>
  858. bool is_flag_active() const
  859. {
  860. flag_handler* flags_entries = get_entries_for_flag<Flag>();
  861. bool res = (*flags_entries[ m_active_state_ids[0] ])(*this);
  862. for (int i = 1; i < nr_regions ; ++i)
  863. {
  864. res = BinaryOp() (res,(*flags_entries[ m_active_state_ids[i] ])(*this));
  865. }
  866. return res;
  867. }
  868. // checks if a flag is active using no binary op if 1 region, or OR if > 1 regions
  869. template <class Flag>
  870. bool is_flag_active() const
  871. {
  872. return FlagHelper<Flag,(nr_regions>1)>::helper(*this,get_entries_for_flag<Flag>());
  873. }
  874. // Visit the states (only active states, recursive).
  875. template <typename Visitor>
  876. constexpr void visit(Visitor&& visitor)
  877. {
  878. visit<visit_mode::active_recursive>(std::forward<Visitor>(visitor));
  879. }
  880. // Visit the states.
  881. // How to traverse is selected with visit_mode.
  882. template <visit_mode Mode, typename Visitor>
  883. constexpr void visit(Visitor&& visitor)
  884. {
  885. static_assert(
  886. is_valid(Mode),
  887. "Mode must specify one of active_states or all_states");
  888. constexpr bool recursive = has_flag(Mode, visit_mode::recursive);
  889. if constexpr (has_flag(Mode, visit_mode::active_states))
  890. {
  891. if (m_running)
  892. {
  893. for (const int state_id : m_active_state_ids)
  894. {
  895. using table = visitor_dispatch_table<Visitor, recursive>;
  896. table::dispatch(*this, state_id, std::forward<Visitor>(visitor));
  897. }
  898. }
  899. }
  900. // all states
  901. else
  902. {
  903. mp11::tuple_for_each(m_states,
  904. [&visitor](auto& state)
  905. {
  906. std::invoke(std::forward<Visitor>(visitor), state);
  907. using State = std::decay_t<decltype(state)>;
  908. // recursive needs to be repeated in this lambda,
  909. // MSVC does not recognize the constexpr correctly.
  910. constexpr bool recursive = has_flag(Mode, visit_mode::recursive);
  911. if constexpr (has_back_end_tag<State>::value && recursive)
  912. {
  913. state.template visit<Mode>(std::forward<Visitor>(visitor));
  914. }
  915. }
  916. );
  917. }
  918. }
  919. // Puts the given event into the deferred events queue.
  920. template <
  921. class Event,
  922. bool C = deferred_events_member::value,
  923. typename = std::enable_if_t<C>>
  924. void defer_event(Event const& event)
  925. {
  926. compile_policy_impl::defer_event(*this, event);
  927. }
  928. protected:
  929. static_assert(std::is_same_v<typename config_t::fsm_parameter, transition_owner> ||
  930. (std::is_same_v<typename config_t::fsm_parameter, typename config_t::root_sm> &&
  931. !std::is_same_v<typename config_t::root_sm, no_root_sm>),
  932. "fsm_parameter must be transition_owner or root_sm"
  933. );
  934. using fsm_parameter_t = mp11::mp_if_c<
  935. std::is_same_v<typename config_t::fsm_parameter, transition_owner>,
  936. derived_t,
  937. typename config_t::root_sm>;
  938. fsm_parameter_t& get_fsm_argument()
  939. {
  940. if constexpr (std::is_same_v<typename config_t::fsm_parameter,
  941. transition_owner>)
  942. {
  943. return *static_cast<derived_t*>(this);
  944. }
  945. else
  946. {
  947. return get_root_sm();
  948. }
  949. }
  950. // Checks if an event is an end interrupt event.
  951. template <typename Event>
  952. bool is_end_interrupt_event(const Event& event) const
  953. {
  954. return compile_policy_impl::is_end_interrupt_event(*this, event);
  955. }
  956. // Helpers used to reset the state machine.
  957. void reset_active_state_ids()
  958. {
  959. size_t index = 0;
  960. mp11::mp_for_each<initial_states_identity>(
  961. [this, &index](auto state_identity)
  962. {
  963. using State = typename decltype(state_identity)::type;
  964. m_active_state_ids[index++] = get_state_id<State>();
  965. });
  966. m_history.reset_active_state_ids(m_active_state_ids);
  967. }
  968. // handling of deferred events
  969. void try_process_deferred_events()
  970. {
  971. if constexpr (deferred_events_member::value)
  972. {
  973. deferred_events_t& deferred_events = get_deferred_events();
  974. if (deferred_events.queue.empty())
  975. {
  976. return;
  977. }
  978. active_state_ids_t active_state_ids = m_active_state_ids;
  979. // Iteratively process all of the events within the deferred
  980. // queue up to (but not including) newly deferred events.
  981. auto it = deferred_events.queue.begin();
  982. do
  983. {
  984. if (deferred_events.cur_seq_cnt == it->seq_cnt)
  985. {
  986. return;
  987. }
  988. if (it->is_event_deferred())
  989. {
  990. it = std::next(it);
  991. }
  992. else
  993. {
  994. deferred_event_t deferred_event = std::move(*it);
  995. it = deferred_events.queue.erase(it);
  996. const process_result result = deferred_event.process_event();
  997. if ((result & process_result::HANDLED_TRUE) &&
  998. (active_state_ids != m_active_state_ids))
  999. {
  1000. // The active state configuration has changed.
  1001. // Start from the beginning, we might be able
  1002. // to process events that stayed in the queue before.
  1003. active_state_ids = m_active_state_ids;
  1004. it = deferred_events.queue.begin();
  1005. }
  1006. }
  1007. } while (it != deferred_events.queue.end());
  1008. }
  1009. }
  1010. // handling of eventless transitions
  1011. void try_process_completion_event(EventSource source, bool handled)
  1012. {
  1013. using first_completion_event = mp11::mp_find_if<event_set_mp11, has_completion_event>;
  1014. // if none is found in the SM, nothing to do
  1015. if constexpr (first_completion_event::value != mp11::mp_size<event_set_mp11>::value)
  1016. {
  1017. if (handled)
  1018. {
  1019. process_event_internal(
  1020. mp11::mp_at<event_set_mp11, first_completion_event>{},
  1021. source | EventSource::EVENT_SOURCE_DIRECT);
  1022. }
  1023. }
  1024. }
  1025. // Handling of enqueued events.
  1026. void try_process_queued_events()
  1027. {
  1028. if constexpr (events_queue_member::value)
  1029. {
  1030. process_queued_events();
  1031. }
  1032. }
  1033. // Main function used internally to make transitions
  1034. // Can only be called for internally (for example in an action method) generated events.
  1035. template<class Event>
  1036. process_result process_event_internal(Event const& event,
  1037. EventSource source = EventSource::EVENT_SOURCE_DEFAULT)
  1038. {
  1039. // The compile policy decides whether the event needs to be wrapped or not.
  1040. // After wrapping it should call back process_event_internal_impl.
  1041. return compile_policy_impl::process_event_internal(*this, event, source);
  1042. }
  1043. template<class Event>
  1044. process_result process_event_internal_impl(Event const& event, EventSource source)
  1045. {
  1046. // If the state machine has terminate or interrupt flags, check them.
  1047. if constexpr (mp11::mp_any_of<state_set, is_state_blocking_t>::value)
  1048. {
  1049. // If the state machine is terminated, do not handle any event.
  1050. if (is_flag_active<TerminateFlag>())
  1051. {
  1052. return process_result::HANDLED_TRUE;
  1053. }
  1054. // If the state machine is interrupted, do not handle any event
  1055. // unless the event is the end interrupt event.
  1056. if (is_flag_active<InterruptedFlag>() && !is_end_interrupt_event(event))
  1057. {
  1058. return process_result::HANDLED_TRUE;
  1059. }
  1060. }
  1061. // If we have an event queue and are already processing events,
  1062. // enqueue it for later processing.
  1063. if constexpr (events_queue_member::value)
  1064. {
  1065. if (m_event_processing)
  1066. {
  1067. enqueue_event(event);
  1068. return process_result::HANDLED_TRUE;
  1069. }
  1070. }
  1071. // If deferred events are configured and the event is to be deferred
  1072. // in the active state configuration, then defer it for later processing.
  1073. if constexpr (has_any_deferred_event::value)
  1074. {
  1075. if (is_event_deferred(event))
  1076. {
  1077. compile_policy_impl::defer_event(*this, event);
  1078. return process_result::HANDLED_DEFERRED;
  1079. }
  1080. }
  1081. // Process the event.
  1082. m_event_processing = true;
  1083. process_result handled;
  1084. const bool is_direct_call = source & EventSource::EVENT_SOURCE_DIRECT;
  1085. if constexpr (has_no_exception_thrown<front_end_t>::value)
  1086. {
  1087. handled = do_process_event(event, is_direct_call);
  1088. }
  1089. else
  1090. {
  1091. // when compiling without exception support there is no formal parameter "e" in the catch handler.
  1092. // Declaring a local variable here does not hurt and will be "used" to make the code in the handler
  1093. // compilable although the code will never be executed.
  1094. std::exception e;
  1095. BOOST_TRY
  1096. {
  1097. handled = do_process_event(event, is_direct_call);
  1098. }
  1099. BOOST_CATCH (std::exception& e)
  1100. {
  1101. // give a chance to the concrete state machine to handle
  1102. this->exception_caught(event, get_fsm_argument(), e);
  1103. handled = process_result::HANDLED_FALSE;
  1104. }
  1105. BOOST_CATCH_END
  1106. }
  1107. // at this point we allow the next transition be executed without enqueing
  1108. // so that completion events and deferred events execute now (if any)
  1109. m_event_processing = false;
  1110. // Process completion transitions BEFORE any other event in the
  1111. // pool (UML Standard 2.3 15.3.14)
  1112. try_process_completion_event(source, (handled & process_result::HANDLED_TRUE));
  1113. // After handling, take care of the queued and deferred events.
  1114. // Default:
  1115. // Handle deferred events queue with higher prio than events queue.
  1116. if constexpr (!has_event_queue_before_deferred_queue<front_end_t>::value)
  1117. {
  1118. if (!(EventSource::EVENT_SOURCE_DEFERRED & source))
  1119. {
  1120. try_process_deferred_events();
  1121. // Handle any new events generated into the queue, but only if
  1122. // we're not already processing from the message queue.
  1123. if (!(EventSource::EVENT_SOURCE_MSG_QUEUE & source))
  1124. {
  1125. try_process_queued_events();
  1126. }
  1127. }
  1128. }
  1129. // Non-default:
  1130. // Handle events queue with higher prio than deferred events queue.
  1131. else
  1132. {
  1133. if (!(EventSource::EVENT_SOURCE_MSG_QUEUE & source))
  1134. {
  1135. try_process_queued_events();
  1136. if (!(EventSource::EVENT_SOURCE_DEFERRED & source))
  1137. {
  1138. try_process_deferred_events();
  1139. }
  1140. }
  1141. }
  1142. return handled;
  1143. }
  1144. // minimum event processing without exceptions, queues, etc.
  1145. template<class Event>
  1146. process_result do_process_event(Event const& event, bool is_direct_call)
  1147. {
  1148. if constexpr (deferred_events_member::value)
  1149. {
  1150. if (is_direct_call)
  1151. {
  1152. get_deferred_events().cur_seq_cnt += 1;
  1153. }
  1154. }
  1155. process_result handled = process_result::HANDLED_FALSE;
  1156. // Dispatch the event to every region.
  1157. for (int region_id=0; region_id<nr_regions; region_id++)
  1158. {
  1159. handled = static_cast<process_result>(
  1160. static_cast<int>(handled) |
  1161. static_cast<int>(sm_dispatch_table::dispatch(*this, region_id, m_active_state_ids[region_id], event))
  1162. );
  1163. }
  1164. // Process the event in the internal table of this fsm if the event is processable (present in the table).
  1165. if constexpr (mp11::mp_set_contains<processable_events_internal_table,Event>::value)
  1166. {
  1167. handled = static_cast<process_result>(
  1168. static_cast<int>(handled) |
  1169. static_cast<int>(sm_dispatch_table::dispatch_internal(*this, 0, m_active_state_ids[0], event))
  1170. );
  1171. }
  1172. // if the event has not been handled and we have orthogonal zones, then
  1173. // generate an error on every active state
  1174. // for state machine states contained in other state machines, do not handle
  1175. // but let the containing sm handle the error, unless the event was generated in this fsm
  1176. // (by calling process_event on this fsm object, is_direct_call == true)
  1177. // completion events do not produce an error
  1178. if ((!is_contained() || is_direct_call) && !handled && !compile_policy_impl::is_completion_event(event))
  1179. {
  1180. for (const auto state_id: m_active_state_ids)
  1181. {
  1182. this->no_transition(event, get_fsm_argument(), state_id);
  1183. }
  1184. }
  1185. return handled;
  1186. }
  1187. private:
  1188. // helper for flag handling. Uses OR by default on orthogonal zones.
  1189. template <class Flag,bool OrthogonalStates>
  1190. struct FlagHelper
  1191. {
  1192. static bool helper(state_machine_base const& sm,flag_handler* )
  1193. {
  1194. // by default we use OR to accumulate the flags
  1195. return sm.is_flag_active<Flag,std::logical_or<bool>>();
  1196. }
  1197. };
  1198. template <class Flag>
  1199. struct FlagHelper<Flag,false>
  1200. {
  1201. static bool helper(state_machine_base const& sm,flag_handler* flags_entries)
  1202. {
  1203. // just one active state, so we can call operator[] with 0
  1204. return flags_entries[sm.get_active_state_ids()[0]](sm);
  1205. }
  1206. };
  1207. // handling of flag
  1208. // defines a true and false functions plus a forwarding one for composite states
  1209. template <class State,class Flag>
  1210. struct FlagHandler
  1211. {
  1212. static bool flag_true(state_machine_base const& )
  1213. {
  1214. return true;
  1215. }
  1216. static bool flag_false(state_machine_base const& )
  1217. {
  1218. return false;
  1219. }
  1220. static bool forward(state_machine_base const& fsm)
  1221. {
  1222. return fsm.template get_state<State>().template is_flag_active<Flag>();
  1223. }
  1224. };
  1225. template <class Flag>
  1226. struct init_flags
  1227. {
  1228. private:
  1229. // helper function, helps hiding the forward function for non-state machines states.
  1230. template <class T>
  1231. void helper (flag_handler* an_entry,int offset, ::boost::mpl::true_ const & )
  1232. {
  1233. // composite => forward
  1234. an_entry[offset] = &FlagHandler<T,Flag>::forward;
  1235. }
  1236. template <class T>
  1237. void helper (flag_handler* an_entry,int offset, ::boost::mpl::false_ const & )
  1238. {
  1239. // default no flag
  1240. an_entry[offset] = &FlagHandler<T,Flag>::flag_false;
  1241. }
  1242. // attributes
  1243. flag_handler* entries;
  1244. public:
  1245. init_flags(flag_handler* entries_)
  1246. : entries(entries_)
  1247. {}
  1248. // Flags initializer function object, used with for_each
  1249. template <class State>
  1250. void operator()( mp11::mp_identity<State> const& )
  1251. {
  1252. typedef typename get_flag_list<State>::type flags;
  1253. typedef mp11::mp_contains<flags,Flag > found;
  1254. BOOST_STATIC_CONSTANT(int, state_id = (get_state_id<State>()));
  1255. if (found::type::value)
  1256. {
  1257. // the type defined the flag => true
  1258. entries[state_id] = &FlagHandler<State,Flag>::flag_true;
  1259. }
  1260. else
  1261. {
  1262. // false or forward
  1263. typedef typename ::boost::mpl::and_<
  1264. typename has_back_end_tag<State>::type,
  1265. typename ::boost::mpl::not_<
  1266. typename has_non_forwarding_flag<Flag>::type>::type >::type composite_no_forward;
  1267. helper<State>(entries,state_id,::boost::mpl::bool_<composite_no_forward::type::value>());
  1268. }
  1269. }
  1270. };
  1271. // maintains for every flag a static array containing the flag value for every state
  1272. template <class Flag>
  1273. flag_handler* get_entries_for_flag() const
  1274. {
  1275. BOOST_STATIC_CONSTANT(int, max_state = (mp11::mp_size<state_set>::value));
  1276. static flag_handler flags_entries[max_state];
  1277. // build a state list, but only once
  1278. static flag_handler* flags_entries_ptr =
  1279. (mp11::mp_for_each<mp11::mp_transform<mp11::mp_identity, state_set>>
  1280. (init_flags<Flag>(flags_entries)),
  1281. flags_entries);
  1282. return flags_entries_ptr;
  1283. }
  1284. template <class Event, class Fsm, bool InitialStart = false>
  1285. void internal_start(Event const& event, Fsm& fsm)
  1286. {
  1287. m_running = true;
  1288. // Call on_entry on this SM first.
  1289. static_cast<front_end_t*>(this)->on_entry(event, fsm);
  1290. // Then call on_entry on the states.
  1291. if constexpr (InitialStart)
  1292. {
  1293. mp11::mp_for_each<initial_states_identity>(
  1294. [this, &event, &fsm](auto state_identity)
  1295. {
  1296. using State = typename decltype(state_identity)::type;
  1297. execute_entry(this->get_state<State>(), event, fsm);
  1298. });
  1299. }
  1300. else
  1301. {
  1302. // Visit active states non-recursively.
  1303. visit(
  1304. [&event, &fsm](auto& state)
  1305. {
  1306. // TODO:
  1307. // Add filter to rule out impossible entry states.
  1308. execute_entry(state, event, fsm);
  1309. });
  1310. }
  1311. // give a chance to handle an anonymous (eventless) transition
  1312. try_process_completion_event(EventSource::EVENT_SOURCE_DEFAULT, true);
  1313. }
  1314. // helper to find out if a SM has an active exit state and is therefore waiting for exiting
  1315. template <class State, class StateOwner>
  1316. inline
  1317. bool is_exit_state_active()
  1318. {
  1319. if constexpr (has_pseudo_exit<State>::value)
  1320. {
  1321. typedef typename StateOwner::type Owner;
  1322. Owner& owner = get_state<Owner&>();
  1323. const int state_id = owner.template get_state_id<State>();
  1324. for (const auto active_state_id : owner.get_active_state_ids())
  1325. {
  1326. if (active_state_id == state_id)
  1327. {
  1328. return true;
  1329. }
  1330. }
  1331. }
  1332. return false;
  1333. }
  1334. template <class State>
  1335. struct find_region_id
  1336. {
  1337. template <int region,int Dummy=0>
  1338. struct In
  1339. {
  1340. enum {region_index=region};
  1341. };
  1342. enum {region_index = In<State::zone_index>::region_index };
  1343. };
  1344. // entry for states machines which are themselves embedded in other state machines (composites)
  1345. template <class Event, class Fsm>
  1346. void on_entry(Event const& event, Fsm& fsm)
  1347. {
  1348. // block immediate handling of events
  1349. m_event_processing = true;
  1350. // by default we activate the history/init states, can be overwritten by direct events.
  1351. m_active_state_ids = m_history.on_entry(event);
  1352. // this variant is for the standard case, entry due to activation of the containing FSM
  1353. if constexpr (!has_direct_entry<Event>::value)
  1354. {
  1355. internal_start(event, fsm);
  1356. }
  1357. // this variant is for the direct entry case
  1358. else if constexpr (has_direct_entry<Event>::value)
  1359. {
  1360. // Set the new active state(s) first, this includes
  1361. // a normal direct entry (or entries) and a pseudo entry.
  1362. using entry_states = to_mp_list_t<typename Event::active_state>;
  1363. mp11::mp_for_each<mp11::mp_transform<mp11::mp_identity, entry_states>>(
  1364. [this](auto state_identity)
  1365. {
  1366. using State = typename decltype(state_identity)::type::wrapped_entry;
  1367. static constexpr int region_index = find_region_id<State>::region_index;
  1368. static_assert(region_index >= 0 && region_index < nr_regions);
  1369. m_active_state_ids[region_index] = get_state_id<State>();
  1370. }
  1371. );
  1372. internal_start(event.m_event, fsm);
  1373. // in case of a pseudo entry process the transition in the zone of the newly active state
  1374. // (entry pseudo states are, according to UML, a state connecting 1 transition outside to 1 inside
  1375. if constexpr (has_pseudo_entry<typename Event::active_state>::value)
  1376. {
  1377. static_assert(!mpl::is_sequence<typename Event::active_state>::value);
  1378. process_event(event.m_event);
  1379. }
  1380. }
  1381. // handle messages which were generated and blocked in the init calls
  1382. m_event_processing = false;
  1383. // look for deferred events waiting
  1384. try_process_deferred_events();
  1385. try_process_queued_events();
  1386. }
  1387. template <class Event,class Fsm>
  1388. void on_exit(Event const& event, Fsm& fsm)
  1389. {
  1390. // first recursively exit the sub machines
  1391. // forward the event for handling by sub state machines
  1392. visit(
  1393. [&event, &fsm](auto& state)
  1394. {
  1395. // TODO:
  1396. // Filter out impossible exit states.
  1397. state.on_exit(event, fsm);
  1398. }
  1399. );
  1400. // then call our own exit
  1401. (static_cast<front_end_t*>(this))->on_exit(event,fsm);
  1402. // give the history a chance to handle this (or not).
  1403. m_history.on_exit(this->m_active_state_ids);
  1404. // history decides what happens with deferred events
  1405. if (!m_history.process_deferred_events(event))
  1406. {
  1407. if constexpr (deferred_events_member::value)
  1408. {
  1409. get_deferred_events_queue().clear();
  1410. }
  1411. }
  1412. }
  1413. // calls entry or on_entry depending on the state type
  1414. template <class State, class Event, class Fsm>
  1415. static void execute_entry(State& state, Event const& event, Fsm& fsm)
  1416. {
  1417. // calls on_entry on the fsm then handles direct entries, fork, entry pseudo state
  1418. if constexpr (has_back_end_tag<State>::value)
  1419. {
  1420. state.on_entry(event,fsm);
  1421. }
  1422. else if constexpr (has_pseudo_exit<State>::value)
  1423. {
  1424. // calls on_entry on the state then forward the event to the transition which should be defined inside the
  1425. // contained fsm
  1426. state.on_entry(event,fsm);
  1427. state.forward_event(event);
  1428. }
  1429. else if constexpr (has_direct_entry<Event>::value)
  1430. {
  1431. state.on_entry(event.m_event, fsm);
  1432. }
  1433. else
  1434. {
  1435. state.on_entry(event, fsm);
  1436. }
  1437. }
  1438. // helper allowing special handling of direct entries / fork
  1439. template <class Target,class State,class Event>
  1440. static void convert_event_and_execute_entry(State& state,Event const& event, state_machine_base& sm)
  1441. {
  1442. auto& fsm = sm.get_fsm_argument();
  1443. if constexpr (has_explicit_entry_state<Target>::value || mpl::is_sequence<Target>::value)
  1444. {
  1445. // for the direct entry, pack the event in a wrapper so that we handle it differently during fsm entry
  1446. execute_entry(state,direct_entry_event<Target,Event>(event),fsm);
  1447. }
  1448. else
  1449. {
  1450. // if the target is a normal state, do the standard entry handling
  1451. execute_entry(state,event,fsm);
  1452. }
  1453. }
  1454. template <typename State>
  1455. using state_filter_predicate = mp11::mp_or<
  1456. has_pseudo_exit<State>,
  1457. has_back_end_tag<State>
  1458. >;
  1459. using states_to_init = mp11::mp_copy_if<
  1460. states_t,
  1461. state_filter_predicate>;
  1462. // initializes the SM
  1463. template <class TRootSm>
  1464. void init(TRootSm& root_sm)
  1465. {
  1466. if constexpr (!std::is_same_v<root_sm_t, no_root_sm>)
  1467. {
  1468. static_assert(
  1469. std::is_same_v<TRootSm, root_sm_t>,
  1470. "The configured root_sm must match the used one"
  1471. );
  1472. static_assert(
  1473. std::is_same_v<context_t, no_context> ||
  1474. std::is_same_v<context_t, typename TRootSm::context_t>,
  1475. "The configured context must match the root sm's one");
  1476. }
  1477. m_root_sm = static_cast<void*>(&root_sm);
  1478. mp11::mp_for_each<mp11::mp_transform<mp11::mp_identity, states_to_init>>(
  1479. [this, &root_sm](auto state_identity)
  1480. {
  1481. using State = typename decltype(state_identity)::type;
  1482. auto& state = this->get_state<State>();
  1483. if constexpr (has_pseudo_exit<State>::value)
  1484. {
  1485. state.set_forward_fct(
  1486. [&root_sm](typename State::event const& event)
  1487. {
  1488. return root_sm.process_event(event);
  1489. }
  1490. );
  1491. }
  1492. if constexpr (is_back_end<State>::value)
  1493. {
  1494. static_assert(
  1495. std::is_same_v<compile_policy, typename State::compile_policy>,
  1496. "All compile policies must be identical"
  1497. );
  1498. state.init(root_sm);
  1499. }
  1500. }
  1501. );
  1502. }
  1503. // Dispatch table for calling invoking visitors with active states.
  1504. template <typename Visitor, bool Recursive>
  1505. class visitor_dispatch_table
  1506. {
  1507. public:
  1508. visitor_dispatch_table()
  1509. {
  1510. using state_identities = mp11::mp_transform<mp11::mp_identity, state_set>;
  1511. mp11::mp_for_each<state_identities>(
  1512. [this](auto state_identity)
  1513. {
  1514. using State = typename decltype(state_identity)::type;
  1515. m_cells[get_state_id<State>()] = &accept<State>;
  1516. }
  1517. );
  1518. }
  1519. template<typename State>
  1520. static void accept(state_machine_base& sm, Visitor visitor)
  1521. {
  1522. auto& state = sm.template get_state<State>();
  1523. visitor(state);
  1524. if constexpr (has_back_end_tag<State>::value && Recursive)
  1525. {
  1526. state.template visit
  1527. <visit_mode::active_states | visit_mode::recursive>
  1528. (std::forward<Visitor>(visitor));
  1529. }
  1530. }
  1531. static void dispatch(state_machine_base& sm, int index, Visitor visitor)
  1532. {
  1533. instance().m_cells[index](sm, visitor);
  1534. }
  1535. private:
  1536. using cell_t = void (*)(state_machine_base&, Visitor);
  1537. static visitor_dispatch_table& instance()
  1538. {
  1539. static visitor_dispatch_table instance;
  1540. return instance;
  1541. }
  1542. cell_t m_cells[mp11::mp_size<state_set>::value];
  1543. };
  1544. struct optional_members :
  1545. events_queue_member,
  1546. deferred_events_member,
  1547. context_member
  1548. {
  1549. template <typename T>
  1550. typename T::type& get()
  1551. {
  1552. return static_cast<T*>(this)->instance;
  1553. }
  1554. template <typename T>
  1555. const typename T::type& get() const
  1556. {
  1557. return static_cast<const T*>(this)->instance;
  1558. }
  1559. };
  1560. // data members
  1561. active_state_ids_t m_active_state_ids;
  1562. optional_members m_optional_members;
  1563. concrete_history m_history{};
  1564. bool m_event_processing{false};
  1565. void* m_root_sm{nullptr};
  1566. states_t m_states{};
  1567. bool m_running{false};
  1568. };
  1569. } // detail
  1570. /**
  1571. * @brief Back-end for state machines.
  1572. *
  1573. * Can take 1...3 parameters.
  1574. *
  1575. * @tparam T0 (mandatory) : Front-end
  1576. * @tparam T1 (optional) : State machine config
  1577. * @tparam T2 (optional) : Derived class (required when inheriting from state_machine)
  1578. */
  1579. template <typename ...T>
  1580. class state_machine;
  1581. template <class FrontEnd, class Config, class Derived>
  1582. class state_machine<FrontEnd, Config, Derived>
  1583. : public detail::state_machine_base<FrontEnd, Config, Derived>
  1584. {
  1585. using Base = detail::state_machine_base<FrontEnd, Config, Derived>;
  1586. public:
  1587. using Base::Base;
  1588. };
  1589. template <class FrontEnd, class Config>
  1590. class state_machine<FrontEnd, Config>
  1591. : public detail::state_machine_base<FrontEnd, Config, state_machine<FrontEnd, Config>>
  1592. {
  1593. using Base = detail::state_machine_base<FrontEnd, Config, state_machine<FrontEnd, Config>>;
  1594. public:
  1595. using Base::Base;
  1596. };
  1597. template <class FrontEnd>
  1598. class state_machine<FrontEnd>
  1599. : public detail::state_machine_base<FrontEnd, default_state_machine_config, state_machine<FrontEnd>>
  1600. {
  1601. using Base = detail::state_machine_base<FrontEnd, default_state_machine_config, state_machine<FrontEnd>>;
  1602. public:
  1603. using Base::Base;
  1604. };
  1605. }}} // boost::msm::backmp11
  1606. #endif //BOOST_MSM_BACKMP11_STATE_MACHINE_H