#include #include #include #include #include using Void::Coro::Task; using Void::Fsm::State; using Void::Fsm::StateKey; namespace Fsm = Void::Fsm; // Demonstrates the header/source split the module is designed for: the machine // declares its states as forward declarations inside `struct States { … };` // (this block is what would live in a header), and the states are *realised* // out-of-line at namespace scope (this is what would live in a .cpp). The base // auto-registers them by reflecting `States`; no behaviour is written outside a // state. The constructor is also defined out-of-line, after the realisations, // so the states are complete when the base registers them. namespace { struct Charge { int amount; }; struct Dispense { }; // ── "header" part ────────────────────────────────────────────────────── class Vending : public Fsm::Machine { public: using Success = int; // dispensed credit int credit = 0; struct States { struct Idle; // first => initial struct Collecting; struct Done; }; Vending(); // realised below, after the states }; } // namespace // ── "source" part: state realisations (namespace scope) ───────────────────── struct Vending::States::Idle : Vending::State { Task run() { co_await await_event(); // first coin -> start collecting co_return next(); } }; struct Vending::States::Collecting : Vending::State { Task run() { auto& m = self(); for (;;) { auto ev = co_await await_any(); if (std::holds_alternative(ev)) { co_return next(); } m.credit += std::get(ev).amount; } } }; struct Vending::States::Done : Vending::State { Task run() { co_return succeed(self().credit); } }; Vending::Vending() = default; // base registers Idle/Collecting/Done from States // @tag integration Void::Testing::Test split_machine_runs_with_out_of_line_states() { Vending fsm; fsm.start(); fsm.send(Charge{10}); // Idle -> Collecting (first coin counted there too?) fsm.send(Charge{5}, Charge{10}); fsm.send(Dispense{}); const auto outcome = fsm.wait(); Void::Testing::expect(outcome.has_value()); // Idle consumes the first Charge to leave; Collecting sums 5 + 10 = 15. Void::Testing::expect_eq(*outcome, 15); } Void::Testing::Test split_machine_auto_registers_states_in_order() { Vending fsm; const auto& names = fsm.state_names(); Void::Testing::expect_eq(names.size(), std::size_t{3}); Void::Testing::expect_eq(names[0], std::string{"Idle"}); // initial Void::Testing::expect_eq(names[1], std::string{"Collecting"}); Void::Testing::expect_eq(names[2], std::string{"Done"}); }