feat(Script): bounded Lua evaluator with transactional host results (#17)

This commit is contained in:
faumaray committed 2026-12-03 07:02:48 +00:00
1 parent ba49098798
commit 08038000cc
1 file changed
+58
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <Void/Script/Types.hpp>
#include <expected>
#include <functional>
#include <span>
#include <string>
#include <vector>
namespace Void::Script
{
/// Host function: receives integer arguments, returns an integer or an error
/// message. It must not commit externally visible state itself; the evaluator
/// records each call in `Result::host_calls` so the caller can commit after a
/// successful evaluation.
using HostFunction = std::function<std::expected<Integer, std::string>(
std::span<const Integer>)>;
struct Host {
std::string name;
HostFunction function;
};
/// Bounded Lua text evaluator.
///
/// Each `evaluate` call creates a fresh, isolated Lua state, applies the
/// allocator, instruction and host-call limits, exposes the integer-keyed
/// inputs as `input[key]`, registers the host functions as globals, and runs
/// the chunk with a protected call. Only integer return values are accepted
/// and collected into an owned result. On failure the state is discarded, so
/// inputs and the caller's host state are untouched; a later valid evaluation
/// starts clean.
class LuaEvaluator
{
public:
explicit LuaEvaluator(Limits limits = Limits{},
std::vector<Host> hosts = {})
: limits_(limits)
, hosts_(std::move(hosts))
{
}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] std::expected<Result, Error>
evaluate(std::string_view source,
std::span<const Input> inputs = {}) const;
private:
Limits limits_;
std::vector<Host> hosts_;
};
} // namespace Void::Script