mirror of
https://github.com/allankoechke/mbs.git
synced 2026-11-29 09:17:52 +00:00
feat: add expression precompilation API and custom function registry
- F14: compile(source) separated from evaluation so an expression can be parsed once and evaluated many times - F15: register user-defined C++ functions callable from expressions, replacing the hardcoded method dispatch with a named registry
This commit is contained in:
@@ -1,12 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace mbs {
|
||||
|
||||
namespace ast { struct Expr; }
|
||||
|
||||
struct SourceLocation {
|
||||
std::size_t line{1};
|
||||
std::size_t column{1};
|
||||
@@ -44,4 +51,40 @@ namespace mbs {
|
||||
|
||||
EvalBoolResult eval_true(std::string_view source, const nlohmann::json &context,
|
||||
std::size_t max_source_length = 0);
|
||||
|
||||
using FunctionDef = std::function<nlohmann::json(
|
||||
const nlohmann::json& target,
|
||||
const std::vector<nlohmann::json>& args)>;
|
||||
|
||||
using FunctionRegistry = std::unordered_map<std::string, FunctionDef>;
|
||||
|
||||
class CompiledExpr {
|
||||
public:
|
||||
CompiledExpr() = default;
|
||||
explicit operator bool() const { return static_cast<bool>(ast_); }
|
||||
private:
|
||||
friend class Script;
|
||||
std::shared_ptr<const ast::Expr> ast_;
|
||||
std::string source_;
|
||||
};
|
||||
|
||||
class Script {
|
||||
public:
|
||||
Script() = default;
|
||||
|
||||
CompiledExpr compile(std::string_view source, std::size_t max_source_length = 0) const;
|
||||
|
||||
EvalValueResult eval_val(const CompiledExpr& compiled, const nlohmann::json& context) const;
|
||||
EvalBoolResult eval_true(const CompiledExpr& compiled, const nlohmann::json& context) const;
|
||||
|
||||
EvalValueResult eval_val(std::string_view source, const nlohmann::json& context,
|
||||
std::size_t max_source_length = 0) const;
|
||||
EvalBoolResult eval_true(std::string_view source, const nlohmann::json& context,
|
||||
std::size_t max_source_length = 0) const;
|
||||
|
||||
void register_function(std::string name, FunctionDef fn);
|
||||
|
||||
private:
|
||||
FunctionRegistry functions_;
|
||||
};
|
||||
} // namespace mbs
|
||||
|
||||
@@ -15,6 +15,15 @@ namespace mbs {
|
||||
namespace {
|
||||
|
||||
thread_local int t_eval_depth = 0;
|
||||
thread_local const FunctionRegistry* t_func_registry = nullptr;
|
||||
|
||||
struct RegistryGuard {
|
||||
const FunctionRegistry* prev;
|
||||
explicit RegistryGuard(const FunctionRegistry* r) : prev(t_func_registry) { t_func_registry = r; }
|
||||
~RegistryGuard() { t_func_registry = prev; }
|
||||
RegistryGuard(const RegistryGuard&) = delete;
|
||||
RegistryGuard& operator=(const RegistryGuard&) = delete;
|
||||
};
|
||||
|
||||
struct DepthGuard {
|
||||
DepthGuard() {
|
||||
@@ -315,6 +324,12 @@ nlohmann::json call_method(const nlohmann::json& v, const std::string& name,
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
if (t_func_registry) {
|
||||
auto it = t_func_registry->find(name);
|
||||
if (it != t_func_registry->end()) {
|
||||
return it->second(v, args);
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -625,31 +640,32 @@ nlohmann::json eval_expr(const ast::Expr& expr, const nlohmann::json& context) {
|
||||
|
||||
namespace {
|
||||
|
||||
std::optional<std::string> semantic_check_impl(const ast::Expr& expr) {
|
||||
std::optional<std::string> semantic_check_impl(const ast::Expr& expr,
|
||||
const FunctionRegistry* funcs) {
|
||||
switch (expr.kind) {
|
||||
case ast::Expr::Kind::Literal:
|
||||
case ast::Expr::Kind::ContextVar:
|
||||
return std::nullopt;
|
||||
case ast::Expr::Kind::Unary: {
|
||||
return semantic_check_impl(*expr.child);
|
||||
return semantic_check_impl(*expr.child, funcs);
|
||||
}
|
||||
case ast::Expr::Kind::Binary: {
|
||||
auto a = semantic_check_impl(*expr.left);
|
||||
auto a = semantic_check_impl(*expr.left, funcs);
|
||||
if (a.has_value()) {
|
||||
return a;
|
||||
}
|
||||
return semantic_check_impl(*expr.right);
|
||||
return semantic_check_impl(*expr.right, funcs);
|
||||
}
|
||||
case ast::Expr::Kind::Ternary: {
|
||||
auto a = semantic_check_impl(*expr.left);
|
||||
auto a = semantic_check_impl(*expr.left, funcs);
|
||||
if (a.has_value()) return a;
|
||||
auto b = semantic_check_impl(*expr.right);
|
||||
auto b = semantic_check_impl(*expr.right, funcs);
|
||||
if (b.has_value()) return b;
|
||||
return semantic_check_impl(*expr.elseExpr);
|
||||
return semantic_check_impl(*expr.elseExpr, funcs);
|
||||
}
|
||||
case ast::Expr::Kind::Chain: {
|
||||
if (expr.chainBase) {
|
||||
auto b = semantic_check_impl(*expr.chainBase);
|
||||
auto b = semantic_check_impl(*expr.chainBase, funcs);
|
||||
if (b.has_value()) {
|
||||
return b;
|
||||
}
|
||||
@@ -711,24 +727,27 @@ std::optional<std::string> semantic_check_impl(const ast::Expr& expr) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!known && funcs && funcs->count(seg.name)) {
|
||||
known = true;
|
||||
}
|
||||
if (!known) {
|
||||
return std::string("unknown method: ") + seg.name;
|
||||
}
|
||||
for (const auto& a : seg.args) {
|
||||
auto e = semantic_check_impl(*a);
|
||||
auto e = semantic_check_impl(*a, funcs);
|
||||
if (e.has_value()) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
} else if (seg.kind == ast::Segment::Kind::Index) {
|
||||
return semantic_check_impl(*seg.indexExpr);
|
||||
return semantic_check_impl(*seg.indexExpr, funcs);
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
case ast::Expr::Kind::Array: {
|
||||
for (const auto& el : expr.arrayElems) {
|
||||
auto e = semantic_check_impl(*el);
|
||||
auto e = semantic_check_impl(*el, funcs);
|
||||
if (e.has_value()) {
|
||||
return e;
|
||||
}
|
||||
@@ -737,7 +756,7 @@ std::optional<std::string> semantic_check_impl(const ast::Expr& expr) {
|
||||
}
|
||||
case ast::Expr::Kind::Object: {
|
||||
for (const auto& p : expr.objectPairs) {
|
||||
auto e = semantic_check_impl(*p.value);
|
||||
auto e = semantic_check_impl(*p.value, funcs);
|
||||
if (e.has_value()) {
|
||||
return e;
|
||||
}
|
||||
@@ -751,6 +770,18 @@ std::optional<std::string> semantic_check_impl(const ast::Expr& expr) {
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string> semantic_check(const ast::Expr& expr) { return semantic_check_impl(expr); }
|
||||
std::optional<std::string> semantic_check(const ast::Expr& expr) {
|
||||
return semantic_check_impl(expr, nullptr);
|
||||
}
|
||||
|
||||
std::optional<std::string> semantic_check(const ast::Expr& expr, const FunctionRegistry& funcs) {
|
||||
return semantic_check_impl(expr, &funcs);
|
||||
}
|
||||
|
||||
nlohmann::json eval_expr(const ast::Expr& expr, const nlohmann::json& context,
|
||||
const FunctionRegistry& funcs) {
|
||||
RegistryGuard rg(&funcs);
|
||||
return eval_expr(expr, context);
|
||||
}
|
||||
|
||||
} // namespace mbs
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
#include "ast.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace mbs {
|
||||
|
||||
@@ -17,10 +20,18 @@ struct EvalError : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
/// Error message if invalid, else empty.
|
||||
using FunctionDef = std::function<nlohmann::json(
|
||||
const nlohmann::json& target,
|
||||
const std::vector<nlohmann::json>& args)>;
|
||||
|
||||
using FunctionRegistry = std::unordered_map<std::string, FunctionDef>;
|
||||
|
||||
std::optional<std::string> semantic_check(const ast::Expr& expr);
|
||||
std::optional<std::string> semantic_check(const ast::Expr& expr, const FunctionRegistry& funcs);
|
||||
|
||||
nlohmann::json eval_expr(const ast::Expr& expr, const nlohmann::json& context);
|
||||
nlohmann::json eval_expr(const ast::Expr& expr, const nlohmann::json& context,
|
||||
const FunctionRegistry& funcs);
|
||||
|
||||
bool json_truthy(const nlohmann::json& j);
|
||||
|
||||
|
||||
@@ -59,4 +59,77 @@ EvalBoolResult eval_true(const std::string_view source, const nlohmann::json& co
|
||||
return EvalBoolResult{true, json_truthy(value), {}, std::nullopt};
|
||||
}
|
||||
|
||||
// --- Script class ---
|
||||
|
||||
CompiledExpr Script::compile(std::string_view source, std::size_t max_source_length) const {
|
||||
if (max_source_length > 0 && source.size() > max_source_length) {
|
||||
throw std::runtime_error("source exceeds maximum length");
|
||||
}
|
||||
auto ast = parse(source);
|
||||
const auto err = semantic_check(*ast, functions_);
|
||||
if (err.has_value()) {
|
||||
throw std::runtime_error(*err);
|
||||
}
|
||||
CompiledExpr compiled;
|
||||
compiled.ast_ = std::move(ast);
|
||||
compiled.source_ = std::string(source);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
EvalValueResult Script::eval_val(const CompiledExpr& compiled, const nlohmann::json& context) const {
|
||||
try {
|
||||
if (!compiled.ast_) {
|
||||
return EvalErr{"expression not compiled", std::nullopt};
|
||||
}
|
||||
return EvalOk{eval_expr(*compiled.ast_, context, functions_)};
|
||||
} catch (const ParseError& ex) {
|
||||
return EvalErr{ex.what(), ex.loc};
|
||||
} catch (const std::exception& ex) {
|
||||
return EvalErr{ex.what(), std::nullopt};
|
||||
}
|
||||
}
|
||||
|
||||
EvalBoolResult Script::eval_true(const CompiledExpr& compiled, const nlohmann::json& context) const {
|
||||
const auto r = eval_val(compiled, context);
|
||||
if (std::holds_alternative<EvalErr>(r)) {
|
||||
const auto&[error, loc] = std::get<EvalErr>(r);
|
||||
return EvalBoolResult{false, false, error, loc};
|
||||
}
|
||||
const auto&[value] = std::get<EvalOk>(r);
|
||||
return EvalBoolResult{true, json_truthy(value), {}, std::nullopt};
|
||||
}
|
||||
|
||||
EvalValueResult Script::eval_val(std::string_view source, const nlohmann::json& context,
|
||||
std::size_t max_source_length) const {
|
||||
try {
|
||||
if (max_source_length > 0 && source.size() > max_source_length) {
|
||||
return EvalErr{"source exceeds maximum length", std::nullopt};
|
||||
}
|
||||
const auto ast = parse(source);
|
||||
if (const auto err = semantic_check(*ast, functions_); err.has_value()) {
|
||||
return EvalErr{*err, std::nullopt};
|
||||
}
|
||||
return EvalOk{eval_expr(*ast, context, functions_)};
|
||||
} catch (const ParseError& ex) {
|
||||
return EvalErr{ex.what(), ex.loc};
|
||||
} catch (const std::exception& ex) {
|
||||
return EvalErr{ex.what(), std::nullopt};
|
||||
}
|
||||
}
|
||||
|
||||
EvalBoolResult Script::eval_true(std::string_view source, const nlohmann::json& context,
|
||||
std::size_t max_source_length) const {
|
||||
const auto r = eval_val(source, context, max_source_length);
|
||||
if (std::holds_alternative<EvalErr>(r)) {
|
||||
const auto&[error, loc] = std::get<EvalErr>(r);
|
||||
return EvalBoolResult{false, false, error, loc};
|
||||
}
|
||||
const auto&[value] = std::get<EvalOk>(r);
|
||||
return EvalBoolResult{true, json_truthy(value), {}, std::nullopt};
|
||||
}
|
||||
|
||||
void Script::register_function(std::string name, FunctionDef fn) {
|
||||
functions_[std::move(name)] = std::move(fn);
|
||||
}
|
||||
|
||||
} // namespace mbs
|
||||
|
||||
@@ -296,3 +296,161 @@ TEST_CASE("&& and || always return bool (B2)", "[bugfix]") {
|
||||
REQUIRE(std::get<EvalOk>(r).value.is_boolean());
|
||||
}
|
||||
}
|
||||
|
||||
// --- Precompilation API (F14) ---
|
||||
|
||||
TEST_CASE("Script::compile + eval_val reuses AST", "[precompile]") {
|
||||
mbs::Script s;
|
||||
auto compiled = s.compile("@x + 1");
|
||||
|
||||
SECTION("evaluates with different contexts") {
|
||||
auto r1 = s.eval_val(compiled, json{{"x", 1}});
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r1));
|
||||
REQUIRE(std::get<EvalOk>(r1).value == 2.0);
|
||||
|
||||
auto r2 = s.eval_val(compiled, json{{"x", 2}});
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r2));
|
||||
REQUIRE(std::get<EvalOk>(r2).value == 3.0);
|
||||
}
|
||||
|
||||
SECTION("eval_true on compiled expression") {
|
||||
auto r = s.eval_true(compiled, json{{"x", 1}});
|
||||
REQUIRE(r.ok);
|
||||
REQUIRE(r.value == true);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Script::compile rejects invalid expressions", "[precompile]") {
|
||||
mbs::Script s;
|
||||
REQUIRE_THROWS(s.compile("1 +"));
|
||||
}
|
||||
|
||||
TEST_CASE("Script::compile respects max_source_length", "[precompile]") {
|
||||
mbs::Script s;
|
||||
REQUIRE_THROWS_AS(s.compile("1 + 2", 3), std::runtime_error);
|
||||
REQUIRE_NOTHROW(s.compile("1 + 2", 10));
|
||||
}
|
||||
|
||||
TEST_CASE("Script::eval_val with source string works", "[precompile]") {
|
||||
mbs::Script s;
|
||||
auto r = s.eval_val("1 + 2", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 3.0);
|
||||
}
|
||||
|
||||
TEST_CASE("Script::eval_true with source string works", "[precompile]") {
|
||||
mbs::Script s;
|
||||
auto r = s.eval_true("1 > 0", json::object());
|
||||
REQUIRE(r.ok);
|
||||
REQUIRE(r.value == true);
|
||||
}
|
||||
|
||||
TEST_CASE("Uncompiled CompiledExpr returns error", "[precompile]") {
|
||||
mbs::Script s;
|
||||
mbs::CompiledExpr empty;
|
||||
REQUIRE(!empty);
|
||||
auto r = s.eval_val(empty, json::object());
|
||||
REQUIRE(std::holds_alternative<EvalErr>(r));
|
||||
}
|
||||
|
||||
// --- Custom Function Registry (F15) ---
|
||||
|
||||
TEST_CASE("register_function: basic custom method", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("double", [](const json& target, const std::vector<json>&) -> json {
|
||||
if (!target.is_number()) return nullptr;
|
||||
return target.get<double>() * 2;
|
||||
});
|
||||
|
||||
auto r = s.eval_val("(5).double()", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 10.0);
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: custom method with arguments", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("add", [](const json& target, const std::vector<json>& args) -> json {
|
||||
if (!target.is_number() || args.empty() || !args[0].is_number()) return nullptr;
|
||||
return target.get<double>() + args[0].get<double>();
|
||||
});
|
||||
|
||||
auto r = s.eval_val("(10).add(5)", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 15.0);
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: custom method on string", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("reverse", [](const json& target, const std::vector<json>&) -> json {
|
||||
if (!target.is_string()) return nullptr;
|
||||
std::string result = target.get<std::string>();
|
||||
std::reverse(result.begin(), result.end());
|
||||
return result;
|
||||
});
|
||||
|
||||
auto r = s.eval_val(R"("hello".reverse())", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == "olleh");
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: unknown method still fails semantic check", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
REQUIRE_THROWS(s.compile("(5).unknown()"));
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: registered method passes semantic check", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("custom", [](const json& target, const std::vector<json>&) -> json {
|
||||
return target;
|
||||
});
|
||||
REQUIRE_NOTHROW(s.compile("(5).custom()"));
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: works with compiled expressions", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("triple", [](const json& target, const std::vector<json>&) -> json {
|
||||
if (!target.is_number()) return nullptr;
|
||||
return target.get<double>() * 3;
|
||||
});
|
||||
|
||||
auto compiled = s.compile("@x.triple()");
|
||||
auto r1 = s.eval_val(compiled, json{{"x", 3}});
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r1));
|
||||
REQUIRE(std::get<EvalOk>(r1).value == 9.0);
|
||||
|
||||
auto r2 = s.eval_val(compiled, json{{"x", 7}});
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r2));
|
||||
REQUIRE(std::get<EvalOk>(r2).value == 21.0);
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: custom method in nested expression", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("double", [](const json& target, const std::vector<json>&) -> json {
|
||||
if (!target.is_number()) return nullptr;
|
||||
return target.get<double>() * 2;
|
||||
});
|
||||
|
||||
auto r = s.eval_val("(3).double() + (4).double()", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 14.0);
|
||||
}
|
||||
|
||||
TEST_CASE("register_function: builtin methods still work alongside custom", "[custom-func]") {
|
||||
mbs::Script s;
|
||||
s.register_function("double", [](const json& target, const std::vector<json>&) -> json {
|
||||
if (!target.is_number()) return nullptr;
|
||||
return target.get<double>() * 2;
|
||||
});
|
||||
|
||||
SECTION("builtin size still works") {
|
||||
auto r = s.eval_val(R"("hello".size())", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 5);
|
||||
}
|
||||
|
||||
SECTION("custom double works") {
|
||||
auto r = s.eval_val("(5).double()", json::object());
|
||||
REQUIRE(std::holds_alternative<EvalOk>(r));
|
||||
REQUIRE(std::get<EvalOk>(r).value == 10.0);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user