mirror of
https://github.com/allankoechke/expr_eval.git
synced 2026-12-02 17:20:16 +00:00
84 lines
3.0 KiB
C++
84 lines
3.0 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
|
|
#include <builtin-features.inc>
|
|
#include <shunting-yard.h>
|
|
#include "containers.h"
|
|
#include <functions.h>
|
|
|
|
using cparse::TokenMap;
|
|
using cparse::calculator;
|
|
using cparse::packToken;
|
|
|
|
// https://deepwiki.com/search/generate-cmake-file-to-build-c_7fa8d271-b0bd-4da7-ae77-b2ea5c2f9b27
|
|
|
|
static bool evaluateExpr(const std::string& expr, const cparse::TokenMap& vars) {
|
|
cparse::packToken result = cparse::calculator::calculate(expr.c_str(), vars);
|
|
return result.asBool(); // true/false
|
|
}
|
|
|
|
static bool evaluateExpr(const std::string& expr, const nlohmann::json& vars) {
|
|
const auto jsonToTokenMap = [&](const nlohmann::json& j) {
|
|
cparse::TokenMap map;
|
|
|
|
for (auto& [key, value] : j.items()) {
|
|
if (value.is_null()) {
|
|
map[key] = cparse::packToken::None();
|
|
} else if (value.is_boolean()) {
|
|
map[key] = value.get<bool>();
|
|
} else if (value.is_number_integer()) {
|
|
map[key] = value.get<int64_t>();
|
|
} else if (value.is_number_float()) {
|
|
map[key] = value.get<double>();
|
|
} else if (value.is_string()) {
|
|
map[key] = value.get<std::string>();
|
|
} else if (value.is_object()) {
|
|
map[key] = jsonToTokenMap(value); // Recursive conversion
|
|
} else if (value.is_array()) {
|
|
cparse::TokenList list;
|
|
for (const auto& item : value) {
|
|
if (item.is_object()) {
|
|
list.push(jsonToTokenMap(item));
|
|
} else {
|
|
// Convert primitive types
|
|
if (item.is_string()) list.push(item.get<std::string>());
|
|
else if (item.is_number_integer()) list.push(item.get<int64_t>());
|
|
else if (item.is_number_float()) list.push(item.get<double>());
|
|
else if (item.is_boolean()) list.push(item.get<bool>());
|
|
else if (item.is_null()) list.push(cparse::packToken::None());
|
|
}
|
|
}
|
|
map[key] = list;
|
|
}
|
|
}
|
|
|
|
return map;
|
|
};
|
|
|
|
std::cout << vars.dump() << std::endl;
|
|
const auto t_vars = jsonToTokenMap(vars);
|
|
return evaluateExpr(expr, t_vars);
|
|
}
|
|
|
|
int main() {
|
|
cparse_startup();
|
|
cparse::TokenMap vars;
|
|
|
|
// Initialize with actual data
|
|
cparse::TokenMap auth_map;
|
|
auth_map["id"] = "user123";
|
|
auth_map["role"] = "admin";
|
|
vars["auth"] = auth_map;
|
|
|
|
// Test the expression
|
|
std::string cmd = "auth.id == 'user123'";
|
|
std::cout << "auth.id == 'user123r' ? " << evaluateExpr(cmd, vars) << std::endl;
|
|
|
|
cmd = "auth.role == 'admin'";
|
|
std::cout << "auth.role == 'admin' ? " << evaluateExpr(cmd, vars) << std::endl;
|
|
|
|
cmd = "auth.id == 'user123r' || auth.role == 'admin'";
|
|
std::cout << "auth.id == 'user123r' || auth.role == 'admin' ? " << evaluateExpr(cmd, vars) << std::endl;
|
|
|
|
return 0;
|
|
} |