From ec9e466d7a04446b9f70ff55742b2b15de9080ce Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 15 Jun 2026 01:20:56 +0300 Subject: [PATCH] FSM (4): one signature-inferred State (drops Reactive/Continue bases) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 run() { ... } Coro::Task run(Cfg c) { ... } // startup-entry (launch data) }; struct Idle : State { // reactive void transitions(TransitionBuilder& on) { on.event().to(); } }; struct After : State { // continuation Coro::Task ok(ChildSuccess auto s) { use s.value; } Coro::Task 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() a per-state driver thunk is stored (reactive table vs entry, by whether S has a TransitionBuilder& member); drive() calls it. startMachine(data) builds a Launch step carrying a launcher (injects data into Sub's initial startup-entry) + a dispatcher (dispatch_result) that builds the ChildSuccess/Failure box and calls Next's matching handler. - Removed Reactive/Continue 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 (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 --- CLAUDE.md | 11 +- include/Void/Fsm/Detail/Continuation.hpp | 76 ------ include/Void/Fsm/Detail/Engine.hpp | 32 +-- include/Void/Fsm/Detail/Roles.hpp | 283 ++++++++++++++++++++++ include/Void/Fsm/Machine.hpp | 254 +++++++++---------- include/Void/Fsm/Step.hpp | 23 +- src/Fsm/Engine.cpp | 14 +- tests/internal/FsmServiceHotReload.cpp | 2 +- tests/standalone/Fsm/Basic.cpp | 14 +- tests/standalone/Fsm/Concurrency.cpp | 4 +- tests/standalone/Fsm/Direct.cpp | 31 ++- tests/standalone/Fsm/Events.cpp | 2 +- tests/standalone/Fsm/Hierarchy.cpp | 6 +- tests/standalone/Fsm/Lifecycle.cpp | 4 +- tests/standalone/Fsm/Nesting.cpp | 10 +- tests/standalone/Fsm/Policies.cpp | 16 +- tests/standalone/Fsm/Reactive.cpp | 19 +- tests/standalone/Fsm/Serialize.cpp | 4 +- tests/standalone/Fsm/SubMachine.cpp | 85 +++---- tests/standalone/Service/Orchestrator.cpp | 4 +- 20 files changed, 536 insertions(+), 358 deletions(-) delete mode 100644 include/Void/Fsm/Detail/Continuation.hpp create mode 100644 include/Void/Fsm/Detail/Roles.hpp diff --git a/CLAUDE.md b/CLAUDE.md index 8a146fc..47684ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -147,11 +147,18 @@ Other key points: ### Fsm module (inheritance + coroutine workflow) -`Void::Fsm::Machine` (CRTP) — derive it; declare states as nested structs deriving `State`; each implements `Coro::Task run()` returning `next()` / `succeed(...)` / `fail(...)`. There is no statechart/event-graph; states drive themselves. +`Void::Fsm::Machine` (CRTP) — derive it; declare states as nested structs deriving the **single** base `State`. There is no statechart/event-graph; states drive themselves. + +**One `State`, signature-inferred roles.** There is one base class; the engine infers what each state does **purely from member signatures** via P2996 (`Detail/Roles.hpp`) — no `override`, no framework-mandated names: +- **entry** — a member returning `Step`/`Coro::Task` with no params (`Task run()`); a **startup-entry** overload takes the launch data (`Task run(Cfg)`), used when reached via `startMachine` (data routed there, not the constructor). +- **reactive** — a member taking `TransitionBuilder&` (`void transitions(TransitionBuilder& on)`); the engine runs its declared table. +- **continuation handlers** — two members distinguished by parameter type, `ok(ChildSuccess auto s)` / `no(ChildFailure auto f)` (`s.value`/`f.value` are the sub's typed Success/Failure); the engine picks by the launched sub's outcome. + +Mechanics: at `add()` a `Detail::make_driver()` reflection thunk is stored (reactive table vs entry, chosen by whether `S` has a `TransitionBuilder&` member); `drive()` calls the thunk. `startMachine(data…)` (knows `Sub`, `Next`, and the data types) builds a `Launch` step carrying a launcher (runs `Sub`, injecting `data` into its initial state's startup-entry) and a dispatcher (`Detail::dispatch_result`) that builds `ChildSuccessBox<…>`/`ChildFailureBox<…>` and calls `Next`'s matching handler. The reflection selectors must **not** be coroutines (`template for` + member splicing fails inside a coroutine body in this GCC build), so they `return` a `Task` (wrapping plain `Step` via `ready_task`). The discovery is invocability-based — **no parameter-type reflection (P3096)**. **Typed results.** A machine declares its result types as nested types *reflected by name* — `struct Success {…}` (or `using Success = int;`) and `struct Failure {…}`, each defaulting to `void`. `Outcome = std::expected` (a void failure becomes `std::monostate`); `succeed(Success{…})` / `fail(Failure{…})` carry them (nullary when void). Engine/system faults (no initial state, jump to an unregistered state, a state with no entry) are a **separate `FsmError` channel** — `status()==Faulted`, `system_error()` returns the `FsmError`, never the typed `Failure`. Because `Derived` is incomplete at CRTP base instantiation, the engine stores outcomes type-erased and rebuilds the typed `Outcome` in `wait()`/`run_blocking()` (function templates defaulted on `Derived`); `Detail::SuccessOf`/`FailureOf` resolve the nested types by plain name lookup (`Detail/Result.hpp`). -Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` template + `States<>`, nested `State`/`Reactive`/`Continue` bases, lifecycle, events, nesting, persistence); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable` templates, aliased by `Machine::Reactive`); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Continuation.hpp` (`Detail::Continuation` = `Continue`, with a `void` specialization); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase`); `Detail/TypeName.hpp` (`type_name()`). +Header layout (include `` — a thin umbrella): `Machine.hpp` (the `Machine` template + `States<>`, the single nested `State` base, lifecycle, events, nesting, persistence); `Detail/Roles.hpp` (the signature-inference: `ChildSuccess`/`ChildFailure` concepts + boxes, `invoke_entry`/`invoke_startup`/`invoke_handler`/`dispatch_result`/`make_driver`/`has_transitions`); `Detail/Result.hpp` (`SuccessOf`/`FailureOf`/`OutcomeOf`); `Detail/Reactive.hpp` (the declarative transition DSL as standalone `Detail::TransitionBuilder`/`EventClause`/`AfterClause`/`TransitionTable` templates); `Detail/Awaiter.hpp` (one `Detail::EventAwaiter` behind `make_event_awaiter`, used by all `await_*`); `Detail/Introspect.hpp` (`StateInfo`/`EdgeInfo` + `to_mermaid`); `Detail/Engine.{hpp,cpp}` (the non-template `ExecutionContext` + `StateBase` — only `on_enter`/`on_exit` remain virtual); `Detail/TypeName.hpp` (`type_name()`). - **Async by default**: a non-template `Detail::ExecutionContext` (`src/Fsm/Engine.cpp`) owns one `Async::ManualExecutor` + worker thread + a lock-free MPSC event queue + a typed event mailbox. A single consumer (worker, or the embedder via `pump()` when `MachineOptions{.own_worker=false}`) touches all mutable state, so state code is lock-free/single-threaded. `start()`/`run_blocking()`/`wait()` for worker mode; `pump()` for embedder mode (deterministic tests). - **Events**: `co_await await_event()` consumes the oldest queued `E` (typed mailbox), suspending until one arrives; `post(e)` is lock-free from any thread. diff --git a/include/Void/Fsm/Detail/Continuation.hpp b/include/Void/Fsm/Detail/Continuation.hpp deleted file mode 100644 index d46c385..0000000 --- a/include/Void/Fsm/Detail/Continuation.hpp +++ /dev/null @@ -1,76 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace Void::Fsm::Detail -{ - namespace Coro = Void::Coro; - - // Base for a state that resumes from a sub-machine launched via - // startMachine(). `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`. - // - // 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 class Continuation : public StateT - { - using Succ = SuccessOf; - using Fail = FailureOf; - using SuccArg = - std::conditional_t, std::monostate, Succ>; - using FailArg = - std::conditional_t, std::monostate, Fail>; - - public: - - Coro::Task resume(LaunchResult lr) final - { - if (lr.kind == LaunchResult::Kind::Failure) { - if constexpr (std::is_void_v) { - co_return co_await on_failure(std::monostate{}); - } else { - co_return co_await on_failure( - std::any_cast(std::move(lr.failure))); - } - } - if constexpr (std::is_void_v) { - co_return co_await on_success(std::monostate{}); - } else { - co_return co_await on_success( - std::any_cast(std::move(lr.value))); - } - } - - Coro::Task run() override - { - co_return Step::fault(FsmError{ - "continuation state entered without a sub-machine result " - "(reach it via startMachine())"}); - } - - protected: - - virtual Coro::Task 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 on_failure(FailArg /*error*/) - { - co_return Step::fault( - FsmError{"unhandled sub-machine failure"}); - } - }; -} // namespace Void::Fsm::Detail diff --git a/include/Void/Fsm/Detail/Engine.hpp b/include/Void/Fsm/Detail/Engine.hpp index 2e4b465..fed147c 100644 --- a/include/Void/Fsm/Detail/Engine.hpp +++ b/include/Void/Fsm/Detail/Engine.hpp @@ -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::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:: + /// 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 on_enter(); virtual Coro::Task 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 run(); - - /// Entered carrying a sub-machine result (from - /// startMachine()). Default ignores it and runs run(); - /// Continue states override to dispatch on_success / on_failure. - virtual Coro::Task resume(LaunchResult result); }; struct EventEnvelope { diff --git a/include/Void/Fsm/Detail/Roles.hpp b/include/Void/Fsm/Detail/Roles.hpp new file mode 100644 index 0000000..0e86439 --- /dev/null +++ b/include/Void/Fsm/Detail/Roles.hpp @@ -0,0 +1,283 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#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, no params +// - startup-entry: the same taking the sub-machine's startup-data argument +// - reactive : a member taking TransitionBuilder& +// - 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 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 struct ChildSuccessBox { + T value; + }; + template <> struct ChildSuccessBox { + }; + + /// The failure value of a launched sub-machine (`no(ChildFailure auto f)`; + /// `f.value` is the sub's typed Failure, absent for void). + template struct ChildFailureBox { + T value; + }; + template <> struct ChildFailureBox { + }; + + namespace Detail + { + template inline constexpr bool is_csucc = false; + template + inline constexpr bool is_csucc> = true; + template inline constexpr bool is_cfail = false; + template + inline constexpr bool is_cfail> = true; + } // namespace Detail + + template + concept ChildSuccess = Detail::is_csucc>; + template + concept ChildFailure = Detail::is_cfail>; + + namespace Detail + { + namespace Coro = Void::Coro; + namespace meta = std::meta; + + /// The owning machine type of a state S (via State::self()). + template + using MachineOf = + std::remove_cvref_t().self())>; + + template struct first_state_helper; + template + struct first_state_helper> { + using type = F; + }; + + /// A machine's initial state type: its nested `Initial` if declared, + /// else the first entry of `States<...>`. + template consteval auto initial_state_probe() + { + if constexpr (requires { typename M::Initial; }) { + return std::type_identity{}; + } else { + return std::type_identity< + typename first_state_helper::type>{}; + } + } + template + using InitialStateOf = + typename decltype(initial_state_probe())::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 ready_task(Step s) { co_return s; } + + // ── entry (0-arg member returning Step / Task) ────────────── + template Coro::Task 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().[:m:]()); + if constexpr (std::is_same_v) { + return ready_task(s.[:m:]()); + } else if constexpr (std::is_same_v>) { + 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 + Coro::Task 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().[:m:]( + std::declval()...)); + if constexpr (std::is_same_v) { + return ready_task(s.[:m:](std::move(data)...)); + } else if constexpr (std::is_same_v>) { + 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 + Coro::Task 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().[:m:](std::declval())); + if constexpr (std::is_same_v) { + return ready_task(s.[:m:](std::move(box))); + } else if constexpr (std::is_same_v>) { + 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 + Coro::Task dispatch_result(Next& s, LaunchResult lr) + { + using Succ = SuccessOf; + using Fail = FailureOf; + if (lr.kind == LaunchResult::Kind::Failure) { + ChildFailureBox box; + if constexpr (!std::is_void_v) { + box.value = std::any_cast(std::move(lr.failure)); + } + return invoke_handler(s, std::move(box)); + } + ChildSuccessBox box; + if constexpr (!std::is_void_v) { + box.value = std::any_cast(std::move(lr.value)); + } + return invoke_handler(s, std::move(box)); + } + + // ── reactive (member taking TransitionBuilder&) ──────────────── + template consteval bool has_transitions() + { + using D = MachineOf; + 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& b) { + x.[:m:](b); + }) { + found = true; + } + } + return found; + } + + /// Fill `table` from S's transitions-shaped member (if any). + template + void collect_transitions(S& s, TransitionTable& table) + { + TransitionBuilder 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& 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 Coro::Task drive_reactive(S& s) + { + using D = MachineOf; + TransitionTable table; + collect_transitions(s, table); + std::vector types; + types.reserve(table.events.size()); + for (const auto& e : table.events) { + types.push_back(e.type); + } + for (;;) { + std::optional 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 + [[nodiscard]] std::function(StateBase&)> make_driver() + { + return [](StateBase& base) -> Coro::Task { + S& s = static_cast(base); + if constexpr (has_transitions()) { + co_return co_await drive_reactive(s); + } else { + co_return co_await invoke_entry(s); + } + }; + } + } // namespace Detail +} // namespace Void::Fsm diff --git a/include/Void/Fsm/Machine.hpp b/include/Void/Fsm/Machine.hpp index f373316..180358a 100644 --- a/include/Void/Fsm/Machine.hpp +++ b/include/Void/Fsm/Machine.hpp @@ -4,11 +4,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -70,21 +70,23 @@ namespace Void::Fsm std::uint64_t step{0}; }; - // ── Machine ───────────────────────────────────────── + // ── Machine ────────────────────────────────────────────────── // - // 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() / 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 { + // class Login : public Void::Fsm::Machine { // public: + // using Success = Token; // int attempts = 0; - // struct Check : State { - // Coro::Task run() override { - // if (++self().attempts > 3) co_return fail("locked"); - // co_return self().service().ok() ? succeed(true) + // struct Check : State { // entry by signature + // Coro::Task run() { + // if (++self().attempts > 3) co_return fail(); + // co_return self().service().ok() ? succeed(Token{}) // : next(); // } // }; @@ -282,19 +284,16 @@ namespace Void::Fsm return m_machine->template await_any(); } - /// Launch a sub-machine `Sub` (constructed from `args`, - /// sharing this machine's executor/events/services), then - /// transition to `Next` — which must derive - /// Continue. When Sub finishes the engine - /// calls Next's on_success(result) or on_failure(error): - /// co_return startMachine(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(seed); template [[nodiscard]] Step startMachine(Args&&... args) const { - static_assert( - std::is_base_of_v, Next>, - "startMachine: Next must derive " - "Continue"); return m_machine->template start_machine( std::forward(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(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, + // 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()`). // - // struct AfterLogin : Continue { // Sub = - // Machine<..,bool> - // Coro::Task on_success(bool ok) override { - // co_return ok ? next() : next(); } - // Coro::Task on_failure(FsmError e) override { - // co_return fail(e.message); } - // }; - template - using Continue = Detail::Continuation; - - // ── reactive (declarative) states ───────────────────────────── + // struct Idle : State { // reactive + // void transitions(TransitionBuilder& on) { + // on.event().to(); + // on.after(5s).to(); } }; + // struct After : State { // continuation + // Coro::Task ok(ChildSuccess auto s){ ... } + // Coro::Task 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().guard([](Idle& s, const Go& g){...}) - // .action([](Idle& s, const Go&){...}) - // .to(); - // on.event().to(); - // on.after(5s).to(); - // } - // }; - - // 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; using TransitionBuilder = Detail::TransitionBuilder; - 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 run() final - { - TransitionTable table; - collect(table); - std::vector types; - types.reserve(table.events.size()); - for (const auto& e : table.events) { - types.push_back(e.type); - } - for (;;) { - std::optional - 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()); + // describe() collector: fills a table if S is reactive. + m_collectors.emplace( + key, + [](Detail::StateBase& base, + TransitionTable& table) -> bool { + if constexpr (Detail::has_transitions()) { + Detail::collect_transitions(static_cast(base), + table); + return true; + } + return false; + }); } template void initial() @@ -495,6 +435,8 @@ namespace Void::Fsm m_name_to_type.erase(m_names[static_cast(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(), "startMachine: Next is not in States<...>"); } + using Init = Detail::InitialStateOf; auto launcher = - [this, - tup = std::make_tuple(std::forward( - args)...)]() mutable -> Coro::Task { - // Run Sub on the shared executor and read its raw result so - // Success / Failure / Fault are all distinguishable. - Sub child = std::make_from_tuple(std::move(tup)); + [this, ... data = std::forward( + args)]() mutable -> Coro::Task { + // 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 { + return Detail::invoke_startup( + static_cast(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 { + return Detail::dispatch_result( + static_cast(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(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() 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()>> m_factories; + // Per-state signature-inferred driver thunk (entry / reactive). + std::unordered_map( + Detail::StateBase&)>> + m_drivers; + // Per-state describe() collector (reactive table, if any). + std::unordered_map< + std::type_index, + std::function> + m_collectors; std::unordered_map m_index; std::vector m_names; std::unordered_map @@ -1235,8 +1215,14 @@ namespace Void::Fsm std::function()> m_region_probe; // Set by a Launch step's sub-machine result; consumed by the next - // state's resume() (a Continue dispatch). + // state via the bound dispatcher below. std::optional 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(Detail::StateBase&)> + m_startup_injector; // External jump request (jump()); applied by drive() at the // next transition boundary. diff --git a/include/Void/Fsm/Step.hpp b/include/Void/Fsm/Step.hpp index 9b25764..52227b5 100644 --- a/include/Void/Fsm/Step.hpp +++ b/include/Void/Fsm/Step.hpp @@ -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(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()> launcher) + std::function()> 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()> m_launcher; + Dispatch m_dispatch; }; } // namespace Void::Fsm diff --git a/src/Fsm/Engine.cpp b/src/Fsm/Engine.cpp index 4d4d86b..d898a62 100644 --- a/src/Fsm/Engine.cpp +++ b/src/Fsm/Engine.cpp @@ -5,20 +5,10 @@ namespace Void::Fsm::Detail { - // Default state lifecycle hooks. + // Default state lifecycle hooks (no-ops). The state's behaviour is driven + // by a per-state, signature-inferred thunk built at registration. Coro::Task StateBase::on_enter() { co_return; } Coro::Task StateBase::on_exit() { co_return; } - Coro::Task StateBase::run() - { - co_return Step::fault(FsmError{"state defines no entry"}); - } - - Coro::Task StateBase::resume(LaunchResult /*result*/) - { - // A plain state entered with a pending sub-machine result just runs; - // Continue overrides this to dispatch on_success / on_failure. - co_return co_await run(); - } ExecutionContext::~ExecutionContext() { stop(); } diff --git a/tests/internal/FsmServiceHotReload.cpp b/tests/internal/FsmServiceHotReload.cpp index a692799..0de0471 100644 --- a/tests/internal/FsmServiceHotReload.cpp +++ b/tests/internal/FsmServiceHotReload.cpp @@ -44,7 +44,7 @@ namespace using Success = int; struct Work : State { - Task run() override + Task run() { auto& svc = service(); const int total = svc.accumulate(1); diff --git a/tests/standalone/Fsm/Basic.cpp b/tests/standalone/Fsm/Basic.cpp index b92e4fc..11e5f47 100644 --- a/tests/standalone/Fsm/Basic.cpp +++ b/tests/standalone/Fsm/Basic.cpp @@ -22,7 +22,7 @@ namespace std::vector* log = nullptr; struct Start : State { - Task run() override + Task run() { if (self().log) { self().log->push_back("start"); @@ -32,7 +32,7 @@ namespace }; struct Work : State { - Task run() override + Task run() { auto& m = self(); ++m.count; @@ -63,7 +63,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Boom : State { - Task run() override { co_return fail("kaboom"); } + Task run() { co_return fail("kaboom"); } }; using States = Void::Fsm::States; @@ -114,7 +114,7 @@ Void::Testing::Test fsm_void_result_succeeds() { struct Trivial : Void::Fsm::Machine { struct Done : State { - Task run() override { co_return succeed(); } + Task run() { co_return succeed(); } }; using States = Void::Fsm::States; Trivial() @@ -137,13 +137,13 @@ Void::Testing::Test fsm_dynamic_state_registration() bool express; struct Express : State { - Task run() override { co_return succeed(99); } + Task run() { co_return succeed(99); } }; struct Normal : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct Start : State { - Task run() override + Task run() { if (self().has_state()) { co_return next_dynamic(); diff --git a/tests/standalone/Fsm/Concurrency.cpp b/tests/standalone/Fsm/Concurrency.cpp index d007264..94434af 100644 --- a/tests/standalone/Fsm/Concurrency.cpp +++ b/tests/standalone/Fsm/Concurrency.cpp @@ -32,7 +32,7 @@ namespace long long target; struct Run : State { - Task run() override + Task run() { auto& m = self(); while (m.total < m.target) { @@ -138,7 +138,7 @@ Void::Testing::Test fsm_resolves_service_through_context() using Success = int; struct Go : State { - Task run() override + Task run() { co_return succeed(service().twice(21)); } diff --git a/tests/standalone/Fsm/Direct.cpp b/tests/standalone/Fsm/Direct.cpp index e0ab709..8925a16 100644 --- a/tests/standalone/Fsm/Direct.cpp +++ b/tests/standalone/Fsm/Direct.cpp @@ -29,7 +29,7 @@ namespace int total = 0; struct Take : State { - Task run() override + Task run() { auto a = co_await await_event(); self().total += a.n; @@ -64,13 +64,13 @@ namespace using Success = int; struct A : State { - Task run() override { co_return goto_state(); } + Task run() { co_return goto_state(); } }; struct B : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct C : State { - Task run() override { co_return succeed(3); } + Task run() { co_return succeed(3); } }; using States = Fsm::States; }; @@ -99,14 +99,14 @@ namespace using Success = int; struct Loop : State { - Task run() override + Task run() { co_await await_event(); co_return next(); } }; struct Done : State { - Task run() override { co_return succeed(99); } + Task run() { co_return succeed(99); } }; using States = Fsm::States; @@ -148,10 +148,7 @@ namespace int runs = 0; struct Once : State { - Task run() override - { - co_return succeed(++self().runs); - } + Task run() { co_return succeed(++self().runs); } }; using States = Fsm::States; }; @@ -177,10 +174,10 @@ namespace using Success = int; struct A : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct B : State { - Task run() override { co_return succeed(2); } + Task run() { co_return succeed(2); } }; using States = Fsm::States; // initial = A }; @@ -208,17 +205,17 @@ namespace using Success = int; struct A : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct B : State { - Task run() override { co_return succeed(2); } + Task run() { co_return succeed(2); } }; struct C : State { - Task run() override { co_return succeed(3); } + Task run() { co_return succeed(3); } }; // Not in States<> — added via replace<>. struct Extra : State { - Task run() override { co_return succeed(7); } + Task run() { co_return succeed(7); } }; using States = Fsm::States; }; @@ -261,7 +258,7 @@ namespace using Success = int; struct W : State { - Task run() override + Task run() { co_await await_event(); co_return succeed(5); diff --git a/tests/standalone/Fsm/Events.cpp b/tests/standalone/Fsm/Events.cpp index 76f2eff..70185f5 100644 --- a/tests/standalone/Fsm/Events.cpp +++ b/tests/standalone/Fsm/Events.cpp @@ -30,7 +30,7 @@ namespace std::vector* order = nullptr; struct Waiting : State { - Task run() override + Task run() { auto& m = self(); // Two typed mailboxes: pull whichever arrives. diff --git a/tests/standalone/Fsm/Hierarchy.cpp b/tests/standalone/Fsm/Hierarchy.cpp index ba7e107..71eac19 100644 --- a/tests/standalone/Fsm/Hierarchy.cpp +++ b/tests/standalone/Fsm/Hierarchy.cpp @@ -32,7 +32,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Waiting : State { - Task run() override + Task run() { auto ev = co_await await_any(); if (std::holds_alternative(ev)) { @@ -58,7 +58,7 @@ namespace using Success = std::string; struct Running : State { - Task run() override + Task run() { auto r = co_await run_region(); if (r.has_value()) { @@ -68,7 +68,7 @@ namespace } }; struct Aborted : State { - Task run() override + Task run() { co_return succeed(std::string{"aborted"}); } diff --git a/tests/standalone/Fsm/Lifecycle.cpp b/tests/standalone/Fsm/Lifecycle.cpp index 4f22177..d0a9921 100644 --- a/tests/standalone/Fsm/Lifecycle.cpp +++ b/tests/standalone/Fsm/Lifecycle.cpp @@ -27,7 +27,7 @@ namespace self().log.push_back("enter A"); co_return; } - Task run() override + Task run() { self().log.push_back("run A"); co_return next(); @@ -45,7 +45,7 @@ namespace self().log.push_back("enter B"); co_return; } - Task run() override + Task run() { self().log.push_back("run B"); co_return succeed(1); diff --git a/tests/standalone/Fsm/Nesting.cpp b/tests/standalone/Fsm/Nesting.cpp index a7b8e31..731326b 100644 --- a/tests/standalone/Fsm/Nesting.cpp +++ b/tests/standalone/Fsm/Nesting.cpp @@ -20,7 +20,7 @@ namespace int seed; struct Compute : State { - Task run() override + Task run() { auto& m = self(); co_return succeed(m.seed * 10); @@ -45,7 +45,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Boom : State { - Task run() override { co_return fail("child boom"); } + Task run() { co_return fail("child boom"); } }; FailingChild() : Void::Fsm::Machine( @@ -64,7 +64,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Start : State { - Task run() override + Task run() { auto a = co_await run_child(3); // 30 auto b = co_await run_child(4); // 40 @@ -91,7 +91,7 @@ namespace using Failure = Void::Fsm::FsmError; struct Start : State { - Task run() override + Task run() { auto r = co_await run_child(); if (!r.has_value()) { @@ -136,7 +136,7 @@ Void::Testing::Test fsm_nesting_with_worker_thread() using Success = int; struct Start : State { - Task run() override + Task run() { auto a = co_await run_child(5); // 50 co_return succeed(a.value_or(-1)); diff --git a/tests/standalone/Fsm/Policies.cpp b/tests/standalone/Fsm/Policies.cpp index 69b32a6..51439cb 100644 --- a/tests/standalone/Fsm/Policies.cpp +++ b/tests/standalone/Fsm/Policies.cpp @@ -31,7 +31,7 @@ namespace int retries; // how many tries with_retry gets struct Try : State { - Task run() override + Task run() { auto& m = self(); const bool ok = co_await with_retry( @@ -46,7 +46,7 @@ namespace }; struct Fallback : State { - Task run() override + Task run() { co_return succeed(std::string{"fallback"}); } @@ -92,10 +92,10 @@ namespace using Success = int; struct A : State { - Task run() override { co_return next(); } + Task run() { co_return next(); } }; struct B : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; using States = Void::Fsm::States; Pipe() @@ -155,8 +155,8 @@ namespace using Success = int; - struct Idle : Reactive { - void transitions(TransitionBuilder& on) override + struct Idle : State { + void transitions(TransitionBuilder& on) { on.event() .guard([](Flow&, const Go&) { return true; }) @@ -166,10 +166,10 @@ namespace } }; struct Active : State { - Task run() override { co_return next(); } + Task run() { co_return next(); } }; struct Done : State { - Task run() override { co_return succeed(0); } + Task run() { co_return succeed(0); } }; using States = Void::Fsm::States; Flow() {} diff --git a/tests/standalone/Fsm/Reactive.cpp b/tests/standalone/Fsm/Reactive.cpp index 34636df..014778e 100644 --- a/tests/standalone/Fsm/Reactive.cpp +++ b/tests/standalone/Fsm/Reactive.cpp @@ -32,8 +32,8 @@ namespace int total = 0; std::vector trace; - struct Idle : Reactive { - void transitions(TransitionBuilder& on) override + struct Idle : State { + void transitions(TransitionBuilder& on) { // Guarded: only positive amounts advance. on.event() @@ -52,10 +52,7 @@ namespace // Imperative terminal state: reports the accumulated total. struct Done : State { - Task run() override - { - co_return succeed(self().total); - } + Task run() { co_return succeed(self().total); } }; using States = Void::Fsm::States; @@ -97,7 +94,7 @@ namespace using Success = std::string; struct Waiting : State { - Task run() override + Task run() { auto w = co_await await_event_for(15ms); if (w.has_value()) { @@ -140,18 +137,18 @@ namespace using Success = int; - struct Pending : Reactive { - void transitions(TransitionBuilder& on) override + struct Pending : State { + void transitions(TransitionBuilder& on) { on.event().template to(); on.after(15ms).template to(); } }; struct Resolved : State { - Task run() override { co_return succeed(1); } + Task run() { co_return succeed(1); } }; struct Expired : State { - Task run() override { co_return succeed(2); } + Task run() { co_return succeed(2); } }; using States = Void::Fsm::States; Deadline() {} diff --git a/tests/standalone/Fsm/Serialize.cpp b/tests/standalone/Fsm/Serialize.cpp index efaa40e..84f77c1 100644 --- a/tests/standalone/Fsm/Serialize.cpp +++ b/tests/standalone/Fsm/Serialize.cpp @@ -26,14 +26,14 @@ namespace Data data; struct Ingest : State { - Task run() override + Task run() { co_await await_event(); // park here co_return next(); } }; struct Process : State { - Task run() override + Task run() { auto& m = self(); m.data.processed += 1; diff --git a/tests/standalone/Fsm/SubMachine.cpp b/tests/standalone/Fsm/SubMachine.cpp index 7e2aba3..6b23334 100644 --- a/tests/standalone/Fsm/SubMachine.cpp +++ b/tests/standalone/Fsm/SubMachine.cpp @@ -3,20 +3,25 @@ #include #include -#include using Void::Coro::Task; +using Void::Fsm::ChildFailure; +using Void::Fsm::ChildSuccess; using Void::Fsm::FsmError; using Void::Fsm::Step; namespace Fsm = Void::Fsm; -// startMachine(args...) launches a full sub-FSM on the parent's -// shared executor/events/services, then enters Next — a Continue -// state — and the engine dispatches to on_success / on_failure by the outcome. +// startMachine(data) launches a full sub-FSM on the parent's shared +// executor/events/services (startup data routed to Sub's initial-state +// startup-entry), then enters Next. The engine dispatches the sub's typed +// outcome to Next's signature-matched handler — a member taking +// `ChildSuccess auto` (success) or `ChildFailure auto` (failure). No override, +// no fixed names. namespace { - // Sub-machine seeded by constructor arg: doubles `seed`, fails if negative. + // Sub-machine seeded via its startup-entry (run(int)): doubles the seed, + // fails (typed FsmError) if negative. class Doubler : public Fsm::Machine { public: @@ -24,20 +29,16 @@ namespace using Success = int; using Failure = Void::Fsm::FsmError; - int seed; - struct Run : State { - Task run() override + Task run(int seed) { - if (self().seed < 0) { + if (seed < 0) { co_return fail("negative"); } - co_return succeed(self().seed * 2); + co_return succeed(seed * 2); } }; using States = Fsm::States; - - explicit Doubler(int s = 0) : seed(s) {} }; class Calc : public Fsm::Machine @@ -49,20 +50,20 @@ namespace int input = 0; struct Start : State { - Task run() override + Task run() { co_return startMachine( self().input); } }; - struct AfterDouble : Continue { - Task on_success(int v) override + struct AfterDouble : State { + Task ok(ChildSuccess auto s) { - co_return succeed("doubled:" + std::to_string(v)); + co_return succeed("doubled:" + std::to_string(s.value)); } - Task on_failure(FsmError e) override + Task no(ChildFailure auto f) { - co_return succeed("failed:" + e.message); + co_return succeed("failed:" + f.value.message); } }; using States = Fsm::States; @@ -98,7 +99,7 @@ namespace public: struct Ping : State { - Task run() override { co_return succeed(); } + Task run() { co_return succeed(); } }; using States = Fsm::States; }; @@ -110,23 +111,18 @@ namespace using Success = int; struct Go : State { - Task run() override - { - co_return startMachine(); - } + Task run() { co_return startMachine(); } }; - struct Done : Continue { - Task on_success(std::monostate) override - { - co_return succeed(42); - } + struct Done : State { + // void-result sub: ChildSuccess box has no value. + Task ok(ChildSuccess auto) { co_return succeed(42); } }; using States = Fsm::States; }; } // namespace // @tag integration -Void::Testing::Test submachine_void_result_calls_nullary_on_success() +Void::Testing::Test submachine_void_result_calls_success_handler() { Host fsm; const auto outcome = fsm.run_blocking(); @@ -134,7 +130,7 @@ Void::Testing::Test submachine_void_result_calls_nullary_on_success() Void::Testing::expect_eq(*outcome, 42); } -// ── chained startMachine (a Continue state launches another) ───────────────── +// ── chained startMachine (a continuation state launches another) ───────────── namespace { @@ -145,21 +141,21 @@ namespace using Success = int; struct A : State { - Task run() override + Task run() { co_return startMachine(3); // 3 -> 6 } }; - struct B : Continue { - Task on_success(int v) override + struct B : State { + Task ok(ChildSuccess auto s) { - co_return startMachine(v); // 6 -> 12 + co_return startMachine(s.value); // 6 -> 12 } }; - struct C : Continue { - Task on_success(int v) override + struct C : State { + Task ok(ChildSuccess auto s) { - co_return succeed(v); + co_return succeed(s.value); } }; using States = Fsm::States; @@ -167,7 +163,7 @@ namespace } // namespace // @tag integration -Void::Testing::Test submachine_chains_through_continue_states() +Void::Testing::Test submachine_chains_through_continuation_states() { Chain fsm; const auto outcome = fsm.run_blocking(); @@ -189,7 +185,7 @@ namespace using Success = int; struct W : State { - Task run() override + Task run() { co_await await_event(); co_return succeed(7); @@ -205,15 +201,12 @@ namespace using Success = int; struct Begin : State { - Task run() override - { - co_return startMachine(); - } + Task run() { co_return startMachine(); } }; - struct Fin : Continue { - Task on_success(int v) override + struct Fin : State { + Task ok(ChildSuccess auto s) { - co_return succeed(v); + co_return succeed(s.value); } }; using States = Fsm::States; diff --git a/tests/standalone/Service/Orchestrator.cpp b/tests/standalone/Service/Orchestrator.cpp index 3a17033..7c7d7f8 100644 --- a/tests/standalone/Service/Orchestrator.cpp +++ b/tests/standalone/Service/Orchestrator.cpp @@ -75,7 +75,7 @@ namespace int times; struct Run : State { - Task run() override + Task run() { auto& m = self(); int last = 0; @@ -116,7 +116,7 @@ Void::Testing::Test orchestrator_launches_and_supervises() using Success = int; struct Run : State { - Task run() override + Task run() { int last = 0; for (int i = 0; i < 5; ++i) {