#include #include #include namespace Void::Fsm { // ── helpers ─────────────────────────────────────────────────────────── Action wrap_sync(SyncAction fn) { if (!fn) { return {}; } return [fn = std::move(fn)](Machine& m, const Event& e) -> Coro::Task { fn(m, e); co_return; }; } // ── MachineDef ──────────────────────────────────────────────────────── bool MachineDef::is_ancestor_or_self(StateId ancestor, StateId state) const { StateId cur = state; while (cur != kInvalidState) { if (cur == ancestor) { return true; } cur = m_states[cur].parent; } return false; } StateId MachineDef::lca(StateId a, StateId b) const { // Equalize depths, then climb together. StateId x = a; StateId y = b; while (m_states[x].depth > m_states[y].depth) { x = m_states[x].parent; } while (m_states[y].depth > m_states[x].depth) { y = m_states[y].parent; } while (x != y) { x = m_states[x].parent; y = m_states[y].parent; } return x; } // ── Builder ─────────────────────────────────────────────────────────── Builder::Builder() { // State 0 is the implicit root. MachineDef::StateNode root; root.name = ""; root.parent = kInvalidState; root.depth = 0; m_def.m_states.push_back(std::move(root)); m_def.m_state_ids.emplace("", kRootState); } StateRef Builder::state(std::string_view name, StateRef parent) { if (const auto it = m_def.m_state_ids.find(std::string{name}); it != m_def.m_state_ids.end()) { return StateRef{it->second}; } const auto id = static_cast(m_def.m_states.size()); MachineDef::StateNode node; node.name = std::string{name}; node.parent = parent.valid() ? parent.id() : kRootState; node.depth = m_def.m_states[node.parent].depth + 1; m_def.m_states.push_back(std::move(node)); m_def.m_states[parent.valid() ? parent.id() : kRootState] .children.push_back(id); m_def.m_state_ids.emplace(std::string{name}, id); return StateRef{id}; } EventId Builder::event(std::string_view name) { if (const auto it = m_def.m_event_ids.find(std::string{name}); it != m_def.m_event_ids.end()) { return it->second; } const auto id = static_cast(m_def.m_event_names.size()); m_def.m_event_names.emplace_back(name); m_def.m_event_ids.emplace(std::string{name}, id); return id; } Builder& Builder::initial(StateRef child) { const auto parent = m_def.m_states[child.id()].parent; m_def.m_states[parent].initial = child.id(); return *this; } Builder& Builder::parallel(StateRef composite) { m_def.m_states[composite.id()].parallel = true; return *this; } Builder& Builder::on_entry(StateRef state, Action action) { m_def.m_states[state.id()].entry = std::move(action); return *this; } Builder& Builder::on_entry(StateRef state, SyncAction action) { return on_entry(state, wrap_sync(std::move(action))); } Builder& Builder::on_exit(StateRef state, Action action) { m_def.m_states[state.id()].exit = std::move(action); return *this; } Builder& Builder::on_exit(StateRef state, SyncAction action) { return on_exit(state, wrap_sync(std::move(action))); } Builder& Builder::history(StateRef composite, History kind) { m_def.m_states[composite.id()].history = kind; return *this; } Builder& Builder::defer(StateRef state, EventId id) { m_def.m_states[state.id()].deferred.push_back(id); return *this; } Builder& Builder::timeout(StateRef state, std::chrono::milliseconds after, EventId fires) { m_def.m_states[state.id()].timeout = MachineDef::Timeout{after, fires}; return *this; } TransitionBuilder Builder::transition(StateRef from, EventId on, StateRef to) { MachineDef::TransitionDef t; t.from = from.id(); t.on = on; t.to = to.id(); t.internal = false; m_def.m_transitions.push_back(std::move(t)); return TransitionBuilder{*this, m_def.m_transitions.size() - 1}; } TransitionBuilder Builder::internal(StateRef in, EventId on) { MachineDef::TransitionDef t; t.from = in.id(); t.on = on; t.to = kInvalidState; t.internal = true; m_def.m_transitions.push_back(std::move(t)); return TransitionBuilder{*this, m_def.m_transitions.size() - 1}; } TransitionBuilder& TransitionBuilder::guard(Guard g) { m_builder->m_def.m_transitions[m_index].guard = std::move(g); return *this; } TransitionBuilder& TransitionBuilder::action(Action a) { m_builder->m_def.m_transitions[m_index].action = std::move(a); return *this; } TransitionBuilder& TransitionBuilder::action(SyncAction a) { return action(wrap_sync(std::move(a))); } std::expected, DefError> Builder::build() { if (m_consumed) { return std::unexpected{DefError{"Builder::build() called twice"}}; } auto& def = m_def; // Every composite (state with children) that is entered must know // where to go: an initial child — parallel composites enter all // children instead. Default a single-child composite's initial. for (StateId id = 0; id < def.m_states.size(); ++id) { auto& node = def.m_states[id]; if (node.children.empty()) { if (node.parallel) { return std::unexpected{DefError{ std::format("parallel state '{}' has no child regions", node.name)}}; } if (id == kRootState) { return std::unexpected{DefError{"machine has no states"}}; } continue; } if (node.parallel) { continue; } if (node.initial == kInvalidState) { if (node.children.size() == 1) { node.initial = node.children.front(); } else if (id == kRootState) { // Convention: the first declared top-level state. node.initial = node.children.front(); } else { return std::unexpected{DefError{std::format( "composite state '{}' needs initial()", node.name)}}; } } if (!def.is_ancestor_or_self(id, node.initial) || node.initial == id) { return std::unexpected{DefError{std::format( "initial of '{}' is not a descendant", node.name)}}; } } // Transition sanity. for (const auto& t : def.m_transitions) { if (t.from == kInvalidState || t.from >= def.m_states.size()) { return std::unexpected{ DefError{"transition from unknown state"}}; } if (!t.internal && (t.to == kInvalidState || t.to >= def.m_states.size())) { return std::unexpected{DefError{"transition to unknown state"}}; } if (t.on == kInvalidEvent || t.on >= def.m_event_names.size()) { return std::unexpected{DefError{"transition on unknown event"}}; } } // Index transitions by source state, in definition order. def.m_transitions_by_state.assign(def.m_states.size(), {}); for (std::size_t i = 0; i < def.m_transitions.size(); ++i) { def.m_transitions_by_state[def.m_transitions[i].from].push_back(i); } m_consumed = true; auto out = std::make_shared(std::move(m_def)); Void::Log::debug("Fsm", "built definition: {} states, {} events, " "{} transitions", out->m_states.size(), out->m_event_names.size(), out->m_transitions.size()); return out; } } // namespace Void::Fsm