FSM (4): one signature-inferred State (drops Reactive/Continue bases)
There is now a single state base, `State`. The engine infers each state's
role purely from member signatures via P2996 — no `override`, no
framework-mandated names:
struct Work : State { // entry
Coro::Task<Step> run() { ... }
Coro::Task<Step> run(Cfg c) { ... } // startup-entry (launch data)
};
struct Idle : State { // reactive
void transitions(TransitionBuilder& on) { on.event<Go>().to<Run>(); }
};
struct After : State { // continuation
Coro::Task<Step> ok(ChildSuccess auto s) { use s.value; }
Coro::Task<Step> no(ChildFailure auto f) { use f.value; }
};
- Detail/Roles.hpp: ChildSuccess/ChildFailure concepts over boxes, plus the
reflection selectors (invoke_entry / invoke_startup / invoke_handler /
dispatch_result / has_transitions / make_driver). At add<S>() a per-state
driver thunk is stored (reactive table vs entry, by whether S has a
TransitionBuilder& member); drive() calls it. startMachine<Sub, Next>(data)
builds a Launch step carrying a launcher (injects data into Sub's initial
startup-entry) + a dispatcher (dispatch_result<Next, Sub>) that builds the
ChildSuccess/Failure box and calls Next's matching handler.
- Removed Reactive/Continue<R> bases, StateKind/kind(), StateBase::run/resume
(only on_enter/on_exit remain virtual). Reactive states keep the same DSL.
- Toolchain note: template-for + member splicing fails inside a coroutine
body in this GCC build, so the selectors are non-coroutines returning a
Task<Step> (plain Step wrapped via ready_task). Discovery is
invocability-based — no parameter-type reflection (P3096). Probe-verified.
All FSM tests migrated to the nameless style (SubMachine: Continue ->
ChildSuccess/Failure handlers + startup-entry seeding; reactive states drop
the Reactive base/override). 995 tests (992 green, 3 skipped), ASan clean,
-Werror clean; lone intermittent failure remains the pre-existing racy
plugin hot-reload-under-load test.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e9eb838ea
commit
ec9e466d7a
20 files changed
+536
-358
No files matched your search
@@ -1,76 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
// Base for a state that resumes from a sub-machine launched via
|
||||
// startMachine<Sub, This>(). `StateT` is the owning machine's nested State;
|
||||
// `Sub` is the launched machine. The engine enters this state carrying the
|
||||
// sub's LaunchResult and calls resume(), which dispatches to on_success /
|
||||
// on_failure by the outcome. Machine exposes it as `Continue<Sub>`.
|
||||
//
|
||||
// on_success takes the sub's typed Success, on_failure its typed Failure
|
||||
// (a void result becomes a std::monostate argument).
|
||||
//
|
||||
// NOTE: this is the interim Phase-1 form; Phase 2 replaces it with
|
||||
// signature-inferred ChildSuccess/ChildFailure handlers.
|
||||
template <typename StateT, typename Sub> class Continuation : public StateT
|
||||
{
|
||||
using Succ = SuccessOf<Sub>;
|
||||
using Fail = FailureOf<Sub>;
|
||||
using SuccArg =
|
||||
std::conditional_t<std::is_void_v<Succ>, std::monostate, Succ>;
|
||||
using FailArg =
|
||||
std::conditional_t<std::is_void_v<Fail>, std::monostate, Fail>;
|
||||
|
||||
public:
|
||||
|
||||
Coro::Task<Step> resume(LaunchResult lr) final
|
||||
{
|
||||
if (lr.kind == LaunchResult::Kind::Failure) {
|
||||
if constexpr (std::is_void_v<Fail>) {
|
||||
co_return co_await on_failure(std::monostate{});
|
||||
} else {
|
||||
co_return co_await on_failure(
|
||||
std::any_cast<Fail>(std::move(lr.failure)));
|
||||
}
|
||||
}
|
||||
if constexpr (std::is_void_v<Succ>) {
|
||||
co_return co_await on_success(std::monostate{});
|
||||
} else {
|
||||
co_return co_await on_success(
|
||||
std::any_cast<Succ>(std::move(lr.value)));
|
||||
}
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() override
|
||||
{
|
||||
co_return Step::fault(FsmError{
|
||||
"continuation state entered without a sub-machine result "
|
||||
"(reach it via startMachine<Sub, This>())"});
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
virtual Coro::Task<Step> on_success(SuccArg result) = 0;
|
||||
|
||||
/// Default: a sub-machine failure the parent didn't handle becomes
|
||||
/// a system fault. Override to recover.
|
||||
virtual Coro::Task<Step> on_failure(FailArg /*error*/)
|
||||
{
|
||||
co_return Step::fault(
|
||||
FsmError{"unhandled sub-machine failure"});
|
||||
}
|
||||
};
|
||||
} // namespace Void::Fsm::Detail
|
||||
@@ -26,39 +26,21 @@
|
||||
|
||||
namespace Void::Fsm::Detail
|
||||
{
|
||||
/// How the engine drives a state.
|
||||
enum class StateKind {
|
||||
Imperative, // defines run() returning a Step
|
||||
Reactive // defines a transition table (Phase B)
|
||||
};
|
||||
|
||||
/// Type-erased state. Concrete states derive Machine<Derived,R>::State
|
||||
/// (or ::Reactive); the engine drives the lifecycle: on_enter → run →
|
||||
/// on_exit, following the Step that run() returns.
|
||||
/// Type-erased state. Concrete states derive the single Machine<Derived>::
|
||||
/// State base; the engine drives each via a signature-inferred per-state
|
||||
/// thunk (entry / reactive table / continuation handlers).
|
||||
class StateBase
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~StateBase() = default;
|
||||
|
||||
[[nodiscard]] virtual StateKind kind() const noexcept
|
||||
{
|
||||
return StateKind::Imperative;
|
||||
}
|
||||
|
||||
/// Entry/exit hooks. Default no-ops; states may override either
|
||||
/// or both to split behaviour out of run().
|
||||
/// Optional entry/exit lifecycle hooks (default no-ops). The
|
||||
/// state's behaviour (entry / reactive table / continuation
|
||||
/// handlers) is discovered by signature via a per-state driver
|
||||
/// thunk — there is no virtual run().
|
||||
virtual Coro::Task<void> on_enter();
|
||||
virtual Coro::Task<void> on_exit();
|
||||
|
||||
/// Main body. Default fails (a state must define run() unless it
|
||||
/// is reactive, in which case the engine uses its table).
|
||||
virtual Coro::Task<Step> run();
|
||||
|
||||
/// Entered carrying a sub-machine result (from
|
||||
/// startMachine<Sub, This>()). Default ignores it and runs run();
|
||||
/// Continue<R> states override to dispatch on_success / on_failure.
|
||||
virtual Coro::Task<Step> resume(LaunchResult result);
|
||||
};
|
||||
|
||||
struct EventEnvelope {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <optional>
|
||||
#include <type_traits>
|
||||
#include <typeinfo>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#endif
|
||||
|
||||
// Signature-inferred state roles. There is ONE state base (`State`); the engine
|
||||
// discovers what each state does purely from its member signatures via P2996 —
|
||||
// no `override`, no framework-mandated names:
|
||||
// - entry : a member returning Step / Coro::Task<Step>, no params
|
||||
// - startup-entry: the same taking the sub-machine's startup-data argument
|
||||
// - reactive : a member taking TransitionBuilder<D>&
|
||||
// - result handlers (continuation): members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the boxes below)
|
||||
// All discovery is invocability-based (types known at the generation site), so
|
||||
// no parameter-type reflection (P3096) is required.
|
||||
|
||||
namespace Void::Fsm
|
||||
{
|
||||
// Defined in Machine.hpp; forward-declared so InitialStateOf can pattern
|
||||
// match the state list.
|
||||
template <typename...> struct States;
|
||||
|
||||
/// The success value of a launched sub-machine, handed to a continuation
|
||||
/// handler written `ok(ChildSuccess auto s)` — `s.value` is the sub's
|
||||
/// typed Success (absent for a void-result sub).
|
||||
template <typename T> struct ChildSuccessBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildSuccessBox<void> {
|
||||
};
|
||||
|
||||
/// The failure value of a launched sub-machine (`no(ChildFailure auto f)`;
|
||||
/// `f.value` is the sub's typed Failure, absent for void).
|
||||
template <typename T> struct ChildFailureBox {
|
||||
T value;
|
||||
};
|
||||
template <> struct ChildFailureBox<void> {
|
||||
};
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <class> inline constexpr bool is_csucc = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_csucc<ChildSuccessBox<T>> = true;
|
||||
template <class> inline constexpr bool is_cfail = false;
|
||||
template <class T>
|
||||
inline constexpr bool is_cfail<ChildFailureBox<T>> = true;
|
||||
} // namespace Detail
|
||||
|
||||
template <class X>
|
||||
concept ChildSuccess = Detail::is_csucc<std::remove_cvref_t<X>>;
|
||||
template <class X>
|
||||
concept ChildFailure = Detail::is_cfail<std::remove_cvref_t<X>>;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
namespace meta = std::meta;
|
||||
|
||||
/// The owning machine type of a state S (via State::self()).
|
||||
template <typename S>
|
||||
using MachineOf =
|
||||
std::remove_cvref_t<decltype(std::declval<S&>().self())>;
|
||||
|
||||
template <typename> struct first_state_helper;
|
||||
template <typename F, typename... R>
|
||||
struct first_state_helper<States<F, R...>> {
|
||||
using type = F;
|
||||
};
|
||||
|
||||
/// A machine's initial state type: its nested `Initial` if declared,
|
||||
/// else the first entry of `States<...>`.
|
||||
template <typename M> consteval auto initial_state_probe()
|
||||
{
|
||||
if constexpr (requires { typename M::Initial; }) {
|
||||
return std::type_identity<typename M::Initial>{};
|
||||
} else {
|
||||
return std::type_identity<
|
||||
typename first_state_helper<typename M::States>::type>{};
|
||||
}
|
||||
}
|
||||
template <typename M>
|
||||
using InitialStateOf =
|
||||
typename decltype(initial_state_probe<M>())::type;
|
||||
|
||||
/// Wrap a ready Step in a Task. (The reflection selectors below must
|
||||
/// NOT be coroutines — `template for` + member splicing fails inside a
|
||||
/// coroutine body in this build — so they return a Task instead.)
|
||||
inline Coro::Task<Step> ready_task(Step s) { co_return s; }
|
||||
|
||||
// ── entry (0-arg member returning Step / Task<Step>) ──────────────
|
||||
template <typename S> Coro::Task<Step> invoke_entry(S& s)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x) { x.[:m:](); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:]());
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:]());
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:]();
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(FsmError{
|
||||
"state has no entry (a no-arg method returning Step)"}));
|
||||
}
|
||||
|
||||
// ── startup-entry (member taking the startup-data argument[s]) ────
|
||||
template <typename S, typename... DataT>
|
||||
Coro::Task<Step> invoke_startup(S& s, DataT... data)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, DataT... d) { x.[:m:](d...); }) {
|
||||
using R = decltype(std::declval<S&>().[:m:](
|
||||
std::declval<DataT>()...));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:](std::move(data)...));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:](std::move(data)...);
|
||||
}
|
||||
}
|
||||
}
|
||||
// No data-taking entry: fall back to the plain entry.
|
||||
return invoke_entry(s);
|
||||
}
|
||||
|
||||
// ── continuation handler (member taking a ChildSuccess/Failure box)
|
||||
template <typename S, typename Box>
|
||||
Coro::Task<Step> invoke_handler(S& s, Box box)
|
||||
{
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, Box b) { x.[:m:](b); }) {
|
||||
using R =
|
||||
decltype(std::declval<S&>().[:m:](std::declval<Box>()));
|
||||
if constexpr (std::is_same_v<R, Step>) {
|
||||
return ready_task(s.[:m:](std::move(box)));
|
||||
} else if constexpr (std::is_same_v<R, Coro::Task<Step>>) {
|
||||
return s.[:m:](std::move(box));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ready_task(Step::fault(
|
||||
FsmError{"continuation has no handler for this sub-machine "
|
||||
"result (ChildSuccess auto / ChildFailure auto)"}));
|
||||
}
|
||||
|
||||
/// Dispatch a sub-machine's LaunchResult into the Next state's
|
||||
/// signature-matched handler. Knows Next and Sub (so the box types are
|
||||
/// concrete); built at the startMachine call site.
|
||||
template <typename Next, typename Sub>
|
||||
Coro::Task<Step> dispatch_result(Next& s, LaunchResult lr)
|
||||
{
|
||||
using Succ = SuccessOf<Sub>;
|
||||
using Fail = FailureOf<Sub>;
|
||||
if (lr.kind == LaunchResult::Kind::Failure) {
|
||||
ChildFailureBox<Fail> box;
|
||||
if constexpr (!std::is_void_v<Fail>) {
|
||||
box.value = std::any_cast<Fail>(std::move(lr.failure));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
}
|
||||
ChildSuccessBox<Succ> box;
|
||||
if constexpr (!std::is_void_v<Succ>) {
|
||||
box.value = std::any_cast<Succ>(std::move(lr.value));
|
||||
}
|
||||
return invoke_handler(s, std::move(box));
|
||||
}
|
||||
|
||||
// ── reactive (member taking TransitionBuilder<D>&) ────────────────
|
||||
template <typename S> consteval bool has_transitions()
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
bool found = false;
|
||||
template for (constexpr auto m :
|
||||
std::define_static_array(meta::members_of(
|
||||
^^S, meta::access_context::current())))
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// Fill `table` from S's transitions-shaped member (if any).
|
||||
template <typename S, typename D>
|
||||
void collect_transitions(S& s, TransitionTable<D>& table)
|
||||
{
|
||||
TransitionBuilder<D> builder{table};
|
||||
static constexpr auto members = std::define_static_array(
|
||||
meta::members_of(^^S, meta::access_context::current()));
|
||||
template for (constexpr auto m : members)
|
||||
{
|
||||
if constexpr (requires(S& x, TransitionBuilder<D>& b) {
|
||||
x.[:m:](b);
|
||||
}) {
|
||||
s.[:m:](builder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reactive drive loop (relocated from the old Reactive::run()):
|
||||
/// wait for a declared event or the timeout, check guards in order, run
|
||||
/// the action, transition.
|
||||
template <typename S> Coro::Task<Step> drive_reactive(S& s)
|
||||
{
|
||||
using D = MachineOf<S>;
|
||||
TransitionTable<D> table;
|
||||
collect_transitions(s, table);
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size());
|
||||
for (const auto& e : table.events) {
|
||||
types.push_back(e.type);
|
||||
}
|
||||
for (;;) {
|
||||
std::optional<std::chrono::steady_clock::time_point> deadline;
|
||||
if (table.has_timeout) {
|
||||
deadline =
|
||||
std::chrono::steady_clock::now() + table.timeout_after;
|
||||
}
|
||||
auto ev = co_await s.machine().await_any_event(types, deadline);
|
||||
if (!ev) {
|
||||
co_return std::move(table.timeout_step);
|
||||
}
|
||||
D& d = s.self();
|
||||
for (auto& e : table.events) {
|
||||
if (*e.type != *ev->type) {
|
||||
continue;
|
||||
}
|
||||
if (e.guard && !e.guard(d, ev->value)) {
|
||||
continue;
|
||||
}
|
||||
if (e.action) {
|
||||
co_await e.action(d, ev->value);
|
||||
}
|
||||
co_return std::move(e.step);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-state driver thunk built at registration (S is complete):
|
||||
/// reactive states run the table, others run the entry.
|
||||
template <typename S>
|
||||
[[nodiscard]] std::function<Coro::Task<Step>(StateBase&)> make_driver()
|
||||
{
|
||||
return [](StateBase& base) -> Coro::Task<Step> {
|
||||
S& s = static_cast<S&>(base);
|
||||
if constexpr (has_transitions<S>()) {
|
||||
co_return co_await drive_reactive(s);
|
||||
} else {
|
||||
co_return co_await invoke_entry(s);
|
||||
}
|
||||
};
|
||||
}
|
||||
} // namespace Detail
|
||||
} // namespace Void::Fsm
|
||||
+120
-134
@@ -4,11 +4,11 @@
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Fsm/Detail/Awaiter.hpp>
|
||||
#include <Void/Fsm/Detail/Continuation.hpp>
|
||||
#include <Void/Fsm/Detail/Engine.hpp>
|
||||
#include <Void/Fsm/Detail/Introspect.hpp>
|
||||
#include <Void/Fsm/Detail/Reactive.hpp>
|
||||
#include <Void/Fsm/Detail/Result.hpp>
|
||||
#include <Void/Fsm/Detail/Roles.hpp>
|
||||
#include <Void/Fsm/Detail/TypeName.hpp>
|
||||
#include <Void/Fsm/Step.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
@@ -70,21 +70,23 @@ namespace Void::Fsm
|
||||
std::uint64_t step{0};
|
||||
};
|
||||
|
||||
// ── Machine<Derived, ResultT> ─────────────────────────────────────────
|
||||
// ── Machine<Derived> ──────────────────────────────────────────────────
|
||||
//
|
||||
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive
|
||||
// it, declare states as nested structs deriving `State`, list them in
|
||||
// `using States = Fsm::States<...>`, and implement each state's async
|
||||
// run() to return next<S>() / succeed(...) / fail(...). States reach
|
||||
// their owning machine (and its data + sub-methods) via self().
|
||||
// Inheritance + coroutine workflow FSM, CRTP for typed access. Derive it,
|
||||
// declare states as nested structs deriving the single `State`, list them
|
||||
// in `using States = Fsm::States<...>`. The engine infers each state's role
|
||||
// from member signatures (entry / reactive table / continuation handlers);
|
||||
// states reach their machine (data + sub-methods) via self(). Result types
|
||||
// are the nested `Success`/`Failure` (default void).
|
||||
//
|
||||
// class Login : public Void::Fsm::Machine<Login, bool> {
|
||||
// class Login : public Void::Fsm::Machine<Login> {
|
||||
// public:
|
||||
// using Success = Token;
|
||||
// int attempts = 0;
|
||||
// struct Check : State {
|
||||
// Coro::Task<Step> run() override {
|
||||
// if (++self().attempts > 3) co_return fail("locked");
|
||||
// co_return self().service<IAuth>().ok() ? succeed(true)
|
||||
// struct Check : State { // entry by signature
|
||||
// Coro::Task<Step> run() {
|
||||
// if (++self().attempts > 3) co_return fail();
|
||||
// co_return self().service<IAuth>().ok() ? succeed(Token{})
|
||||
// : next<Check>();
|
||||
// }
|
||||
// };
|
||||
@@ -282,19 +284,16 @@ namespace Void::Fsm
|
||||
return m_machine->template await_any<Es...>();
|
||||
}
|
||||
|
||||
/// Launch a sub-machine `Sub` (constructed from `args`,
|
||||
/// sharing this machine's executor/events/services), then
|
||||
/// transition to `Next` — which must derive
|
||||
/// Continue<Sub::result_type>. When Sub finishes the engine
|
||||
/// calls Next's on_success(result) or on_failure(error):
|
||||
/// co_return startMachine<Login, AfterLogin>(user, 3);
|
||||
/// Launch a sub-machine `Sub` (startup data routed to its
|
||||
/// initial-state startup-entry; shares this machine's
|
||||
/// executor/events/services), then transition to `Next`.
|
||||
/// When Sub finishes the engine calls Next's signature
|
||||
/// -matched handler — a member taking `ChildSuccess auto`
|
||||
/// (Sub succeeded) or `ChildFailure auto` (Sub failed):
|
||||
/// co_return startMachine<Login, AfterLogin>(seed);
|
||||
template <typename Sub, typename Next, typename... Args>
|
||||
[[nodiscard]] Step startMachine(Args&&... args) const
|
||||
{
|
||||
static_assert(
|
||||
std::is_base_of_v<Continue<Sub>, Next>,
|
||||
"startMachine<Sub, Next>: Next must derive "
|
||||
"Continue<Sub>");
|
||||
return m_machine->template start_machine<Sub, Next>(
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
@@ -310,106 +309,33 @@ namespace Void::Fsm
|
||||
Machine* m_machine{nullptr};
|
||||
};
|
||||
|
||||
// ── continuation states ───────────────────────────────────────
|
||||
// ── one State, signature-inferred roles ───────────────────────
|
||||
//
|
||||
// A state that resumes from a launched sub-machine. Reach it with
|
||||
// `co_return startMachine<Sub, Next>(args...)`; the engine runs Sub
|
||||
// then enters Next, dispatching to on_success / on_failure by the
|
||||
// outcome:
|
||||
// There is a single base, `State`. The engine infers what each
|
||||
// state does from member signatures (no `override`, no fixed
|
||||
// names):
|
||||
// - entry : a member returning Step/Coro::Task<Step>,
|
||||
// no params (a startup-data overload may take
|
||||
// the sub's startup argument);
|
||||
// - reactive : a member taking `TransitionBuilder&` (the
|
||||
// declarative table below);
|
||||
// - continuation : members taking `ChildSuccess auto` /
|
||||
// `ChildFailure auto` (the sub's typed result
|
||||
// after `startMachine<Sub, This>()`).
|
||||
//
|
||||
// struct AfterLogin : Continue<bool> { // Sub =
|
||||
// Machine<..,bool>
|
||||
// Coro::Task<Step> on_success(bool ok) override {
|
||||
// co_return ok ? next<Home>() : next<Locked>(); }
|
||||
// Coro::Task<Step> on_failure(FsmError e) override {
|
||||
// co_return fail(e.message); }
|
||||
// };
|
||||
template <typename Sub>
|
||||
using Continue = Detail::Continuation<State, Sub>;
|
||||
|
||||
// ── reactive (declarative) states ─────────────────────────────
|
||||
// struct Idle : State { // reactive
|
||||
// void transitions(TransitionBuilder& on) {
|
||||
// on.event<Go>().to<Running>();
|
||||
// on.after(5s).to<TimedOut>(); } };
|
||||
// struct After : State { // continuation
|
||||
// Coro::Task<Step> ok(ChildSuccess auto s){ ... }
|
||||
// Coro::Task<Step> no(ChildFailure auto f){ ... } };
|
||||
//
|
||||
// A reactive state declares a transition table instead of an
|
||||
// imperative run(): it waits for the declared events (or a
|
||||
// timeout), checks guards in order, runs actions, and
|
||||
// transitions. Mix freely with imperative State subclasses.
|
||||
//
|
||||
// struct Idle : Reactive {
|
||||
// void transitions(TransitionBuilder& on) override {
|
||||
// on.event<Go>().guard([](Idle& s, const Go& g){...})
|
||||
// .action([](Idle& s, const Go&){...})
|
||||
// .to<Running>();
|
||||
// on.event<Stop>().to<Done>();
|
||||
// on.after(5s).to<TimedOut>();
|
||||
// }
|
||||
// };
|
||||
|
||||
// The declarative transition DSL lives in Detail/Reactive.hpp;
|
||||
// these aliases give reactive states the ergonomic nested names.
|
||||
// The declarative DSL lives in Detail/Reactive.hpp; these aliases
|
||||
// give the `transitions(TransitionBuilder&)` member its type.
|
||||
using TransitionTable = Detail::TransitionTable<Derived>;
|
||||
using TransitionBuilder = Detail::TransitionBuilder<Derived>;
|
||||
|
||||
class Reactive : public State
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] Detail::StateKind
|
||||
kind() const noexcept override
|
||||
{
|
||||
return Detail::StateKind::Reactive;
|
||||
}
|
||||
|
||||
/// Declare this state's event/timeout transitions.
|
||||
virtual void transitions(TransitionBuilder& on) = 0;
|
||||
|
||||
/// Build this state's table without running it — used by
|
||||
/// describe()/to_mermaid() for introspection.
|
||||
void collect(TransitionTable& table)
|
||||
{
|
||||
TransitionBuilder builder{table};
|
||||
transitions(builder);
|
||||
}
|
||||
|
||||
Coro::Task<Step> run() final
|
||||
{
|
||||
TransitionTable table;
|
||||
collect(table);
|
||||
std::vector<const std::type_info*> types;
|
||||
types.reserve(table.events.size());
|
||||
for (const auto& e : table.events) {
|
||||
types.push_back(e.type);
|
||||
}
|
||||
for (;;) {
|
||||
std::optional<std::chrono::steady_clock::time_point>
|
||||
deadline;
|
||||
if (table.has_timeout) {
|
||||
deadline = std::chrono::steady_clock::now() +
|
||||
table.timeout_after;
|
||||
}
|
||||
auto ev = co_await this->machine().await_any_event(
|
||||
types, deadline);
|
||||
if (!ev) {
|
||||
co_return std::move(table.timeout_step);
|
||||
}
|
||||
Derived& d = this->self();
|
||||
bool matched = false;
|
||||
for (auto& e : table.events) {
|
||||
if (*e.type != *ev->type) {
|
||||
continue;
|
||||
}
|
||||
if (e.guard && !e.guard(d, ev->value)) {
|
||||
continue;
|
||||
}
|
||||
if (e.action) {
|
||||
co_await e.action(d, ev->value);
|
||||
}
|
||||
co_return std::move(e.step);
|
||||
}
|
||||
(void)matched; // unmatched event is dropped
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── construction ──────────────────────────────────────────────
|
||||
explicit Machine(Options options = {}) : m_options(options)
|
||||
{
|
||||
@@ -448,6 +374,20 @@ namespace Void::Fsm
|
||||
s->m_machine = this;
|
||||
return s;
|
||||
});
|
||||
// Signature-inferred driver thunk (entry or reactive table).
|
||||
m_drivers.emplace(key, Detail::make_driver<S>());
|
||||
// describe() collector: fills a table if S is reactive.
|
||||
m_collectors.emplace(
|
||||
key,
|
||||
[](Detail::StateBase& base,
|
||||
TransitionTable& table) -> bool {
|
||||
if constexpr (Detail::has_transitions<S>()) {
|
||||
Detail::collect_transitions(static_cast<S&>(base),
|
||||
table);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename S> void initial()
|
||||
@@ -495,6 +435,8 @@ namespace Void::Fsm
|
||||
m_name_to_type.erase(m_names[static_cast<std::size_t>(idx)]);
|
||||
m_names.erase(m_names.begin() + idx);
|
||||
m_factories.erase(key);
|
||||
m_drivers.erase(key);
|
||||
m_collectors.erase(key);
|
||||
m_index.erase(idxIt);
|
||||
// Re-pack the indices of states that followed S.
|
||||
for (auto& [k, v] : m_index) {
|
||||
@@ -838,14 +780,24 @@ namespace Void::Fsm
|
||||
Derived::States::template contains<Next>(),
|
||||
"startMachine<Sub, Next>: Next is not in States<...>");
|
||||
}
|
||||
using Init = Detail::InitialStateOf<Sub>;
|
||||
auto launcher =
|
||||
[this,
|
||||
tup = std::make_tuple(std::forward<Args>(
|
||||
args)...)]() mutable -> Coro::Task<LaunchResult> {
|
||||
// Run Sub on the shared executor and read its raw result so
|
||||
// Success / Failure / Fault are all distinguishable.
|
||||
Sub child = std::make_from_tuple<Sub>(std::move(tup));
|
||||
[this, ... data = std::forward<Args>(
|
||||
args)]() mutable -> Coro::Task<LaunchResult> {
|
||||
// Run Sub on the shared executor. Startup data (if any) is
|
||||
// delivered to Sub's initial-state startup-entry via an
|
||||
// injector, not the constructor.
|
||||
Sub child;
|
||||
child.attach(m_ctx, m_services);
|
||||
if constexpr (sizeof...(Args) > 0) {
|
||||
child.m_startup_injector =
|
||||
[... d = std::move(data)](
|
||||
Detail::StateBase& base) mutable
|
||||
-> Coro::Task<Step> {
|
||||
return Detail::invoke_startup<Init>(
|
||||
static_cast<Init&>(base), std::move(d)...);
|
||||
};
|
||||
}
|
||||
co_await child.drive();
|
||||
LaunchResult lr;
|
||||
switch (child.m_status.load(std::memory_order_acquire)) {
|
||||
@@ -865,7 +817,14 @@ namespace Void::Fsm
|
||||
}
|
||||
co_return lr;
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher));
|
||||
Step::Dispatch dispatch =
|
||||
[](Detail::StateBase& base,
|
||||
LaunchResult lr) -> Coro::Task<Step> {
|
||||
return Detail::dispatch_result<Next, Sub>(
|
||||
static_cast<Next&>(base), std::move(lr));
|
||||
};
|
||||
return Step::launch(typeid(Next), std::move(launcher),
|
||||
std::move(dispatch));
|
||||
}
|
||||
|
||||
// ── observation ───────────────────────────────────────────────
|
||||
@@ -924,11 +883,11 @@ namespace Void::Fsm
|
||||
si.name = name;
|
||||
si.initial = (name == initial_name);
|
||||
const auto* ti = m_name_to_type.at(name);
|
||||
auto state = m_factories.at(std::type_index{*ti})();
|
||||
si.reactive = state->kind() == Detail::StateKind::Reactive;
|
||||
if (auto* reactive = dynamic_cast<Reactive*>(state.get())) {
|
||||
TransitionTable table;
|
||||
reactive->collect(table);
|
||||
const std::type_index key{*ti};
|
||||
auto state = m_factories.at(key)();
|
||||
TransitionTable table;
|
||||
si.reactive = m_collectors.at(key)(*state, table);
|
||||
if (si.reactive) {
|
||||
for (const auto& e : table.events) {
|
||||
si.edges.push_back(
|
||||
EdgeInfo{e.event_name, e.target_name,
|
||||
@@ -1102,6 +1061,7 @@ namespace Void::Fsm
|
||||
fault("no initial state");
|
||||
co_return;
|
||||
}
|
||||
bool first = true;
|
||||
for (;;) {
|
||||
// Apply an external jump<S>() at this transition boundary.
|
||||
if (const auto* j =
|
||||
@@ -1109,6 +1069,7 @@ namespace Void::Fsm
|
||||
j != nullptr) {
|
||||
cur = j;
|
||||
m_pending_result.reset();
|
||||
m_pending_dispatch = nullptr;
|
||||
}
|
||||
const auto it = m_factories.find(std::type_index{*cur});
|
||||
if (it == m_factories.end()) {
|
||||
@@ -1118,20 +1079,29 @@ namespace Void::Fsm
|
||||
set_current(cur);
|
||||
auto state = it->second();
|
||||
co_await state->on_enter();
|
||||
// A state entered via startMachine resumes from the sub's
|
||||
// result; otherwise it runs.
|
||||
// Decide how the state runs: a launched sub's result (via
|
||||
// the bound dispatcher), the startup injector for the first
|
||||
// state, or the signature-inferred driver thunk.
|
||||
Step step;
|
||||
if (m_pending_result.has_value()) {
|
||||
if (m_pending_dispatch) {
|
||||
LaunchResult pending = std::move(*m_pending_result);
|
||||
auto dispatch = std::move(m_pending_dispatch);
|
||||
m_pending_result.reset();
|
||||
m_pending_dispatch = nullptr;
|
||||
if (pending.kind == LaunchResult::Kind::Fault) {
|
||||
fault(std::move(pending.fault.message));
|
||||
co_return;
|
||||
}
|
||||
step = co_await state->resume(std::move(pending));
|
||||
step = co_await dispatch(*state, std::move(pending));
|
||||
} else if (first && m_startup_injector) {
|
||||
auto inject = std::move(m_startup_injector);
|
||||
m_startup_injector = nullptr;
|
||||
step = co_await inject(*state);
|
||||
} else {
|
||||
step = co_await state->run();
|
||||
step = co_await m_drivers.at(std::type_index{*cur})(
|
||||
*state);
|
||||
}
|
||||
first = false;
|
||||
co_await state->on_exit();
|
||||
fire_after(current_state());
|
||||
switch (step.kind()) {
|
||||
@@ -1141,6 +1111,7 @@ namespace Void::Fsm
|
||||
case Step::Kind::Launch:
|
||||
m_pending_result.emplace(
|
||||
co_await step.run_launch());
|
||||
m_pending_dispatch = step.take_dispatch();
|
||||
cur = step.target();
|
||||
continue;
|
||||
case Step::Kind::Success:
|
||||
@@ -1214,6 +1185,15 @@ namespace Void::Fsm
|
||||
std::type_index,
|
||||
std::function<std::unique_ptr<Detail::StateBase>()>>
|
||||
m_factories;
|
||||
// Per-state signature-inferred driver thunk (entry / reactive).
|
||||
std::unordered_map<std::type_index, std::function<Coro::Task<Step>(
|
||||
Detail::StateBase&)>>
|
||||
m_drivers;
|
||||
// Per-state describe() collector (reactive table, if any).
|
||||
std::unordered_map<
|
||||
std::type_index,
|
||||
std::function<bool(Detail::StateBase&, TransitionTable&)>>
|
||||
m_collectors;
|
||||
std::unordered_map<std::type_index, int> m_index;
|
||||
std::vector<std::string> m_names;
|
||||
std::unordered_map<std::string, const std::type_info*>
|
||||
@@ -1235,8 +1215,14 @@ namespace Void::Fsm
|
||||
std::function<std::vector<std::string>()> m_region_probe;
|
||||
|
||||
// Set by a Launch step's sub-machine result; consumed by the next
|
||||
// state's resume() (a Continue<R> dispatch).
|
||||
// state via the bound dispatcher below.
|
||||
std::optional<LaunchResult> m_pending_result;
|
||||
Step::Dispatch m_pending_dispatch;
|
||||
|
||||
// Seeds the initial state's startup-entry with launch data (set by
|
||||
// the parent's launcher before driving this machine).
|
||||
std::function<Coro::Task<Step>(Detail::StateBase&)>
|
||||
m_startup_injector;
|
||||
|
||||
// External jump request (jump<S>()); applied by drive() at the
|
||||
// next transition boundary.
|
||||
|
||||
@@ -12,6 +12,11 @@ namespace Void::Fsm
|
||||
{
|
||||
namespace Coro = Void::Coro;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
class StateBase;
|
||||
}
|
||||
|
||||
/// An engine/system fault — a programming error in the machine itself (no
|
||||
/// initial state, transition to an unregistered state, …). Distinct from a
|
||||
/// machine's typed `Failure` result: faults travel a separate channel
|
||||
@@ -65,16 +70,23 @@ namespace Void::Fsm
|
||||
return s;
|
||||
}
|
||||
|
||||
/// A bound dispatcher: given the entered Next state and the sub's
|
||||
/// LaunchResult, calls Next's signature-matched handler.
|
||||
using Dispatch = std::function<Coro::Task<Step>(Detail::StateBase&,
|
||||
LaunchResult)>;
|
||||
|
||||
/// Launch a sub-machine, then enter `target` (a continuation state)
|
||||
/// with the sub's LaunchResult.
|
||||
/// with the sub's LaunchResult, dispatched via `dispatch`.
|
||||
[[nodiscard]] static Step
|
||||
launch(const std::type_info& target,
|
||||
std::function<Coro::Task<LaunchResult>()> launcher)
|
||||
std::function<Coro::Task<LaunchResult>()> launcher,
|
||||
Dispatch dispatch)
|
||||
{
|
||||
Step s;
|
||||
s.m_kind = Kind::Launch;
|
||||
s.m_target = ⌖
|
||||
s.m_launcher = std::move(launcher);
|
||||
s.m_dispatch = std::move(dispatch);
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -112,12 +124,19 @@ namespace Void::Fsm
|
||||
return m_launcher();
|
||||
}
|
||||
|
||||
/// Take the bound dispatcher for a Launch step.
|
||||
[[nodiscard]] Dispatch take_dispatch()
|
||||
{
|
||||
return std::move(m_dispatch);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Kind m_kind{Kind::Fail};
|
||||
const std::type_info* m_target{nullptr};
|
||||
std::any m_payload;
|
||||
std::function<Coro::Task<LaunchResult>()> m_launcher;
|
||||
Dispatch m_dispatch;
|
||||
};
|
||||
|
||||
} // namespace Void::Fsm
|
||||
Reference in new issue
Block a user