diff --git a/include/Void/Async/Executor.hpp b/include/Void/Async/Executor.hpp new file mode 100644 index 0000000..f3866ba --- /dev/null +++ b/include/Void/Async/Executor.hpp @@ -0,0 +1,115 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace Void::Async +{ + +// ── Executor ────────────────────────────────────────────────────────────────── +// Minimal scheduling interface bridging Coro::Task to a driving thread. +// post() must be safe to call from any thread. + +class Executor +{ +public: + virtual ~Executor() = default; + + // Schedule a coroutine for resumption on this executor. Thread-safe. + virtual void post(std::coroutine_handle<> handle) = 0; +}; + +// ── ManualExecutor ──────────────────────────────────────────────────────────── +// An executor whose queue is drained explicitly by its owning thread. +// post() is lock-free from any thread; run_one()/drain() must only be +// called from a single consumer thread (typically the owner's loop). + +class ManualExecutor final : public Executor +{ +public: + void post(std::coroutine_handle<> handle) override + { + queue_.push(handle); + } + + // Resume one pending coroutine. Returns false if none was pending. + bool run_one() + { + auto h = queue_.try_pop(); + if (!h) { + return false; + } + h->resume(); + return true; + } + + // Resume pending coroutines until the queue drains. Returns how many + // coroutines were resumed (including ones posted while draining). + std::size_t drain() + { + std::size_t count = 0; + while (run_one()) { + ++count; + } + return count; + } + + [[nodiscard]] bool empty() const noexcept { return queue_.empty(); } + +private: + MpscQueue> queue_; +}; + +// ── schedule_on ─────────────────────────────────────────────────────────────── +// Awaitable that re-schedules the awaiting coroutine onto an executor: +// +// co_await schedule_on(executor); // resumes on the executor's thread + +struct ScheduleAwaiter { + Executor& executor; + + [[nodiscard]] bool await_ready() const noexcept { return false; } + void await_suspend(std::coroutine_handle<> h) const { executor.post(h); } + void await_resume() const noexcept {} +}; + +[[nodiscard]] inline ScheduleAwaiter schedule_on(Executor& executor) +{ + return ScheduleAwaiter{executor}; +} + +// ── spawn ───────────────────────────────────────────────────────────────────── +// Launch a Task detached, driven on the given executor. The wrapper +// coroutine owns the task; its frame self-destroys on completion. An +// exception escaping the task terminates (there is no awaiter to receive +// it) — handle errors inside the task. + +namespace Detail +{ + struct DetachedTask { + struct promise_type { + DetachedTask get_return_object() noexcept { return {}; } + std::suspend_never initial_suspend() noexcept { return {}; } + std::suspend_never final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept { std::terminate(); } + }; + }; + + inline DetachedTask spawn_impl(Executor& executor, Coro::Task task) + { + co_await schedule_on(executor); + co_await std::move(task); + } +} // namespace Detail + +inline void spawn(Executor& executor, Coro::Task task) +{ + Detail::spawn_impl(executor, std::move(task)); +} + +} // namespace Void::Async diff --git a/include/Void/Async/MpscQueue.hpp b/include/Void/Async/MpscQueue.hpp new file mode 100644 index 0000000..be10694 --- /dev/null +++ b/include/Void/Async/MpscQueue.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include + +namespace Void::Async +{ + +// ── MpscQueue ────────────────────────────────────────────────────────────── +// Unbounded multi-producer / single-consumer queue (Vyukov scheme). +// +// push() — any thread; wait-free (one exchange + one store, no CAS loop). +// try_pop() — exactly ONE consumer thread; lock-free. +// +// Memory reclamation is trivial by construction: only the consumer ever +// dereferences and frees popped nodes, so there are no hazard pointers, no +// epochs, and no ABA window (no compare-and-swap on shared nodes at all). +// +// Known Vyukov subtlety: a producer can be preempted between swapping the +// tail and linking the previous node's `next`. During that window the chain +// is transiently broken and try_pop() reports the queue as empty even though +// later-pushed items exist. Callers must treat empty() / nullopt as a hint +// and re-poll; items are never lost. +// +// The queue carries no blocking facility by design — consumers that need to +// sleep when idle pair it with a std::binary_semaphore (see ManualExecutor +// and the Fsm worker for the pattern). + +template +class MpscQueue +{ +public: + MpscQueue() : head_{new Node{}}, tail_{head_} {} + + MpscQueue(const MpscQueue&) = delete; + MpscQueue& operator=(const MpscQueue&) = delete; + MpscQueue(MpscQueue&&) = delete; + MpscQueue& operator=(MpscQueue&&) = delete; + + ~MpscQueue() + { + // No concurrent access is permitted during destruction. + Node* n = head_; + while (n) { + Node* next = n->next.load(std::memory_order_relaxed); + delete n; + n = next; + } + } + + // Enqueue from any thread. Wait-free. + void push(T value) + { + Node* node = new Node{std::move(value)}; + Node* prev = tail_.exchange(node, std::memory_order_acq_rel); + // A consumer scanning right now sees prev->next == nullptr and + // treats the queue as empty until this store lands (see above). + prev->next.store(node, std::memory_order_release); + } + + // Dequeue. Must only ever be called from one consumer thread. + // Returns nullopt when the queue is empty *or* a producer is mid-link. + [[nodiscard]] std::optional try_pop() + { + Node* head = head_; + Node* next = head->next.load(std::memory_order_acquire); + if (!next) { + return std::nullopt; + } + std::optional result{std::move(*next->value)}; + next->value.reset(); + head_ = next; + delete head; + return result; + } + + // Consumer-side emptiness hint; racy when observed from other threads. + [[nodiscard]] bool empty() const noexcept + { + return head_->next.load(std::memory_order_acquire) == nullptr; + } + +private: + struct Node { + Node() = default; + explicit Node(T v) : value{std::move(v)} {} + + std::atomic next{nullptr}; + std::optional value{}; // disengaged only in the stub node + }; + + Node* head_; // consumer-owned; always the consumed stub + std::atomic tail_; // producers swap themselves in here +}; + +} // namespace Void::Async diff --git a/include/Void/Data/Reflect.hpp b/include/Void/Data/Reflect.hpp new file mode 100644 index 0000000..4b2de92 --- /dev/null +++ b/include/Void/Data/Reflect.hpp @@ -0,0 +1,423 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#define VOID_HAS_JSON_REFLECTION 1 +#endif + +// ── Reflection → JSON ───────────────────────────────────────────────────────── +// Serialize/deserialize aggregate structs to Json::Value using C++26 P2996 +// reflection (GCC 16+, -freflection). Field names become object keys. +// +// Customization: a type providing +// Json::Value to_json() const; +// static std::expected from_json(const Json::Value&); +// always wins over reflection — and is the only path on compilers without +// , where the Reflectable concept is false. +// +// Deserialization tolerance (the backward/forward-compat contract): +// * unknown JSON fields are ignored +// * missing fields keep the default-initialized member value +// * a present field with the wrong JSON type is an error +// +// Versioned envelopes for hot-reload state migration: +// to_versioned_json(s) -> {"__version": N, "data": {...}} +// from_versioned_json -> runs a MigrationChain when the stored +// version is older than StateTraits::version. + +namespace Void::Json +{ + +struct ReflectError { + std::string field; // dotted path of the offending field ("" if global) + std::string message; +}; + +// ── customization point ─────────────────────────────────────────────────────── + +template +concept HasMemberToJson = requires(const T& t) { + { t.to_json() } -> std::same_as; +}; + +template +concept HasMemberFromJson = requires(const Value& v) { + { T::from_json(v) } -> std::same_as>; +}; + +// ── supported leaf / container shapes ───────────────────────────────────────── + +namespace ReflectDetail +{ + template + struct IsOptional : std::false_type {}; + template + struct IsOptional> : std::true_type {}; + + template + struct IsVector : std::false_type {}; + template + struct IsVector> : std::true_type {}; + + template + struct IsStringMap : std::false_type {}; + template + struct IsStringMap> : std::true_type {}; +} // namespace ReflectDetail + +#ifdef VOID_HAS_JSON_REFLECTION + +template +concept ReflectableAggregate = + std::is_aggregate_v && !std::is_array_v && + std::is_default_constructible_v; + +#else + +template +concept ReflectableAggregate = false; + +#endif + +template +concept JsonConvertible = + HasMemberToJson || std::same_as || std::is_arithmetic_v || + std::is_enum_v || std::same_as || + ReflectDetail::IsOptional::value || ReflectDetail::IsVector::value || + ReflectDetail::IsStringMap::value || ReflectableAggregate; + +// Anything serializable through this header (customized or reflected). +template +concept Reflectable = JsonConvertible; + +// ── to_json ─────────────────────────────────────────────────────────────────── + +template +[[nodiscard]] Value to_json(const T& v); + +namespace ReflectDetail +{ + template + Value leaf_to_json(const T& v) + { + if constexpr (HasMemberToJson) { + return v.to_json(); + } + else if constexpr (std::same_as) { + return Value{v}; + } + else if constexpr (std::is_enum_v) { +#ifdef VOID_HAS_ENUM_REFLECTION + // Enum values serialize by name — stable across binary versions. + return Value{Void::Detail::enum_name(v)}; +#else + return Value{static_cast( + static_cast>(v))}; +#endif + } + else if constexpr (std::is_arithmetic_v) { + return Value{static_cast(v)}; + } + else if constexpr (std::same_as) { + return Value{v}; + } + else if constexpr (IsOptional::value) { + return v ? Json::to_json(*v) : Value{nullptr}; + } + else if constexpr (IsVector::value) { + auto arr = Json::array(); + arr.as_array().reserve(v.size()); + for (const auto& e : v) { + arr.as_array().push_back(Json::to_json(e)); + } + return arr; + } + else if constexpr (IsStringMap::value) { + auto obj = Json::object(); + for (const auto& [k, e] : v) { + obj.as_object().emplace_back(k, Json::to_json(e)); + } + return obj; + } + else { + static_assert(ReflectableAggregate, + "type is not serializable via Json reflection"); +#ifdef VOID_HAS_JSON_REFLECTION + auto obj = Json::object(); + static constexpr auto members = std::define_static_array( + std::meta::nonstatic_data_members_of( + ^^T, std::meta::access_context::current())); + template for (constexpr auto m : members) { + obj.as_object().emplace_back( + std::string{std::meta::identifier_of(m)}, + Json::to_json(v.[:m:])); + } + return obj; +#endif + } + } +} // namespace ReflectDetail + +template +[[nodiscard]] Value to_json(const T& v) +{ + return ReflectDetail::leaf_to_json(v); +} + +// ── from_json ───────────────────────────────────────────────────────────────── + +template +[[nodiscard]] std::expected from_json(const Value& j); + +namespace ReflectDetail +{ + [[nodiscard]] inline ReflectError nest(std::string_view field, + ReflectError inner) + { + if (inner.field.empty()) { + inner.field = std::string{field}; + } + else { + inner.field = std::string{field} + "." + inner.field; + } + return inner; + } + + template + std::expected leaf_from_json(const Value& j) + { + if constexpr (HasMemberFromJson) { + return T::from_json(j); + } + else if constexpr (std::same_as) { + if (!j.is_bool()) { + return std::unexpected{ReflectError{"", "expected bool"}}; + } + return j.as_bool(); + } + else if constexpr (std::is_enum_v) { +#ifdef VOID_HAS_ENUM_REFLECTION + if (!j.is_string()) { + return std::unexpected{ + ReflectError{"", "expected enum name string"}}; + } + auto parsed = Void::Detail::enum_parse(j.as_string()); + if (!parsed) { + return std::unexpected{ReflectError{ + "", "unknown enumerator '" + j.as_string() + "'"}}; + } + return *parsed; +#else + if (!j.is_number()) { + return std::unexpected{ + ReflectError{"", "expected enum number"}}; + } + return static_cast( + static_cast>(j.as_number())); +#endif + } + else if constexpr (std::is_arithmetic_v) { + if (!j.is_number()) { + return std::unexpected{ReflectError{"", "expected number"}}; + } + return static_cast(j.as_number()); + } + else if constexpr (std::same_as) { + if (!j.is_string()) { + return std::unexpected{ReflectError{"", "expected string"}}; + } + return j.as_string(); + } + else if constexpr (IsOptional::value) { + using U = typename T::value_type; + if (j.is_null()) { + return T{std::nullopt}; + } + auto inner = Json::from_json(j); + if (!inner) { + return std::unexpected{std::move(inner).error()}; + } + return T{std::move(*inner)}; + } + else if constexpr (IsVector::value) { + using U = typename T::value_type; + if (!j.is_array()) { + return std::unexpected{ReflectError{"", "expected array"}}; + } + T out; + out.reserve(j.as_array().size()); + std::size_t index = 0; + for (const auto& e : j.as_array()) { + auto inner = Json::from_json(e); + if (!inner) { + return std::unexpected{nest( + "[" + std::to_string(index) + "]", + std::move(inner).error())}; + } + out.push_back(std::move(*inner)); + ++index; + } + return out; + } + else if constexpr (IsStringMap::value) { + using U = typename T::mapped_type; + if (!j.is_object()) { + return std::unexpected{ReflectError{"", "expected object"}}; + } + T out; + for (const auto& [k, e] : j.as_object()) { + auto inner = Json::from_json(e); + if (!inner) { + return std::unexpected{nest(k, std::move(inner).error())}; + } + out.emplace(k, std::move(*inner)); + } + return out; + } + else { + static_assert(ReflectableAggregate, + "type is not deserializable via Json reflection"); +#ifdef VOID_HAS_JSON_REFLECTION + if (!j.is_object()) { + return std::unexpected{ReflectError{"", "expected object"}}; + } + T out{}; + static constexpr auto members = std::define_static_array( + std::meta::nonstatic_data_members_of( + ^^T, std::meta::access_context::current())); + std::optional failure; + template for (constexpr auto m : members) { + if (!failure) { + constexpr auto name = std::meta::identifier_of(m); + using MT = [:std::meta::type_of(m):]; + if (const Value* field = j.find(name)) { + auto inner = Json::from_json(*field); + if (!inner) { + failure = nest(name, std::move(inner).error()); + } + else { + out.[:m:] = std::move(*inner); + } + } + // absent field: keep the default-initialized value + } + } + if (failure) { + return std::unexpected{std::move(*failure)}; + } + return out; +#endif + } + } +} // namespace ReflectDetail + +template +[[nodiscard]] std::expected from_json(const Value& j) +{ + return ReflectDetail::leaf_from_json(j); +} + +// ── versioned envelope + migrations ─────────────────────────────────────────── + +// Specialize to bump a state type's schema version: +// template <> struct Void::Json::StateTraits { +// static constexpr std::uint32_t version = 3; +// }; +template +struct StateTraits { + static constexpr std::uint32_t version = 1; +}; + +// Ordered chain of per-version JSON transforms. Each step upgrades the bare +// "data" payload from `from_version` to `from_version + 1`. +class MigrationChain +{ +public: + using Step = std::function; + + MigrationChain& add(std::uint32_t from_version, Step step) + { + steps_.emplace(from_version, std::move(step)); + return *this; + } + + [[nodiscard]] std::expected + migrate(Value data, std::uint32_t from, std::uint32_t to) const + { + while (from < to) { + auto it = steps_.find(from); + if (it == steps_.end()) { + return std::unexpected{ReflectError{ + "__version", "no migration step from version " + + std::to_string(from)}}; + } + data = it->second(std::move(data)); + ++from; + } + return data; + } + + [[nodiscard]] bool empty() const noexcept { return steps_.empty(); } + +private: + std::map steps_; +}; + +template +[[nodiscard]] Value to_versioned_json(const T& v) +{ + auto envelope = object(); + envelope.as_object().emplace_back( + "__version", Value{static_cast(StateTraits::version)}); + envelope.as_object().emplace_back("data", to_json(v)); + return envelope; +} + +template +[[nodiscard]] std::expected + from_versioned_json(const Value& envelope, + const MigrationChain& migrations = {}) +{ + if (!envelope.is_object()) { + return std::unexpected{ReflectError{"", "expected envelope object"}}; + } + const Value* version = envelope.find("__version"); + const Value* data = envelope.find("data"); + if (!version || !version->is_number() || !data) { + return std::unexpected{ + ReflectError{"__version", "malformed versioned envelope"}}; + } + const auto from = static_cast(version->as_number()); + constexpr auto to = StateTraits::version; + if (from > to) { + return std::unexpected{ReflectError{ + "__version", "stored version " + std::to_string(from) + + " is newer than supported version " + + std::to_string(to)}}; + } + if (from == to) { + return from_json(*data); + } + auto migrated = migrations.migrate(*data, from, to); + if (!migrated) { + return std::unexpected{std::move(migrated).error()}; + } + return from_json(*migrated); +} + +} // namespace Void::Json diff --git a/tests/standalone/Async/Executor.cpp b/tests/standalone/Async/Executor.cpp new file mode 100644 index 0000000..4116c77 --- /dev/null +++ b/tests/standalone/Async/Executor.cpp @@ -0,0 +1,150 @@ +#include +#include +#include +#include + +#include +#include +#include + +using Void::Async::ManualExecutor; +using Void::Async::schedule_on; +using Void::Async::spawn; +using Void::Coro::Task; + +// ── schedule_on ─────────────────────────────────────────────────────────────── + +Void::Testing::Test executor_schedule_on_hops_to_drain() +{ + ManualExecutor ex; + std::vector order; + + spawn(ex, [](ManualExecutor& ex2, std::vector& log) + -> Task { + log.push_back("before"); + co_await schedule_on(ex2); + log.push_back("after"); + }(ex, order)); + + // spawn() posts the wrapper; nothing ran yet. + Void::Testing::expect_eq(order.size(), std::size_t{0}); + + ex.drain(); + Void::Testing::expect_eq(order.size(), std::size_t{2}); + Void::Testing::expect_eq(order[0], std::string{"before"}); + Void::Testing::expect_eq(order[1], std::string{"after"}); +} + +Void::Testing::Test executor_run_one_steps_individually() +{ + ManualExecutor ex; + int counter = 0; + + spawn(ex, [](ManualExecutor& ex2, int& c) -> Task { + ++c; + co_await schedule_on(ex2); + ++c; + }(ex, counter)); + + Void::Testing::expect(ex.run_one()); // runs until the re-schedule point + Void::Testing::expect_eq(counter, 1); + Void::Testing::expect(ex.run_one()); // resumes after the hop + Void::Testing::expect_eq(counter, 2); + Void::Testing::expect(!ex.run_one()); + Void::Testing::expect(ex.empty()); +} + +Void::Testing::Test executor_drain_returns_resume_count() +{ + ManualExecutor ex; + int counter = 0; + + for (int i = 0; i < 3; ++i) { + spawn(ex, [](int& c) -> Task { + ++c; + co_return; + }(counter)); + } + + const auto resumed = ex.drain(); + Void::Testing::expect_eq(resumed, std::size_t{3}); + Void::Testing::expect_eq(counter, 3); +} + +// ── spawn lifetime ──────────────────────────────────────────────────────────── + +namespace +{ + struct DtorProbe { + int* flag; + ~DtorProbe() + { + if (flag) { + ++*flag; + } + } + DtorProbe(int* f) : flag{f} {} + DtorProbe(DtorProbe&& o) noexcept : flag{o.flag} { o.flag = nullptr; } + DtorProbe(const DtorProbe&) = delete; + }; +} // namespace + +Void::Testing::Test executor_spawn_destroys_frame_on_completion() +{ + ManualExecutor ex; + int destroyed = 0; + + spawn(ex, [](DtorProbe probe) -> Task { + (void)probe; + co_return; + }(DtorProbe{&destroyed})); + + Void::Testing::expect_eq(destroyed, 0); + ex.drain(); + // Both the task frame and the wrapper frame are gone; the probe captured + // by value inside the coroutine frame must have been destroyed. + Void::Testing::expect_eq(destroyed, 1); +} + +Void::Testing::Test executor_nested_task_awaiting() +{ + ManualExecutor ex; + int result = 0; + + spawn(ex, [](int& out) -> Task { + auto inner = []() -> Task { co_return 21; }; + out = co_await inner() + co_await inner(); + }(result)); + + ex.drain(); + Void::Testing::expect_eq(result, 42); +} + +// ── cross-thread posting ────────────────────────────────────────────────────── + +// @tag concurrency +Void::Testing::Test executor_post_from_other_threads() +{ + ManualExecutor ex; + int counter = 0; + constexpr int tasks = 100; + + std::vector threads; + threads.reserve(4); + for (int t = 0; t < 4; ++t) { + threads.emplace_back([&ex, &counter] { + for (int i = 0; i < tasks / 4; ++i) { + spawn(ex, [](int& c) -> Task { + ++c; + co_return; + }(counter)); + } + }); + } + for (auto& t : threads) { + t.join(); + } + + ex.drain(); + Void::Testing::expect_eq(counter, tasks); +} diff --git a/tests/standalone/Async/MpscQueue.cpp b/tests/standalone/Async/MpscQueue.cpp new file mode 100644 index 0000000..84aae65 --- /dev/null +++ b/tests/standalone/Async/MpscQueue.cpp @@ -0,0 +1,120 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Void::Async::MpscQueue; + +// ── single-threaded basics ──────────────────────────────────────────────────── + +Void::Testing::Test mpsc_starts_empty() +{ + MpscQueue q; + Void::Testing::expect(q.empty()); + Void::Testing::expect(!q.try_pop().has_value()); +} + +Void::Testing::Test mpsc_push_pop_roundtrip() +{ + MpscQueue q; + q.push(1); + q.push(2); + q.push(3); + Void::Testing::expect(!q.empty()); + Void::Testing::expect_eq(*q.try_pop(), 1); + Void::Testing::expect_eq(*q.try_pop(), 2); + Void::Testing::expect_eq(*q.try_pop(), 3); + Void::Testing::expect(!q.try_pop().has_value()); + Void::Testing::expect(q.empty()); +} + +Void::Testing::Test mpsc_interleaved_push_pop() +{ + MpscQueue q; + q.push(1); + Void::Testing::expect_eq(*q.try_pop(), 1); + q.push(2); + q.push(3); + Void::Testing::expect_eq(*q.try_pop(), 2); + q.push(4); + Void::Testing::expect_eq(*q.try_pop(), 3); + Void::Testing::expect_eq(*q.try_pop(), 4); + Void::Testing::expect(!q.try_pop().has_value()); +} + +Void::Testing::Test mpsc_move_only_payload() +{ + MpscQueue> q; + q.push(std::make_unique(42)); + auto v = q.try_pop(); + Void::Testing::expect(v.has_value()); + Void::Testing::expect_eq(**v, 42); +} + +Void::Testing::Test mpsc_destructor_releases_pending_items() +{ + // Leaks (pending nodes not freed) would be caught under ASan/valgrind. + MpscQueue q; + q.push(std::string(256, 'a')); + q.push(std::string(256, 'b')); +} + +// ── multi-producer stress ───────────────────────────────────────────────────── + +// @tag stress, concurrency +Void::Testing::Test mpsc_multi_producer_stress() +{ + constexpr int producers = 8; + constexpr int per_producer = 100'000; + + MpscQueue> q; // {producer id, sequence} + std::atomic go{false}; + + std::vector threads; + threads.reserve(producers); + for (int p = 0; p < producers; ++p) { + threads.emplace_back([&q, &go, p] { + go.wait(false); + for (int i = 0; i < per_producer; ++i) { + q.push({p, i}); + } + }); + } + + go = true; + go.notify_all(); + + // Consume on this thread while producers run. nullopt is only a hint + // (Vyukov mid-link window), so completion is tracked by count. + std::vector next_seq(producers, 0); + long long received = 0; + constexpr long long total = + static_cast(producers) * per_producer; + while (received < total) { + auto item = q.try_pop(); + if (!item) { + std::this_thread::yield(); + continue; + } + const auto [p, seq] = *item; + // per-producer FIFO must hold + Void::Testing::expect_eq(seq, next_seq[static_cast(p)]); + ++next_seq[static_cast(p)]; + ++received; + } + + for (auto& t : threads) { + t.join(); + } + Void::Testing::expect(!q.try_pop().has_value()); + for (int p = 0; p < producers; ++p) { + Void::Testing::expect_eq(next_seq[static_cast(p)], + per_producer); + } +} diff --git a/tests/standalone/Data/Reflect.cpp b/tests/standalone/Data/Reflect.cpp new file mode 100644 index 0000000..84c8152 --- /dev/null +++ b/tests/standalone/Data/Reflect.cpp @@ -0,0 +1,245 @@ +#include +#include +#include + +#include +#include +#include +#include + +#ifdef VOID_HAS_JSON_REFLECTION + +namespace +{ + enum class Color { Red, Green, Blue }; + + struct Point { + double x = 0; + double y = 0; + }; + + struct Shape { + std::string name; + Color color = Color::Red; + std::vector points; + std::optional opacity; + std::map tags; + bool visible = true; + int layer = 0; + }; +} // namespace + +// ── round trips ─────────────────────────────────────────────────────────────── + +Void::Testing::Test reflect_flat_round_trip() +{ + const Point p{1.5, -2.0}; + const auto j = Void::Json::to_json(p); + Void::Testing::expect(j.is_object()); + Void::Testing::expect_eq(j["x"].as_number(), 1.5); + + const auto back = Void::Json::from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->x, 1.5); + Void::Testing::expect_eq(back->y, -2.0); +} + +Void::Testing::Test reflect_nested_round_trip() +{ + Shape s; + s.name = "tri"; + s.color = Color::Blue; + s.points = {{0, 0}, {1, 0}, {0, 1}}; + s.opacity = 0.5; + s.tags = {{"kind", 3}, {"z", 9}}; + s.visible = false; + s.layer = 7; + + const auto j = Void::Json::to_json(s); + const auto back = Void::Json::from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->name, std::string{"tri"}); + Void::Testing::expect(back->color == Color::Blue); + Void::Testing::expect_eq(back->points.size(), std::size_t{3}); + Void::Testing::expect_eq(back->points[2].y, 1.0); + Void::Testing::expect(back->opacity.has_value()); + Void::Testing::expect_eq(*back->opacity, 0.5); + Void::Testing::expect_eq(back->tags.at("kind"), 3); + Void::Testing::expect(!back->visible); + Void::Testing::expect_eq(back->layer, 7); +} + +Void::Testing::Test reflect_enum_serializes_by_name() +{ + const Shape s{.name = "x", .color = Color::Green}; + const auto j = Void::Json::to_json(s); + Void::Testing::expect_eq(j["color"].as_string(), std::string{"Green"}); +} + +Void::Testing::Test reflect_optional_null_round_trip() +{ + const Shape s{.name = "noop"}; + const auto j = Void::Json::to_json(s); + Void::Testing::expect(j["opacity"].is_null()); + + const auto back = Void::Json::from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect(!back->opacity.has_value()); +} + +// ── tolerance ───────────────────────────────────────────────────────────────── + +Void::Testing::Test reflect_unknown_fields_ignored() +{ + const auto j = Void::Json::parse( + R"({"x": 1.0, "y": 2.0, "future_field": "whatever"})"); + Void::Testing::expect(j.has_value()); + const auto p = Void::Json::from_json(*j); + Void::Testing::expect(p.has_value()); + Void::Testing::expect_eq(p->x, 1.0); +} + +Void::Testing::Test reflect_missing_fields_keep_defaults() +{ + const auto j = Void::Json::parse(R"({"name": "partial"})"); + Void::Testing::expect(j.has_value()); + const auto s = Void::Json::from_json(*j); + Void::Testing::expect(s.has_value()); + Void::Testing::expect_eq(s->name, std::string{"partial"}); + Void::Testing::expect(s->visible); // default kept + Void::Testing::expect_eq(s->layer, 0); +} + +// ── errors ──────────────────────────────────────────────────────────────────── + +Void::Testing::Test reflect_type_mismatch_reports_field_path() +{ + const auto j = Void::Json::parse( + R"({"name": "s", "points": [{"x": 0, "y": 0}, {"x": "oops"}]})"); + Void::Testing::expect(j.has_value()); + const auto s = Void::Json::from_json(*j); + Void::Testing::expect(!s.has_value()); + Void::Testing::expect_eq(s.error().field, std::string{"points.[1].x"}); +} + +Void::Testing::Test reflect_non_object_rejected() +{ + const auto s = Void::Json::from_json(Void::Json::Value{42}); + Void::Testing::expect(!s.has_value()); +} + +// ── versioned envelope + migrations ─────────────────────────────────────────── + +namespace +{ + struct StateV3 { + std::string title; // v1: "name", v2: renamed to "title" + int count = 0; // v1/v2 + bool enabled = true; // added in v3 + }; +} // namespace + +template <> +struct Void::Json::StateTraits { + static constexpr std::uint32_t version = 3; +}; + +namespace +{ + Void::Json::MigrationChain state_migrations() + { + Void::Json::MigrationChain chain; + // v1 -> v2: rename "name" to "title" + chain.add(1, [](Void::Json::Value data) { + if (auto* name = data.find("name")) { + data.as_object().emplace_back("title", std::move(*name)); + } + return data; + }); + // v2 -> v3: nothing structural; "enabled" appears with its default + chain.add(2, [](Void::Json::Value data) { return data; }); + return chain; + } +} // namespace + +Void::Testing::Test reflect_versioned_envelope_round_trip() +{ + const StateV3 s{.title = "t", .count = 5, .enabled = false}; + const auto j = Void::Json::to_versioned_json(s); + Void::Testing::expect_eq(j["__version"].as_int(), std::int64_t{3}); + + const auto back = Void::Json::from_versioned_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->count, 5); + Void::Testing::expect(!back->enabled); +} + +Void::Testing::Test reflect_migration_v1_to_v3() +{ + const auto v1 = Void::Json::parse( + R"({"__version": 1, "data": {"name": "legacy", "count": 9}})"); + Void::Testing::expect(v1.has_value()); + + const auto s = + Void::Json::from_versioned_json(*v1, state_migrations()); + Void::Testing::expect(s.has_value()); + Void::Testing::expect_eq(s->title, std::string{"legacy"}); + Void::Testing::expect_eq(s->count, 9); + Void::Testing::expect(s->enabled); // default for the field added in v3 +} + +Void::Testing::Test reflect_migration_missing_step_fails() +{ + const auto v1 = Void::Json::parse( + R"({"__version": 1, "data": {"name": "legacy"}})"); + Void::Testing::expect(v1.has_value()); + + const auto s = Void::Json::from_versioned_json(*v1); // no chain + Void::Testing::expect(!s.has_value()); +} + +Void::Testing::Test reflect_newer_version_rejected() +{ + const auto v9 = Void::Json::parse(R"({"__version": 9, "data": {}})"); + Void::Testing::expect(v9.has_value()); + const auto s = Void::Json::from_versioned_json(*v9); + Void::Testing::expect(!s.has_value()); +} + +// ── customization point ─────────────────────────────────────────────────────── + +namespace +{ + struct Custom { + int doubled = 0; + + [[nodiscard]] Void::Json::Value to_json() const + { + return Void::Json::Value{doubled / 2}; + } + + static std::expected + from_json(const Void::Json::Value& v) + { + if (!v.is_number()) { + return std::unexpected{ + Void::Json::ReflectError{"", "expected number"}}; + } + return Custom{static_cast(v.as_number()) * 2}; + } + }; +} // namespace + +Void::Testing::Test reflect_member_customization_wins() +{ + const Custom c{10}; + const auto j = Void::Json::to_json(c); + Void::Testing::expect(j.is_number()); + Void::Testing::expect_eq(j.as_int(), std::int64_t{5}); + + const auto back = Void::Json::from_json(j); + Void::Testing::expect(back.has_value()); + Void::Testing::expect_eq(back->doubled, 10); +} + +#endif // VOID_HAS_JSON_REFLECTION