Files
htab/engine/evaluator.cpp
T

312 lines
11 KiB
C++
Raw Normal View History

#include "engine/evaluator.hpp"
#include "engine/functions/registry.hpp"
#include "engine/workbook.hpp"
#include <algorithm>
#include <cmath>
#include <variant>
namespace htab {
namespace {
constexpr int kMaxArrayCells = 1000000;
Value eval_scalar_binary(BinOp op, const Value& a, const Value& b) {
if (a.is_error()) return a;
if (b.is_error()) return b;
switch (op) {
case BinOp::Add:
case BinOp::Sub:
case BinOp::Mul:
case BinOp::Div:
case BinOp::Pow: {
auto na = to_number(a);
if (std::holds_alternative<ErrorCode>(na)) return Value::make_error(std::get<ErrorCode>(na));
auto nb = to_number(b);
if (std::holds_alternative<ErrorCode>(nb)) return Value::make_error(std::get<ErrorCode>(nb));
double da = std::get<double>(na);
double db = std::get<double>(nb);
switch (op) {
case BinOp::Add: return Value::make_checked_number(da + db);
case BinOp::Sub: return Value::make_checked_number(da - db);
case BinOp::Mul: return Value::make_checked_number(da * db);
case BinOp::Div:
if (db == 0.0) return Value::make_error(ErrorCode::Div0);
return Value::make_checked_number(da / db);
case BinOp::Pow:
if (da == 0.0 && db < 0.0) return Value::make_error(ErrorCode::Div0);
return Value::make_checked_number(std::pow(da, db));
default: break;
}
break;
}
case BinOp::Concat: {
auto sa = to_string(a);
if (std::holds_alternative<ErrorCode>(sa)) return Value::make_error(std::get<ErrorCode>(sa));
auto sb = to_string(b);
if (std::holds_alternative<ErrorCode>(sb)) return Value::make_error(std::get<ErrorCode>(sb));
return Value::make_string(std::get<std::string>(sa) + std::get<std::string>(sb));
}
case BinOp::Eq:
case BinOp::Neq:
case BinOp::Lt:
case BinOp::Gt:
case BinOp::Le:
case BinOp::Ge: {
auto cmp = compare_values(a, b);
if (std::holds_alternative<ErrorCode>(cmp)) return Value::make_error(std::get<ErrorCode>(cmp));
int c = std::get<int>(cmp);
switch (op) {
case BinOp::Eq: return Value::make_bool(c == 0);
case BinOp::Neq: return Value::make_bool(c != 0);
case BinOp::Lt: return Value::make_bool(c < 0);
case BinOp::Gt: return Value::make_bool(c > 0);
case BinOp::Le: return Value::make_bool(c <= 0);
case BinOp::Ge: return Value::make_bool(c >= 0);
default: break;
}
break;
}
default:
break;
}
return Value::make_error(ErrorCode::Value);
}
Value eval_scalar_unary(char op, const Value& v) {
if (v.is_error()) return v;
auto n = to_number(v);
if (std::holds_alternative<ErrorCode>(n)) return Value::make_error(std::get<ErrorCode>(n));
double d = std::get<double>(n);
return Value::make_checked_number(op == '-' ? -d : d);
}
Value eval_scalar_percent(const Value& v) {
if (v.is_error()) return v;
auto n = to_number(v);
if (std::holds_alternative<ErrorCode>(n)) return Value::make_error(std::get<ErrorCode>(n));
return Value::make_checked_number(std::get<double>(n) / 100.0);
}
Value broadcast_binary(BinOp op, const Value& lhs, const Value& rhs) {
if (!lhs.is_array() && !rhs.is_array()) {
return eval_scalar_binary(op, lhs, rhs);
}
int lr = lhs.is_array() ? lhs.as_array()->rows : 1;
int lc = lhs.is_array() ? lhs.as_array()->cols : 1;
int rr = rhs.is_array() ? rhs.as_array()->rows : 1;
int rc = rhs.is_array() ? rhs.as_array()->cols : 1;
if (lr <= 0 || lc <= 0 || rr <= 0 || rc <= 0) {
return Value::make_error(ErrorCode::Value);
}
if (lr != rr && lr != 1 && rr != 1) return Value::make_error(ErrorCode::Value);
if (lc != rc && lc != 1 && rc != 1) return Value::make_error(ErrorCode::Value);
int out_r = std::max(lr, rr);
int out_c = std::max(lc, rc);
if (static_cast<int64_t>(out_r) * out_c > kMaxArrayCells) {
return Value::make_error(ErrorCode::Num);
}
auto out = std::make_shared<Array2D>(out_r, out_c);
for (int r = 0; r < out_r; ++r) {
for (int c = 0; c < out_c; ++c) {
const Value& va = lhs.is_array() ? lhs.as_array()->at(lr == 1 ? 0 : r, lc == 1 ? 0 : c) : lhs;
const Value& vb = rhs.is_array() ? rhs.as_array()->at(rr == 1 ? 0 : r, rc == 1 ? 0 : c) : rhs;
out->at(r, c) = eval_scalar_binary(op, va, vb);
}
}
if (out_r == 1 && out_c == 1) {
return out->at(0, 0);
}
return Value::make_array(std::move(out));
}
template <typename Fn>
Value map_unary(const Value& v, Fn&& fn) {
if (!v.is_array()) return fn(v);
const auto& arr = v.as_array();
if (!arr || arr->rows <= 0 || arr->cols <= 0) {
return Value::make_error(ErrorCode::Value);
}
auto out = std::make_shared<Array2D>(arr->rows, arr->cols);
for (int r = 0; r < arr->rows; ++r) {
for (int c = 0; c < arr->cols; ++c) {
out->at(r, c) = fn(arr->at(r, c));
}
}
if (arr->rows == 1 && arr->cols == 1) {
return out->at(0, 0);
}
return Value::make_array(std::move(out));
}
int resolve_sheet(const std::string& sheet_name, const EvalContext& ctx) {
if (sheet_name.empty()) return ctx.current_sheet;
return ctx.wb->find_sheet(sheet_name);
}
} // namespace
Value deref_to_value(const EvalResult& res, const Workbook& wb) {
if (!res.is_ref) {
return res.value;
}
if (res.ranges.size() != 1) {
return Value::make_error(ErrorCode::Value);
}
const CellRange& rng = res.ranges[0];
int rc = rng.row_count();
int cc = rng.col_count();
if (rc == 1 && cc == 1) {
return wb.get_scalar_value(rng.sheet, rng.r1, rng.c1);
}
if (static_cast<int64_t>(rc) * cc > kMaxArrayCells) {
return Value::make_error(ErrorCode::Num);
}
auto arr = std::make_shared<Array2D>(rc, cc);
for (int r = 0; r < rc; ++r) {
for (int c = 0; c < cc; ++c) {
arr->at(r, c) = wb.get_scalar_value(rng.sheet, rng.r1 + r, rng.c1 + c);
}
}
return Value::make_array(std::move(arr));
}
EvalResult evaluate_ast(const Expr* expr, const EvalContext& ctx) {
if (!expr || !ctx.wb) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
switch (expr->kind) {
case Expr::Kind::Literal: {
return EvalResult::from_value(static_cast<const LiteralExpr*>(expr)->value);
}
case Expr::Kind::UnknownName: {
return EvalResult::from_value(Value::make_error(ErrorCode::Name));
}
case Expr::Kind::CellRef: {
const auto& ref = static_cast<const CellRefExpr*>(expr)->ref;
if (ref.invalid) {
return EvalResult::from_value(Value::make_error(ErrorCode::Ref));
}
int s = resolve_sheet(ref.sheet_name, ctx);
if (s < 0) {
return EvalResult::from_value(Value::make_error(ErrorCode::Ref));
}
return EvalResult::from_range(CellRange{s, ref.row, ref.col, ref.row, ref.col});
}
case Expr::Kind::Range: {
const auto* rng = static_cast<const RangeExpr*>(expr);
EvalResult lr = evaluate_ast(rng->lhs.get(), ctx);
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
// Inherit sheet name when writing Sheet2!A1:B5 where RHS omitted the sheet prefix.
EvalContext rhs_ctx = ctx;
if (rng->lhs->kind == Expr::Kind::CellRef && rng->rhs->kind == Expr::Kind::CellRef) {
const auto& lref = static_cast<const CellRefExpr*>(rng->lhs.get())->ref;
const auto& rref = static_cast<const CellRefExpr*>(rng->rhs.get())->ref;
if (!lref.sheet_name.empty() && rref.sheet_name.empty() && !lr.ranges.empty()) {
rhs_ctx.current_sheet = lr.ranges[0].sheet;
}
}
EvalResult rr = evaluate_ast(rng->rhs.get(), rhs_ctx);
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
if (lr.ranges.size() != 1 || rr.ranges.size() != 1) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
const CellRange& a = lr.ranges[0];
const CellRange& b = rr.ranges[0];
if (a.sheet != b.sheet) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
return EvalResult::from_range(CellRange{
a.sheet,
std::min(a.r1, b.r1),
std::min(a.c1, b.c1),
std::max(a.r2, b.r2),
std::max(a.c2, b.c2),
});
}
case Expr::Kind::Unary: {
const auto* u = static_cast<const UnaryExpr*>(expr);
Value val = deref_to_value(evaluate_ast(u->operand.get(), ctx), *ctx.wb);
return EvalResult::from_value(
map_unary(val, [op = u->op](const Value& item) { return eval_scalar_unary(op, item); }));
}
case Expr::Kind::Percent: {
const auto* p = static_cast<const PercentExpr*>(expr);
Value val = deref_to_value(evaluate_ast(p->operand.get(), ctx), *ctx.wb);
return EvalResult::from_value(map_unary(val, eval_scalar_percent));
}
case Expr::Kind::Binary: {
const auto* b = static_cast<const BinaryExpr*>(expr);
EvalResult lr = evaluate_ast(b->lhs.get(), ctx);
EvalResult rr = evaluate_ast(b->rhs.get(), ctx);
if (b->op == BinOp::Union) {
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
std::vector<CellRange> combined = std::move(lr.ranges);
combined.insert(combined.end(), rr.ranges.begin(), rr.ranges.end());
return EvalResult::from_ranges(std::move(combined));
}
if (b->op == BinOp::Intersect) {
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
std::vector<CellRange> overlaps;
for (const auto& ra : lr.ranges) {
for (const auto& rb : rr.ranges) {
if (ra.sheet != rb.sheet) continue;
int r1 = std::max(ra.r1, rb.r1);
int c1 = std::max(ra.c1, rb.c1);
int r2 = std::min(ra.r2, rb.r2);
int c2 = std::min(ra.c2, rb.c2);
if (r1 <= r2 && c1 <= c2) {
overlaps.push_back(CellRange{ra.sheet, r1, c1, r2, c2});
}
}
}
if (overlaps.empty()) {
return EvalResult::from_value(Value::make_error(ErrorCode::NA));
}
return EvalResult::from_ranges(std::move(overlaps));
}
Value lv = deref_to_value(lr, *ctx.wb);
Value rv = deref_to_value(rr, *ctx.wb);
return EvalResult::from_value(broadcast_binary(b->op, lv, rv));
}
case Expr::Kind::Call: {
const auto* call = static_cast<const CallExpr*>(expr);
const auto* fn = FunctionRegistry::instance().find(call->name);
if (!fn) {
return EvalResult::from_value(Value::make_error(ErrorCode::Name));
}
return (*fn)(call->args, ctx);
}
}
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
} // namespace htab